From 497a52c10a38e06b3b3731e03d4ea38f76cf2e24 Mon Sep 17 00:00:00 2001 From: Vignesh Joglekar Date: Tue, 22 Nov 2022 06:50:58 -0600 Subject: [PATCH] Add support for intervals (#1574) Co-authored-by: Vini Brasil Co-authored-by: Vignesh Joglekar --- assets/js/dashboard/mount.js | 3 +- .../dashboard/stats/graph/date-formatter.js | 127 ++++++++++++ assets/js/dashboard/stats/graph/graph-util.js | 63 ++---- .../dashboard/stats/graph/interval-picker.js | 67 +++++++ assets/js/dashboard/stats/graph/top-stats.js | 6 +- .../js/dashboard/stats/graph/visitor-graph.js | 189 ++++++++++++++---- lib/plausible/stats/interval.ex | 31 +-- .../controllers/api/stats_controller.ex | 2 +- .../controllers/stats_controller.ex | 3 +- .../templates/stats/stats.html.eex | 17 +- .../api/stats_controller/main_graph_test.exs | 66 ------ 11 files changed, 396 insertions(+), 178 deletions(-) create mode 100644 assets/js/dashboard/stats/graph/date-formatter.js create mode 100644 assets/js/dashboard/stats/graph/interval-picker.js diff --git a/assets/js/dashboard/mount.js b/assets/js/dashboard/mount.js index b5d45aff6..a94848a27 100644 --- a/assets/js/dashboard/mount.js +++ b/assets/js/dashboard/mount.js @@ -17,7 +17,8 @@ if (container) { embedded: container.dataset.embedded, background: container.dataset.background, isDbip: container.dataset.isDbip === 'true', - flags: JSON.parse(container.dataset.flags) + flags: JSON.parse(container.dataset.flags), + validIntervalsByPeriod: JSON.parse(container.dataset.validIntervalsByPeriod) } const loggedIn = container.dataset.loggedIn === 'true' diff --git a/assets/js/dashboard/stats/graph/date-formatter.js b/assets/js/dashboard/stats/graph/date-formatter.js new file mode 100644 index 000000000..a44beaaca --- /dev/null +++ b/assets/js/dashboard/stats/graph/date-formatter.js @@ -0,0 +1,127 @@ +import {parseUTCDate, formatMonthYYYY, formatDay, formatDayShort} from '../../util/date' + +const browserDateFormat = Intl.DateTimeFormat(navigator.language, { hour: 'numeric' }) + +const is12HourClock = function() { + return browserDateFormat.resolvedOptions().hour12 +} + +const parseISODate = function(isoDate) { + const date = parseUTCDate(isoDate) + const minutes = date.getMinutes(); + return { date, minutes } +} + +const formatHours = function(isoDate) { + const monthIndex = 1 + const dateParts = isoDate.split(/[^0-9]/); + dateParts[monthIndex] = dateParts[monthIndex] - 1 + + const localDate = new Date(...dateParts) + return browserDateFormat.format(localDate) +} + +const monthIntervalFormatter = { + long(isoDate, options) { + const formatted = this.short(isoDate, options) + return options.isBucketPartial ? `Partial of ${formatted}` : formatted + }, + short(isoDate, _options) { + const { date } = parseISODate(isoDate) + return formatMonthYYYY(date) + } +} + +const weekIntervalFormatter = { + long(isoDate, options) { + const formatted = this.short(isoDate, options) + return options.isBucketPartial ? `Partial week of ${formatted}` : `Week of ${formatted}` + }, + short(isoDate, _options) { + const { date } = parseISODate(isoDate) + return formatDayShort(date) + } +} + +const dateIntervalFormatter = { + long(isoDate, _options) { + const { date } = parseISODate(isoDate) + return formatDay(date) + }, + short(isoDate, _options) { + const { date } = parseISODate(isoDate) + return formatDayShort(date) + } +} + +const hourIntervalFormatter = { + long(isoDate, options) { + return this.short(isoDate, options) + }, + short(isoDate, _options) { + const formatted = formatHours(isoDate) + + if (is12HourClock()) { + return formatted.replace(' ', '').toLowerCase() + } else { + return formatted.replace(/[^0-9]/g, '').concat(":00") + } + } +} + +const minuteIntervalFormatter = { + long(isoDate, options) { + if (options.period == 'realtime') { + const minutesAgo = Math.abs(isoDate) + return minutesAgo === 1 ? '1 minute ago' : minutesAgo + ' minutes ago' + } else { + return this.short(isoDate, options) + } + }, + short(isoDate, options) { + if (options.period === 'realtime') return isoDate + 'm' + + const { minutes } = parseISODate(isoDate) + const formatted = formatHours(isoDate) + if (is12HourClock()) { + return formatted.replace(' ', ':' + (minutes < 10 ? `0${minutes}` : minutes)).toLowerCase() + } else { + return formatted.replace(/[^0-9]/g, '').concat(":" + (minutes < 10 ? `0${minutes}` : minutes)) + } + } +} + +// Each interval has a different date and time format. This object maps each +// interval with two functions: `long` and `short`, that formats date and time +// accordingly. +const factory = { + month: monthIntervalFormatter, + week: weekIntervalFormatter, + date: dateIntervalFormatter, + hour: hourIntervalFormatter, + minute: minuteIntervalFormatter +} + +/** + * Returns a function that formats a ISO 8601 timestamp based on the given + * arguments. + * + * The preferred date and time format in the dashboard depends on the selected + * interval and period. For example, in real-time view only the time is necessary, + * while other intervals require dates to be displayed. + * + * @param {string} interval - The interval of the query, e.g. `minute`, `hour` + * @param {boolean} longForm - Whether the formatted result should be in long or + * short form. + * @param {string} period - The period of the query, e.g. `12mo`, `day` + * @param {boolean} isPeriodFull - Indicates whether the interval has been cut + * off by the requested date range or not. If false, the returned formatted date + * indicates this cut off, e.g. `Partial week of November 8`. + */ +export default function dateFormatter(interval, longForm, period, isPeriodFull) { + const displayMode = longForm ? 'long' : 'short' + const options = { period: period, interval: interval, isBucketPartial: !isPeriodFull } + return function(isoDate, _index, _ticks) { + return factory[interval][displayMode](isoDate, options) + } +} diff --git a/assets/js/dashboard/stats/graph/graph-util.js b/assets/js/dashboard/stats/graph/graph-util.js index 69c5519e6..98000e69a 100644 --- a/assets/js/dashboard/stats/graph/graph-util.js +++ b/assets/js/dashboard/stats/graph/graph-util.js @@ -1,5 +1,7 @@ -import { parseUTCDate, formatMonthYYYY, formatDay } from '../../util/date' import numberFormatter, {durationFormatter} from '../../util/number-formatter' +import dateFormatter from './date-formatter.js' + +export const INTERVALS = ["month", "week", "date", "hour", "minute"] export const METRIC_MAPPING = { 'Unique visitors (last 30 min)': 'visitors', @@ -27,39 +29,7 @@ export const METRIC_FORMATTER = { 'conversions': numberFormatter, } -export const dateFormatter = (interval, longForm) => { - return function(isoDate, _index, _ticks) { - let date = parseUTCDate(isoDate) - - if (interval === 'month') { - return formatMonthYYYY(date); - } else if (interval === 'date') { - return formatDay(date); - } else if (interval === 'hour') { - const parts = isoDate.split(/[^0-9]/); - date = new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]) - - const dateFormat = Intl.DateTimeFormat(navigator.language, { hour: 'numeric' }) - const twelveHourClock = dateFormat.resolvedOptions().hour12 - const formattedHours = dateFormat.format(date) - - if (twelveHourClock) { - return formattedHours.replace(' ', '').toLowerCase() - } else { - return formattedHours.replace(/[^0-9]/g, '').concat(":00") - } - } else if (interval === 'minute') { - if (longForm) { - const minutesAgo = Math.abs(isoDate) - return minutesAgo === 1 ? '1 minute ago' : minutesAgo + ' minutes ago' - } else { - return isoDate + 'm' - } - } - } -} - -export const GraphTooltip = (graphData, metric) => { +export const GraphTooltip = (graphData, metric, query) => { return (context) => { const tooltipModel = context.tooltip; const offset = document.getElementById("main-graph-canvas").getBoundingClientRect() @@ -93,23 +63,22 @@ export const GraphTooltip = (graphData, metric) => { return bodyItem.lines; } - function renderLabel(label, prev_label) { - const formattedLabel = dateFormatter(graphData.interval, true)(label) - const prev_formattedLabel = prev_label && dateFormatter(graphData.interval, true)(prev_label) - - if (graphData.interval === 'month') { - return !prev_label ? formattedLabel : prev_formattedLabel - } + // Returns a string describing the bucket. Used when hovering the graph to + // show time buckets. + function renderBucketLabel(label) { + const isPeriodFull = graphData.full_intervals?.[label] + const formattedLabel = dateFormatter(graphData.interval, true, query.period, isPeriodFull)(label) - if (graphData.interval === 'date') { - return !prev_label ? formattedLabel : prev_formattedLabel + if (query.period === 'realtime') { + return dateFormatter(graphData.interval, true, query.period)(label) } - if (graphData.interval === 'hour') { - return !prev_label ? `${dateFormatter("date", true)(label)}, ${formattedLabel}` : `${dateFormatter("date", true)(prev_label)}, ${dateFormatter(graphData.interval, true)(prev_label)}` + if (graphData.interval === 'hour' || graphData.interval == 'minute') { + const date = dateFormatter("date", true, query.period)(label) + return `${date}, ${formattedLabel}` } - return !prev_label ? formattedLabel : prev_formattedLabel + return formattedLabel } // Set Tooltip Body @@ -134,7 +103,7 @@ export const GraphTooltip = (graphData, metric) => {
- ${renderLabel(label)} + ${renderBucketLabel(label)}
${METRIC_FORMATTER[metric](point)}
diff --git a/assets/js/dashboard/stats/graph/interval-picker.js b/assets/js/dashboard/stats/graph/interval-picker.js new file mode 100644 index 000000000..890ce2586 --- /dev/null +++ b/assets/js/dashboard/stats/graph/interval-picker.js @@ -0,0 +1,67 @@ +import { Menu, Transition } from '@headlessui/react'; +import { ChevronDownIcon } from '@heroicons/react/20/solid' +import React, { Fragment } from 'react'; +import classNames from 'classnames' +import * as storage from '../../util/storage' + +export const INTERVAL_LABELS = { + 'minute': 'Minutes', + 'hour': 'Hours', + 'date': 'Days', + 'week': 'Weeks', + 'month': 'Months' +} + +export const getStoredInterval = function(period, domain) { + return storage.getItem(`interval__${period}__${domain}`) +} + +export const storeInterval = function(period, domain, interval) { + storage.setItem(`interval__${period}__${domain}`, interval) +} + +function DropdownItem({ option, currentInterval, updateInterval }) { + return ( + updateInterval(option)} key={option} disabled={option == currentInterval}> + {({ active }) => ( + + { INTERVAL_LABELS[option] } + + )} + + ) +} + +export function IntervalPicker({ graphData, query, site, updateInterval }) { + if (query.period == 'realtime') return null + + const currentInterval = graphData?.interval + const options = site.validIntervalsByPeriod[query.period] + + return ( + + + { INTERVAL_LABELS[currentInterval] } + + + + + { options.map((option) => DropdownItem({ option, currentInterval, updateInterval })) } + + + + ) +} diff --git a/assets/js/dashboard/stats/graph/top-stats.js b/assets/js/dashboard/stats/graph/top-stats.js index 670222460..960ad5cc8 100644 --- a/assets/js/dashboard/stats/graph/top-stats.js +++ b/assets/js/dashboard/stats/graph/top-stats.js @@ -1,6 +1,6 @@ import React from "react"; -import classNames from "classnames"; import { Tooltip } from '../../util/tooltip' +import classNames from "classnames"; import numberFormatter, { durationFormatter } from '../../util/number-formatter' import { METRIC_MAPPING } from './graph-util' @@ -113,10 +113,10 @@ export default class TopStats extends React.Component { ) }) - if (query && query.period === 'realtime') { + if (stats && query && query.period === 'realtime') { stats.push(
) } - return stats + return stats || null; } } diff --git a/assets/js/dashboard/stats/graph/visitor-graph.js b/assets/js/dashboard/stats/graph/visitor-graph.js index ee8a72b04..1eb0d80fe 100644 --- a/assets/js/dashboard/stats/graph/visitor-graph.js +++ b/assets/js/dashboard/stats/graph/visitor-graph.js @@ -5,9 +5,19 @@ import { navigateToQuery } from '../../query' import * as api from '../../api' import * as storage from '../../util/storage' import LazyLoader from '../../components/lazy-loader' -import {GraphTooltip, buildDataSet, dateFormatter, METRIC_MAPPING, METRIC_LABELS, METRIC_FORMATTER} from './graph-util'; +import {GraphTooltip, buildDataSet, INTERVALS, METRIC_MAPPING, METRIC_LABELS, METRIC_FORMATTER} from './graph-util'; +import dateFormatter from './date-formatter'; import TopStats from './top-stats'; +import { IntervalPicker, getStoredInterval, storeInterval } from './interval-picker'; +import FadeIn from '../../fade-in'; import * as url from '../../util/url' +import classNames from "classnames"; + +const LOADING_STATE = { + loading: 'loading', + refreshing: 'refreshing', + loaded: 'loaded' +} class LineGraph extends React.Component { constructor(props) { @@ -21,7 +31,7 @@ class LineGraph extends React.Component { } regenerateChart() { - const { graphData, metric } = this.props + const { graphData, metric, query } = this.props const graphEl = document.getElementById("main-graph-canvas") this.ctx = graphEl.getContext('2d'); const dataSet = buildDataSet(graphData.plot, graphData.present_index, this.ctx, METRIC_LABELS[metric]) @@ -43,7 +53,7 @@ class LineGraph extends React.Component { mode: 'index', intersect: false, position: 'average', - external: GraphTooltip(graphData, metric) + external: GraphTooltip(graphData, metric, query) }, }, responsive: true, @@ -67,7 +77,23 @@ class LineGraph extends React.Component { grid: { display: false }, ticks: { maxTicksLimit: 8, - callback: function(val, _index, _ticks) { return dateFormatter(graphData.interval)(this.getLabelForValue(val)) }, + callback: function (val, _index, _ticks) { + if (graphData.interval === 'hour' && query.period !== 'day') { + const date = dateFormatter("date", false, query.period)(this.getLabelForValue(val)) + const hour = dateFormatter(graphData.interval, false, query.period)(this.getLabelForValue(val)) + + // Returns a combination of date and hour. This is because + // small intervals like hour may return multiple days + // depending on the query period. + return `${date}, ${hour}` + } + + if (graphData.interval === 'minute' && query.period !== 'realtime') { + return dateFormatter("hour", false, query.period)(this.getLabelForValue(val)) + } + + return dateFormatter(graphData.interval, false, query.period)(this.getLabelForValue(val)) + }, color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined } } @@ -106,15 +132,18 @@ class LineGraph extends React.Component { const { graphData, metric, darkTheme } = this.props; const tooltip = document.getElementById('chartjs-tooltip'); - if (metric && graphData && ( + if ( graphData !== prevProps.graphData || darkTheme !== prevProps.darkTheme - )) { - if (this.chart) { - this.chart.destroy(); + ) { + + if (metric && graphData) { + if (this.chart) { + this.chart.destroy(); + } + this.chart = this.regenerateChart(); + this.chart.update(); } - this.chart = this.regenerateChart(); - this.chart.update(); if (tooltip) { tooltip.style.display = 'none'; @@ -208,7 +237,7 @@ class LineGraph extends React.Component { return ( - + ) } @@ -230,7 +259,7 @@ class LineGraph extends React.Component { } importedNotice() { - const source = this.props.topStatData.imported_source; + const source = this.props.topStatData && this.props.topStatData.imported_source; if (source) { const withImported = this.props.topStatData.with_imported; @@ -251,21 +280,25 @@ class LineGraph extends React.Component { } render() { - const { updateMetric, metric, topStatData, query } = this.props + const { updateMetric, metric, topStatData, query, site, graphData } = this.props const extraClass = this.props.graphData && this.props.graphData.interval === 'hour' ? '' : 'cursor-pointer' return (
- +
-
- {this.downloadLink()} - {this.samplingNotice()} +
+ { this.downloadLink() } + { this.samplingNotice() } { this.importedNotice() } + { site.flags && site.flags.intervals && + }
- + + +
) @@ -278,36 +311,76 @@ export default class VisitorGraph extends React.Component { constructor(props) { super(props) this.state = { - loading: 2, - metric: storage.getItem(`metric__${this.props.site.domain}`) || 'visitors' + topStatsLoadingState: LOADING_STATE.loading, + mainGraphLoadingState: LOADING_STATE.loading, + metric: storage.getItem(`metric__${this.props.site.domain}`) || 'visitors', + interval: getStoredInterval(this.props.query.period, this.props.site.domain) } this.onVisible = this.onVisible.bind(this) this.updateMetric = this.updateMetric.bind(this) this.fetchTopStatData = this.fetchTopStatData.bind(this) this.fetchGraphData = this.fetchGraphData.bind(this) + this.maybeRollbackInterval = this.maybeRollbackInterval.bind(this) + this.updateInterval = this.updateInterval.bind(this) + } + + isIntervalValid({ query, site }) { + const period = query?.period + const validIntervalsForPeriod = site.validIntervalsByPeriod[period] || [] + const storedInterval = getStoredInterval(period, site.domain) + + return validIntervalsForPeriod.includes(storedInterval) + } + + maybeRollbackInterval() { + if (this.isIntervalValid(this.props)) { + const interval = getStoredInterval(this.props.query.period, this.props.site.domain) + + this.setState({interval}, () => { + this.fetchGraphData() + }) + } else { + this.setState({interval: undefined}, () => { + this.setState({graphData: null}) + this.fetchGraphData() + }) + } + } + + updateInterval(interval) { + if (INTERVALS.includes(interval)) { + this.setState({interval, mainGraphLoadingState: LOADING_STATE.refreshing}, this.maybeRollbackInterval) + storeInterval(this.props.query.period, this.props.site.domain, interval) + } } onVisible() { - this.fetchGraphData() + this.setState({mainGraphLoadingState: LOADING_STATE.loading}, this.maybeRollbackInterval) this.fetchTopStatData() if (this.props.timer) { - this.props.timer.onTick(this.fetchGraphData) + this.props.timer.onTick(this.maybeRollbackInterval) this.props.timer.onTick(this.fetchTopStatData) } } componentDidUpdate(prevProps, prevState) { - const { metric, topStatData } = this.state; + const { metric, topStatData, interval } = this.state; if (this.props.query !== prevProps.query) { - this.setState({ loading: 3, graphData: null, topStatData: null }) - this.fetchGraphData() + if (metric) { + this.setState({ mainGraphLoadingState: LOADING_STATE.loading, topStatsLoadingState: LOADING_STATE.loading, graphData: null, topStatData: null }, this.maybeRollbackInterval) + } else { + this.setState({ topStatsLoadingState: LOADING_STATE.loading, topStatData: null }) + } this.fetchTopStatData() } if (metric !== prevState.metric) { - this.setState({loading: 1, graphData: null}) - this.fetchGraphData() + this.setState({mainGraphLoadingState: LOADING_STATE.refreshing}, this.maybeRollbackInterval) + } + + if (interval !== prevState.interval && interval) { + this.setState({mainGraphLoadingState: LOADING_STATE.refreshing}, this.maybeRollbackInterval) } const savedMetric = storage.getItem(`metric__${this.props.site.domain}`) @@ -335,45 +408,75 @@ export default class VisitorGraph extends React.Component { } fetchGraphData() { - if (this.state.metric) { - api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/main-graph`, this.props.query, {metric: this.state.metric || 'none'}) + if (!this.state.metric) { + this.setState({ mainGraphLoadingState: LOADING_STATE.ready, graphData: null }) + return + } + + const url = `/api/stats/${encodeURIComponent(this.props.site.domain)}/main-graph` + let params = {metric: this.state.metric || 'none'} + if (this.state.interval) { params.interval = this.state.interval } + + api.get(url, this.props.query, params) .then((res) => { - this.setState((state) => ({ loading: state.loading-2, graphData: res })) + this.setState({ mainGraphLoadingState: LOADING_STATE.ready, graphData: res }) return res }) - } else { - this.setState((state) => ({ loading: state.loading-2, graphData: null })) - } + .catch((err) => { + console.log(err) + this.setState({ mainGraphLoadingState: LOADING_STATE.ready, graphData: false }) + }) } fetchTopStatData() { api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/top-stats`, this.props.query) .then((res) => { - this.setState((state) => ({ loading: state.loading-1, topStatData: res })) + this.setState({ topStatsLoadingState: LOADING_STATE.ready, topStatData: res }) return res }) - } + } renderInner() { const { query, site } = this.props; - const { graphData, metric, topStatData, loading } = this.state; + const { graphData, metric, topStatData, topStatsLoadingState, mainGraphLoadingState } = this.state; const theme = document.querySelector('html').classList.contains('dark') || false - if ((loading <= 1 && topStatData) || (topStatData && graphData)) { - return ( - - ) - } + const topStatsReadyOrRefreshing = (topStatsLoadingState === LOADING_STATE.ready || topStatsLoadingState === LOADING_STATE.refreshing) + const mainGraphReadyOrRefreshing = (mainGraphLoadingState === LOADING_STATE.ready || mainGraphLoadingState === LOADING_STATE.refreshing) + const noMetricOrRefreshing = (!metric || mainGraphLoadingState === LOADING_STATE.refreshing) + const topStatAndGraphLoaded = !!(topStatData && graphData) + + const showGraph = + topStatsReadyOrRefreshing && + mainGraphReadyOrRefreshing && + (topStatData && noMetricOrRefreshing || topStatAndGraphLoaded) + + return ( + + + + ) } render() { - const {metric, topStatData, graphData} = this.state + const {metric, mainGraphLoadingState, topStatsLoadingState} = this.state + const loaderClassName = classNames('mx-auto loading', { + 'pt-52 sm:pt-56 md:pt-60': mainGraphLoadingState == LOADING_STATE.refreshing, + 'pt-32 sm:pt-36 md:pt-48': mainGraphLoadingState !== LOADING_STATE.refreshing && metric, + 'pt-16 sm:pt-14 md:pt-18 lg:pt-5': mainGraphLoadingState !== LOADING_STATE.refreshing && !metric + }) + + const loadingOrRefreshing = + mainGraphLoadingState == LOADING_STATE.refreshing || + mainGraphLoadingState == LOADING_STATE.loading || + topStatsLoadingState == LOADING_STATE.refreshing || + topStatsLoadingState == LOADING_STATE.loading return (
- {this.state.loading > 0 &&
} + {loadingOrRefreshing &&
} {this.renderInner()}
diff --git a/lib/plausible/stats/interval.ex b/lib/plausible/stats/interval.ex index 75f55f78b..3ce469dd3 100644 --- a/lib/plausible/stats/interval.ex +++ b/lib/plausible/stats/interval.ex @@ -38,20 +38,21 @@ defmodule Plausible.Stats.Interval do end end - @allowed_intervals_for_period %{ + @valid_by_period %{ "realtime" => ["minute"], "day" => ["minute", "hour"], - "7d" => ["minute", "hour", "date"], - "month" => ["minute", "hour", "date", "week"], - "30d" => ["minute", "hour", "date", "week"], - "6mo" => ["minute", "hour", "date", "week", "month"], - "12mo" => ["minute", "hour", "date", "week", "month"], - "year" => ["minute", "hour", "date", "week", "month"], - "custom" => ["minute", "hour", "date", "week", "month"], - "all" => ["minute", "hour", "date", "week", "month"] + "7d" => ["hour", "date"], + "month" => ["date", "week"], + "30d" => ["date", "week"], + "6mo" => ["date", "week", "month"], + "12mo" => ["date", "week", "month"], + "year" => ["date", "week", "month"], + "custom" => ["date", "week", "month"], + "all" => ["date", "week", "month"] } + def valid_by_period, do: @valid_by_period - @spec allowed_for_period?(period(), t()) :: boolean() + @spec valid_for_period?(period(), t()) :: boolean() @doc """ Returns whether the given interval is valid for a time period. @@ -61,18 +62,18 @@ defmodule Plausible.Stats.Interval do ## Examples - iex> Plausible.Stats.Interval.allowed_for_period?("month", "date") + iex> Plausible.Stats.Interval.valid_for_period?("month", "date") true - iex> Plausible.Stats.Interval.allowed_for_period?("30d", "month") + iex> Plausible.Stats.Interval.valid_for_period?("30d", "month") false - iex> Plausible.Stats.Interval.allowed_for_period?("realtime", "week") + iex> Plausible.Stats.Interval.valid_for_period?("realtime", "week") false """ - def allowed_for_period?(period, interval) do - allowed = Map.get(@allowed_intervals_for_period, period, []) + def valid_for_period?(period, interval) do + allowed = Map.get(@valid_by_period, period, []) interval in allowed end end diff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.ex index cfac6aad8..acfc4cdfd 100644 --- a/lib/plausible_web/controllers/api/stats_controller.ex +++ b/lib/plausible_web/controllers/api/stats_controller.ex @@ -1211,7 +1211,7 @@ defmodule PlausibleWeb.Api.StatsController do defp validate_interval_granularity(params) do with %{"interval" => interval, "period" => period} <- params, - true <- Plausible.Stats.Interval.allowed_for_period?(period, interval) do + true <- Plausible.Stats.Interval.valid_for_period?(period, interval) do :ok else %{} -> diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.ex index fc99b4772..b18872357 100644 --- a/lib/plausible_web/controllers/stats_controller.ex +++ b/lib/plausible_web/controllers/stats_controller.ex @@ -308,7 +308,8 @@ defmodule PlausibleWeb.StatsController do defp get_flags(user) do %{ - custom_dimension_filter: FunWithFlags.enabled?(:custom_dimension_filter, for: user) + custom_dimension_filter: FunWithFlags.enabled?(:custom_dimension_filter, for: user), + intervals: FunWithFlags.enabled?(:intervals, for: user) } end diff --git a/lib/plausible_web/templates/stats/stats.html.eex b/lib/plausible_web/templates/stats/stats.html.eex index fcf2379b6..bd3cf37a9 100644 --- a/lib/plausible_web/templates/stats/stats.html.eex +++ b/lib/plausible_web/templates/stats/stats.html.eex @@ -12,7 +12,22 @@ <% end %>
-
+
<%= if !@conn.assigns[:current_user] && @conn.assigns[:demo] do %>
diff --git a/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs index 8d80e95af..0230510eb 100644 --- a/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs +++ b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs @@ -387,72 +387,6 @@ defmodule PlausibleWeb.Api.StatsController.MainGraphTest do describe "GET /api/stats/main-graph - varying intervals" do setup [:create_user, :log_in, :create_new_site] - test "displays visitors for a month on an hourly scale", %{conn: conn, site: site} do - populate_stats(site, [ - build(:pageview, timestamp: ~N[2021-01-01 00:00:00]), - build(:pageview, timestamp: ~N[2021-01-01 01:01:00]) - ]) - - conn = - get( - conn, - "/api/stats/#{site.domain}/main-graph?period=month&date=2021-01-01&metric=visitors&interval=hour" - ) - - assert %{"plot" => plot} = json_response(conn, 200) - - assert Enum.count(plot) == 721 - assert List.first(plot) == 1 - assert Enum.at(plot, 1) == 1 - end - - test "displays visitors for a day on a minute scale", %{conn: conn, site: site} do - populate_stats(site, [ - build(:pageview, timestamp: ~N[2021-01-01 00:00:00]), - build(:pageview, timestamp: ~N[2021-01-01 00:15:01]), - build(:pageview, timestamp: ~N[2021-01-01 00:15:02]) - ]) - - conn = - get( - conn, - "/api/stats/#{site.domain}/main-graph?period=day&date=2021-01-01&metric=visitors&interval=minute" - ) - - assert %{"plot" => plot} = json_response(conn, 200) - - assert Enum.count(plot) == 1440 - assert List.first(plot) == 1 - assert Enum.at(plot, 15) == 2 - end - - test "displays visitors for date range on a minute scale", %{conn: conn, site: site} do - populate_stats(site, [ - build(:pageview, timestamp: ~N[2021-01-01 00:00:00]), - build(:pageview, timestamp: ~N[2021-01-01 00:15:01]), - build(:pageview, timestamp: ~N[2021-01-01 00:15:02]), - build(:pageview, timestamp: ~N[2021-01-02 00:10:00]), - build(:pageview, timestamp: ~N[2021-01-02 00:11:01]), - build(:pageview, timestamp: ~N[2021-01-02 01:00:02]), - build(:pageview, timestamp: ~N[2021-01-04 03:10:00]), - build(:pageview, timestamp: ~N[2021-01-04 04:11:01]), - build(:pageview, timestamp: ~N[2021-01-04 05:00:02]) - ]) - - conn = - get( - conn, - "/api/stats/#{site.domain}/main-graph?period=custom&from=2021-01-01&to=2021-01-04&metric=visitors&interval=minute" - ) - - assert %{"plot" => plot} = json_response(conn, 200) - - assert Enum.count(plot) == 4321 - assert List.first(plot) == 1 - assert Enum.at(plot, 15) == 2 - assert Enum.at(plot, 1450) == 1 - end - test "displays visitors for 6mo on a day scale", %{conn: conn, site: site} do populate_stats(site, [ build(:pageview, timestamp: ~N[2021-01-01 00:00:00]),