Skip to content

📈 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!

Implement the initial uptime monitoring UI structure

Blue Moused0abe436edd2
diff --git a/app/api/index.ts b/app/api/index.ts
index c2a533dd7..949d63521 100644
--- a/app/api/index.ts
+++ b/app/api/index.ts
@@ -984,6 +984,15 @@ export const deleteAlert = (id: string) =>
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
+export const deleteMonitor = (pid: string, id: string) =>
+ api
+ .delete(`project/${pid}/monitor/${id}`)
+ .then((response) => response.data)
+ .catch((error) => {
+ debug('%s', error)
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
export const reGenerateCaptchaSecretKey = (pid: string) =>
api
.post(`project/secret-gen/${pid}`)
diff --git a/app/pages/Project/Alerts/View/ProjectAlertsView.tsx b/app/pages/Project/Alerts/View/ProjectAlertsView.tsx
index adb7fe96b..9facec9e1 100644
--- a/app/pages/Project/Alerts/View/ProjectAlertsView.tsx
+++ b/app/pages/Project/Alerts/View/ProjectAlertsView.tsx
@@ -189,7 +189,6 @@ const ProjectAlerts = ({ projectId }: IProjectAlerts): JSX.Element => {
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState<boolean>(false)
const navigate = useNavigate()
- // @ts-ignore
const limits = PLAN_LIMITS[user?.planCode] || PLAN_LIMITS.trial
const isLimitReached = authenticated && total >= limits?.maxAlerts
diff --git a/app/pages/Project/View/ViewProject.tsx b/app/pages/Project/View/ViewProject.tsx
index e358ccef8..aa7ffcc5c 100644
--- a/app/pages/Project/View/ViewProject.tsx
+++ b/app/pages/Project/View/ViewProject.tsx
@@ -21,6 +21,7 @@ import {
BookmarkIcon,
TrashIcon,
PencilIcon,
+ ClockIcon,
} from '@heroicons/react/24/outline'
import cx from 'clsx'
import dayjs from 'dayjs'
@@ -182,6 +183,7 @@ import CountryDropdown from './components/CountryDropdown'
import MetricCards, { MetricCard } from './components/MetricCards'
import PerformanceMetricCards from './components/PerformanceMetricCards'
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'
@@ -578,7 +580,7 @@ const ViewProject = ({
try {
const funnels = await getFunnels(id, projectPassword)
- await updateProject(id, {
+ updateProject(id, {
funnels,
})
} catch (reason: any) {
@@ -942,7 +944,6 @@ const ViewProject = ({
[t],
)
- // tabs is a tabs for project
const tabs: {
id: string
label: string
@@ -997,6 +998,11 @@ const ViewProject = ({
label: t('dashboard.alerts'),
icon: BellIcon,
},
+ {
+ id: PROJECT_TABS.uptime,
+ label: t('dashboard.uptime'),
+ icon: ClockIcon,
+ },
...adminTabs,
]
@@ -3695,6 +3701,7 @@ const ViewProject = ({
{/* Tabs selector */}
<TabsSelector />
{activeTab !== PROJECT_TABS.alerts &&
+ activeTab !== PROJECT_TABS.uptime &&
(activeTab !== PROJECT_TABS.sessions || !activePSID) &&
(activeFunnel || activeTab !== PROJECT_TABS.funnels) && (
<>
@@ -3870,45 +3877,43 @@ const ViewProject = ({
headless
/>
)}
- {activeTab !== PROJECT_TABS.funnels &&
- activeTab !== PROJECT_TABS.sessions &&
- activeTab !== PROJECT_TABS.errors && (
- <Dropdown
- header={t('project.exportData')}
- items={_filter(
- [
- ...exportTypes,
- ...customExportTypes,
- !isSelfhosted && {
- label: t('project.lookingForMore'),
- lookingForMore: true,
- onClick: () => {},
- },
- ],
- (el) => !!el,
- )}
- title={[<ArrowDownTrayIcon key='download-icon' className='h-5 w-5 stroke-2' />]}
- labelExtractor={(item) => item.label}
- keyExtractor={(item) => item.label}
- onSelect={(item, e) => {
- if (item.lookingForMore) {
- e?.stopPropagation()
- window.open(MARKETPLACE_URL, '_blank')
+ {_includes([PROJECT_TABS.traffic, PROJECT_TABS.performance], activeTab) && (
+ <Dropdown
+ header={t('project.exportData')}
+ items={_filter(
+ [
+ ...exportTypes,
+ ...customExportTypes,
+ !isSelfhosted && {
+ label: t('project.lookingForMore'),
+ lookingForMore: true,
+ onClick: () => {},
+ },
+ ],
+ (el) => !!el,
+ )}
+ title={[<ArrowDownTrayIcon key='download-icon' className='h-5 w-5 stroke-2' />]}
+ labelExtractor={(item) => item.label}
+ keyExtractor={(item) => item.label}
+ onSelect={(item, e) => {
+ if (item.lookingForMore) {
+ e?.stopPropagation()
+ window.open(MARKETPLACE_URL, '_blank')
- return
- }
+ return
+ }
- trackCustom('DASHBOARD_EXPORT', {
- type: item.label === t('project.asCSV') ? 'csv' : 'extension',
- })
+ trackCustom('DASHBOARD_EXPORT', {
+ type: item.label === t('project.asCSV') ? 'csv' : 'extension',
+ })
- item.onClick(panelsData, t)
- }}
- chevron='mini'
- buttonClassName='!p-2 rounded-md hover:bg-white hover:shadow-sm dark:hover:bg-slate-800 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200 focus:dark:border-gray-200'
- headless
- />
- )}
+ item.onClick(panelsData, t)
+ }}
+ chevron='mini'
+ buttonClassName='!p-2 rounded-md hover:bg-white hover:shadow-sm dark:hover:bg-slate-800 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 focus:dark:ring-gray-200 focus:dark:border-gray-200'
+ headless
+ />
+ )}
<div
className={cx(
'space-x-2 border-gray-200 dark:border-gray-600 sm:mr-3 lg:border-x lg:px-3',
@@ -4676,6 +4681,9 @@ const ViewProject = ({
{activeTab === PROJECT_TABS.alerts && !isSharedProject && project?.isOwner && authenticated && (
<ProjectAlertsView projectId={id} />
)}
+ {activeTab === PROJECT_TABS.uptime && !isSharedProject && project?.isOwner && authenticated && (
+ <Uptime projectId={id} />
+ )}
{analyticsLoading && (activeTab === PROJECT_TABS.traffic || activeTab === PROJECT_TABS.performance) && (
<Loader />
)}
diff --git a/app/pages/Project/uptime/Settings.tsx b/app/pages/Project/uptime/Settings.tsx
new file mode 100644
index 000000000..2f2d4c0de
--- /dev/null
+++ b/app/pages/Project/uptime/Settings.tsx
@@ -0,0 +1,414 @@
+import React, { useEffect, useMemo, useState } from 'react'
+import { useNavigate, useParams, useLocation, Link } from '@remix-run/react'
+import { useTranslation, Trans } from 'react-i18next'
+import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'
+
+import _isEmpty from 'lodash/isEmpty'
+import _size from 'lodash/size'
+import _replace from 'lodash/replace'
+import _find from 'lodash/find'
+import _split from 'lodash/split'
+import _keys from 'lodash/keys'
+import _filter from 'lodash/filter'
+import _reduce from 'lodash/reduce'
+import _values from 'lodash/values'
+import _findKey from 'lodash/findKey'
+import _toNumber from 'lodash/toNumber'
+import { clsx as cx } from 'clsx'
+import Input from 'ui/Input'
+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 } 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 { useDispatch, useSelector } from 'react-redux'
+import { StateType } from 'redux/store'
+import { errorsActions } from 'redux/reducers/errors'
+import { alertsActions } from 'redux/reducers/alerts'
+import UIActions from 'redux/reducers/ui'
+
+const INTEGRATIONS_LINK = `${routes.user_settings}#integrations`
+
+const UptimeSettings = (): JSX.Element => {
+ const { alerts, total } = useSelector((state: StateType) => state.ui.alerts)
+ const { user, loading } = useSelector((state: StateType) => state.auth)
+
+ const dispatch = useDispatch()
+
+ const navigate = useNavigate()
+ const { id, pid } = useParams()
+ const { pathname } = useLocation()
+ const { t } = useTranslation('common')
+ const isSettings: boolean =
+ !_isEmpty(id) && _replace(_replace(routes.alert_settings, ':id', id as string), ':pid', pid as string) === pathname
+ const alert = useMemo(() => _find(alerts, { id }), [alerts, id])
+ const [form, setForm] = useState<Partial<IAlerts>>({
+ pid,
+ name: '',
+ queryTime: QUERY_TIME.LAST_1_HOUR,
+ queryCondition: QUERY_CONDITION.GREATER_THAN,
+ queryMetric: QUERY_METRIC.PAGE_VIEWS,
+ active: true,
+ queryCustomEvent: '',
+ })
+ const [validated, setValidated] = useState<boolean>(false)
+ const [errors, setErrors] = useState<{
+ [key: string]: string
+ }>({})
+ const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)
+ const [showModal, setShowModal] = useState<boolean>(false)
+
+ const showError = (message: string) => dispatch(errorsActions.genericError({ message }))
+ const generateAlerts = (message: string) => dispatch(alertsActions.generateAlerts({ message, type: 'success' }))
+ const setProjectAlerts = (alerts: IAlerts[]) => dispatch(UIActions.setProjectAlerts(alerts))
+ const setProjectAlertsTotal = (total: number) => dispatch(UIActions.setProjectAlertsTotal({ total }))
+
+ const isIntegrationLinked = useMemo(() => {
+ if (_isEmpty(user)) {
+ return false
+ }
+
+ return Boolean(
+ (user.telegramChatId && user.isTelegramChatIdConfirmed) || user.slackWebhookUrl || user.discordWebhookUrl,
+ )
+ }, [user])
+
+ const queryTimeTMapping: {
+ [key: string]: string
+ } = useMemo(() => {
+ const values = _values(QUERY_TIME)
+
+ return _reduce(
+ values,
+ (prev, curr) => {
+ const [, amount, metric] = _split(curr, '_')
+ let translated
+
+ if (metric === 'minutes') {
+ translated = t('alert.xMinutes', { amount })
+ }
+
+ if (metric === 'hour') {
+ translated = t('alert.xHour', { amount })
+ }
+
+ if (metric === 'hours') {
+ translated = t('alert.xHours', { amount })
+ }
+
+ return {
+ ...prev,
+ [curr]: translated,
+ }
+ },
+ {},
+ )
+ }, [t])
+
+ const queryConditionTMapping: {
+ [key: string]: string
+ } = useMemo(() => {
+ const values = _values(QUERY_CONDITION)
+
+ return _reduce(
+ values,
+ (prev, curr) => ({
+ ...prev,
+ [curr]: t(`alert.conditions.${curr}`),
+ }),
+ {},
+ )
+ }, [t])
+
+ const queryMetricTMapping: {
+ [key: string]: string
+ } = useMemo(() => {
+ const values = _values(QUERY_METRIC)
+
+ return _reduce(
+ values,
+ (prev, curr) => ({
+ ...prev,
+ [curr]: t(`alert.metrics.${curr}`),
+ }),
+ {},
+ )
+ }, [t])
+
+ useEffect(() => {
+ if (!_isEmpty(alert)) {
+ setForm(alert)
+ }
+ }, [alert])
+
+ const validate = () => {
+ const allErrors: {
+ [key: string]: string
+ } = {}
+
+ if (_isEmpty(form.name) || _size(form.name) < 3) {
+ allErrors.name = t('alert.noNameError')
+ }
+
+ if (form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && _isEmpty(form.queryCustomEvent)) {
+ allErrors.queryCustomEvent = t('alert.noCustomEventError')
+ }
+
+ if (Number.isNaN(_toNumber(form.queryValue))) {
+ allErrors.queryValue = t('alert.queryValueError')
+ }
+
+ const valid = _isEmpty(_keys(allErrors))
+
+ setErrors(allErrors)
+ setValidated(valid)
+ }
+
+ const onSubmit = (data: Partial<IAlerts>) => {
+ if (isSettings) {
+ updateAlert(id as string, data)
+ .then((res) => {
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ setProjectAlerts([..._filter(alerts, (a) => a.id !== id), res])
+ generateAlerts(t('alertsSettings.alertUpdated'))
+ })
+ .catch((err) => {
+ showError(err.message || err || 'Something went wrong')
+ })
+ } else {
+ createAlert(data as ICreateAlert)
+ .then((res) => {
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ setProjectAlerts([...alerts, res])
+ setProjectAlertsTotal(total + 1)
+ generateAlerts(t('alertsSettings.alertCreated'))
+ })
+ .catch((err) => {
+ showError(err.message || err || 'Something went wrong')
+ })
+ }
+ }
+
+ const onDelete = () => {
+ if (!id) {
+ showError('Something went wrong')
+ return
+ }
+
+ deleteAlert(id)
+ .then(() => {
+ setProjectAlerts(_filter(alerts, (a) => a.id !== id))
+ setProjectAlertsTotal(total - 1)
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ generateAlerts(t('alertsSettings.alertDeleted'))
+ })
+ .catch((err) => {
+ showError(err.message || err || 'Something went wrong')
+ })
+ }
+
+ const onCancel = () => {
+ navigate(`/projects/${pid}?tab=${PROJECT_TABS.alerts}`)
+ }
+
+ useEffect(() => {
+ validate()
+ }, [form]) // eslint-disable-line
+
+ const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const { target } = event
+
+ setForm((prevForm) => ({
+ ...prevForm,
+ [target.name]: target.value,
+ }))
+ }
+
+ const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+ setBeenSubmitted(true)
+
+ if (validated) {
+ onSubmit(form)
+ }
+ }
+
+ const title = isSettings
+ ? t('alert.settingsOf', {
+ name: form.name,
+ })
+ : t('alert.create')
+
+ return (
+ <div
+ className={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', {
+ 'pb-40': isSettings,
+ })}
+ >
+ <form className='mx-auto w-full max-w-7xl' onSubmit={handleSubmit}>
+ <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{title}</h2>
+ {!loading && !isIntegrationLinked && (
+ <div className='mt-2 flex items-center whitespace-pre-wrap rounded bg-blue-50 px-5 py-3 text-base dark:bg-slate-800 dark:text-gray-50'>
+ <ExclamationTriangleIcon className='mr-1 h-5 w-5' />
+ <Trans
+ t={t}
+ i18nKey='alert.noIntegration'
+ components={{
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
+ url: <Link to={INTEGRATIONS_LINK} className='text-blue-600 hover:underline dark:text-blue-500' />,
+ }}
+ />
+ </div>
+ )}
+ <Input
+ name='name'
+ label={t('alert.name')}
+ value={form.name || ''}
+ placeholder={t('alert.name')}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.name : null}
+ />
+ <Checkbox
+ checked={Boolean(form.active)}
+ onChange={(checked) =>
+ setForm((prev) => ({
+ ...prev,
+ active: checked,
+ }))
+ }
+ name='active'
+ className='mt-4'
+ label={t('alert.enabled')}
+ hint={t('alert.enabledHint')}
+ />
+ <div className='mt-4'>
+ <Select
+ id='queryMetric'
+ label={t('alert.metric')}
+ items={_values(queryMetricTMapping)}
+ title={form.queryMetric ? queryMetricTMapping[form.queryMetric] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryMetricTMapping, (predicate) => predicate === item)
+
+ setForm((prevForm) => ({
+ ...prevForm,
+ queryMetric: key,
+ }))
+ }}
+ capitalise
+ />
+ </div>
+ {form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && (
+ <Input
+ name='queryCustomEvent'
+ label={t('alert.customEvent')}
+ value={form.queryCustomEvent || ''}
+ placeholder={t('alert.customEvent')}
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.queryCustomEvent : null}
+ />
+ )}
+ <div className='mt-4'>
+ <Select
+ id='queryCondition'
+ label={t('alert.condition')}
+ items={_values(queryConditionTMapping)}
+ title={form.queryCondition ? queryConditionTMapping[form.queryCondition] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryConditionTMapping, (predicate) => predicate === item)
+
+ setForm((prevForm) => ({
+ ...prevForm,
+ queryCondition: key,
+ }))
+ }}
+ capitalise
+ />
+ </div>
+ <Input
+ name='queryValue'
+ label={t('alert.threshold')}
+ value={form.queryValue || ''}
+ placeholder='10'
+ className='mt-4'
+ onChange={handleInput}
+ error={beenSubmitted ? errors.queryValue : null}
+ />
+ <div className='mt-4'>
+ <Select
+ id='queryTime'
+ label={t('alert.time')}
+ items={_values(queryTimeTMapping)}
+ title={form.queryTime ? queryTimeTMapping[form.queryTime] : ''}
+ onSelect={(item) => {
+ const key = _findKey(queryTimeTMapping, (predicate) => predicate === item)
+
+ setForm((prevForm) => ({
+ ...prevForm,
+ queryTime: key,
+ }))
+ }}
+ capitalise
+ />
+ </div>
+ {isSettings ? (
+ <div className='mt-5 flex items-center justify-between'>
+ <Button onClick={() => setShowModal(true)} danger semiSmall>
+ <>
+ <ExclamationTriangleIcon className='mr-1 h-5 w-5' />
+ {t('alert.delete')}
+ </>
+ </Button>
+ <div className='flex items-center justify-between'>
+ <Button
+ className='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}
+ secondary
+ regular
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' primary regular>
+ {t('common.save')}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className='mt-5 flex items-center justify-between'>
+ <Button
+ className='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}
+ secondary
+ regular
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' primary regular>
+ {t('common.save')}
+ </Button>
+ </div>
+ )}
+ </form>
+ <Modal
+ onClose={() => setShowModal(false)}
+ onSubmit={onDelete}
+ submitText={t('alert.delete')}
+ closeText={t('common.close')}
+ title={t('alert.qDelete')}
+ message={t('alert.deleteHint')}
+ submitType='danger'
+ type='error'
+ isOpened={showModal}
+ />
+ </div>
+ )
+}
+
+export default withAuthentication(UptimeSettings, auth.authenticated)
diff --git a/app/pages/Project/uptime/View.tsx b/app/pages/Project/uptime/View.tsx
new file mode 100644
index 000000000..abee61dc3
--- /dev/null
+++ b/app/pages/Project/uptime/View.tsx
@@ -0,0 +1,223 @@
+import React, { useMemo, memo, useState } from 'react'
+import _map from 'lodash/map'
+import _isEmpty from 'lodash/isEmpty'
+import _replace from 'lodash/replace'
+import _filter from 'lodash/filter'
+import { useNavigate } from '@remix-run/react'
+import { useTranslation } from 'react-i18next'
+import { useDispatch, useSelector } from 'react-redux'
+import {
+ CurrencyDollarIcon,
+ AdjustmentsVerticalIcon,
+ TrashIcon,
+ PlusCircleIcon,
+ ClockIcon,
+} from '@heroicons/react/24/outline'
+
+import routes from 'utils/routes'
+import Button from 'ui/Button'
+import Modal from 'ui/Modal'
+import PaidFeature from 'modals/PaidFeature'
+import { PLAN_LIMITS } from 'redux/constants'
+import UIActions from 'redux/reducers/ui'
+import { alertsActions } from 'redux/reducers/alerts'
+import { errorsActions } from 'redux/reducers/errors'
+import { deleteMonitor as deleteMonitorApi } from 'api'
+import { StateType } from 'redux/store'
+import { Monitor } from 'redux/models/Uptime'
+
+// 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 {
+ monitor: Monitor
+ deleteMonitor: (id: string) => void
+ openMonitor: (id: string) => void
+}
+
+const MonitorCard = ({ monitor, openMonitor, deleteMonitor }: IMonitorCard): JSX.Element => {
+ const { t } = useTranslation()
+ const [showDeleteModal, setShowDeleteModal] = useState(false)
+
+ return (
+ <>
+ <li
+ onClick={() => openMonitor(monitor.id)}
+ className='min-h-[120px] cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 hover:bg-gray-100 dark:border-slate-800/25 dark:bg-[#162032] dark:hover:bg-slate-800'
+ >
+ <div className='px-4 py-4'>
+ <div className='flex justify-between'>
+ <div>
+ <p className='flex items-center gap-x-2 text-lg text-slate-900 dark:text-gray-50'>
+ <span className='font-semibold'>{monitor.name}</span>
+ {/* <Separator />
+ <span>{queryMetric}</span> */}
+ </p>
+ </div>
+ <div className='flex gap-2'>
+ <AdjustmentsVerticalIcon
+ role='button'
+ aria-label={t('common.settings')}
+ onClick={(e) => {
+ e.stopPropagation()
+ openMonitor(monitor.id)
+ }}
+ className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500'
+ />
+ <TrashIcon
+ onClick={(e) => {
+ e.stopPropagation()
+ setShowDeleteModal(true)
+ }}
+ role='button'
+ aria-label={t('common.delete')}
+ className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500'
+ />
+ </div>
+ </div>
+ </div>
+ </li>
+ <Modal
+ onClose={() => setShowDeleteModal(false)}
+ onSubmit={() => deleteMonitor(monitor.id)}
+ submitText={t('monitor.delete')}
+ closeText={t('common.close')}
+ title={t('monitor.qDelete')}
+ message={t('monitor.deleteHint')}
+ submitType='danger'
+ type='error'
+ isOpened={showDeleteModal}
+ />
+ </>
+ )
+}
+
+interface AddMonitorProps {
+ handleNewMonitor: () => void
+ isLimitReached: boolean
+}
+
+const AddMonitor = ({ handleNewMonitor, isLimitReached }: AddMonitorProps): JSX.Element => {
+ const { t } = useTranslation()
+
+ return (
+ <li
+ onClick={handleNewMonitor}
+ className='group flex h-auto min-h-[120px] cursor-pointer items-center justify-center rounded-lg border-2 border-dashed border-gray-300 hover:border-gray-400 dark:border-gray-500 dark:hover:border-gray-600'
+ >
+ <div>
+ {isLimitReached ? (
+ <CurrencyDollarIcon className='mx-auto h-12 w-12 text-gray-400 group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
+ ) : (
+ <PlusCircleIcon className='mx-auto h-12 w-12 text-gray-400 group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
+ )}
+ <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50 group-hover:dark:text-gray-400'>
+ {t('monitor.create')}
+ </span>
+ </div>
+ </li>
+ )
+}
+
+interface UptimeProps {
+ projectId: string
+}
+
+const Uptime = ({ projectId }: UptimeProps): JSX.Element => {
+ const { t } = 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<boolean>(false)
+ const navigate = useNavigate()
+
+ const limits = PLAN_LIMITS[user?.planCode] || PLAN_LIMITS.trial
+ const isLimitReached = authenticated && total >= limits?.maxMonitors
+
+ const projectMonitors = useMemo(() => {
+ if (loading) return []
+ return _filter(monitors, (monitor) => monitor.projectId === projectId)
+ }, [projectId, monitors, loading])
+
+ const handleNewMonitor = () => {
+ if (isLimitReached) {
+ setIsPaidFeatureOpened(true)
+ return
+ }
+
+ navigate(_replace(routes.create_uptime, ':pid', projectId))
+ }
+
+ 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,
+ }),
+ )
+ dispatch(
+ alertsActions.generateAlerts({
+ message: t('monitor.monitorDeleted'),
+ type: 'success',
+ }),
+ )
+ } catch (reason: any) {
+ dispatch(
+ errorsActions.genericError({
+ message: reason?.response?.data?.message || reason?.message || 'Something went wrong',
+ }),
+ )
+ }
+ }
+
+ return (
+ <div>
+ <div className='mt-4'>
+ {loading && <div>{t('common.loading')}</div>}
+ {!loading && _isEmpty(projectMonitors) && (
+ <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' />
+ <p className='text-3xl font-bold'>{t('dashboard.uptime')}</p>
+ </div>
+ <p className='mt-2 whitespace-pre-wrap text-lg text-gray-100'>{t('dashboard.uptimeDesc')}</p>
+ <Button
+ onClick={handleNewMonitor}
+ className='mt-6 rounded-md border border-transparent bg-white px-3 py-2 text-base font-medium text-gray-700 hover:bg-indigo-50 md:px-4'
+ secondary
+ large
+ >
+ <>
+ {isLimitReached && <CurrencyDollarIcon className='mr-1 h-5 w-5' />}
+ {t('monitor.create')}
+ </>
+ </Button>
+ </div>
+ )}
+ {!loading && !_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) => (
+ <MonitorCard
+ key={monitor.id}
+ monitor={monitor}
+ openMonitor={(id) => {
+ navigate(_replace(_replace(routes.uptime_settings, ':pid', projectId), ':id', id))
+ }}
+ deleteMonitor={onDelete}
+ />
+ ))}
+ <AddMonitor handleNewMonitor={handleNewMonitor} isLimitReached={isLimitReached} />
+ </ul>
+ )}
+ </div>
+ <PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} />
+ </div>
+ )
+}
+
+export default memo(Uptime) as typeof Uptime
diff --git a/app/redux/constants/index.ts b/app/redux/constants/index.ts
index c31f9bedd..aa4f11959 100644
--- a/app/redux/constants/index.ts
+++ b/app/redux/constants/index.ts
@@ -548,6 +548,7 @@ const PRODUCTION_PROJECT_TABS: IStringObject = {
sessions: 'sessions',
errors: 'errors',
alerts: 'alerts',
+ uptime: 'uptime',
}
export const PROJECT_TABS = isSelfhosted ? SELFHOSTED_PROJECT_TABS : PRODUCTION_PROJECT_TABS
@@ -659,6 +660,8 @@ export const PLAN_LIMITS = {
yearly: 0,
},
},
+ maxAlerts: 0,
+ maxMonitors: 0,
},
free: {
index: 0, // 'downgrade' or 'upgrade' logic depends on this
@@ -679,6 +682,8 @@ export const PLAN_LIMITS = {
yearly: 0,
},
},
+ maxAlerts: 1,
+ maxMonitors: 1,
},
trial: {
index: 0, // 'downgrade' or 'upgrade' logic depends on this
@@ -699,6 +704,8 @@ export const PLAN_LIMITS = {
yearly: 0,
},
},
+ maxAlerts: 50,
+ maxMonitors: 20,
},
hobby: {
index: 1, // 'downgrade' or 'upgrade' logic depends on this
@@ -721,6 +728,8 @@ export const PLAN_LIMITS = {
},
pid: 813694, // Plan ID
ypid: 813695, // Plan ID - Yearly billing
+ maxAlerts: 50,
+ maxMonitors: 20,
},
freelancer: {
index: 2, // 'downgrade' or 'upgrade' logic depends on this
@@ -743,6 +752,8 @@ export const PLAN_LIMITS = {
},
pid: 752316, // Plan ID
ypid: 776469, // Plan ID - Yearly billing
+ maxAlerts: 50,
+ maxMonitors: 20,
},
'200k': {
index: 3, // 'downgrade' or 'upgrade' logic depends on this
@@ -765,6 +776,8 @@ export const PLAN_LIMITS = {
},
pid: 854654, // Plan ID
ypid: 854655, // Plan ID - Yearly billing
+ maxAlerts: 50,
+ maxMonitors: 20,
},
'500k': {
index: 4, // 'downgrade' or 'upgrade' logic depends on this
@@ -787,6 +800,8 @@ export const PLAN_LIMITS = {
},
pid: 854656, // Plan ID
ypid: 854657, // Plan ID - Yearly billing
+ maxAlerts: 50,
+ maxMonitors: 20,
},
startup: {
index: 5, // 'downgrade' or 'upgrade' logic depends on this
@@ -809,6 +824,8 @@ export const PLAN_LIMITS = {
},
pid: 752317,
ypid: 776470,
+ maxAlerts: 50,
+ maxMonitors: 20,
},
'2m': {
index: 6, // 'downgrade' or 'upgrade' logic depends on this
@@ -831,6 +848,8 @@ export const PLAN_LIMITS = {
},
pid: 854663,
ypid: 854664,
+ maxAlerts: 50,
+ maxMonitors: 20,
},
enterprise: {
index: 7, // 'downgrade' or 'upgrade' logic depends on this
@@ -853,6 +872,8 @@ export const PLAN_LIMITS = {
},
pid: 752318,
ypid: 776471,
+ maxAlerts: 50,
+ maxMonitors: 20,
},
'10m': {
index: 8, // 'downgrade' or 'upgrade' logic depends on this
@@ -875,6 +896,8 @@ export const PLAN_LIMITS = {
},
pid: 854665,
ypid: 854666,
+ maxAlerts: 50,
+ maxMonitors: 20,
},
}
diff --git a/app/redux/models/IUser.ts b/app/redux/models/IUser.ts
index c62ae41b5..25d05c020 100644
--- a/app/redux/models/IUser.ts
+++ b/app/redux/models/IUser.ts
@@ -7,10 +7,24 @@ export enum DashboardBlockReason {
'subscription_cancelled' = 'subscription_cancelled',
}
+enum PlanCode {
+ none = 'none',
+ free = 'free',
+ trial = 'trial',
+ hobby = 'hobby',
+ freelancer = 'freelancer',
+ '200k' = '200k',
+ '500k' = '500k',
+ startup = 'startup',
+ '2m' = '2m',
+ enterprise = 'enterprise',
+ '10m' = '10m',
+}
+
export interface IUser {
id: string
roles: string[]
- planCode: string
+ planCode: PlanCode
nickname: string
email: string
isActive: boolean
diff --git a/app/redux/models/Uptime.ts b/app/redux/models/Uptime.ts
new file mode 100644
index 000000000..8cb5f7c70
--- /dev/null
+++ b/app/redux/models/Uptime.ts
@@ -0,0 +1,20 @@
+export interface Monitor {
+ id: string
+ type: string
+ name: string
+ url: string
+ interval: number
+ retries: number
+ retryInterval: number
+ timeout: number
+ acceptedStatusCodes: number[]
+ description: string | null
+ projectId: string
+ createdAt: Date
+ updatedAt: Date
+ httpOptions: {
+ method: string[]
+ body?: Record<string, unknown>
+ headers?: Record<string, string>
+ }
+}
diff --git a/app/redux/reducers/ui/index.ts b/app/redux/reducers/ui/index.ts
index e3ff264fd..864113fd8 100644
--- a/app/redux/reducers/ui/index.ts
+++ b/app/redux/reducers/ui/index.ts
@@ -3,6 +3,7 @@ import { cacheActions } from './cache'
import { miscActions } from './misc'
import { projectsActions } from './projects'
import { themeActions } from './theme'
+import { monitorActions } from './monitors'
const UIActions = {
...alertsActions,
@@ -10,6 +11,7 @@ const UIActions = {
...miscActions,
...projectsActions,
...themeActions,
+ ...monitorActions,
}
export default UIActions
diff --git a/app/redux/reducers/ui/monitors.ts b/app/redux/reducers/ui/monitors.ts
new file mode 100644
index 000000000..4cc66f043
--- /dev/null
+++ b/app/redux/reducers/ui/monitors.ts
@@ -0,0 +1,37 @@
+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.reducer
diff --git a/app/redux/store/index.ts b/app/redux/store/index.ts
index 2f436f181..91dbe9297 100644
--- a/app/redux/store/index.ts
+++ b/app/redux/store/index.ts
@@ -11,6 +11,7 @@ import projectsSlice from '../reducers/ui/projects'
import alertsProjectsSlice from '../reducers/ui/alerts'
import themeSlice from '../reducers/ui/theme'
import cacheSlice from '../reducers/ui/cache'
+import monitorsSlice from '../reducers/ui/monitors'
const rootReducer = combineReducers({
auth: authSlice,
@@ -22,6 +23,7 @@ const rootReducer = combineReducers({
alerts: alertsProjectsSlice,
theme: themeSlice,
cache: cacheSlice,
+ monitors: monitorsSlice,
}),
})
diff --git a/app/routes/projects.$pid.uptime.create.tsx b/app/routes/projects.$pid.uptime.create.tsx
new file mode 100644
index 000000000..00d48ac72
--- /dev/null
+++ b/app/routes/projects.$pid.uptime.create.tsx
@@ -0,0 +1,5 @@
+import UptimeSettings from 'pages/Project/uptime/Settings'
+
+export default function Settings() {
+ return <UptimeSettings />
+}
diff --git a/app/routes/projects.$pid.uptime.settings.$id.tsx b/app/routes/projects.$pid.uptime.settings.$id.tsx
new file mode 100644
index 000000000..952e17bdb
--- /dev/null
+++ b/app/routes/projects.$pid.uptime.settings.$id.tsx
@@ -0,0 +1,5 @@
+import ProjectAlertsSettings from 'pages/Project/Alerts/Settings'
+
+export default function Index() {
+ return <ProjectAlertsSettings />
+}
diff --git a/app/utils/routes.ts b/app/utils/routes.ts
index f915f8bf1..823bb68f0 100644
--- a/app/utils/routes.ts
+++ b/app/utils/routes.ts
@@ -28,6 +28,8 @@ const routes = Object.freeze({
about: '/about',
create_alert: '/projects/:pid/alerts/create',
alert_settings: '/projects/:pid/alerts/settings/:id',
+ create_uptime: '/projects/:pid/uptime/create',
+ uptime_settings: '/projects/:pid/uptime/settings/:id',
press: '/press',
transfer_confirm: '/project/transfer/confirm',
transfer_reject: '/project/transfer/cancel',
diff --git a/public/locales/en.json b/public/locales/en.json
index b99dae4d8..7eda0279f 100644
--- a/public/locales/en.json
+++ b/public/locales/en.json
@@ -661,6 +661,7 @@
"alertDeleted": "The alert has been deleted"
},
"dashboard": {
+ "uptime": "Uptime",
"newProject": "New project",
"newFunnel": "New funnel",
"reloadPage": "Reload page",
@@ -708,6 +709,7 @@
"alerts": "Alerts",
"alertsDesc": "Automated alerts is a powerful tool that allows you to run automated tasks when specific events occur.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram.",
"funnelsDesc": "Funnels is a powerful tool that allows you to track the conversion rate of your users through a series of steps.\nThe analysis provided by the marketing funnel gives you the ability to discover potential problems, improve your website, and boost your conversion rate.",
+ "uptimeDesc": "Swetrix uptime is a powerful tool that allows you to monitor the uptime of your websites.\nThe analysis provided by the uptime gives you the ability to discover potential problems before your customers notice them.",
"frontend": "Frontend",
"backend": "Backend",
"network": "Network",
@@ -726,6 +728,15 @@
"median": "Median",
"xPercentile": "{{x}}th percentile"
},
+ "monitor": {
+ "create": "Create a monitor",
+ "delete": "Delete monitor",
+ "monitorCreated": "Uptime monitor created",
+ "monitorUpdated": "Uptime monitor has been updated",
+ "monitorDeleted": "Uptime monitor deleted",
+ "qDelete": "Delete the monitor?",
+ "deleteHint": "This action is irreversible.\nThe uptime monitor and all the data related to it will be deleted from our servers."
+ },
"alert": {
"create": "Create an alert",
"customEvent": "Custom event name",