📈 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
(feature) Referral program (#362)
Andrii Romasiune54e5b6566c9
diff --git a/app/App.tsx b/app/App.tsxindex 284132059..70b9ddf1c 100644--- a/app/App.tsx+++ b/app/App.tsx@@ -9,6 +9,7 @@ import { useAlert } from '@blaumaus/react-alert'import cx from 'clsx'import _some from 'lodash/some'import _includes from 'lodash/includes'+import _startsWith from 'lodash/startsWith'import 'dayjs/locale/ru'import 'dayjs/locale/uk'@@ -135,10 +136,12 @@ const App: React.FC<IApp> = ({ ssrTheme, ssrAuthenticated }) => {const isMinimalFooter = _some(minimalFooterPages, (page) => _includes(pathname, page))+ const isReferralPage = _startsWith(pathname, '/ref/')+return (// eslint-disable-next-line react/jsx-no-useless-fragment<Suspense fallback={<></>}>- {pathname !== routesPath.main && (+ {pathname !== routesPath.main && !isReferralPage && (<Header ssrTheme={ssrTheme} authenticated={authenticated} />)}{/* @ts-ignore */}@@ -147,7 +150,9 @@ const App: React.FC<IApp> = ({ ssrTheme, ssrAuthenticated }) => {<Outlet /></Suspense></ScrollToTop>- <Footer minimal={isMinimalFooter} authenticated={authenticated} />+ {!isReferralPage && (+ <Footer minimal={isMinimalFooter} authenticated={authenticated} />+ )}</Suspense>)}diff --git a/app/api/index.ts b/app/api/index.tsindex 8815d5aeb..d3092f605 100644--- a/app/api/index.ts+++ b/app/api/index.ts@@ -136,8 +136,8 @@ export const login = (credentials: {export const signup = (data: {email: string,- password: string- repeat: string+ password: string,+ refCode?: string,}) =>api.post('v1/auth/register', data)@@ -186,6 +186,42 @@ export const setShowLiveVisitorsInTitle = (show: boolean) =>throw new Error(errorsArray)})+export const generateRefCode = () =>+ api+ .post('/user/generate-ref-code')+ .then((response): Partial<IUser> => response.data)+ .catch((error) => {+ const errorsArray = error.response.data.message+ if (_isArray(errorsArray)) {+ throw errorsArray+ }+ throw new Error(errorsArray)+ })++export const getPayoutsInfo = () =>+ api+ .get('/user/payouts/info')+ .then((response): Partial<IUser> => response.data)+ .catch((error) => {+ const errorsArray = error.response.data.message+ if (_isArray(errorsArray)) {+ throw errorsArray+ }+ throw new Error(errorsArray)+ })++export const getReferrals = () =>+ api+ .get('/user/referrals')+ .then((response): Partial<IUser> => response.data)+ .catch((error) => {+ const errorsArray = error.response.data.message+ if (_isArray(errorsArray)) {+ throw errorsArray+ }+ throw new Error(errorsArray)+ })+export const forgotPassword = (email: {email: string}) =>@@ -911,9 +947,9 @@ export const generateSSOAuthURL = (provider: string) =>: error.response.data.message})-export const getJWTBySSOHash = (hash: string, provider: string) =>+export const getJWTBySSOHash = (hash: string, provider: string, refCode?: string) =>api- .post('v1/auth/sso/hash', { hash, provider })+ .post('v1/auth/sso/hash', { hash, provider, refCode }).then((response): unknown => response.data).catch((error) => {debug('%s', error)@@ -1082,6 +1118,15 @@ export const receiveLoginNotification = (receiveLoginNotifications: boolean) =>throw error})+export const setPaypalEmail = (paypalPaymentsEmail: string | null) =>+ api+ .patch('user/set-paypal-email', { paypalPaymentsEmail })+ .then((response) => response.data)+ .catch((error) => {+ debug('%s', error)+ throw error+ })+export const previewSubscriptionUpdate = (planId: number) =>api.post('user/preview-plan', { planId })diff --git a/app/components/Header/index.tsx b/app/components/Header/index.tsxindex 1f8e90875..bdc00bc7b 100644--- a/app/components/Header/index.tsx+++ b/app/components/Header/index.tsx@@ -3,7 +3,7 @@ import React, {memo, Fragment, useRef, useMemo, MutableRefObject,} from 'react'-import { Link, useLocation } from '@remix-run/react'+import { Link } from '@remix-run/react'import { useDispatch, useSelector } from 'react-redux'import { useTranslation } from 'react-i18next'import Flag from 'react-flagkit'@@ -422,7 +422,7 @@ const AuthedHeader = ({)const NotAuthedHeader = ({- switchTheme, theme, onLanguageChange, t, language, colourBackground,+ switchTheme, theme, onLanguageChange, t, language, colourBackground, refPage,}: {switchTheme: (a?: string) => void,theme: string,@@ -430,6 +430,7 @@ const NotAuthedHeader = ({t: (key: string) => string,language: string,colourBackground: boolean,+ refPage?: boolean,}) => (<headerclassName={cx('relative overflow-x-clip', {@@ -440,47 +441,61 @@ const NotAuthedHeader = ({<div className='w-full py-4 flex items-center justify-between border-b border-indigo-500 dark:border-slate-600 lg:border-none'><div className='flex items-center'>{/* Logo */}- <Link to={routesPath.main}>- <span className='sr-only'>Swetrix</span>- <img- className='h-7 -translate-y-[3px]'- height='28'- src={theme === 'dark' ? '/assets/logo_white.png' : '/assets/logo_blue.png'}- alt='Swetrix'- />- </Link>+ {refPage ? (+ <span>+ <span className='sr-only'>Swetrix</span>+ <img+ className='h-7 -translate-y-[3px]'+ height='28'+ src={theme === 'dark' ? '/assets/logo_white.png' : '/assets/logo_blue.png'}+ alt='Swetrix'+ />+ </span>+ ) : (+ <Link to={routesPath.main}>+ <span className='sr-only'>Swetrix</span>+ <img+ className='h-7 -translate-y-[3px]'+ height='28'+ src={theme === 'dark' ? '/assets/logo_white.png' : '/assets/logo_blue.png'}+ alt='Swetrix'+ />+ </Link>+ )}- <div className='hidden ml-10 space-x-1 lg:flex gap-4 items-center'>- <a- href={BLOG_URL}- className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'- target='_blank'- rel='noreferrer noopener'- >- {t('footer.blog')}- </a>- {!isSelfhosted && (- <>- <Link- to={routesPath.features}- className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'- >- {t('common.features')}- </Link>- <Link- to={`${routesPath.main}#pricing`}- className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'- key='Pricing'- >- {t('common.pricing')}- </Link>- </>- )}- <a href={DOCS_URL} className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white' target='_blank' rel='noreferrer noopener'>- {/* <DocumentTextIcon className='w-5 h-5 mr-1' /> */}- {t('common.docs')}- </a>- </div>+ {!refPage && (+ <div className='hidden ml-10 space-x-1 lg:flex gap-4 items-center'>+ <a+ href={BLOG_URL}+ className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'+ target='_blank'+ rel='noreferrer noopener'+ >+ {t('footer.blog')}+ </a>+ {!isSelfhosted && (+ <>+ <Link+ to={routesPath.features}+ className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'+ >+ {t('common.features')}+ </Link>+ <Link+ to={`${routesPath.main}#pricing`}+ className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'+ key='Pricing'+ >+ {t('common.pricing')}+ </Link>+ </>+ )}+ <a href={DOCS_URL} className='font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white' target='_blank' rel='noreferrer noopener'>+ {/* <DocumentTextIcon className='w-5 h-5 mr-1' /> */}+ {t('common.docs')}+ </a>+ </div>+ )}</div><div className='hidden md:flex justify-center items-center flex-wrap ml-1 md:ml-10 space-y-1 sm:space-y-0 space-x-2 md:space-x-4'>{/* Language selector */}@@ -509,13 +524,17 @@ const NotAuthedHeader = ({switchTheme={switchTheme}t={t}/>- <span className='text-slate-700'>- |- </span>- <Link to={routesPath.signin} className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'>- {t('auth.common.signin')}- <ArrowSmallRightIcon className='ml-1 stroke-2 h-4 w-4 mt-[1px]' />- </Link>+ {!refPage && (+ <>+ <span className='text-slate-700'>+ |+ </span>+ <Link to={routesPath.signin} className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'>+ {t('auth.common.signin')}+ <ArrowSmallRightIcon className='ml-1 stroke-2 h-4 w-4 mt-[1px]' />+ </Link>+ </>+ )}</div><div className='md:hidden flex justify-center items-center'>{/* Theme switch */}@@ -536,37 +555,39 @@ const NotAuthedHeader = ({</Popover.Button></div></div>- <div className='py-4 flex gap-4 flex-wrap justify-center space-x-2 lg:hidden'>- <a- href={BLOG_URL}- className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'- target='_blank'- rel='noreferrer noopener'- >- {t('footer.blog')}- </a>- <Link- to={`${routesPath.main}#pricing`}- className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'- key='Pricing'- >- {t('common.pricing')}- </Link>- <Link- to={routesPath.features}- className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'- >- {t('common.features')}- </Link>- <a- href={DOCS_URL}- className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'- target='_blank'- rel='noreferrer noopener'- >- {t('common.docs')}- </a>- </div>+ {!refPage && (+ <div className='py-4 flex gap-4 flex-wrap justify-center space-x-2 lg:hidden'>+ <a+ href={BLOG_URL}+ className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'+ target='_blank'+ rel='noreferrer noopener'+ >+ {t('footer.blog')}+ </a>+ <Link+ to={`${routesPath.main}#pricing`}+ className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'+ key='Pricing'+ >+ {t('common.pricing')}+ </Link>+ <Link+ to={routesPath.features}+ className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'+ >+ {t('common.features')}+ </Link>+ <a+ href={DOCS_URL}+ className='flex items-center font-semibold leading-6 text-base text-slate-800 hover:text-slate-700 dark:text-slate-200 dark:hover:text-white'+ target='_blank'+ rel='noreferrer noopener'+ >+ {t('common.docs')}+ </a>+ </div>+ )}</nav></header>)@@ -574,9 +595,11 @@ const NotAuthedHeader = ({interface IHeader {ssrTheme: 'dark' | 'light'authenticated: boolean+ refPage?: boolean+ transparent?: boolean}-const Header: React.FC<IHeader> = ({ ssrTheme, authenticated }): JSX.Element => {+const Header: React.FC<IHeader> = ({ ssrTheme, authenticated, refPage, transparent }): JSX.Element => {const { t, i18n: { language } }: {t: (key: string, options?: {[key: string]: string | number | null@@ -587,7 +610,6 @@ const Header: React.FC<IHeader> = ({ ssrTheme, authenticated }): JSX.Element =>const _dispatch = useDispatch()const { user } = useSelector((state: StateType) => state.auth)const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)- const { pathname } = useLocation()// @ts-ignoreconst buttonRef: MutableRefObject<HTMLButtonElement> = useRef<HTMLButtonElement>()const theme = isBrowser ? reduxTheme : ssrTheme@@ -653,7 +675,7 @@ const Header: React.FC<IHeader> = ({ ssrTheme, authenticated }): JSX.Element =>theme={theme}onLanguageChange={onLanguageChange}language={language}- colourBackground={pathname !== routesPath.main}+ colourBackground={!transparent}t={t}/>) : (@@ -662,7 +684,8 @@ const Header: React.FC<IHeader> = ({ ssrTheme, authenticated }): JSX.Element =>theme={theme}onLanguageChange={onLanguageChange}language={language}- colourBackground={pathname !== routesPath.main}+ colourBackground={!transparent}+ refPage={refPage}t={t}/>)}diff --git a/app/pages/MainPage/Pricing.tsx b/app/pages/MainPage/Pricing.tsxindex e46d14f75..d08dd0a38 100644--- a/app/pages/MainPage/Pricing.tsx+++ b/app/pages/MainPage/Pricing.tsx@@ -15,7 +15,7 @@ import cx from 'clsx'import Modal from 'ui/Modal'import Spin from 'ui/icons/Spin'import {- CONTACT_EMAIL, paddleLanguageMapping, PLAN_LIMITS, CURRENCIES,+ CONTACT_EMAIL, paddleLanguageMapping, PLAN_LIMITS, CURRENCIES, BillingFrequency, REFERRAL_DISCOUNT_CODE,} from 'redux/constants'import { errorsActions } from 'redux/reducers/errors'import { alertsActions } from 'redux/reducers/alerts'@@ -136,11 +136,6 @@ const getTiers = (t: (key: string, options?: {},]-const BillingFrequency = {- monthly: 'monthly',- yearly: 'yearly',-}-interface IPricingItem {tier: anyuser: IUser@@ -382,6 +377,10 @@ const Pricing = ({ t, language, authenticated }: IPricing) => {return}+ const discountCode = (user.referrerID && (user.planCode === 'trial' || user.planCode === 'none'))+ ? REFERRAL_DISCOUNT_CODE+ : null+// @ts-ignorewindow.Paddle.Checkout.open({product: billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,@@ -393,6 +392,7 @@ const Pricing = ({ t, language, authenticated }: IPricing) => {title: tier.name,displayModeTheme: theme,country: metainfo.country,+ discountCode,})}}@@ -575,7 +575,19 @@ const Pricing = ({ t, language, authenticated }: IPricing) => {<Loader />)}{subUpdatePreview === false && (- <p className='whitespace-pre-line'>{t('billing.previewLoadingError')}</p>+ <p className='whitespace-pre-line'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='billing.previewLoadingError'+ values={{+ email: CONTACT_EMAIL,+ }}+ components={{+ mail: <a title={`Email us at ${CONTACT_EMAIL}`} href={`mailto:${CONTACT_EMAIL}`} className='font-medium text-indigo-600 hover:text-indigo-500 dark:text-indigo-400' />,+ }}+ />+ </p>)}{subUpdatePreview && (<div>diff --git a/app/pages/MainPage/index.tsx b/app/pages/MainPage/index.tsxindex 212b5de10..429199609 100644--- a/app/pages/MainPage/index.tsx+++ b/app/pages/MainPage/index.tsx@@ -123,7 +123,7 @@ const COMPETITOR_FEATURE_TABLE: {},}-const Lines = (): JSX.Element => (+export const Lines = (): JSX.Element => (<div className='relative pointer-events-none'><div className='absolute rotate-6 right-[-48rem] top-[32rem] h-px w-[800%] bg-gradient-to-l from-slate-600 dark:from-slate-400 opacity-10' /><div className='absolute rotate-[96deg] top-[22.26rem] xl:top-[23.5rem] -left-60 ml-[-0.5px] h-96 w-[2px] rounded-full bg-gradient-to-t from-emerald-600 dark:from-emerald-700 opacity-50' />@@ -210,7 +210,7 @@ const Main: React.FC<IMain> = ({ ssrTheme, ssrAuthenticated }): JSX.Element => {}}/></div>- <Header ssrTheme={ssrTheme} authenticated={authenticated} />+ <Header ssrTheme={ssrTheme} authenticated={authenticated} transparent /><div className='flex justify-center items-center py-2 px-2'><ahref='https://bank.gov.ua/en/news/all/natsionalniy-bank-vidkriv-spetsrahunok-dlya-zboru-koshtiv-na-potrebi-armiyi'@@ -319,7 +319,7 @@ const Main: React.FC<IMain> = ({ ssrTheme, ssrAuthenticated }): JSX.Element => {{/* end first block with live demo */}{/* section Core Analytics Features */}<div className='dark:bg-slate-900 bg-white px-4 pb-24'>- <section className='flex pt-16 md:pt-48 flex-col-reverse md:flex-row items-center md:items-start md:justify-between max-w-7xl m-auto'>+ <section id='core-analytics' className='flex pt-16 md:pt-48 flex-col-reverse md:flex-row items-center md:items-start md:justify-between max-w-7xl m-auto'><picture><source srcSet={theme === 'dark' ? '/assets/CoreFeaturesDark.webp' : '/assets/CoreFeaturesLight.webp'} type='image/webp' /><img src={theme === 'dark' ? '/assets/CoreFeaturesDark.png' : '/assets/CoreFeaturesLight.png'} className='md:max-w-md md:mr-3 mt-3 mb-3 md:mt-0 lg:max-w-full md:relative md:-top-10' alt='Core Analytics Features' />diff --git a/app/pages/ReferralPage/index.tsx b/app/pages/ReferralPage/index.tsxnew file mode 100644index 000000000..c617b43d7--- /dev/null+++ b/app/pages/ReferralPage/index.tsx@@ -0,0 +1,157 @@+import React from 'react'+import { Link, useParams } from '@remix-run/react'+import { useSelector } from 'react-redux'+import { useTranslation, Trans } from 'react-i18next'+import { ArrowSmallRightIcon } from '@heroicons/react/24/outline'++import { StateType } from 'redux/store/index'+import Header from 'components/Header'+import routes from 'routesPath'+import { Lines } from 'pages/MainPage'++import {+ isBrowser, REFERRAL_COOKIE_DAYS, REFERRAL_DISCOUNT,+} from 'redux/constants'++interface IReferralPage {+ ssrTheme: 'dark' | 'light'+}++const ReferralPage = ({ ssrTheme }: IReferralPage): JSX.Element => {+ const { t }: {+ t: (key: string, options?: {+ [key: string]: string | number,+ }) => string,+ } = useTranslation('common')+ const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)+ const theme = isBrowser ? reduxTheme : ssrTheme++ // Referral code+ const { id } = useParams()++ return (+ <div className='overflow-hidden'>+ <main className='bg-white dark:bg-slate-900 min-h-[100vh]'>+ <div className='relative overflow-x-clip isolate'>+ <svg+ className='absolute inset-0 -z-10 h-full w-full stroke-gray-200 dark:stroke-white/10 [mask-image:radial-gradient(100%_100%_at_top_right,white,transparent)]'+ aria-hidden='true'+ >+ <defs>+ <pattern+ id='rect-pattern'+ width={200}+ height={200}+ x='50%'+ y={-1}+ patternUnits='userSpaceOnUse'+ >+ <path d='M.5 200V.5H200' fill='none' />+ </pattern>+ </defs>+ <svg x='50%' y={-1} className='overflow-visible fill-white dark:fill-gray-800/20'>+ <path+ d='M-200 0h201v201h-201Z M600 0h201v201h-201Z M-400 600h201v201h-201Z M200 800h201v201h-201Z'+ strokeWidth={0}+ />+ </svg>+ <rect width='100%' height='100%' strokeWidth={0} fill='url(#rect-pattern)' />+ </svg>+ <div+ className='absolute left-[calc(50%-4rem)] top-10 -z-10 transform-gpu blur-3xl sm:left-[calc(50%-18rem)] lg:left-48 lg:top-[calc(50%-30rem)] xl:left-[calc(50%-24rem)]'+ aria-hidden='true'+ >+ <div+ className='aspect-[1108/632] w-[69.25rem] bg-gradient-to-r from-[#80caff] to-[#4f46e5] opacity-20'+ style={{+ clipPath:+ 'polygon(73.6% 51.7%, 91.7% 11.8%, 100% 46.4%, 97.4% 82.2%, 92.5% 84.9%, 75.7% 64%, 55.3% 47.5%, 46.5% 49.4%, 45% 62.9%, 50.3% 87.2%, 21.3% 64.1%, 0.1% 100%, 5.4% 51.1%, 21.4% 63.9%, 58.9% 0.2%, 73.6% 51.7%)',+ }}+ />+ </div>+ <Header ssrTheme={ssrTheme} authenticated={false} refPage transparent />+ <div+ className='relative pt-10 lg:pt-24 pb-5 xl:px-8 lg:px-6 sm:px-3 mx-auto min-h-[740px]'+ >+ <div className='relative z-20 flex flex-row content-between 2xl:mr-[14vw] 2xl:justify-center justify-center lg:justify-start'>+ <div className='lg:mt-0 text-left relative lg:mr-14 px-4'>+ <h1 className='max-w-2xl text-2xl sm:text-4xl md:text-5xl font-extrabold text-slate-900 dark:text-white sm:leading-none xl:leading-[110%]'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='main.slogan'+ components={{+ span: <span className='from-indigo-700 to-indigo-700 dark:from-indigo-600 dark:to-indigo-400 text-transparent bg-clip-text bg-gradient-to-r' />,+ }}+ />+ </h1>+ <p className='text-base text-slate-700 dark:text-slate-300 sm:text-xl lg:text-lg xl:text-lg mt-5'>+ {t('referral.desc')}+ </p>+ <h2 className='text-xl sm:text-xl md:text-xl font-medium text-slate-900 dark:text-white sm:leading-none xl:leading-[110%] mt-10'>+ {t('referral.buttons', {+ discount: REFERRAL_DISCOUNT,+ })}+ </h2>+ <div className='mt-4 flex flex-col items-center sm:flex-row'>+ <Link+ to={`/ref/${id}${routes.signup}`}+ className='rounded-md !duration-300 transition-all w-full sm:max-w-[210px] h-12 flex items-center justify-center sm:mr-6 shadow-sm ring-1 text-white bg-slate-900 ring-slate-900 hover:bg-slate-700 dark:bg-indigo-700 dark:ring-indigo-700 dark:hover:bg-indigo-600'+ aria-label={t('titles.signup')}+ >+ <span className='text-base font-semibold mr-1'>+ {t('common.getStarted')}+ </span>+ <ArrowSmallRightIcon className='h-4 w-5 mt-[1px]' />+ </Link>+ <Link+ to={`/ref/${id}/index#core-analytics`}+ className='rounded-md !duration-300 transition-all sm:mt-0 mt-2 ring-1 ring-slate-900 dark:ring-white/20 w-full sm:max-w-[210px] h-12 flex items-center justify-center shadow-sm text-slate-900 dark:text-white bg-transparent hover:bg-slate-200 dark:hover:bg-gray-800'+ aria-label={t('titles.signup')}+ >+ <span className='text-base font-semibold'>+ {t('common.learnMore')}+ </span>+ </Link>+ </div>+ <p className='text-base tracking-tighter font-medium text-slate-500 dark:text-slate-500 mt-5'>+ {t('referral.cookieDetails', {+ days: REFERRAL_COOKIE_DAYS,+ discount: REFERRAL_DISCOUNT,+ })}+ </p>+ </div>+ <div className='max-w-md xl:max-w-lg hidden lg:block'>+ <Lines />+ <picture>+ <source srcSet={theme === 'dark' ? '/assets/screenshot_dark.webp' : '/assets/screenshot_light.webp'} type='image/webp' />+ <img+ src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}+ className='h-full min-w-[880px] rounded-xl relative shadow-2xl ring-1 ring-gray-900/10 dark:ring-white/10'+ width='100%'+ height='auto'+ alt='Swetrix Analytics dashboard'+ />+ </picture>+ </div>+ </div>+ <div className='my-10 block lg:hidden relative z-20 px-4 md:px-0'>+ <picture>+ <source srcSet={theme === 'dark' ? '/assets/screenshot_dark.webp' : '/assets/screenshot_light.webp'} type='image/webp' />+ <img+ src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}+ className='rounded-xl relative shadow-2xl w-full ring-1 ring-gray-900/10 dark:ring-white/10'+ width='100%'+ height='auto'+ alt='Swetrix Analytics dashboard'+ />+ </picture>+ </div>+ </div>+ </div>+ </main>+ </div>+ )+}++export default ReferralPagediff --git a/app/pages/UserSettings/UserSettings.container.tsx b/app/pages/UserSettings/UserSettings.container.tsxindex 2519ebcd4..0327b4566 100644--- a/app/pages/UserSettings/UserSettings.container.tsx+++ b/app/pages/UserSettings/UserSettings.container.tsx@@ -19,6 +19,8 @@ const mapStateToProps = (state: StateType) => {isPaidTierUsed: state.auth.isPaidTierUsed,theme: state.ui.theme.theme,loading: state.auth.loading,+ activeReferrals: state.ui.cache.activeReferrals,+ referralStatistics: state.ui.cache.referralStatistics,}}@@ -67,6 +69,12 @@ const mapDispatchToProps = (dispatch: AppDispatch) => ({}),)},+ setCache: (key: string, value: any) => {+ dispatch(UIActions.setCache({+ key,+ value,+ }))+ },sharedProjectError: (message: string) => {dispatch(errorsActions.sharedProjectFailed({diff --git a/app/pages/UserSettings/UserSettings.tsx b/app/pages/UserSettings/UserSettings.tsxindex 9bcce1015..60a8d3526 100644--- a/app/pages/UserSettings/UserSettings.tsx+++ b/app/pages/UserSettings/UserSettings.tsx@@ -1,6 +1,6 @@/* eslint-disable no-param-reassign, react/forbid-prop-types */import React, {- useState, useEffect, memo, useRef,+ useState, useEffect, memo, useRef, useMemo,} from 'react'import { useNavigate } from '@remix-run/react'import { ClientOnly } from 'remix-utils'@@ -11,6 +11,7 @@ import _isNull from 'lodash/isNull'import _findIndex from 'lodash/findIndex'import _map from 'lodash/map'import _keys from 'lodash/keys'+import _find from 'lodash/find'import {EnvelopeIcon,ExclamationTriangleIcon,@@ -18,6 +19,10 @@ import {CurrencyDollarIcon,ClipboardDocumentIcon,ChevronDownIcon,+ UserIcon,+ ChatBubbleLeftEllipsisIcon,+ ComputerDesktopIcon,+ CursorArrowRaysIcon,} from '@heroicons/react/24/outline'import PropTypes from 'prop-types'import dayjs from 'dayjs'@@ -66,12 +71,43 @@ import ProjectList from './components/ProjectList'import TwoFA from './components/TwoFA'import Integrations from './components/Integrations'import Socialisations from './components/Socialisations'+import Referral from './components/Referral'import NoSharedProjects from './components/NoSharedProjects'dayjs.extend(utc)const timeFormatArray = _map(TimeFormat, (key) => key)+const TAB_MAPPING = {+ ACCOUNT: 'account',+ REFERRALS: 'referrals',+ INTERFACE: 'interface',+ COMMUNICATIONS: 'communications',+}++const getTabs = (t: (key: string) => string) => ([+ {+ id: TAB_MAPPING.ACCOUNT,+ label: t('profileSettings.account'),+ icon: UserIcon,+ },+ {+ id: TAB_MAPPING.COMMUNICATIONS,+ label: 'Communications',+ icon: ChatBubbleLeftEllipsisIcon,+ },+ {+ id: TAB_MAPPING.INTERFACE,+ label: 'Interface settings',+ icon: ComputerDesktopIcon,+ },+ {+ id: TAB_MAPPING.REFERRALS,+ label: t('profileSettings.referral.title'),+ icon: CursorArrowRaysIcon,+ },+])+interface IProps {onDelete: (t: (key: string) => string, deletionFeedback: string, callback: () => void) => void,onDeleteProjectCache: () => void,@@ -98,6 +134,9 @@ interface IProps {logoutLocal: () => void,logoutAll: () => void,loading: boolean,+ setCache: (key: string, value: any) => void,+ activeReferrals: any[],+ referralStatistics: any,}interface IForm extends Partial<IUser> {@@ -112,6 +151,7 @@ const UserSettings = ({genericError, onGDPRExportFailed, updateProfileFailed, updateUserProfileAsync,accountUpdated, setAPIKey, user, dontRemember, isPaidTierUsed, // setThemeType, themeType,linkSSO, unlinkSSO, theme, updateShowLiveVisitorsInTitle, logoutAll, loading, logoutLocal,+ referralStatistics, activeReferrals, setCache,}: IProps): JSX.Element => {const navigate = useNavigate()const {@@ -124,7 +164,7 @@ const UserSettings = ({}) => string;} = useTranslation('common')-+ const [activeTab, setActiveTab] = useState<string>(TAB_MAPPING.ACCOUNT)const [form, setForm] = useState<IForm>({email: user.email || '',password: '',@@ -159,6 +199,9 @@ const UserSettings = ({const copyTimerRef = useRef(null)+ const tabs = getTabs(t)+ const activeTabLabel = useMemo(() => _find(tabs, tab => tab.id === activeTab)?.label, [tabs, activeTab])+const validate = () => {const allErrors = {} as {[key: string]: string;@@ -477,9 +520,59 @@ const UserSettings = ({<h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{t('titles.profileSettings')}</h2>- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.general')}- </h3>+ {/* Tabs selector */}+ <div className='mt-2'>+ <div className='sm:hidden'>+ <Select+ items={tabs}+ keyExtractor={(item) => item.id}+ labelExtractor={(item) => item.label}+ onSelect={(label) => {+ const selected = _find(tabs, (tab) => tab.label === label)+ if (selected) {+ setActiveTab(selected?.id)+ }+ }}+ title={activeTabLabel}+ />+ </div>+ <div className='hidden sm:block'>+ <div>+ <nav className='-mb-px flex space-x-4' aria-label='Tabs'>+ {_map(tabs, tab => {+ const isCurrent = tab.id === activeTab++ const onClick = () => {+ setActiveTab(tab.id)+ }++ return (+ <div+ key={tab.id}+ onClick={onClick}+ className={cx('group inline-flex items-center whitespace-nowrap py-2 px-1 border-b-2 font-bold text-md cursor-pointer', {+ 'border-slate-900 text-slate-900 dark:text-gray-50 dark:border-gray-50': isCurrent,+ 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:border-gray-300 dark:hover:text-gray-300': !isCurrent,+ })}+ aria-current={isCurrent ? 'page' : undefined}+ >+ <tab.icon+ className={cx(+ isCurrent ? 'text-slate-900 dark:text-gray-50' : 'text-gray-500 group-hover:text-gray-500 dark:text-gray-400 dark:group-hover:text-gray-300',+ '-ml-0.5 mr-2 h-5 w-5',+ )}+ aria-hidden='true'+ />+ <span>+ {tab.label}+ </span>+ </div>+ )+ })}+ </nav>+ </div>+ </div>+ </div><ClientOnlyfallback={(<Loader />@@ -490,67 +583,71 @@ const UserSettings = ({return <Loader />}- return (- <>- <Input- name='email'- id='email'- type='email'- label={t('auth.common.email')}- value={form.email}- placeholder='[email protected]'- className='mt-4'- onChange={handleInput}- error={beenSubmitted ? errors.email : null}- disabled={isSelfhosted}- />- {!isSelfhosted && (- <>- <span- onClick={toggleShowPasswordFields}- className='flex items-center cursor-pointer max-w-max text-gray-900 dark:text-gray-50 hover:underline'- >- {t('auth.common.changePassword')}- <ChevronDownIcon- className={cx('w-4 h-4 ml-2', {- 'rotate-180': showPasswordFields,- })}- />- </span>- {showPasswordFields && (- <div className='grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6 mt-4'>- <Input- name='password'- id='password'- type='password'- label={t('auth.common.password')}- hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}- value={form.password}- placeholder={t('auth.common.password')}- className='sm:col-span-3'- onChange={handleInput}- error={beenSubmitted ? errors.password : null}- />- <Input- name='repeat'- id='repeat'- type='password'- label={t('auth.common.repeat')}- value={form.repeat}- placeholder={t('auth.common.repeat')}- className='sm:col-span-3'- onChange={handleInput}- error={beenSubmitted ? errors.repeat : null}+ if (activeTab === TAB_MAPPING.ACCOUNT) {+ return (+ <>+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.general')}+ </h3>+ <Input+ name='email'+ id='email'+ type='email'+ label={t('auth.common.email')}+ value={form.email}+ placeholder='[email protected]'+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted ? errors.email : null}+ disabled={isSelfhosted}+ />+ {!isSelfhosted && (+ <>+ <span+ onClick={toggleShowPasswordFields}+ className='flex items-center cursor-pointer max-w-max text-gray-900 dark:text-gray-50 hover:underline'+ >+ {t('auth.common.changePassword')}+ <ChevronDownIcon+ className={cx('w-4 h-4 ml-2', {+ 'rotate-180': showPasswordFields,+ })}/>- </div>- )}- <Button className='mt-4' type='submit' primary large>- {t('profileSettings.update')}- </Button>- </>- )}- {/* Theme type switch */}- {/* <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ </span>+ {showPasswordFields && (+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6 mt-4'>+ <Input+ name='password'+ id='password'+ type='password'+ label={t('auth.common.password')}+ hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}+ value={form.password}+ placeholder={t('auth.common.password')}+ className='sm:col-span-3'+ onChange={handleInput}+ error={beenSubmitted ? errors.password : null}+ />+ <Input+ name='repeat'+ id='repeat'+ type='password'+ label={t('auth.common.repeat')}+ value={form.repeat}+ placeholder={t('auth.common.repeat')}+ className='sm:col-span-3'+ onChange={handleInput}+ error={beenSubmitted ? errors.repeat : null}+ />+ </div>+ )}+ <Button className='mt-4' type='submit' primary large>+ {t('profileSettings.update')}+ </Button>+ </>+ )}+ {/* Theme type switch */}+ {/* <hr className='mt-5 border-gray-200 dark:border-gray-600' /><h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>{t('profileSettings.theme')}</h3>@@ -565,299 +662,333 @@ const UserSettings = ({/></div></div> */}- {/* Timezone selector */}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50 flex items-center'>- {t('profileSettings.timezone')}- <div className='ml-5'>- <Beta />- </div>- </h3>- <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>- <div>- <TimezonePicker value={timezone} onChange={_setTimezone} />- </div>- </div>- <Button className='mt-4' onClick={handleTimezoneSave} primary large>- {t('common.save')}- </Button>- {/* Timeformat selector (12 / 24 hour format) */}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.timeFormat')}- </h3>- <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>- <div>- <Select- title={t(`profileSettings.${form.timeFormat}`)}- label={t('profileSettings.selectTimeFormat')}- className='w-full'- items={translatedTimeFormat}- onSelect={(f) => setForm((prev) => ({- ...prev,- timeFormat:- timeFormatArray[- _findIndex(translatedTimeFormat, (freq) => freq === f)- ],- }))}- />- </div>- </div>- <Button className='mt-4' onClick={setAsyncTimeFormat} primary large>- {t('common.save')}- </Button>-- {!isSelfhosted && (- <>- {/* Email reports frequency selector (e.g. monthly, weekly, etc.) */}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.email')}- </h3>- <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>- <div>- <Select- title={t(`profileSettings.${reportFrequency}`)}- label={t('profileSettings.frequency')}- className='w-full'- items={translatedFrequencies}- iconExtractor={reportIconExtractor}- onSelect={(f) => _setReportFrequency(- reportFrequencies[_findIndex(translatedFrequencies, (freq) => freq === f)],- )}- />- </div>- </div>- <Button className='mt-4' onClick={handleReportSave} primary large>- {t('common.save')}- </Button>- </>- )}-- {/* UI Settings */}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.uiSettings')}- </h3>- <Checkbox- checked={user.showLiveVisitorsInTitle}- onChange={handleShowLiveVisitorsSave}- disabled={settingUpdating}- name='active'- id='active'- className='mt-4'- label={t('profileSettings.showVisitorsInTitle')}- />-- {!isSelfhosted && (- <>- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- {/* Integrations setup */}- <h3 id='integrations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.integrations')}- </h3>- <Integrations- user={user}- updateUserData={updateUserData}- handleIntegrationSave={handleIntegrationSave}- genericError={genericError}- />- {user.isTelegramChatIdConfirmed && (- <Checkbox- checked={user.receiveLoginNotifications}- onChange={handleReceiveLoginNotifications}- disabled={settingUpdating}- name='receiveLoginNotifications'- id='receiveLoginNotifications'- className='mt-4'- label={t('profileSettings.receiveLoginNotifications')}- />- )}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />-- {/* API access setup */}- <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.apiKey')}- <div className='ml-5'>- <Beta />- </div>- </h3>- {user.apiKey ? (- <>- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('profileSettings.apiKeyWarning')}- </p>- <p className='mt-4 max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('profileSettings.apiKey')}- </p>- <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2'>- <div className='relative group'>- <Input- name='apiKey'- id='apiKey'- type='text'- className='pr-9'- value={user.apiKey}- onChange={handleInput}- disabled- />- <div className='absolute right-2 top-3'>- <div className='group relative'>- <Button- type='button'- onClick={() => setToClipboard(user.apiKey || '')}- className='opacity-70 hover:opacity-100'- noBorder- >- <>- <ClipboardDocumentIcon className='w-6 h-6' />- {copied && (- <div className='animate-appear bg-white dark:bg-slate-800 cursor-auto rounded p-1 absolute sm:top-0 top-0.5 right-8 text-xs text-green-600'>- {t('common.copied')}- </div>- )}- </>- </Button>+ {!isSelfhosted && (+ <>+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />++ {/* API access setup */}+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.apiKey')}+ <div className='ml-5'>+ <Beta />+ </div>+ </h3>+ {user.apiKey ? (+ <>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.apiKeyWarning')}+ </p>+ <p className='mt-4 max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.apiKey')}+ </p>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2'>+ <div className='relative group'>+ <Input+ name='apiKey'+ id='apiKey'+ type='text'+ className='pr-9'+ value={user.apiKey}+ onChange={handleInput}+ disabled+ />+ <div className='absolute right-2 top-3'>+ <div className='group relative'>+ <Button+ type='button'+ onClick={() => setToClipboard(user.apiKey || '')}+ className='opacity-70 hover:opacity-100'+ noBorder+ >+ <>+ <ClipboardDocumentIcon className='w-6 h-6' />+ {copied && (+ <div className='animate-appear bg-white dark:bg-slate-800 cursor-auto rounded p-1 absolute sm:top-0 top-0.5 right-8 text-xs text-green-600'>+ {t('common.copied')}+ </div>+ )}+ </>+ </Button>+ </div></div></div></div>- </div>- </>- ) : (- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>- {t('profileSettings.noApiKey')}- </p>- )}- {user.apiKey ? (- <Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>- {t('profileSettings.deleteApiKeyBtn')}- </Button>- ) : (- <Button className='mt-4' onClick={onApiKeyGenerate} primary large>- {t('profileSettings.addApiKeyBtn')}- </Button>- )}-- {/* 2FA setting */}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.2fa')}- </h3>- <TwoFA- user={user}- dontRemember={dontRemember}- updateUserData={updateUserData}- genericError={genericError}- />+ </>+ ) : (+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.noApiKey')}+ </p>+ )}+ {user.apiKey ? (+ <Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>+ {t('profileSettings.deleteApiKeyBtn')}+ </Button>+ ) : (+ <Button className='mt-4' onClick={onApiKeyGenerate} primary large>+ {t('profileSettings.addApiKeyBtn')}+ </Button>+ )}- {/* Socialisations setup */}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- <h3 id='socialisations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.socialisations')}- </h3>- <Socialisations- user={user}- genericError={genericError}- linkSSO={linkSSO}- unlinkSSO={unlinkSSO}- theme={theme}- />+ {/* 2FA setting */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.2fa')}+ </h3>+ <TwoFA+ user={user}+ dontRemember={dontRemember}+ updateUserData={updateUserData}+ genericError={genericError}+ />- {/* Shared projects setting */}- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>- {t('profileSettings.shared')}- </h3>- <div>- {!_isEmpty(user.sharedProjects) ? (- <div className='mt-3 flex flex-col'>- <div className='-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8'>- <div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>- <div className='overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg'>- <table className='min-w-full divide-y divide-gray-300 dark:divide-gray-600'>- <thead>- <tr className='dark:bg-slate-800'>- <th- scope='col'- className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 dark:text-white'- >- {t('profileSettings.sharedTable.project')}- </th>- <th- scope='col'- className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-white'- >- {t('profileSettings.sharedTable.role')}- </th>- <th- scope='col'- className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-white'- >- {t('profileSettings.sharedTable.joinedOn')}- </th>- <th scope='col' className='relative py-3.5 pl-3 pr-4 sm:pr-6' />- </tr>- </thead>- <tbody className='divide-y divide-gray-300 dark:divide-gray-600'>- {_map(user.sharedProjects, (item) => (- <ProjectList- key={item.id}- item={item}- removeProject={removeProject}- removeShareProject={removeShareProject}- setUserShareData={setUserShareData}- setProjectsShareData={setProjectsShareData}- userSharedUpdate={userSharedUpdate}- sharedProjectError={sharedProjectError}- />- ))}- </tbody>- </table>+ {/* Socialisations setup */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 id='socialisations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.socialisations')}+ </h3>+ <Socialisations+ user={user}+ genericError={genericError}+ linkSSO={linkSSO}+ unlinkSSO={unlinkSSO}+ theme={theme}+ />++ {/* Shared projects setting */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.shared')}+ </h3>+ <div>+ {!_isEmpty(user.sharedProjects) ? (+ <div className='mt-3 flex flex-col'>+ <div className='-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8'>+ <div className='inline-block min-w-full py-2 align-middle md:px-6 lg:px-8'>+ <div className='overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg'>+ <table className='min-w-full divide-y divide-gray-300 dark:divide-gray-600'>+ <thead>+ <tr className='dark:bg-slate-800'>+ <th+ scope='col'+ className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 dark:text-white'+ >+ {t('profileSettings.sharedTable.project')}+ </th>+ <th+ scope='col'+ className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-white'+ >+ {t('profileSettings.sharedTable.role')}+ </th>+ <th+ scope='col'+ className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-white'+ >+ {t('profileSettings.sharedTable.joinedOn')}+ </th>+ <th scope='col' className='relative py-3.5 pl-3 pr-4 sm:pr-6' />+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-300 dark:divide-gray-600'>+ {_map(user.sharedProjects, (item) => (+ <ProjectList+ key={item.id}+ item={item}+ removeProject={removeProject}+ removeShareProject={removeShareProject}+ setUserShareData={setUserShareData}+ setProjectsShareData={setProjectsShareData}+ userSharedUpdate={userSharedUpdate}+ sharedProjectError={sharedProjectError}+ />+ ))}+ </tbody>+ </table>+ </div></div></div></div>+ ) : (+ <NoSharedProjects t={t} />+ )}+ </div>+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ {!user.isActive && (+ <div+ className='flex cursor-pointer mt-4 pl-0 underline text-blue-600 hover:text-indigo-800 dark:hover:text-indigo-600'+ onClick={() => onEmailConfirm(setError)}+ >+ <EnvelopeIcon className='mt-0.5 mr-2 w-6 h-6 text-blue-500' />+ {t('profileSettings.noLink')}</div>- ) : (- <NoSharedProjects t={t} />)}- </div>- <hr className='mt-5 border-gray-200 dark:border-gray-600' />- {!user.isActive && (- <div- className='flex cursor-pointer mt-4 pl-0 underline text-blue-600 hover:text-indigo-800 dark:hover:text-indigo-600'- onClick={() => onEmailConfirm(setError)}- >- <EnvelopeIcon className='mt-0.5 mr-2 w-6 h-6 text-blue-500' />- {t('profileSettings.noLink')}- </div>- )}- <div className='flex flex-wrap justify-center sm:justify-between gap-2 mt-4'>- <Button onClick={() => setShowExportModal(true)} semiSmall primary>- <>- <ArrowDownTrayIcon className='w-5 h-5 mr-1' />- {t('profileSettings.requestExport')}- </>- </Button>- <div className='flex justify-center flex-wrap gap-2'>- <Button onClick={logoutAll} semiSmall semiDanger>- <>- {/* We need this div for the button to match the height of the button after it */}- <div className='h-5' />- {t('profileSettings.logoutAll')}- </>- </Button>- <Button onClick={() => setShowModal(true)} semiSmall danger>+ <div className='flex flex-wrap justify-center sm:justify-between gap-2 mt-4'>+ <Button onClick={() => setShowExportModal(true)} semiSmall primary><>- <ExclamationTriangleIcon className='w-5 h-5 mr-1' />- {t('profileSettings.delete')}+ <ArrowDownTrayIcon className='w-5 h-5 mr-1' />+ {t('profileSettings.requestExport')}</></Button>+ <div className='flex justify-center flex-wrap gap-2'>+ <Button onClick={logoutAll} semiSmall semiDanger>+ <>+ {/* We need this div for the button to match the height of the button after it */}+ <div className='h-5' />+ {t('profileSettings.logoutAll')}+ </>+ </Button>+ <Button onClick={() => setShowModal(true)} semiSmall danger>+ <>+ <ExclamationTriangleIcon className='w-5 h-5 mr-1' />+ {t('profileSettings.delete')}+ </>+ </Button>+ </div></div>+ </>+ )}+ </>+ )+ }++ if (activeTab === TAB_MAPPING.INTERFACE) {+ return (+ <>+ {/* Timezone selector */}+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50 flex items-center'>+ {t('profileSettings.timezone')}+ <div className='ml-5'>+ <Beta />+ </div>+ </h3>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>+ <div>+ <TimezonePicker value={timezone} onChange={_setTimezone} />+ </div>+ </div>+ <Button className='mt-4' onClick={handleTimezoneSave} primary large>+ {t('common.save')}+ </Button>+ {/* Timeformat selector (12 / 24 hour format) */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.timeFormat')}+ </h3>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>+ <div>+ <Select+ title={t(`profileSettings.${form.timeFormat}`)}+ label={t('profileSettings.selectTimeFormat')}+ className='w-full'+ items={translatedTimeFormat}+ onSelect={(f) => setForm((prev) => ({+ ...prev,+ timeFormat:+ timeFormatArray[+ _findIndex(translatedTimeFormat, (freq) => freq === f)+ ],+ }))}+ /></div>- </>- )}- </>- )+ </div>+ <Button className='mt-4' onClick={setAsyncTimeFormat} primary large>+ {t('common.save')}+ </Button>++ {/* UI Settings */}+ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.uiSettings')}+ </h3>+ <Checkbox+ checked={user.showLiveVisitorsInTitle}+ onChange={handleShowLiveVisitorsSave}+ disabled={settingUpdating}+ name='active'+ id='active'+ className='mt-4'+ label={t('profileSettings.showVisitorsInTitle')}+ />+ </>+ )+ }++ if (activeTab === TAB_MAPPING.COMMUNICATIONS) {+ return (+ <>++ {!isSelfhosted && (+ <>+ {/* Email reports frequency selector (e.g. monthly, weekly, etc.) */}+ <h3 className='mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.email')}+ </h3>+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2 mt-4'>+ <div>+ <Select+ title={t(`profileSettings.${reportFrequency}`)}+ label={t('profileSettings.frequency')}+ className='w-full'+ items={translatedFrequencies}+ iconExtractor={reportIconExtractor}+ onSelect={(f) => _setReportFrequency(+ reportFrequencies[_findIndex(translatedFrequencies, (freq) => freq === f)],+ )}+ />+ </div>+ </div>+ <Button className='mt-4' onClick={handleReportSave} primary large>+ {t('common.save')}+ </Button>++ <hr className='mt-5 border-gray-200 dark:border-gray-600' />+ {/* Integrations setup */}+ <h3 id='integrations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.integrations')}+ </h3>+ <Integrations+ user={user}+ updateUserData={updateUserData}+ handleIntegrationSave={handleIntegrationSave}+ genericError={genericError}+ />+ {user.isTelegramChatIdConfirmed && (+ <Checkbox+ checked={user.receiveLoginNotifications}+ onChange={handleReceiveLoginNotifications}+ disabled={settingUpdating}+ name='receiveLoginNotifications'+ id='receiveLoginNotifications'+ className='mt-4'+ label={t('profileSettings.receiveLoginNotifications')}+ />+ )}+ </>+ )}+ </>+ )+ }++ if (activeTab === TAB_MAPPING.REFERRALS) {+ return (+ <>+ <h3 id='socialisations' className='flex items-center mt-2 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.title')}+ </h3>+ <Referral+ user={user}+ genericError={genericError}+ updateUserData={updateUserData}+ referralStatistics={referralStatistics}+ activeReferrals={activeReferrals}+ setCache={setCache}+ accountUpdated={accountUpdated}+ />+ </>+ )+ }++ return null}}</ClientOnly></form>@@ -980,6 +1111,9 @@ UserSettings.propTypes = {theme: PropTypes.string.isRequired,logoutLocal: PropTypes.func.isRequired,logoutAll: PropTypes.func.isRequired,+ referralStatistics: PropTypes.object.isRequired,+ activeReferrals: PropTypes.array.isRequired,+ setCache: PropTypes.func.isRequired,}export default memo(withAuthentication(UserSettings, auth.authenticated))diff --git a/app/pages/UserSettings/components/Referral.tsx b/app/pages/UserSettings/components/Referral.tsxnew file mode 100644index 000000000..cbc35ac23--- /dev/null+++ b/app/pages/UserSettings/components/Referral.tsx@@ -0,0 +1,352 @@+import React, {+ memo, useState, useRef, useEffect,+} from 'react'+import { useTranslation, Trans } from 'react-i18next'+import { ClipboardDocumentIcon } from '@heroicons/react/24/outline'+import dayjs from 'dayjs'+import _isEmpty from 'lodash/isEmpty'+import _map from 'lodash/map'++import {+ generateRefCode, getPayoutsInfo, getReferrals, setPaypalEmail,+} from 'api'+import Tooltip from 'ui/Tooltip'+import Highlighted from 'ui/Highlighted'+import Input from 'ui/Input'+import Button from 'ui/Button'+import { IUser } from 'redux/models/IUser'+import {+ REF_URL_PREFIX, DOCS_REFERRAL_PROGRAM_URL, REFERRAL_PENDING_PAYOUT_DAYS, calculateReferralCut,+ PLAN_LIMITS, CURRENCIES, BillingFrequency, MERCHANT_FEE, REFERRAL_CUT,+} from 'redux/constants'+import { isValidEmail } from 'utils/validator'++interface IReferral {+ user: IUser,+ genericError: (message: string) => void,+ updateUserData: (data: Partial<IUser>) => void,+ setCache: (key: string, value: any) => void,+ activeReferrals: any[],+ referralStatistics: any,+ accountUpdated: (t: string) => void,+}++const Referral = ({+ user, genericError, updateUserData, referralStatistics, activeReferrals, setCache, accountUpdated,+}: IReferral) => {+ const { t, i18n: { language } } = useTranslation('common')+ const [copied, setCopied] = useState(false)+ const [refCodeGenerating, setRefCodeGenerating] = useState(false)+ const [referralStatsRequested, setReferralStatsRequested] = useState(false)+ const [activeReferralsRequested, setActiveReferralsRequested] = useState(false)+ const [paypalInputError, setPaypalInputError] = useState<string | null>(null)+ const [isPaypalEmailLoading, setIsPaypalEmailLoading] = useState<boolean>(false)+ const [paypalEmailAddress, setPaypalEmailAddress] = useState<string | null>(user.paypalPaymentsEmail)+ const copyTimerRef = useRef(null)++ const refUrl = `${REF_URL_PREFIX}${user?.refCode}`++ useEffect(() => {+ return () => {+ // @ts-ignore+ clearTimeout(copyTimerRef.current)+ }+ }, [])++ useEffect(() => {+ const getRefStats = async () => {+ try {+ const info = await getPayoutsInfo()+ setCache('referralStatistics', info)+ } catch (reason) {+ console.error('[Referral][getRefStats] Something went wrong whilst requesting payouts information', reason)+ genericError(t('apiNotifications.payoutInfoError'))+ }+ }++ const getActiveReferrals = async () => {+ try {+ const info = await getReferrals()+ setCache('activeReferrals', info)+ } catch (reason) {+ console.error('[Referral][getActiveReferrals] Something went wrong whilst requesting active referrals', reason)+ genericError(t('apiNotifications.payoutInfoError'))+ }+ }++ if (!referralStatsRequested && _isEmpty(referralStatistics)) {+ setReferralStatsRequested(true)+ getRefStats()+ }++ if (!activeReferralsRequested && _isEmpty(activeReferrals)) {+ setActiveReferralsRequested(true)+ getActiveReferrals()+ }+ }, [referralStatistics, referralStatsRequested, setCache, genericError, activeReferralsRequested, activeReferrals, t])++ const onRefCodeGenerate = async () => {+ if (refCodeGenerating || user.refCode) {+ return+ }++ setRefCodeGenerating(true)++ try {+ const { refCode } = await generateRefCode()+ updateUserData({+ refCode,+ })+ } catch (e) {+ genericError(t('apiNotifications.somethingWentWrong'))+ } finally {+ setRefCodeGenerating(false)+ }+ }++ const handlePaypalInput = (e: React.ChangeEvent<HTMLInputElement>) => {+ setPaypalInputError(null)+ setPaypalEmailAddress(e.target.value)+ }++ const updatePaypalEmail = async () => {+ if (paypalEmailAddress) {+ const isValid = isValidEmail(paypalEmailAddress)++ if (!isValid) {+ setPaypalInputError(t('auth.common.badEmailError'))+ return+ }+ }++ setIsPaypalEmailLoading(true)++ try {+ await setPaypalEmail(paypalEmailAddress)+ updateUserData({+ paypalPaymentsEmail: paypalEmailAddress,+ })+ accountUpdated(t('profileSettings.referral.payoutEmailUpdated'))+ } catch (reason) {+ console.error('[Referral][updatePaypalEmail] Something went wrong whilst updating paypal email', reason)+ genericError(t('apiNotifications.somethingWentWrong'))+ }++ setIsPaypalEmailLoading(false)+ }++ const setToClipboard = (value: string) => {+ if (!copied) {+ navigator.clipboard.writeText(value)+ setCopied(true)+ // @ts-ignore+ copyTimerRef.current = setTimeout(() => {+ setCopied(false)+ }, 2000)+ }+ }++ return (+ <>+ <p className='text-base text-gray-900 dark:text-gray-50'>+ <Trans+ // @ts-ignore+ t={t}+ i18nKey='profileSettings.referral.desc'+ components={{+ url: <a+ href={DOCS_REFERRAL_PROGRAM_URL}+ className='font-medium hover:underline text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-500'+ target='_blank'+ rel='noreferrer noopener'+ />,+ }}+ />+ </p>+ <h3 className='flex items-center mt-5 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.payoutEmail')}+ </h3>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.payoutEmailDesc')}+ </p>+ <div className='flex space-x-2 mt-2'>+ <Input+ id='paypal-email'+ type='email'+ value={paypalEmailAddress || ''}+ placeholder='[email protected]'+ onChange={handlePaypalInput}+ error={paypalInputError}+ />+ <Button+ type='button'+ className='h-9'+ loading={isPaypalEmailLoading}+ onClick={updatePaypalEmail}+ primary+ large+ >+ {t('common.save')}+ </Button>+ </div>+ <h3 className='flex items-center mt-5 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.referralLink')}+ </h3>+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.referralLinkDesc')}+ </p>+ {user.refCode && (+ <p className='mt-2 max-w-prose text-base text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.yourReferralLink')}+ </p>+ )}+ {user.refCode ? (+ <div className='grid grid-cols-1 gap-y-6 gap-x-4 lg:grid-cols-2'>+ <div className='relative group'>+ <Input+ name='refCode'+ id='refCode'+ type='text'+ className='pr-9'+ value={refUrl}+ disabled+ />+ <div className='absolute right-2 top-3'>+ <div className='group relative'>+ <Button+ type='button'+ onClick={() => setToClipboard(refUrl)}+ className='opacity-70 hover:opacity-100'+ noBorder+ >+ <>+ <ClipboardDocumentIcon className='w-6 h-6' />+ {copied && (+ <div className='animate-appear bg-white dark:bg-slate-800 cursor-auto rounded p-1 absolute sm:top-0 top-0.5 right-8 text-xs text-green-600'>+ {t('common.copied')}+ </div>+ )}+ </>+ </Button>+ </div>+ </div>+ </div>+ </div>+ ) : (+ <Button+ className='mt-2'+ onClick={onRefCodeGenerate}+ loading={refCodeGenerating}+ primary+ large+ >+ {t('profileSettings.referral.generateRefLink')}+ </Button>+ )}+ {!_isEmpty(referralStatistics) && (+ <>+ <h3 className='flex items-center mt-5 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.referralStats')}+ </h3>+ <div>+ <Tooltip+ text={t('profileSettings.referral.trialDesc')}+ tooltipNode={(+ <span className='text-gray-900 dark:text-gray-50'>{t('profileSettings.referral.trial')}: <Highlighted>{referralStatistics.trials}</Highlighted></span>+ )}+ className='max-w-max !w-auto !h-auto'+ />+ <Tooltip+ text={t('profileSettings.referral.activeDesc')}+ tooltipNode={(+ <span className='text-gray-900 dark:text-gray-50'>{t('profileSettings.referral.active')}: <Highlighted>{referralStatistics.subscribers}</Highlighted></span>+ )}+ className='max-w-max !w-auto !h-auto'+ />+ <Tooltip+ text={t('profileSettings.referral.paidDesc')}+ tooltipNode={(+ <span className='text-gray-900 dark:text-gray-50'>{t('profileSettings.referral.paid')}: <Highlighted>US$ {referralStatistics.paid}</Highlighted></span>+ )}+ className='max-w-max !w-auto !h-auto'+ />+ <Tooltip+ text={t('profileSettings.referral.nextPayoutDesc')}+ tooltipNode={(+ <span className='text-gray-900 dark:text-gray-50'>{t('profileSettings.referral.nextPayout')}: <Highlighted>US$ {referralStatistics.nextPayout}</Highlighted></span>+ )}+ className='max-w-max !w-auto !h-auto'+ />+ <Tooltip+ text={t('profileSettings.referral.pendingDesc', {+ days: REFERRAL_PENDING_PAYOUT_DAYS,+ })}+ tooltipNode={(+ <span className='text-gray-900 dark:text-gray-50'>{t('profileSettings.referral.pending')}: <Highlighted>US$ {referralStatistics.pending}</Highlighted></span>+ )}+ className='max-w-max !w-auto !h-auto'+ />+ </div>+ </>+ )}+ {!_isEmpty(activeReferrals) && (+ <>+ <h3 className='flex items-center mt-5 text-lg font-bold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.activeReferrals')}+ </h3>+ <table className='mt-2 min-w-full shadow ring-1 ring-black ring-opacity-5 md:rounded-lg divide-y divide-gray-300 200 dark:divide-gray-500'>+ <thead className='bg-gray-50 dark:bg-slate-800'>+ <tr>+ <th scope='col' className='py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.activeReferralsTable.plan')}+ </th>+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ <Tooltip+ text={t('profileSettings.referral.activeReferralsTable.yourCutDesc', {+ fee: MERCHANT_FEE,+ amount: REFERRAL_CUT * 100,+ })}+ tooltipNode={<>{t('profileSettings.referral.activeReferralsTable.yourCut')}</>}+ className='max-w-max !w-auto !h-auto'+ />+ </th>+ <th scope='col' className='px-3 py-3.5 text-left text-sm font-semibold text-gray-900 dark:text-gray-50'>+ {t('profileSettings.referral.activeReferralsTable.registrationDate')}+ </th>+ </tr>+ </thead>+ <tbody className='divide-y divide-gray-200 dark:divide-gray-600 bg-white dark:bg-slate-800'>+ {_map(activeReferrals, ({+ billingFrequency, created, planCode, tierCurrency,+ }, index) => {+ // @ts-ignore+ const planPrice = PLAN_LIMITS[planCode].price[tierCurrency][billingFrequency]+ const referrerCut = calculateReferralCut(planPrice)+ const currencySymbol = CURRENCIES[tierCurrency as 'EUR' | 'USD' | 'GBP'].symbol+ const tBillingFrequency = t(billingFrequency === BillingFrequency.monthly ? 'pricing.perMonth' : 'pricing.perYear')++ return (+ <tr key={index}>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50 sm:pl-6'>+ {currencySymbol}{planPrice}/{tBillingFrequency}+ </td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>+ {currencySymbol}{referrerCut}/{tBillingFrequency}+ </td>+ <td className='whitespace-nowrap px-3 py-4 text-sm text-gray-900 dark:text-gray-50'>+ {language === 'en'+ ? dayjs(created).locale(language).format('MMMM D, YYYY')+ : dayjs(created).locale(language).format('D MMMM, YYYY')}+ </td>+ </tr>+ )+ })}+ </tbody>+ </table>+ </>+ )}+ </>+ )+}++export default memo(Referral)diff --git a/app/redux/constants/index.ts b/app/redux/constants/index.tsindex b435101f0..658690aac 100644--- a/app/redux/constants/index.ts+++ b/app/redux/constants/index.ts@@ -218,18 +218,28 @@ export const TWITTER_USERNAME: string = '@swetrix'export const DISCORD_URL: string = 'https://discord.gg/ZVK8Tw2E8j'export const STATUSPAGE_URL: string = 'https://stats.uptimerobot.com/33rvmiXXEz'export const MAIN_URL: string = 'https://swetrix.com'+export const REF_URL_PREFIX: string = `${MAIN_URL}/ref/`export const UTM_GENERATOR_URL: string = 'https://url.swetrix.com'export const LIVE_DEMO_URL: string = '/projects/STEzHcB1rALV'export const MARKETPLACE_URL: string = 'https://marketplace.swetrix.com'export const DOCS_URL: string = 'https://docs.swetrix.com'export const CAPTCHA_URL: string = 'https://captcha.swetrix.com'export const DOCS_CAPTCHA_URL: string = `${DOCS_URL}/captcha/introduction`+export const DOCS_REFERRAL_PROGRAM_URL: string = `${DOCS_URL}/affiliate/about`// Swetrix vs ...export const SWETRIX_VS_GOOGLE: string = 'https://blog.swetrix.com/post/vs-google-analytics/'export const SWETRIX_VS_CLOUDFLARE: string = 'https://blog.swetrix.com/post/vs-cloudflare-analytics/'export const SWETRIX_VS_SIMPLE_ANALYTICS: string = 'https://blog.swetrix.com/post/vs-simple-analytics/'+// Referral program+export const REFERRAL_COOKIE = 'affiliate'+export const REFERRAL_COOKIE_DAYS = 30+export const REFERRAL_DISCOUNT = 20+export const REFERRAL_PENDING_PAYOUT_DAYS = 30+export const REFERRAL_CUT = 0.2+export const REFERRAL_DISCOUNT_CODE = 'REFERRAL_DISCOUNT'+export const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'export type ThemeType = 'dark' | 'light'@@ -437,6 +447,25 @@ export const CURRENCIES: ICurrencies = {EUR, USD, GBP,}+export const MERCHANT_FEE = '5% + 50¢'++// Paddle fee is 5% + 50¢+const calculatePriceAfterFees = (price: number): number => {+ const fee = 0.05 * price + 0.5+ return price - fee+}++export const calculateReferralCut = (originalTierPrice: number): number => {+ const priceAfterFees = calculatePriceAfterFees(originalTierPrice)+ const referralCut = REFERRAL_CUT * priceAfterFees+ return referralCut+}++export const BillingFrequency = {+ monthly: 'monthly',+ yearly: 'yearly',+}+// TODO: Eventually this should be fetched from the API, e.g. GET /config routeexport const PLAN_LIMITS = {free: {diff --git a/app/redux/models/IUser.ts b/app/redux/models/IUser.tsindex b64d09c5e..3f5dcb0ad 100644--- a/app/redux/models/IUser.ts+++ b/app/redux/models/IUser.ts@@ -37,4 +37,7 @@ export interface IUser {tierCurrency: 'USD' | 'EUR' | 'GBP' | nullshowLiveVisitorsInTitle: booleanreceiveLoginNotifications: boolean+ refCode: string | null+ referrerID: string | null+ paypalPaymentsEmail: string | null}diff --git a/app/redux/reducers/ui/cache.ts b/app/redux/reducers/ui/cache.tsindex a95834217..0057722eb 100644--- a/app/redux/reducers/ui/cache.ts+++ b/app/redux/reducers/ui/cache.ts@@ -44,6 +44,8 @@ interface IInitialState {userFlowDescending: {[key: string]: IUserFlow}+ activeReferrals: any[]+ referralStatistics: any}const initialState: IInitialState = {@@ -55,6 +57,8 @@ const initialState: IInitialState = {customEventsPrefs: {},userFlowAscending: {},userFlowDescending: {},+ activeReferrals: [],+ referralStatistics: {},}const cacheSlice = createSlice({@@ -220,6 +224,12 @@ const cacheSlice = createSlice({[key]: payload.data,}},+ setCache(state, { payload }: PayloadAction<{ key: string, value: any }>) {+ const { key, value } = payload++ // @ts-ignore+ state[key] = value+ },},})diff --git a/app/redux/sagas/auth/workers/signup.ts b/app/redux/sagas/auth/workers/signup.tsindex bb7166d20..bc79a1385 100644--- a/app/redux/sagas/auth/workers/signup.ts+++ b/app/redux/sagas/auth/workers/signup.ts@@ -1,10 +1,11 @@import { call, put } from 'redux-saga/effects'import { authActions } from 'redux/reducers/auth'import { errorsActions } from 'redux/reducers/errors'-import _omit from 'lodash/omit'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')@@ -15,17 +16,27 @@ export default function* signupWorder({ payload: { data: rawData, callback } }:password: stringrepeat: stringdontRemember: boolean+ checkIfLeaked: boolean},callback: (isSuccess: boolean) => void}}) {try {- const { repeat, ...data } = rawData- const { dontRemember } = data+ const { dontRemember } = rawData+ const refCode = getCookie(REFERRAL_COOKIE)const {user, accessToken, refreshToken, // theme,// @ts-ignore- } = yield call(signup, _omit(data, ['dontRemember']))+ } = yield call(signup, {+ email: rawData.email,+ password: rawData.password,+ checkIfLeaked: rawData.checkIfLeaked,+ refCode,+ })++ if (refCode) {+ deleteCookie(REFERRAL_COOKIE)+ }yield put(authActions.signupUpSuccessful(user))yield call(setAccessToken, accessToken, dontRemember)diff --git a/app/redux/sagas/auth/workers/sso_auth.ts b/app/redux/sagas/auth/workers/sso_auth.tsindex d0a2ed9cd..aafc8d18c 100644--- a/app/redux/sagas/auth/workers/sso_auth.ts+++ b/app/redux/sagas/auth/workers/sso_auth.ts@@ -5,6 +5,8 @@ import { errorsActions } from 'redux/reducers/errors'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,@@ -50,15 +52,21 @@ export default function* ssoAuth({// Closing the authorisation window after the session expiressetTimeout(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)+ } = yield call(getJWTBySSOHash, uuid, provider, refCode)authWindow.close()+ if (refCode) {+ deleteCookie(REFERRAL_COOKIE)+ }+yield put(authActions.setDontRemember(dontRemember))if (user.isTwoFactorAuthenticationEnabled) {diff --git a/app/routes/ref.$id.$page.tsx b/app/routes/ref.$id.$page.tsxnew file mode 100644index 000000000..96ce409c3--- /dev/null+++ b/app/routes/ref.$id.$page.tsx@@ -0,0 +1,27 @@+import type { LoaderArgs } from '@remix-run/node'+import { redirect } from '@remix-run/node'++import {+ isSelfhosted, REFERRAL_COOKIE, REFERRAL_COOKIE_DAYS,+} from 'redux/constants'+import { generateCookieString } from 'utils/cookie'++// This route sets the affiliate cookie ($id) and redirects to page specified at $page+export async function loader({ params }: LoaderArgs) {+ if (isSelfhosted) {+ return redirect('/login', 302)+ }++ const { id, page } = params++ const init = {+ status: 302,+ headers: {+ 'Set-Cookie': generateCookieString(REFERRAL_COOKIE, id as string, REFERRAL_COOKIE_DAYS * 24 * 60 * 60),+ },+ }++ const redirectPath = page === 'index' ? '/#core-analytics' : `/${page}`++ return redirect(redirectPath, init)+}diff --git a/app/routes/ref.$id.tsx b/app/routes/ref.$id.tsxnew file mode 100644index 000000000..e23125490--- /dev/null+++ b/app/routes/ref.$id.tsx@@ -0,0 +1,25 @@+import type { LoaderArgs } from '@remix-run/node'+import { useLoaderData } from '@remix-run/react'+import { json, redirect } from '@remix-run/node'+import ReferralPage from 'pages/ReferralPage'++import { isSelfhosted } from 'redux/constants'+import { detectTheme } from 'utils/server'++export async function loader({ request }: LoaderArgs) {+ if (isSelfhosted) {+ return redirect('/login', 302)+ }++ const [theme] = detectTheme(request)++ return json({ theme })+}++export default function Index() {+ const {+ theme,+ } = useLoaderData<typeof loader>()++ return <ReferralPage ssrTheme={theme} />+}diff --git a/app/routesPath/index.ts b/app/routesPath/index.tsindex 93642e6fa..9857fb5a9 100644--- a/app/routesPath/index.ts+++ b/app/routesPath/index.ts@@ -32,6 +32,7 @@ const routes = Object.freeze({socialised: '/socialised',project_protected_password: '/projects/:id/password',open: '/open',+ ref: '/ref/:id',})export default routesdiff --git a/app/ui/Button.tsx b/app/ui/Button.tsxindex db8252090..e4716e484 100644--- a/app/ui/Button.tsx+++ b/app/ui/Button.tsx@@ -40,7 +40,7 @@ const Button = ({giant, type, className, loading, semiSmall, semiDanger, noBorder, focus, disabled,}: IButton): JSX.Element => (<button- disabled={disabled}+ disabled={disabled || loading}type={type}onClick={onClick}className={cx('relative inline-flex select-none items-center border leading-4 font-medium rounded-md', {diff --git a/app/ui/Highlighted.tsx b/app/ui/Highlighted.tsxnew file mode 100644index 000000000..7887d2d15--- /dev/null+++ b/app/ui/Highlighted.tsx@@ -0,0 +1,13 @@+import React from 'react'++interface IHighlighted {+ children: React.ReactNode,+}++const Highlighted = ({ children }: IHighlighted) => (+ <span className='px-1 bg-slate-200 text-gray-900 rounded dark:text-gray-50 dark:bg-slate-700'>+ {children}+ </span>+)++export default Highlighteddiff --git a/app/ui/Input.tsx b/app/ui/Input.tsxindex 0f8fe68dc..4580e4f7f 100644--- a/app/ui/Input.tsx+++ b/app/ui/Input.tsx@@ -43,7 +43,11 @@ const Input = ({)}</label></div>- <div className='mt-1 relative'>+ <div+ className={cx('relative', {+ 'mt-1': label && hint,+ })}+ ><inputtype={type}value={value}@@ -65,7 +69,14 @@ const Input = ({</div>)}</div>- <p className='mt-2 text-sm text-gray-500 dark:text-gray-300 whitespace-pre-line' id={`${identifier}-optional`}>{hint}</p>+ {hint && (+ <p+ className='mt-2 text-sm text-gray-500 dark:text-gray-300 whitespace-pre-line'+ id={`${identifier}-optional`}+ >+ {hint}+ </p>+ )}{isError && (<p className='mt-2 text-sm text-red-600 dark:text-red-500' id='email-error'>{error}</p>)}diff --git a/package.json b/package.jsonindex 9ff06aec2..2c9fffc08 100644--- a/package.json+++ b/package.json@@ -112,6 +112,7 @@"lodash/prefer-lodash-method": "warn","import/newline-after-import": "off","@typescript-eslint/consistent-type-imports": "off",+ "jsx-a11y/anchor-has-content": "off","consistent-return": "off","max-len": "off","no-console": "off",diff --git a/public/locales/en.json b/public/locales/en.jsonindex ef23fe832..cfe6d7a03 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -16,6 +16,7 @@"userRemoved": "The user has been removed from your project","userRemoveError": "Error occurred while removing the user from your project","quitProjectError": "Error occurred while quitting the project",+ "payoutInfoError": "Something went wrong whilst requesting payouts information","quitProject": "You have quit the project","acceptInvitationError": "Error occurred while accepting the project invitation","acceptInvitation": "The project invitation has been accepted",@@ -261,6 +262,11 @@"2fa": "Two-factor authentication"}},+ "referral": {+ "desc": "Swetrix is an ethical, open-source and fully cookieless Google Analytics alternative. It allows you to understand your users behaviour, monitor your website performance, track your marketing campaigns and much more. All of that without invading your users' privacy!",+ "cookieDetails": "If you click on the buttons above, a cookie will be stored for {{days}} days to reward the person who referred you and give you {{discount}}% off your first bill.",+ "buttons": "Click on these buttons to receive {{discount}}% off your first bill!"+ },"auth": {"recovery": {"title": "Account recovery",@@ -378,6 +384,7 @@},"profileSettings": {"logoutAll": "Log out from all devices",+ "account": "Account","general": "General settings","update": "Update profile","email": "Email reports",@@ -467,6 +474,35 @@"passwordChangeWarningModal": {"title": "You're about to change your password","body": "You're about to change your password, this will log you out from all devices (including this one) and you will need to log in again with your new password."+ },+ "referral": {+ "title": "Referral program",+ "desc": "Referral program allows you to earn money by inviting new users to Swetrix.\nYou will receive a part of the subscription fee paid by the invited user and will be able to withdraw it to your PayPal account. Learn more about the referral program at <url>Swetrix Referral Program</url> documentation page.",+ "referralLink": "Referral link",+ "payoutEmail": "Referral payout email address",+ "payoutEmailDesc": "We will send your referral payouts via PayPal to this email address each month. Double check that it is correct.",+ "payoutEmailUpdated": "Payout email address has been updated",+ "yourReferralLink": "Your referral link",+ "referralLinkDesc": "This is your referral link, you can share it with your friends and earn money for each user that signs up and buys a paid plan using it.",+ "generateRefLink": "Generate referral link",+ "referralStats": "Referral statistics",+ "activeReferrals": "Active referrals",+ "trial": "Trial referrals",+ "trialDesc": "Trial users referred by you",+ "active": "Active referrals",+ "activeDesc": "Paid subsribers referred by you",+ "paid": "Paid",+ "paidDesc": "Total amount paid to you",+ "nextPayout": "Next payout",+ "nextPayoutDesc": "How much you will get paid next time",+ "pending": "Pending",+ "pendingDesc": "Amount of money pending to be paid to you. It takes {{days}} days for the funds to become available.",+ "activeReferralsTable": {+ "plan": "Referral tier",+ "yourCut": "Your cut",+ "yourCutDesc": "You will receive {{amount}}% of the subscription fee paid by the user after all fees. Currently our merchant provider charges us {{fee}} per transaction.",+ "registrationDate": "Registration date"+ }}},"alertsSettings": {