📈 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
initial of the AI forecasting integration
Blue Mouse7a8260e8d1cc
diff --git a/.env.example b/.env.exampleindex ffa30e09b..96b340cf9 100644--- a/.env.example+++ b/.env.example@@ -1,5 +1,6 @@REACT_APP_API_URL=https://api.swetrix.com/REACT_APP_CDN_URL=https://cdn.swetrix.com/REACT_APP_BLOG_URL=https://blog.swetrix.com/+REACT_APP_AIAPI_URL=https://aiapi.swetrix.com/CHOKIDAR_USEPOLLING=trueGENERATE_SOURCEMAP=falsediff --git a/public/locales/en.json b/public/locales/en.jsonindex 42e644ac4..b7e98965b 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -19,7 +19,9 @@"acceptInvitation": "The project invitation has been accepted","subscriptionUpdated": "Your subscription has been updated","generate2FAError": "Error occurred while generating 2FA code",- "integrationRemovalError": "Error occurred while removing the integration"+ "integrationRemovalError": "Error occurred while removing the integration",+ "enterACorrectNumber": "Please enter a correct number",+ "numberCantBeNegative": "The number cannot be negative"},"common": {"features": "Features",@@ -585,6 +587,11 @@"paidFeature": {"title": "Upgrade your plan to use this feature","desc": "We apologise for the inconvenience, but you must subscribe to a paid plan to use this feature.\n\nWe realise that you might not be ready to buy a paid subscription yet, but buying it will give you not only access to this feature, but also many other great perks, such as access to all the other paid features, higher limits on visits per month and number of websites available, and you will support the growth of a small business :)"+ },+ "forecast": {+ "title": "Traffic forecast",+ "desc": "This is a rough estimate of how much traffic you can expect to get on your website, based on Swetrix AI models.",+ "input": "Enter the quantity of '{{frequency}}' you want to forecast"}},"pricing": {diff --git a/src/api/ai.js b/src/api/ai.jsnew file mode 100644index 000000000..8939888ec--- /dev/null+++ b/src/api/ai.js@@ -0,0 +1,33 @@+/* eslint-disable implicit-arrow-linebreak */+import axios from 'axios'+import Debug from 'debug'+import _isEmpty from 'lodash/isEmpty'++const debug = Debug('swetrix:ai')++const api = axios.create({+ baseURL: process.env.REACT_APP_AIAPI_URL,+})++/**+ * Returns the prediction for the given data.+ *+ * @param {*} chart The chart data, i.e. the `chart` key here -> https://docs.swetrix.com/statistics-api#get-v1log+ * @param {*} periodToForecast How many new entries should be added to the chart data array.+ * @param {*} frequency The frequency of the chart data, e.g. h | w | m+ * @returns The prediction for the given data.+ */+export const getChartPrediction = (chart, periodToForecast, frequency) =>+ api+ .post('', {+ ...chart,+ period_to_forecast: periodToForecast,+ frequency,+ })+ .then((response) => response.data)+ .catch((error) => {+ debug('%s', error)+ throw _isEmpty(error.response.data?.message)+ ? error.response.data+ : error.response.data.message+ })diff --git a/src/api/blog.js b/src/api/blog.jsindex 39a306758..e038e0060 100644--- a/src/api/blog.js+++ b/src/api/blog.js@@ -3,7 +3,7 @@ import axios from 'axios'import Debug from 'debug'import _isEmpty from 'lodash/isEmpty'-const debug = Debug('swetrix:api')+const debug = Debug('swetrix:blog')const api = axios.create({baseURL: process.env.REACT_APP_BLOG_URL,diff --git a/src/modals/Forecast.jsx b/src/modals/Forecast.jsxnew file mode 100644index 000000000..5e08248de--- /dev/null+++ b/src/modals/Forecast.jsx@@ -0,0 +1,85 @@+import React, { useState } from 'react'+import { useTranslation } from 'react-i18next'+import PropTypes from 'prop-types'+import _isNaN from 'lodash/isNaN'++import Modal from 'ui/Modal'+import Input from 'ui/Input'++const DEFAULT_PERIOD = 3++const Forecast = ({+ onClose, onSubmit, isOpened, activeTB,+}) => {+ const { t } = useTranslation('common')+ const [period, setPeriod] = useState(DEFAULT_PERIOD)+ const [error, setError] = useState(null)++ const handleInput = (e) => {+ const { value } = e.target++ setPeriod(value)+ setError(null)+ }++ const _onSubmit = () => {+ const processedPeriod = Number(period)++ if (_isNaN(processedPeriod)) {+ setError(t('apiNotifications.enterACorrectNumber'))+ return+ }++ if (processedPeriod <= 0) {+ setError(t('apiNotifications.numberCantBeNegative'))+ return+ }++ onSubmit(period)+ }++ const _onClose = () => {+ setPeriod(DEFAULT_PERIOD)+ setError(null)+ onClose()+ }++ return (+ <Modal+ onClose={_onClose}+ onSubmit={_onSubmit}+ submitText={t('common.continue')}+ closeText={t('common.cancel')}+ message={(+ <div>+ {t('modals.forecast.desc')}++ <Input+ name='forecast-input'+ id='forecast-input'+ type='text'+ label={t('modals.forecast.input', {+ frequency: activeTB,+ })}+ value={period}+ placeholder={`${DEFAULT_PERIOD}`}+ className='mt-4'+ onChange={handleInput}+ error={error}+ />+ </div>+ )}+ title={t('modals.forecast.title')}+ isOpened={isOpened}+ />+ )+}++Forecast.propTypes = {+ onClose: PropTypes.func.isRequired,+ isOpened: PropTypes.bool.isRequired,+ onSubmit: PropTypes.func.isRequired,+ activeTB: PropTypes.string.isRequired,+}++export default Forecastdiff --git a/src/pages/Project/View/ViewProject.jsx b/src/pages/Project/View/ViewProject.jsxindex a7b9200a1..264a63a88 100644--- a/src/pages/Project/View/ViewProject.jsx+++ b/src/pages/Project/View/ViewProject.jsx@@ -41,7 +41,9 @@ import Dropdown from 'ui/Dropdown'import Checkbox from 'ui/Checkbox'import Select from 'ui/Select'import FlatPicker from 'ui/Flatpicker'+import Robot from 'ui/icons/Robot'import PaidFeature from 'modals/PaidFeature'+import Forecast from 'modals/Forecast'import routes from 'routes'import {getProjectData, getProject, getOverallStats, getLiveVisitors, getPerfData,@@ -87,6 +89,7 @@ const ViewProject = ({const [panelsData, setPanelsData] = useState({})const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)+ const [isForecastOpened, setIsForecastOpened] = useState(false)const [analyticsLoading, setAnalyticsLoading] = useState(true)const [period, setPeriod] = useState(projectViewPrefs[id]?.period || periodPairs[3].period)const [timeBucket, setTimebucket] = useState(projectViewPrefs[id]?.timeBucket || periodPairs[3].tbs[1])@@ -598,6 +601,20 @@ const ViewProject = ({}}+ const onForecastOpen = () => {+ if (isLoading || dataLoading) {+ return+ }++ setIsForecastOpened(true)+ }++ const onForecastSubmit = () => {+ // todo++ setIsForecastOpened(false)+ }+useEffect(() => {const url = new URL(window.location)url.searchParams.delete('tab')@@ -1235,6 +1252,17 @@ const ViewProject = ({<ArrowPathIcon className='w-5 h-5 text-gray-700 dark:text-gray-50' /></button></div>+ <div className='md:border-r border-gray-200 dark:border-gray-600 md:pr-3 mr-3'>+ <button+ type='button'+ onClick={onForecastOpen}+ className={cx('relative shadow-sm rounded-md mt-[1px] px-3 md:px-4 py-2 bg-white text-sm font-medium hover:bg-gray-50 dark:bg-gray-700 dark:hover:bg-gray-600 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', {+ 'cursor-not-allowed opacity-50': isLoading || dataLoading,+ })}+ >+ <Robot containerClassName='w-5 h-5' className='text-gray-700 dark:text-gray-50' />+ </button>+ </div><div className='md:border-r border-gray-200 dark:border-gray-600 md:pr-3 mr-3'><span className='relative z-0 inline-flex shadow-sm rounded-md'>{_map(activePeriod.tbs, (tb, index, { length }) => (@@ -1639,6 +1667,12 @@ const ViewProject = ({isOpened={isPaidFeatureOpened}onClose={() => setIsPaidFeatureOpened(false)}/>+ <Forecast+ isOpened={isForecastOpened}+ onClose={() => setIsForecastOpened(false)}+ onSubmit={onForecastSubmit}+ activeTB={t(`project.${timeBucket}`)}+ /></Title>)}diff --git a/src/ui/icons/Robot.jsx b/src/ui/icons/Robot.jsxnew file mode 100644index 000000000..92a2cf9e1--- /dev/null+++ b/src/ui/icons/Robot.jsx@@ -0,0 +1,31 @@+import React from 'react'+import cx from 'clsx'+import PropTypes from 'prop-types'++const Robot = ({ theme, className, containerClassName }) => {+ const cn = cx(className, {+ 'fill-white': theme === 'dark',+ 'fill-slate-800': theme === 'light',+ })++ return (+ <svg className={containerClassName} width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' strokeWidth='2' strokeLinecap='round' strokeLinejoin='round'>+ <rect x='3' y='11' width='18' height='10' rx='2' className={cn} />+ <circle cx='12' cy='5' r='2' className={cn} />+ <path d='M12 7v4' className={cn} />+ <line x1='8' y1='16' x2='8' y2='16' className={cn} />+ <line x1='16' y1='16' x2='16' y2='16' className={cn} />+ </svg>+ )+}++Robot.propTypes = {+ className: PropTypes.string,+ theme: PropTypes.string.isRequired,+}++Robot.defaultProps = {+ className: '',+}++export default Robot