Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Chart improvements (#990)

Goldflaga08848797dcc
diff --git a/client/messages/cs.json b/client/messages/cs.json
index 3756d75e8..9c2ed2c6b 100644
--- a/client/messages/cs.json
+++ b/client/messages/cs.json
@@ -16,6 +16,8 @@
"Vl357u": "Časový rozsah",
"QirE3M": "Datum začátku",
"T4GOiX": "Datum konce",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Další parametry",
"BkOSF2": "Parametry",
"FEh4ys": "Neplatný JSON",
diff --git a/client/messages/de.json b/client/messages/de.json
index 4351d8549..116d7cc09 100644
--- a/client/messages/de.json
+++ b/client/messages/de.json
@@ -16,6 +16,8 @@
"Vl357u": "Zeitraum",
"QirE3M": "Startdatum",
"T4GOiX": "Enddatum",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Zusätzliche Parameter",
"BkOSF2": "Parameter",
"FEh4ys": "Ungültiges JSON",
diff --git a/client/messages/en.json b/client/messages/en.json
index a6880be7e..b2fbaa593 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -16,6 +16,8 @@
"Vl357u": "Time Range",
"QirE3M": "Start Date",
"T4GOiX": "End Date",
+ "5QYdPU": "Start Time",
+ "0niASN": "End Time",
"mkp+qF": "Additional Parameters",
"BkOSF2": "Parameters",
"FEh4ys": "Invalid JSON",
diff --git a/client/messages/es.json b/client/messages/es.json
index a22c44dda..33201185a 100644
--- a/client/messages/es.json
+++ b/client/messages/es.json
@@ -16,6 +16,8 @@
"Vl357u": "Rango de tiempo",
"QirE3M": "Fecha de inicio",
"T4GOiX": "Fecha de finalización",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Parámetros adicionales",
"BkOSF2": "Parámetros",
"FEh4ys": "JSON no válido",
diff --git a/client/messages/fr.json b/client/messages/fr.json
index 07306d091..8fa9f5972 100644
--- a/client/messages/fr.json
+++ b/client/messages/fr.json
@@ -16,6 +16,8 @@
"Vl357u": "Période",
"QirE3M": "Date de début",
"T4GOiX": "Date de fin",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Paramètres supplémentaires",
"BkOSF2": "Paramètres",
"FEh4ys": "JSON invalide",
diff --git a/client/messages/it.json b/client/messages/it.json
index e9dbeadd5..f6388c804 100644
--- a/client/messages/it.json
+++ b/client/messages/it.json
@@ -16,6 +16,8 @@
"Vl357u": "Intervallo di Tempo",
"QirE3M": "Data di Inizio",
"T4GOiX": "Data di Fine",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Parametri Aggiuntivi",
"BkOSF2": "Parametri",
"FEh4ys": "JSON non valido",
diff --git a/client/messages/ja.json b/client/messages/ja.json
index bb8f1bd48..614e0f3fb 100644
--- a/client/messages/ja.json
+++ b/client/messages/ja.json
@@ -16,6 +16,8 @@
"Vl357u": "期間",
"QirE3M": "開始日",
"T4GOiX": "終了日",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "追加パラメーター",
"BkOSF2": "パラメーター",
"FEh4ys": "無効なJSON",
diff --git a/client/messages/ko.json b/client/messages/ko.json
index 46fcca095..fb3eb2138 100644
--- a/client/messages/ko.json
+++ b/client/messages/ko.json
@@ -16,6 +16,8 @@
"Vl357u": "기간",
"QirE3M": "시작일",
"T4GOiX": "종료일",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "추가 매개변수",
"BkOSF2": "매개변수",
"FEh4ys": "잘못된 JSON",
diff --git a/client/messages/pl.json b/client/messages/pl.json
index 6962e6168..13ee348e6 100644
--- a/client/messages/pl.json
+++ b/client/messages/pl.json
@@ -16,6 +16,8 @@
"Vl357u": "Zakres czasu",
"QirE3M": "Data rozpoczęcia",
"T4GOiX": "Data zakończenia",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Dodatkowe parametry",
"BkOSF2": "Parametry",
"FEh4ys": "Nieprawidłowy JSON",
diff --git a/client/messages/pt.json b/client/messages/pt.json
index 5b040097e..5660ac309 100644
--- a/client/messages/pt.json
+++ b/client/messages/pt.json
@@ -16,6 +16,8 @@
"Vl357u": "Intervalo de Tempo",
"QirE3M": "Data Inicial",
"T4GOiX": "Data Final",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Parâmetros Adicionais",
"BkOSF2": "Parâmetros",
"FEh4ys": "JSON Inválido",
diff --git a/client/messages/uk.json b/client/messages/uk.json
index 78c323077..2979b6fdc 100644
--- a/client/messages/uk.json
+++ b/client/messages/uk.json
@@ -16,6 +16,8 @@
"Vl357u": "Часовий діапазон",
"QirE3M": "Дата початку",
"T4GOiX": "Дата завершення",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "Додаткові параметри",
"BkOSF2": "Параметри",
"FEh4ys": "Недійсний JSON",
diff --git a/client/messages/zh.json b/client/messages/zh.json
index 04ce9392f..4ad324ca7 100644
--- a/client/messages/zh.json
+++ b/client/messages/zh.json
@@ -16,6 +16,8 @@
"Vl357u": "时间范围",
"QirE3M": "开始日期",
"T4GOiX": "结束日期",
+ "5QYdPU": "",
+ "0niASN": "",
"mkp+qF": "其他参数",
"BkOSF2": "参数",
"FEh4ys": "无效的 JSON",
diff --git a/client/src/api/analytics/endpoints/types.ts b/client/src/api/analytics/endpoints/types.ts
index 38770fe73..3f276fa68 100644
--- a/client/src/api/analytics/endpoints/types.ts
+++ b/client/src/api/analytics/endpoints/types.ts
@@ -2,13 +2,16 @@ import { Filter, FilterParameter, TimeBucket } from "@rybbit/shared";
/**
* Common parameters shared across most analytics API endpoints
- * Supports either date range mode OR past-minutes mode
+ * Supports date range, exact datetime range, or past-minutes mode
*/
export interface CommonApiParams {
startDate: string; // YYYY-MM-DD format (empty string for past-minutes mode)
endDate: string; // YYYY-MM-DD format (empty string for past-minutes mode)
timeZone: string; // IANA timezone string
filters?: Filter[];
+ // Optional exact UTC datetime range params.
+ startDateTime?: string;
+ endDateTime?: string;
// Optional past-minutes mode params (when startDate/endDate are empty)
pastMinutesStart?: number;
pastMinutesEnd?: number;
@@ -46,9 +49,18 @@ export interface SortParams {
/**
* Convert CommonApiParams to query params format expected by the API
- * Handles both date range mode and past-minutes mode
+ * Handles date range, exact datetime range, and past-minutes mode
*/
export function toQueryParams(params: CommonApiParams): Record<string, any> {
+ if (params.startDateTime !== undefined && params.endDateTime !== undefined) {
+ return {
+ time_zone: params.timeZone,
+ start_datetime: params.startDateTime,
+ end_datetime: params.endDateTime,
+ filters: params.filters?.length ? params.filters : undefined,
+ };
+ }
+
// Use past-minutes mode if pastMinutesStart is provided
if (params.pastMinutesStart !== undefined) {
return {
diff --git a/client/src/api/analytics/hooks/useGetOverview.ts b/client/src/api/analytics/hooks/useGetOverview.ts
index 64c88265d..3485b3299 100644
--- a/client/src/api/analytics/hooks/useGetOverview.ts
+++ b/client/src/api/analytics/hooks/useGetOverview.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { Time } from "../../../components/DateSelector/types";
import { useStore } from "../../../lib/store";
import { buildApiParams } from "../../utils";
import { fetchOverview } from "../endpoints";
@@ -8,10 +9,8 @@ type PeriodTime = "current" | "previous";
type UseGetOverviewOptions = {
periodTime?: PeriodTime;
site?: number | string;
- overrideTime?:
- | { mode: "past-minutes"; pastMinutesStart: number; pastMinutesEnd: number }
- | { mode: "range"; startDate: string; endDate: string };
- useFilters?: boolean;
+ overrideTime?: Time;
+ useFilters?: boolean;
};
export function useGetOverview({ periodTime, site, overrideTime, useFilters = true }: UseGetOverviewOptions) {
diff --git a/client/src/api/analytics/hooks/useGetOverviewBucketed.ts b/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
index 11970da71..622500961 100644
--- a/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
@@ -1,5 +1,6 @@
import { Filter, TimeBucket } from "@rybbit/shared";
import { UseQueryOptions, UseQueryResult, useQuery } from "@tanstack/react-query";
+import { Time } from "../../../components/DateSelector/types";
import { useStore } from "../../../lib/store";
import { APIResponse } from "../../types";
import { buildApiParams } from "../../utils";
@@ -22,9 +23,7 @@ export function useGetOverviewBucketed({
bucket?: TimeBucket;
dynamicFilters?: Filter[];
refetchInterval?: number;
- overrideTime?:
- | { mode: "past-minutes"; pastMinutesStart: number; pastMinutesEnd: number }
- | { mode: "range"; startDate: string; endDate: string };
+ overrideTime?: Time;
props?: Partial<UseQueryOptions<APIResponse<GetOverviewBucketedResponse>>>;
useFilters?: boolean;
}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {
diff --git a/client/src/api/utils.ts b/client/src/api/utils.ts
index 80b788722..5b91c913b 100644
--- a/client/src/api/utils.ts
+++ b/client/src/api/utils.ts
@@ -8,6 +8,14 @@ import { CommonApiParams } from "./analytics/endpoints/types";
export function getStartAndEndDate(time: Time): { startDate: string | null; endDate: string | null } {
if (time.mode === "range") {
+ if (time.startTime && time.endTime) {
+ const timeZone = getTimezone();
+ const end = DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timeZone });
+ return {
+ startDate: time.startDate,
+ endDate: end.minus({ milliseconds: 1 }).toISODate(),
+ };
+ }
return { startDate: time.startDate, endDate: time.endDate };
}
if (time.mode === "week") {
@@ -62,6 +70,19 @@ export function buildApiParams(time: Time, options: { filters?: Filter[] } = {})
};
}
+ if (time.mode === "range" && time.startTime && time.endTime) {
+ const start = DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone: timeZone });
+ const end = DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timeZone });
+ return {
+ startDate: "",
+ endDate: "",
+ timeZone,
+ filters,
+ startDateTime: start.toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
+ endDateTime: end.toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
+ };
+ }
+
const { startDate, endDate } = getStartAndEndDate(time);
return {
startDate: startDate ?? "",
diff --git a/client/src/app/[site]/api-playground/components/ParameterControls.tsx b/client/src/app/[site]/api-playground/components/ParameterControls.tsx
index 8039cfddf..2f66f5a0a 100644
--- a/client/src/app/[site]/api-playground/components/ParameterControls.tsx
+++ b/client/src/app/[site]/api-playground/components/ParameterControls.tsx
@@ -8,6 +8,7 @@ import { useExtracted } from "next-intl";
import { useParams } from "next/navigation";
import { usePlaygroundStore } from "../hooks/usePlaygroundStore";
import { methodColors, parameterMetadata } from "../utils/endpointConfig";
+import { buildCommonQueryParams } from "../utils/queryParams";
import { FilterBuilder } from "./FilterBuilder";
import { TimezoneSelect } from "./TimezoneSelect";
import { RequestBodyEditor } from "./RequestBodyEditor";
@@ -21,10 +22,14 @@ export function ParameterControls() {
selectedEndpoint,
startDate,
endDate,
+ startTime,
+ endTime,
timeZone,
filters,
setStartDate,
setEndDate,
+ setStartTime,
+ setEndTime,
endpointParams,
setEndpointParam,
pathParams,
@@ -72,7 +77,7 @@ export function ParameterControls() {
}
setIsLoading(true);
- const startTime = performance.now();
+ const requestStartTime = performance.now();
try {
// Build the path
@@ -87,20 +92,7 @@ export function ParameterControls() {
const queryParams: Record<string, any> = {};
if (selectedEndpoint.hasCommonParams) {
- queryParams.start_date = startDate;
- queryParams.end_date = endDate;
- queryParams.time_zone = timeZone;
-
- const apiFilters = filters
- .filter(f => f.value.trim() !== "")
- .map(f => ({
- parameter: f.parameter,
- type: f.operator,
- value: [f.value],
- }));
- if (apiFilters.length > 0) {
- queryParams.filters = JSON.stringify(apiFilters);
- }
+ Object.assign(queryParams, buildCommonQueryParams({ startDate, endDate, startTime, endTime, timeZone, filters }));
}
// Add endpoint-specific params
@@ -124,8 +116,8 @@ export function ParameterControls() {
: undefined
);
- const endTime = performance.now();
- setResponse(result, Math.round(endTime - startTime));
+ const requestEndTime = performance.now();
+ setResponse(result, Math.round(requestEndTime - requestStartTime));
} catch (err: any) {
setResponseError(err.message || t("Request failed"));
}
@@ -254,6 +246,28 @@ export function ParameterControls() {
<Input type="date" value={endDate} onChange={e => setEndDate(e.target.value)} className="h-8 text-xs" />
</div>
</div>
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">{t("Start Time")}</label>
+ <Input
+ type="time"
+ step={1}
+ value={startTime}
+ onChange={e => setStartTime(e.target.value)}
+ className="h-8 text-xs"
+ />
+ </div>
+ <div className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">{t("End Time")}</label>
+ <Input
+ type="time"
+ step={1}
+ value={endTime}
+ onChange={e => setEndTime(e.target.value)}
+ className="h-8 text-xs"
+ />
+ </div>
+ </div>
<TimezoneSelect />
<FilterBuilder />
</div>
diff --git a/client/src/app/[site]/api-playground/components/ResponsePanel.tsx b/client/src/app/[site]/api-playground/components/ResponsePanel.tsx
index ed6a8b513..544e54a2c 100644
--- a/client/src/app/[site]/api-playground/components/ResponsePanel.tsx
+++ b/client/src/app/[site]/api-playground/components/ResponsePanel.tsx
@@ -7,6 +7,7 @@ import { useParams } from "next/navigation";
import { useMemo } from "react";
import { usePlaygroundStore } from "../hooks/usePlaygroundStore";
import { CodeGenConfig } from "../utils/codeGenerators";
+import { buildCommonQueryParams } from "../utils/queryParams";
import { CodeExamples } from "./CodeExamples";
import { BACKEND_URL } from "../../../../lib/const";
@@ -19,6 +20,8 @@ export function ResponsePanel() {
selectedEndpoint,
startDate,
endDate,
+ startTime,
+ endTime,
timeZone,
filters,
endpointParams,
@@ -39,21 +42,7 @@ export function ResponsePanel() {
const qp: Record<string, any> = {};
if (selectedEndpoint.hasCommonParams) {
- qp.start_date = startDate;
- qp.end_date = endDate;
- qp.time_zone = timeZone;
-
- // Convert filters to API format inline
- const apiFilters = filters
- .filter(f => f.value.trim() !== "")
- .map(f => ({
- parameter: f.parameter,
- type: f.operator,
- value: [f.value],
- }));
- if (apiFilters.length > 0) {
- qp.filters = JSON.stringify(apiFilters);
- }
+ Object.assign(qp, buildCommonQueryParams({ startDate, endDate, startTime, endTime, timeZone, filters }));
}
// Add endpoint-specific params
@@ -76,7 +65,7 @@ export function ResponsePanel() {
}
return { queryParams: qp, parsedBody: body };
- }, [selectedEndpoint, startDate, endDate, timeZone, filters, endpointParams, requestBody]);
+ }, [selectedEndpoint, startDate, endDate, startTime, endTime, timeZone, filters, endpointParams, requestBody]);
// Code generation config
const codeConfig: CodeGenConfig = useMemo(() => {
diff --git a/client/src/app/[site]/api-playground/hooks/usePlaygroundStore.ts b/client/src/app/[site]/api-playground/hooks/usePlaygroundStore.ts
index 98738c7c0..6349ebd57 100644
--- a/client/src/app/[site]/api-playground/hooks/usePlaygroundStore.ts
+++ b/client/src/app/[site]/api-playground/hooks/usePlaygroundStore.ts
@@ -17,9 +17,13 @@ interface PlaygroundState {
// Common parameters (independent from store.ts)
startDate: string;
endDate: string;
+ startTime: string;
+ endTime: string;
timeZone: string;
setStartDate: (date: string) => void;
setEndDate: (date: string) => void;
+ setStartTime: (time: string) => void;
+ setEndTime: (time: string) => void;
setTimeZone: (tz: string) => void;
// Filters
@@ -90,9 +94,13 @@ export const usePlaygroundStore = create<PlaygroundState>((set, get) => ({
// Common parameters
startDate: getToday(),
endDate: getToday(),
+ startTime: "",
+ endTime: "",
timeZone: getDefaultTimezone(),
setStartDate: (date) => set({ startDate: date }),
setEndDate: (date) => set({ endDate: date }),
+ setStartTime: (time) => set({ startTime: time }),
+ setEndTime: (time) => set({ endTime: time }),
setTimeZone: (tz) => set({ timeZone: tz }),
// Filters
@@ -173,6 +181,8 @@ export const usePlaygroundStore = create<PlaygroundState>((set, get) => ({
selectedEndpoint: null,
startDate: getToday(),
endDate: getToday(),
+ startTime: "",
+ endTime: "",
timeZone: getDefaultTimezone(),
filters: [],
endpointParams: {},
diff --git a/client/src/app/[site]/api-playground/utils/queryParams.ts b/client/src/app/[site]/api-playground/utils/queryParams.ts
new file mode 100644
index 000000000..afbbe0452
--- /dev/null
+++ b/client/src/app/[site]/api-playground/utils/queryParams.ts
@@ -0,0 +1,57 @@
+import { DateTime } from "luxon";
+
+type PlaygroundFilter = {
+ parameter: string;
+ operator: string;
+ value: string;
+};
+
+type CommonQueryParamInput = {
+ startDate: string;
+ endDate: string;
+ startTime: string;
+ endTime: string;
+ timeZone: string;
+ filters: PlaygroundFilter[];
+};
+
+const toUtcDateTimeParam = (date: string, time: string, timeZone: string) =>
+ DateTime.fromISO(`${date}T${time}`, { zone: timeZone })
+ .toUTC()
+ .toFormat("yyyy-MM-dd HH:mm:ss");
+
+export const buildCommonQueryParams = ({
+ startDate,
+ endDate,
+ startTime,
+ endTime,
+ timeZone,
+ filters,
+}: CommonQueryParamInput): Record<string, any> => {
+ const queryParams: Record<string, any> =
+ startTime && endTime
+ ? {
+ start_datetime: toUtcDateTimeParam(startDate, startTime, timeZone),
+ end_datetime: toUtcDateTimeParam(endDate, endTime, timeZone),
+ time_zone: timeZone,
+ }
+ : {
+ start_date: startDate,
+ end_date: endDate,
+ time_zone: timeZone,
+ };
+
+ const apiFilters = filters
+ .filter(f => f.value.trim() !== "")
+ .map(f => ({
+ parameter: f.parameter,
+ type: f.operator,
+ value: [f.value],
+ }));
+
+ if (apiFilters.length > 0) {
+ queryParams.filters = JSON.stringify(apiFilters);
+ }
+
+ return queryParams;
+};
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index a667732b3..7115769d9 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -53,6 +53,49 @@ const stepBucket = (
}
};
+const floorToBucket = (dt: DateTime, bucket: TimeBucket): DateTime => {
+ switch (bucket) {
+ case "minute":
+ return dt.startOf("minute");
+ case "five_minutes":
+ return dt.set({
+ minute: Math.floor(dt.minute / 5) * 5,
+ second: 0,
+ millisecond: 0,
+ });
+ case "ten_minutes":
+ return dt.set({
+ minute: Math.floor(dt.minute / 10) * 10,
+ second: 0,
+ millisecond: 0,
+ });
+ case "fifteen_minutes":
+ return dt.set({
+ minute: Math.floor(dt.minute / 15) * 15,
+ second: 0,
+ millisecond: 0,
+ });
+ case "hour":
+ return dt.startOf("hour");
+ case "day":
+ return dt.startOf("day");
+ case "week":
+ return dt.startOf("week");
+ case "month":
+ return dt.startOf("month");
+ case "year":
+ return dt.startOf("year");
+ }
+};
+
+const canDragSelectBucket = (bucket: TimeBucket) =>
+ bucket === "minute" ||
+ bucket === "five_minutes" ||
+ bucket === "ten_minutes" ||
+ bucket === "fifteen_minutes" ||
+ bucket === "hour" ||
+ bucket === "day";
+
type Point = {
x: Date;
y: number;
@@ -78,7 +121,9 @@ const formatTooltipValue = (value: number, selectedStat: StatType): string => {
const formatXTick = (
date: Date,
mode: Time["mode"],
- pastMinutesStart: number | undefined
+ bucket: TimeBucket,
+ pastMinutesStart: number | undefined,
+ isExactRange: boolean
) => {
const dt = DateTime.fromJSDate(date, { zone: "utc" })
.setZone(getTimezone())
@@ -89,7 +134,15 @@ const formatXTick = (
}
return dt.toFormat(hour12 ? "ha" : "HH:mm");
}
- if (mode === "day") {
+ if (
+ mode === "day" ||
+ (isExactRange &&
+ (bucket === "minute" ||
+ bucket === "five_minutes" ||
+ bucket === "ten_minutes" ||
+ bucket === "fifteen_minutes" ||
+ bucket === "hour"))
+ ) {
return dt.toFormat(hour12 ? "ha" : "HH:mm");
}
return dt.toFormat(hour12 ? "MMM d" : "dd MMM");
@@ -110,6 +163,7 @@ export function Chart({
const { resolvedTheme } = useTheme();
const isDark = resolvedTheme === "dark";
const timezone = getTimezone();
+ const isExactRange = time.mode === "range" && Boolean(time.startTime && time.endTime);
const clipId = useId().replace(/:/g, "");
const wrapperRef = useRef<HTMLDivElement>(null);
@@ -193,6 +247,7 @@ export function Chart({
const currentMonthStr = DateTime.now().toFormat("yyyy-MM-01");
const shouldNotDisplay =
time.mode === "all-time" ||
+ isExactRange ||
time.mode === "year" ||
(time.mode === "month" && time.month !== currentMonthStr) ||
(time.mode === "day" && time.day !== currentDayStr) ||
@@ -219,6 +274,7 @@ export function Chart({
bucket,
timezone,
chartXMax,
+ isExactRange,
]);
const W = size.width;
@@ -389,10 +445,9 @@ export function Chart({
const handleMouseLeave = () => setHover(null);
- // Drag-to-select range. Day bucket only for now; other buckets would need
- // to also pick the bucket on commit (e.g. switching to week if the selection
- // is > 31 days) and that's out of scope here.
- const dragEnabled = bucket === "day";
+ // Drag-to-select range. Day buckets keep using date ranges; sub-day buckets
+ // commit an exact half-open datetime range [start, end).
+ const dragEnabled = canDragSelectBucket(bucket);
const [dragRaw, setDragRaw] = useState<{
startX: number;
currentX: number;
@@ -400,41 +455,36 @@ export function Chart({
} | null>(null);
// Snap drag positions the same way hover does: to the nearest visible
- // current bucket. Flooring the raw timestamp makes clicks just left of a
- // daily bucket commit the previous day, even while the crosshair shows the
- // intended bucket.
- const pxToDay = useCallback(
+ // current bucket, so the committed selection matches the crosshair.
+ const pxToBucketStart = useCallback(
(px: number) => {
const xDate = xScale.invert(px);
const point = current[bisectCurrent(current, xDate)];
if (point) {
- return DateTime.fromJSDate(point.x, { zone: "utc" })
- .setZone(timezone)
- .startOf("day");
+ return DateTime.fromJSDate(point.x, { zone: "utc" }).setZone(timezone);
}
- return DateTime.fromMillis(xDate.getTime() + 1000, { zone: "utc" })
- .setZone(timezone)
- .startOf("day");
+ return floorToBucket(
+ DateTime.fromMillis(xDate.getTime(), { zone: "utc" }).setZone(timezone),
+ bucket
+ );
},
- [bisectCurrent, current, timezone, xScale]
+ [bisectCurrent, bucket, current, timezone, xScale]
);
const dragSnapped = useMemo(() => {
if (!dragRaw) return null;
const leftPx = Math.min(dragRaw.startX, dragRaw.currentX);
const rightPx = Math.max(dragRaw.startX, dragRaw.currentX);
- const leftDay = pxToDay(leftPx);
- const rightDay = pxToDay(rightPx);
+ const leftBucket = pxToBucketStart(leftPx);
+ const rightBucket = pxToBucketStart(rightPx);
return {
- leftPx: xScale(leftDay.toUTC().toJSDate()),
- rightPx: xScale(rightDay.toUTC().toJSDate()),
- startDate: leftDay.toISODate(),
- endDate: rightDay.toISODate(),
+ leftPx: xScale(leftBucket.toUTC().toJSDate()),
+ rightPx: xScale(rightBucket.toUTC().toJSDate()),
};
- }, [dragRaw, pxToDay, xScale]);
+ }, [dragRaw, pxToBucketStart, xScale]);
const handleMouseDown = (e: React.MouseEvent<SVGRectElement>) => {
- if (!dragEnabled) return;
+ if (!dragEnabled || !current.length) return;
e.preventDefault();
const rect = e.currentTarget.getBoundingClientRect();
const startX = Math.max(
@@ -467,12 +517,33 @@ export function Chart({
if (!moved) return;
const leftPx = Math.min(startX, currentX);
const rightPx = Math.max(startX, currentX);
- const startDate = pxToDay(leftPx).toISODate();
- const endDate = pxToDay(rightPx).toISODate();
- if (startDate && endDate) {
+ const startBucket = pxToBucketStart(leftPx);
+ const endBucket = pxToBucketStart(rightPx);
+
+ if (bucket === "day") {
+ const startDate = startBucket.toISODate();
+ const endDate = endBucket.toISODate();
+ if (!startDate || !endDate) return;
// Pass changeBucket=false so dragging within e.g. an all-time/day
// view doesn't auto-switch to week/month for shorter ranges.
setTime({ mode: "range", startDate, endDate }, false);
+ return;
+ }
+
+ const endExclusive = stepBucket(endBucket, bucket, 1);
+ const startDate = startBucket.toISODate();
+ const endDate = endExclusive.toISODate();
+ if (startDate && endDate) {
+ setTime(
+ {
+ mode: "range",
+ startDate,
+ endDate,
+ startTime: startBucket.toFormat("HH:mm:ss"),
+ endTime: endExclusive.toFormat("HH:mm:ss"),
+ },
+ false
+ );
}
};
@@ -632,7 +703,11 @@ export function Chart({
{formatXTick(
t,
time.mode,
- time.mode === "past-minutes" ? time.pastMinutesStart : undefined
+ bucket,
+ time.mode === "past-minutes"
+ ? time.pastMinutesStart
+ : undefined,
+ isExactRange
)}
</text>
</g>
@@ -687,7 +762,7 @@ export function Chart({
/>
)}
- {/* Drag-to-select range overlay — snapped to whole-day boundaries. */}
+ {/* Drag-to-select range overlay - snapped to bucket boundaries. */}
{dragSnapped && dragRaw?.moved && (
<g pointerEvents="none">
<rect
diff --git a/client/src/app/[site]/main/components/MainSection/chartTimeBounds.ts b/client/src/app/[site]/main/components/MainSection/chartTimeBounds.ts
index b9414bbaf..de6d0b5e4 100644
--- a/client/src/app/[site]/main/components/MainSection/chartTimeBounds.ts
+++ b/client/src/app/[site]/main/components/MainSection/chartTimeBounds.ts
@@ -17,6 +17,30 @@ const bucketEndOffsetMinutes = (bucket: TimeBucket): number => {
}
};
+const stepBucket = (dt: DateTime, bucket: TimeBucket, direction: 1 | -1): DateTime => {
+ const n = direction;
+ switch (bucket) {
+ case "minute":
+ return dt.plus({ minutes: n });
+ case "five_minutes":
+ return dt.plus({ minutes: 5 * n });
+ case "ten_minutes":
+ return dt.plus({ minutes: 10 * n });
+ case "fifteen_minutes":
+ return dt.plus({ minutes: 15 * n });
+ case "hour":
+ return dt.plus({ hours: n });
+ case "day":
+ return dt.plus({ days: n });
+ case "week":
+ return dt.plus({ weeks: n });
+ case "month":
+ return dt.plus({ months: n });
+ case "year":
+ return dt.plus({ years: n });
+ }
+};
+
export type ChartTimeBounds = { min: Date | undefined; max: Date | undefined };
// Returns full-period x-scale bounds so the current and previous charts share
@@ -79,6 +103,16 @@ export const getChartTimeBounds = (
}
if (time.mode === "range") {
+ if (time.startTime && time.endTime) {
+ const start = DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone: timezone });
+ const endExclusive = DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timezone });
+ const displayEnd = stepBucket(endExclusive, bucket, -1);
+ return {
+ min: start.toJSDate(),
+ max: (displayEnd > start ? displayEnd : endExclusive).toJSDate(),
+ };
+ }
+
return {
min: DateTime.fromISO(time.startDate, { zone: timezone }).startOf("day").toJSDate(),
max: DateTime.fromISO(time.endDate, { zone: timezone })
diff --git a/client/src/components/BucketSelection.tsx b/client/src/components/BucketSelection.tsx
index 017ea82b4..62c4bfc6a 100644
--- a/client/src/components/BucketSelection.tsx
+++ b/client/src/components/BucketSelection.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useStore } from "@/lib/store";
+import { getTimezone, useStore } from "@/lib/store";
import { SelectItem, Select, SelectContent, SelectTrigger, SelectValue } from "@/components/ui/select";
import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
@@ -116,10 +116,29 @@ export function BucketSelection() {
}
if (time.mode === "range") {
- const timeRangeLength = DateTime.fromISO(time.endDate).diff(DateTime.fromISO(time.startDate), "days").days + 1;
+ const exactRange = Boolean(time.startTime && time.endTime);
+ const timezone = getTimezone();
+ const exactRangeMinutes = exactRange
+ ? DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timezone }).diff(
+ DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone: timezone }),
+ "minutes"
+ ).minutes
+ : undefined;
+ const timeRangeLength =
+ exactRangeMinutes !== undefined
+ ? exactRangeMinutes / 1440
+ : DateTime.fromISO(time.endDate, { zone: timezone }).diff(
+ DateTime.fromISO(time.startDate, { zone: timezone }),
+ "days"
+ ).days + 1;
return (
<SelectContent>
+ {exactRangeMinutes !== undefined && timeRangeLength <= 1 && (
+ <SelectItem size="sm" value="minute">
+ {t("Min")}
+ </SelectItem>
+ )}
{timeRangeLength <= 7 && (
<SelectItem size="sm" value="five_minutes">
{t("5 Min")}
diff --git a/client/src/components/DateSelector/DateSelector.tsx b/client/src/components/DateSelector/DateSelector.tsx
index 1f4700dd6..7132c8659 100644
--- a/client/src/components/DateSelector/DateSelector.tsx
+++ b/client/src/components/DateSelector/DateSelector.tsx
@@ -10,7 +10,7 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { getTimezoneLabel, timezones } from "@/lib/dateTimeUtils";
+import { getTimezoneLabel, hour12, timezones } from "@/lib/dateTimeUtils";
import { getTimezone, useStore } from "@/lib/store";
import { cn } from "@/lib/utils";
import { Calendar } from "lucide-react";
@@ -18,6 +18,31 @@ import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
import { CustomDateRangePicker } from "./CustomDateRangePicker";
import { Time } from "./types";
+import { TimeBucket } from "@rybbit/shared";
+
+const stepDateTimeBucket = (dt: DateTime, bucket: TimeBucket, direction: 1 | -1): DateTime => {
+ const n = direction;
+ switch (bucket) {
+ case "minute":
+ return dt.plus({ minutes: n });
+ case "five_minutes":
+ return dt.plus({ minutes: 5 * n });
+ case "ten_minutes":
+ return dt.plus({ minutes: 10 * n });
+ case "fifteen_minutes":
+ return dt.plus({ minutes: 15 * n });
+ case "hour":
+ return dt.plus({ hours: n });
+ case "day":
+ return dt.plus({ days: n });
+ case "week":
+ return dt.plus({ weeks: n });
+ case "month":
+ return dt.plus({ months: n });
+ case "year":
+ return dt.plus({ years: n });
+ }
+};
export function DateSelector({
time,
@@ -28,7 +53,7 @@ export function DateSelector({
setTime: (time: Time) => void;
pastMinutesEnabled?: boolean;
}) {
- const { timezone, setTimezone } = useStore();
+ const { timezone, setTimezone, bucket } = useStore();
const t = useExtracted();
const getWellKnownLabel = (wellKnown: string): string => {
@@ -63,6 +88,17 @@ export function DateSelector({
const now = DateTime.now().setZone(tz);
if (time.mode === "range") {
+ if (time.startTime && time.endTime) {
+ const start = DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone: tz });
+ const endExclusive = DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: tz });
+ const displayEnd = stepDateTimeBucket(endExclusive, bucket, -1);
+ const startFormatted = start.toFormat(hour12 ? "MMM d, h:mm a" : "MMM d, HH:mm");
+ const endFormatted = (displayEnd > start ? displayEnd : endExclusive).toFormat(
+ hour12 ? "MMM d, h:mm a" : "MMM d, HH:mm"
+ );
+ return `${startFormatted} - ${endFormatted}`;
+ }
+
const startFormatted = DateTime.fromISO(time.startDate).toFormat("EEEE, MMM d");
const endFormatted = DateTime.fromISO(time.endDate).toFormat("EEEE, MMM d");
return `${startFormatted} - ${endFormatted}`;
diff --git a/client/src/components/DateSelector/types.ts b/client/src/components/DateSelector/types.ts
index 75e9d77c0..e56a1d08a 100644
--- a/client/src/components/DateSelector/types.ts
+++ b/client/src/components/DateSelector/types.ts
@@ -4,13 +4,26 @@ export type DateMode = {
wellKnown?: "today" | "yesterday";
};
-export type DateRangeMode = {
+export type DateOnlyRangeMode = {
mode: "range";
startDate: string;
endDate: string;
+ startTime?: never;
+ endTime?: never;
wellKnown?: "last-3-days" | "last-7-days" | "last-14-days" | "last-30-days" | "last-60-days";
};
+export type DateTimeRangeMode = {
+ mode: "range";
+ startDate: string;
+ endDate: string;
+ startTime: string;
+ endTime: string;
+ wellKnown?: never;
+};
+
+export type DateRangeMode = DateOnlyRangeMode | DateTimeRangeMode;
+
export type WeekMode = {
mode: "week";
week: string;
@@ -41,4 +54,11 @@ export type PastMinutesMode = {
wellKnown?: "last-30-minutes" | "last-1-hour" | "last-6-hours" | "last-24-hours";
};
-export type Time = DateMode | DateRangeMode | WeekMode | MonthMode | YearMode | AllTimeMode | PastMinutesMode;
+export type Time =
+ | DateMode
+ | DateRangeMode
+ | WeekMode
+ | MonthMode
+ | YearMode
+ | AllTimeMode
+ | PastMinutesMode;
diff --git a/client/src/lib/parsers.ts b/client/src/lib/parsers.ts
index cad2fd193..07bdad7dc 100644
--- a/client/src/lib/parsers.ts
+++ b/client/src/lib/parsers.ts
@@ -75,8 +75,8 @@ export const parseAsWellKnown = parseAsStringEnum(wellKnownValues);
export const parseAsIsoDate = parseAsString;
// JSON parsers for complex types
-export const parseAsFilters = parseAsJson<Filter[]>((value) => value as Filter[]);
-export const parseAsStringArray = parseAsJson<string[]>((value) => value as string[]);
+export const parseAsFilters = parseAsJson<Filter[]>(value => value as Filter[]);
+export const parseAsStringArray = parseAsJson<string[]>(value => value as string[]);
// GSC status parser (for OAuth callback)
export const parseAsGscStatus = parseAsString;
@@ -102,6 +102,10 @@ export const analyticsParsers = {
day: parseAsIsoDate,
startDate: parseAsIsoDate,
endDate: parseAsIsoDate,
+ startTime: parseAsOptionalString,
+ endTime: parseAsOptionalString,
+ startDateTime: parseAsOptionalString,
+ endDateTime: parseAsOptionalString,
week: parseAsIsoDate,
month: parseAsIsoDate,
year: parseAsIsoDate,
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index b8c517adf..613785175 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -101,6 +101,38 @@ const recalculateTimeForTimezone = (time: Time, timezone: string): Time | null =
export type StatType = "pageviews" | "sessions" | "users" | "pages_per_session" | "bounce_rate" | "session_duration";
+type RangeWithTimes = Extract<Time, { mode: "range" }> & { startTime: string; endTime: string };
+
+const hasRangeTimes = (time: Time): time is RangeWithTimes =>
+ time.mode === "range" && typeof time.startTime === "string" && typeof time.endTime === "string";
+
+const getRangeDateTimeBounds = (time: RangeWithTimes) => {
+ const zone = getTimezone();
+ return {
+ start: DateTime.fromISO(`${time.startDate}T${time.startTime}`, { zone }),
+ end: DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone }),
+ };
+};
+
+const toRangeWithTimes = (start: DateTime, end: DateTime): RangeWithTimes => ({
+ mode: "range",
+ startDate: start.toISODate() ?? "",
+ startTime: start.toFormat("HH:mm:ss"),
+ endDate: end.toISODate() ?? "",
+ endTime: end.toFormat("HH:mm:ss"),
+});
+
+const getBucketForDateTimeRange = (start: DateTime, end: DateTime): TimeBucket => {
+ const minutes = end.diff(start, "minutes").minutes;
+
+ if (minutes <= 120) return "minute";
+ if (minutes <= 1440) return "five_minutes";
+ if (minutes <= 14 * 1440) return "hour";
+ if (minutes <= 60 * 1440) return "day";
+ if (minutes <= 180 * 1440) return "week";
+ return "month";
+};
+
type Store = {
site: string;
setSite: (site: string) => void;
@@ -191,22 +223,30 @@ export const useStore = create<Store>()(
pastMinutesEnd: time.pastMinutesEnd + timeDiff,
};
} else if (time.mode === "range") {
- const timeRangeLength =
- DateTime.fromISO(time.endDate).diff(DateTime.fromISO(time.startDate), "days").days + 1;
+ if (hasRangeTimes(time)) {
+ const { start, end } = getRangeDateTimeBounds(time);
+ const duration = end.diff(start);
+ bucketToUse = getBucketForDateTimeRange(start, end);
- if (timeRangeLength > 180) {
- bucketToUse = "month";
- } else if (timeRangeLength > 31) {
- bucketToUse = "week";
+ previousTime = toRangeWithTimes(start.minus(duration), end.minus(duration));
} else {
- bucketToUse = "day";
+ const timeRangeLength =
+ DateTime.fromISO(time.endDate).diff(DateTime.fromISO(time.startDate), "days").days + 1;
+
+ if (timeRangeLength > 180) {
+ bucketToUse = "month";
+ } else if (timeRangeLength > 31) {
+ bucketToUse = "week";
+ } else {
+ bucketToUse = "day";
+ }
+
+ previousTime = {
+ mode: "range",
+ startDate: DateTime.fromISO(time.startDate).minus({ days: timeRangeLength }).toISODate() ?? "",
+ endDate: DateTime.fromISO(time.startDate).minus({ days: 1 }).toISODate() ?? "",
+ };
}
-
- previousTime = {
- mode: "range",
- startDate: DateTime.fromISO(time.startDate).minus({ days: timeRangeLength }).toISODate() ?? "",
- endDate: DateTime.fromISO(time.startDate).minus({ days: 1 }).toISODate() ?? "",
- };
} else if (time.mode === "week") {
bucketToUse = "day";
previousTime = {
@@ -301,6 +341,14 @@ export const goBack = () => {
false
);
} else if (time.mode === "range") {
+ if (hasRangeTimes(time)) {
+ const { start, end } = getRangeDateTimeBounds(time);
+ const duration = end.diff(start);
+
+ setTime(toRangeWithTimes(start.minus(duration), end.minus(duration)), false);
+ return;
+ }
+
const startDate = DateTime.fromISO(time.startDate);
const endDate = DateTime.fromISO(time.endDate);
@@ -350,6 +398,21 @@ export const goForward = () => {
day: DateTime.fromISO(time.day).plus({ days: 1 }).toISODate() ?? "",
});
} else if (time.mode === "range") {
+ if (hasRangeTimes(time)) {
+ const { start, end } = getRangeDateTimeBounds(time);
+ const duration = end.diff(start);
+ const proposedStart = start.plus(duration);
+ const proposedEnd = end.plus(duration);
+ const now = DateTime.now().setZone(getTimezone());
+
+ if (proposedStart > now) {
+ return;
+ }
+
+ setTime(toRangeWithTimes(proposedStart, proposedEnd > now ? now : proposedEnd), false);
+ return;
+ }
+
const startDate = DateTime.fromISO(time.startDate);
const endDate = DateTime.fromISO(time.endDate);
const now = DateTime.now();
@@ -433,6 +496,10 @@ export const canGoForward = (time: Time) => {
}
if (time.mode === "range") {
+ if (hasRangeTimes(time)) {
+ return !(getRangeDateTimeBounds(time).end >= DateTime.now().setZone(getTimezone()));
+ }
+
return !(DateTime.fromISO(time.endDate).startOf("day") >= currentDay);
}
diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.ts
index 8a8440991..e3b9aed0c 100644
--- a/client/src/lib/urlParams.ts
+++ b/client/src/lib/urlParams.ts
@@ -179,7 +179,16 @@ export const useSyncStateWithUrl = () => {
if (urlParams.timeMode === "day" && urlParams.day) {
timeFromUrl = { mode: "day", day: urlParams.day };
} else if (urlParams.timeMode === "range" && urlParams.startDate && urlParams.endDate) {
- timeFromUrl = { mode: "range", startDate: urlParams.startDate, endDate: urlParams.endDate };
+ timeFromUrl =
+ urlParams.startTime && urlParams.endTime
+ ? {
+ mode: "range",
+ startDate: urlParams.startDate,
+ endDate: urlParams.endDate,
+ startTime: urlParams.startTime,
+ endTime: urlParams.endTime,
+ }
+ : { mode: "range", startDate: urlParams.startDate, endDate: urlParams.endDate };
} else if (urlParams.timeMode === "week" && urlParams.week) {
timeFromUrl = { mode: "week", week: urlParams.week };
} else if (urlParams.timeMode === "month" && urlParams.month) {
@@ -246,6 +255,10 @@ export const useSyncStateWithUrl = () => {
newParams.day = null;
newParams.startDate = null;
newParams.endDate = null;
+ newParams.startTime = null;
+ newParams.endTime = null;
+ newParams.startDateTime = null;
+ newParams.endDateTime = null;
newParams.week = null;
newParams.month = null;
newParams.year = null;
@@ -253,12 +266,26 @@ export const useSyncStateWithUrl = () => {
newParams.past_minutes_end = null;
} else {
newParams.wellKnown = null;
+ newParams.day = null;
+ newParams.startDate = null;
+ newParams.endDate = null;
+ newParams.startTime = null;
+ newParams.endTime = null;
+ newParams.startDateTime = null;
+ newParams.endDateTime = null;
+ newParams.week = null;
+ newParams.month = null;
+ newParams.year = null;
+ newParams.past_minutes_start = null;
+ newParams.past_minutes_end = null;
// Store explicit date fields based on mode
if (time.mode === "day" && "day" in time) {
newParams.day = time.day;
} else if (time.mode === "range" && "startDate" in time && "endDate" in time) {
newParams.startDate = time.startDate;
newParams.endDate = time.endDate;
+ newParams.startTime = time.startTime ?? null;
+ newParams.endTime = time.endTime ?? null;
} else if (time.mode === "week" && "week" in time) {
newParams.week = time.week;
} else if (time.mode === "month" && "month" in time) {
diff --git a/docs/content/docs/api/getting-started.mdx b/docs/content/docs/api/getting-started.mdx
index ee10faba3..fda3f1ad6 100644
--- a/docs/content/docs/api/getting-started.mdx
+++ b/docs/content/docs/api/getting-started.mdx
@@ -18,6 +18,7 @@ The easiest way to explore and test the API is using the built-in **API Playgrou
The playground provides:
- **Endpoint browser** - Browse all available API endpoints
- **Parameter controls** - Configure request parameters with a visual interface
+- **Exact time ranges** - Test date ranges with optional start and end times
- **Live responses** - See real API responses with your actual data
- **Code generation** - Copy ready-to-use code snippets
@@ -75,7 +76,7 @@ The following parameters are shared across all analytics endpoints.
### Time Parameters
-All endpoints require either date-based or relative time parameters:
+All endpoints require date-based, exact datetime, or relative time parameters:
<TypeTable
type={{
@@ -94,7 +95,19 @@ All endpoints require either date-based or relative time parameters:
time_zone: {
description: 'IANA timezone identifier',
type: 'string',
- typeDescription: 'e.g., "America/New_York", "Europe/London", "Asia/Tokyo"',
+ typeDescription: 'e.g., "America/New_York", "Europe/London", "Asia/Tokyo". Required with date and exact datetime ranges.',
+ required: false,
+ },
+ start_datetime: {
+ description: 'Exact UTC start timestamp for the query period',
+ type: 'string',
+ typeDescription: 'Format: YYYY-MM-DD HH:mm:ss (e.g., "2024-01-15 13:00:00")',
+ required: false,
+ },
+ end_datetime: {
+ description: 'Exact UTC end timestamp for the query period. This boundary is exclusive.',
+ type: 'string',
+ typeDescription: 'Format: YYYY-MM-DD HH:mm:ss (e.g., "2024-01-15 15:00:00")',
required: false,
},
past_minutes_start: {
@@ -114,6 +127,7 @@ All endpoints require either date-based or relative time parameters:
**Note:** You must provide either:
- All three date parameters (`start_date`, `end_date`, `time_zone`), OR
+- All three exact datetime parameters (`start_datetime`, `end_datetime`, `time_zone`), OR
- Both relative parameters (`past_minutes_start`, `past_minutes_end`)
#### Examples
@@ -123,6 +137,11 @@ All endpoints require either date-based or relative time parameters:
?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York
```
+**Exact datetime query (8 AM to 10 AM in New York on Jan 15, sent as UTC):**
+```
+?start_datetime=2024-01-15%2013:00:00&end_datetime=2024-01-15%2015:00:00&time_zone=America/New_York
+```
+
**Relative query (last 60 minutes):**
```
?past_minutes_start=60&past_minutes_end=0
diff --git a/server/src/api/analytics/getErrorBucketed.ts b/server/src/api/analytics/getErrorBucketed.ts
index e18a9871f..4ed7029b5 100644
--- a/server/src/api/analytics/getErrorBucketed.ts
+++ b/server/src/api/analytics/getErrorBucketed.ts
@@ -23,6 +23,16 @@ function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
)})) + INTERVAL 1 DAY
) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
}
+ if (validatedParams.start_datetime && validatedParams.end_datetime && validatedParams.time_zone) {
+ const { start_datetime, end_datetime, time_zone } = validatedParams;
+ return `WITH FILL FROM ${TimeBucketToFn[validatedBucket]}(
+ toTimeZone(toDateTime(${SqlString.escape(start_datetime)}, 'UTC'), ${SqlString.escape(time_zone)})
+ )
+ TO ${TimeBucketToFn[validatedBucket]}(
+ toTimeZone(toDateTime(${SqlString.escape(end_datetime)}, 'UTC'), ${SqlString.escape(time_zone)})
+ )
+ STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
+ }
// For specific past minutes range - convert to exact timestamps for better performance
if (validatedParams.past_minutes_start !== undefined && validatedParams.past_minutes_end !== undefined) {
return `WITH FILL FROM now() - INTERVAL ${validatedParams.past_minutes_start} MINUTE
diff --git a/server/src/api/analytics/getOverview.ts b/server/src/api/analytics/getOverview.ts
index 033bc3fac..fbd47a855 100644
--- a/server/src/api/analytics/getOverview.ts
+++ b/server/src/api/analytics/getOverview.ts
@@ -62,7 +62,16 @@ export interface OverviewRequest {
}
export async function getOverview(req: FastifyRequest<OverviewRequest>, res: FastifyReply) {
- const { start_date, end_date, time_zone, filters, past_minutes_start, past_minutes_end } = req.query;
+ const {
+ start_date,
+ end_date,
+ time_zone,
+ filters,
+ start_datetime,
+ end_datetime,
+ past_minutes_start,
+ past_minutes_end,
+ } = req.query;
const site = req.params.siteId;
const query = getQuery(
@@ -71,6 +80,8 @@ export async function getOverview(req: FastifyRequest<OverviewRequest>, res: Fas
end_date,
time_zone,
filters,
+ start_datetime,
+ end_datetime,
past_minutes_start,
past_minutes_end,
},
diff --git a/server/src/api/analytics/getOverviewBucketed.ts b/server/src/api/analytics/getOverviewBucketed.ts
index d33c2ec60..a6af38ef9 100644
--- a/server/src/api/analytics/getOverviewBucketed.ts
+++ b/server/src/api/analytics/getOverviewBucketed.ts
@@ -3,7 +3,13 @@ import { FastifyReply, FastifyRequest } from "fastify";
import SqlString from "sqlstring";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { validateTimeStatementFillParams } from "./utils/query-validation.js";
-import { getTimeStatement, processResults, TimeBucketToFn, bucketIntervalMap } from "./utils/utils.js";
+import {
+ getTimeStatement,
+ normalizeDatetimeForClickhouse,
+ processResults,
+ TimeBucketToFn,
+ bucketIntervalMap,
+} from "./utils/utils.js";
import { getFilterStatement } from "./utils/getFilterStatement.js";
import { TimeBucket } from "./types.js";
@@ -29,6 +35,23 @@ function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
)
) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
}
+ if (validatedParams.start_datetime && validatedParams.end_datetime && validatedParams.time_zone) {
+ const { start_datetime, end_datetime, time_zone } = validatedParams;
+ const normalizedStartDatetime = normalizeDatetimeForClickhouse(start_datetime);
+ const normalizedEndDatetime = normalizeDatetimeForClickhouse(end_datetime);
+ return `WITH FILL FROM toTimeZone(
+ toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
+ normalizedStartDatetime
+ )}, 'UTC'), ${SqlString.escape(time_zone)}))),
+ 'UTC'
+ )
+ TO toTimeZone(
+ toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
+ normalizedEndDatetime
+ )}, 'UTC'), ${SqlString.escape(time_zone)}))),
+ 'UTC'
+ ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
+ }
// For specific past minutes range - convert to exact timestamps for better performance
if (validatedParams.past_minutes_start !== undefined && validatedParams.past_minutes_end !== undefined) {
const { past_minutes_start: start, past_minutes_end: end } = validatedParams;
@@ -67,7 +90,17 @@ function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
}
const getQuery = (params: FilterParams<{ bucket: TimeBucket }>, siteId: number) => {
- const { start_date, end_date, time_zone, bucket = "hour", filters, past_minutes_start, past_minutes_end } = params;
+ const {
+ start_date,
+ end_date,
+ time_zone,
+ bucket = "hour",
+ filters,
+ start_datetime,
+ end_datetime,
+ past_minutes_start,
+ past_minutes_end,
+ } = params;
const timeStatement = getTimeStatement(params);
const filterStatement = getFilterStatement(filters, siteId, timeStatement);
const pastMinutesRange =
@@ -75,7 +108,7 @@ const getQuery = (params: FilterParams<{ bucket: TimeBucket }>, siteId: number)
? { start: Number(past_minutes_start), end: Number(past_minutes_end) }
: undefined;
- const isAllTime = !start_date && !end_date && !pastMinutesRange;
+ const isAllTime = !start_date && !end_date && !start_datetime && !end_datetime && !pastMinutesRange;
const fillClause = isAllTime ? "" : getTimeStatementFill(params, bucket);
const tzEscaped = SqlString.escape(time_zone);
@@ -161,7 +194,17 @@ export async function getOverviewBucketed(
}>,
res: FastifyReply
) {
- const { start_date, end_date, time_zone, bucket, filters, past_minutes_start, past_minutes_end } = req.query;
+ const {
+ start_date,
+ end_date,
+ time_zone,
+ bucket,
+ filters,
+ start_datetime,
+ end_datetime,
+ past_minutes_start,
+ past_minutes_end,
+ } = req.query;
const site = req.params.siteId;
const query = getQuery(
@@ -171,6 +214,8 @@ export async function getOverviewBucketed(
time_zone,
bucket,
filters,
+ start_datetime,
+ end_datetime,
past_minutes_start,
past_minutes_end,
},
diff --git a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts b/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
index 220b72c1c..9704867ed 100644
--- a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
+++ b/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
@@ -29,6 +29,21 @@ function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
)
) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
}
+ if (validatedParams.start_datetime && validatedParams.end_datetime && validatedParams.time_zone) {
+ const { start_datetime, end_datetime, time_zone } = validatedParams;
+ return `WITH FILL FROM toTimeZone(
+ toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
+ start_datetime
+ )}, 'UTC'), ${SqlString.escape(time_zone)}))),
+ 'UTC'
+ )
+ TO toTimeZone(
+ toDateTime(${TimeBucketToFn[validatedBucket]}(toTimeZone(toDateTime(${SqlString.escape(
+ end_datetime
+ )}, 'UTC'), ${SqlString.escape(time_zone)}))),
+ 'UTC'
+ ) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
+ }
// For specific past minutes range - convert to exact timestamps for better performance
if (validatedParams.past_minutes_start !== undefined && validatedParams.past_minutes_end !== undefined) {
const { past_minutes_start: start, past_minutes_end: end } = validatedParams;
@@ -67,11 +82,22 @@ function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
}
const getQuery = (params: FilterParams<{ bucket: TimeBucket }>, siteId: number) => {
- const { start_date, end_date, time_zone, bucket = "hour", filters, past_minutes_start, past_minutes_end } = params;
+ const {
+ start_date,
+ end_date,
+ time_zone,
+ bucket = "hour",
+ filters,
+ start_datetime,
+ end_datetime,
+ past_minutes_start,
+ past_minutes_end,
+ } = params;
const timeStatement = getTimeStatement(params);
const filterStatement = getFilterStatement(filters, siteId, timeStatement);
- const isAllTime = !start_date && !end_date && !past_minutes_start && !past_minutes_end;
+ const isAllTime =
+ !start_date && !end_date && !start_datetime && !end_datetime && !past_minutes_start && !past_minutes_end;
const query = `
SELECT
diff --git a/server/src/api/analytics/utils/query-validation.ts b/server/src/api/analytics/utils/query-validation.ts
index dcea86ecb..e732b08a3 100644
--- a/server/src/api/analytics/utils/query-validation.ts
+++ b/server/src/api/analytics/utils/query-validation.ts
@@ -9,6 +9,13 @@ import { z } from "zod";
* Date validation regex for YYYY-MM-DD format
*/
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
+const dateTimeRegex = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:?\d{2})?$/;
+
+const parseDateTimeMs = (value: string) => {
+ const normalized = value.includes("T") ? value : value.replace(" ", "T");
+ const withZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized) ? normalized : `${normalized}Z`;
+ return Date.parse(withZone);
+};
/**
* Schema for simplified date parameters without table
@@ -45,6 +52,25 @@ const fillDateParamsSchema = z.object({
),
});
+const dateTimeRangeSchema = z
+ .object({
+ start_datetime: z
+ .string()
+ .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
+ .refine(date => !isNaN(parseDateTimeMs(date)), {
+ message: "Invalid datetime value",
+ }),
+ end_datetime: z
+ .string()
+ .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
+ .refine(date => !isNaN(parseDateTimeMs(date)), {
+ message: "Invalid datetime value",
+ }),
+ })
+ .refine(data => parseDateTimeMs(data.start_datetime) < parseDateTimeMs(data.end_datetime), {
+ message: "start_datetime must be before end_datetime",
+ });
+
/**
* Schema for parameters to getTimeStatement() function
* Either date or pastMinutesRange must be provided
@@ -52,6 +78,7 @@ const fillDateParamsSchema = z.object({
const timeStatementParamsSchema = z
.object({
date: fillDateParamsSchema.optional(),
+ dateTimeRange: dateTimeRangeSchema.optional(),
pastMinutesRange: z
.object({
start: z.number().nonnegative(),
@@ -62,12 +89,13 @@ const timeStatementParamsSchema = z
message: "start must be greater than end (start = older, end = newer)",
}),
})
- .refine(data => data.date !== undefined || data.pastMinutesRange !== undefined, {
- message: "Either date or pastMinutesRange must be provided",
+ .refine(data => data.date !== undefined || data.dateTimeRange !== undefined || data.pastMinutesRange !== undefined, {
+ message: "Either date, dateTimeRange, or pastMinutesRange must be provided",
})
// Set default empty objects if schema validation fails
.catch({
date: undefined,
+ dateTimeRange: undefined,
pastMinutesRange: undefined,
});
@@ -107,6 +135,20 @@ const filterParamsTimeStatementFillSchema = z
},
{ message: "Invalid time zone" }
),
+ start_datetime: z
+ .string()
+ .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
+ .optional()
+ .refine(date => !date || !isNaN(parseDateTimeMs(date)), {
+ message: "Invalid datetime value",
+ }),
+ end_datetime: z
+ .string()
+ .regex(dateTimeRegex, { message: "Invalid datetime format. Use YYYY-MM-DD HH:mm:ss" })
+ .optional()
+ .refine(date => !date || !isNaN(parseDateTimeMs(date)), {
+ message: "Invalid datetime value",
+ }),
past_minutes_start: z
.union([z.string(), z.number()])
.optional()
@@ -134,11 +176,24 @@ const filterParamsTimeStatementFillSchema = z
.refine(
data => {
const hasDateParams = data.start_date && data.end_date && data.time_zone;
+ const hasDateTimeParams = data.start_datetime && data.end_datetime && data.time_zone;
const hasPastMinutesParams = data.past_minutes_start !== undefined && data.past_minutes_end !== undefined;
- return hasDateParams || hasPastMinutesParams;
+ return hasDateParams || hasDateTimeParams || hasPastMinutesParams;
+ },
+ {
+ message:
+ "Either (start_date, end_date, time_zone), (start_datetime, end_datetime, time_zone), or (past_minutes_start, past_minutes_end) must be provided",
+ }
+ )
+ .refine(
+ data => {
+ if (data.start_datetime && data.end_datetime) {
+ return parseDateTimeMs(data.start_datetime) < parseDateTimeMs(data.end_datetime);
+ }
+ return true;
},
{
- message: "Either (start_date, end_date, time_zone) or (past_minutes_start, past_minutes_end) must be provided",
+ message: "start_datetime must be before end_datetime",
}
)
.refine(
diff --git a/server/src/api/analytics/utils/utils.ts b/server/src/api/analytics/utils/utils.ts
index 4fa8a1e48..a8c16ef81 100644
--- a/server/src/api/analytics/utils/utils.ts
+++ b/server/src/api/analytics/utils/utils.ts
@@ -6,10 +6,26 @@ import { db } from "../../../db/postgres/postgres.js";
import { userProfiles } from "../../../db/postgres/schema.js";
import { validateTimeStatementParams } from "./query-validation.js";
+export const normalizeDatetimeForClickhouse = (value: string) => {
+ const normalized = value.includes("T") ? value : value.replace(" ", "T");
+ const withZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(normalized) ? normalized : `${normalized}Z`;
+ return new Date(withZone).toISOString().slice(0, 19).replace("T", " ");
+};
+
export function getTimeStatement(
- params: Pick<FilterParams, "start_date" | "end_date" | "time_zone" | "past_minutes_start" | "past_minutes_end">
+ params: Pick<
+ FilterParams,
+ | "start_date"
+ | "end_date"
+ | "time_zone"
+ | "start_datetime"
+ | "end_datetime"
+ | "past_minutes_start"
+ | "past_minutes_end"
+ >
) {
- const { start_date, end_date, time_zone, past_minutes_start, past_minutes_end } = params;
+ const { start_date, end_date, time_zone, start_datetime, end_datetime, past_minutes_start, past_minutes_end } =
+ params;
// Construct the legacy format for validation
const pastMinutesRange =
@@ -18,10 +34,12 @@ export function getTimeStatement(
: undefined;
const date = start_date && end_date && time_zone ? { start_date, end_date, time_zone } : undefined;
+ const dateTimeRange = start_datetime && end_datetime ? { start_datetime, end_datetime } : undefined;
// Sanitize inputs with Zod
const sanitized = validateTimeStatementParams({
date,
+ dateTimeRange,
pastMinutesRange,
});
@@ -46,6 +64,12 @@ export function getTimeStatement(
)`;
}
+ if (sanitized.dateTimeRange) {
+ const { start_datetime, end_datetime } = sanitized.dateTimeRange;
+ return `AND timestamp >= toDateTime(${SqlString.escape(normalizeDatetimeForClickhouse(start_datetime))}, 'UTC')
+ AND timestamp < toDateTime(${SqlString.escape(normalizeDatetimeForClickhouse(end_datetime))}, 'UTC')`;
+ }
+
// Handle specific range of past minutes - convert to exact timestamps for better performance
if (sanitized.pastMinutesRange) {
const { start, end } = sanitized.pastMinutesRange;
diff --git a/shared/src/params.ts b/shared/src/params.ts
index 0d7fee6a1..128228719 100644
--- a/shared/src/params.ts
+++ b/shared/src/params.ts
@@ -3,6 +3,8 @@ export interface BaseParams {
end_date: string;
time_zone: string;
filters: string;
+ start_datetime?: string;
+ end_datetime?: string;
past_minutes_start?: number;
past_minutes_end?: number;
}