Skip to content

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

feat: Implement past-24-hours mode for analytics (#210)

Bill Yangeb61e330bda1
diff --git a/client/src/api/analytics/useGetGoals.ts b/client/src/api/analytics/useGetGoals.ts
index a8d202463..851b68870 100644
--- a/client/src/api/analytics/useGetGoals.ts
+++ b/client/src/api/analytics/useGetGoals.ts
@@ -5,7 +5,8 @@ import {
GOALS_PAGE_FILTERS,
useStore,
} from "../../lib/store";
-import { authedFetch } from "../utils";
+import { authedFetch, getStartAndEndDate } from "../utils";
+import { getQueryTimeParams } from "./utils";
export interface Goal {
goalId: number;
@@ -43,27 +44,42 @@ export function useGetGoals({
sort = "createdAt",
order = "desc",
enabled = true,
+ minutes,
}: {
- startDate: string;
- endDate: string;
+ startDate?: string;
+ endDate?: string;
page?: number;
pageSize?: number;
sort?: "goalId" | "name" | "goalType" | "createdAt";
order?: "asc" | "desc";
enabled?: boolean;
+ minutes?: number;
}) {
- const { site } = useStore();
+ const { site, time } = useStore();
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
-
const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
+ // If startDate and endDate are not provided, use time from store
+ let timeParams: Record<string, string> = {};
+
+ if (minutes) {
+ // If minutes is explicitly provided, use it
+ timeParams = { minutes: minutes.toString(), timezone };
+ } else if (!startDate || !endDate) {
+ // Otherwise get time parameters from the store's time
+ // This will handle last-24-hours mode automatically
+ const queryParams = getQueryTimeParams(time);
+ timeParams = Object.fromEntries(new URLSearchParams(queryParams));
+ } else {
+ // Use explicitly provided dates if available
+ timeParams = { startDate, endDate, timezone };
+ }
+
return useQuery({
queryKey: [
"goals",
site,
- startDate,
- endDate,
- timezone,
+ timeParams,
filteredFilters,
page,
pageSize,
@@ -72,9 +88,7 @@ export function useGetGoals({
],
queryFn: async () => {
return authedFetch(`${BACKEND_URL}/goals/${site}`, {
- startDate,
- endDate,
- timezone,
+ ...timeParams,
filteredFilters,
page,
pageSize,
@@ -85,3 +99,31 @@ export function useGetGoals({
enabled: !!site && enabled,
});
}
+
+/**
+ * Hook to get goals data for the past X minutes
+ */
+export function useGetGoalsPastMinutes({
+ minutes = 24 * 60,
+ page = 1,
+ pageSize = 10,
+ sort = "createdAt",
+ order = "desc",
+ enabled = true,
+}: {
+ minutes?: number;
+ page?: number;
+ pageSize?: number;
+ sort?: "goalId" | "name" | "goalType" | "createdAt";
+ order?: "asc" | "desc";
+ enabled?: boolean;
+}) {
+ return useGetGoals({
+ minutes,
+ page,
+ pageSize,
+ sort,
+ order,
+ enabled,
+ });
+}
diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/useGetOverviewBucketed.ts
index 5bb906e3e..cd322c50e 100644
--- a/client/src/api/analytics/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/useGetOverviewBucketed.ts
@@ -1,8 +1,12 @@
-import { UseQueryResult, useQuery } from "@tanstack/react-query";
+import {
+ UseQueryOptions,
+ UseQueryResult,
+ useQuery,
+} from "@tanstack/react-query";
import { BACKEND_URL } from "../../lib/const";
-import { APIResponse } from "../types";
-import { getStartAndEndDate, authedFetch } from "../utils";
import { TimeBucket, useStore } from "../../lib/store";
+import { APIResponse } from "../types";
+import { authedFetch, getStartAndEndDate } from "../utils";
type PeriodTime = "current" | "previous";
@@ -20,10 +24,12 @@ export function useGetOverviewBucketed({
periodTime,
site,
bucket = "hour",
+ props,
}: {
periodTime?: PeriodTime;
site?: number | string;
bucket?: TimeBucket;
+ props?: Partial<UseQueryOptions<APIResponse<GetOverviewBucketedResponse>>>;
}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {
const { time, previousTime, filters } = useStore();
@@ -54,28 +60,120 @@ export function useGetOverviewBucketed({
return undefined;
},
staleTime: Infinity,
+ ...props,
});
}
export function useGetOverviewBucketedPastMinutes({
pastMinutes = 24 * 60,
+ pastMinutesStart,
+ pastMinutesEnd,
site,
bucket = "hour",
refetchInterval,
+ props,
}: {
- pastMinutes: number;
+ pastMinutes?: number;
+ pastMinutesStart?: number;
+ pastMinutesEnd?: number;
site?: number | string;
bucket?: TimeBucket;
refetchInterval?: number;
+ props?: Partial<UseQueryOptions<APIResponse<GetOverviewBucketedResponse>>>;
}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {
+ const { filters } = useStore();
+
+ // Determine if we're using a specific range or just pastMinutes
+ const useRange =
+ pastMinutesStart !== undefined && pastMinutesEnd !== undefined;
+
return useQuery({
- queryKey: ["overview-bucketed-past-minutes", pastMinutes, site, bucket],
+ queryKey: useRange
+ ? [
+ "overview-bucketed-past-minutes-range",
+ pastMinutesStart,
+ pastMinutesEnd,
+ site,
+ bucket,
+ filters,
+ ]
+ : ["overview-bucketed-past-minutes", pastMinutes, site, bucket, filters],
+ queryFn: () => {
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ return authedFetch(
+ `${BACKEND_URL}/overview-bucketed/${site}`,
+ useRange
+ ? {
+ timezone,
+ bucket,
+ pastMinutesStart,
+ pastMinutesEnd,
+ filters,
+ }
+ : {
+ timezone,
+ bucket,
+ pastMinutes,
+ filters,
+ }
+ ).then((res) => res.json());
+ },
+ refetchInterval,
+ placeholderData: (_, query: any) => {
+ if (!query?.queryKey) return undefined;
+ const prevQueryKey = query.queryKey as [string, string, string];
+ const [, , prevSite] = prevQueryKey;
+
+ if (prevSite === site) {
+ return query.state.data;
+ }
+ return undefined;
+ },
+ staleTime: Infinity,
+ ...props,
+ });
+}
+
+/**
+ * Hook to get previous time period data for comparison with last-24-hours mode
+ */
+export function useGetOverviewBucketedPreviousPastMinutes({
+ pastMinutes = 24 * 60,
+ site,
+ bucket = "hour",
+ refetchInterval,
+ props,
+}: {
+ pastMinutes?: number;
+ site?: number | string;
+ bucket?: TimeBucket;
+ refetchInterval?: number;
+ props?: Partial<UseQueryOptions<APIResponse<GetOverviewBucketedResponse>>>;
+}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {
+ const { filters } = useStore();
+
+ // For the previous period, we use the pastMinutesStart/End approach
+ // If pastMinutes is 24 * 60 (24 hours), then we fetch 24-48 hour data
+ const pastMinutesStart = pastMinutes * 2; // e.g., 48 hours ago
+ const pastMinutesEnd = pastMinutes; // e.g., 24 hours ago
+
+ return useQuery({
+ queryKey: [
+ "overview-bucketed-previous-past-minutes",
+ pastMinutesStart,
+ pastMinutesEnd,
+ site,
+ bucket,
+ filters,
+ ],
queryFn: () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return authedFetch(`${BACKEND_URL}/overview-bucketed/${site}`, {
timezone,
bucket,
- pastMinutes,
+ pastMinutesStart,
+ pastMinutesEnd,
+ filters,
}).then((res) => res.json());
},
refetchInterval,
@@ -90,5 +188,6 @@ export function useGetOverviewBucketedPastMinutes({
return undefined;
},
staleTime: Infinity,
+ ...props,
});
}
diff --git a/client/src/api/analytics/useSingleCol.ts b/client/src/api/analytics/useSingleCol.ts
index 28c8fb040..d45bc3665 100644
--- a/client/src/api/analytics/useSingleCol.ts
+++ b/client/src/api/analytics/useSingleCol.ts
@@ -28,20 +28,46 @@ export function useSingleCol({
}): UseQueryResult<APIResponse<SingleColResponse[]>> {
const { time, previousTime, site, filters } = useStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
- const { startDate, endDate } = getStartAndEndDate(timeToUse);
- return useQuery({
- queryKey: [parameter, timeToUse, site, filters, limit, useFilters],
- queryFn: () => {
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- return authedFetch(`${BACKEND_URL}/single-col/${site}`, {
- startDate,
- endDate,
- timezone,
+ // Check if we're using last-24-hours mode
+ const isPast24HoursMode = timeToUse.mode === "last-24-hours";
+
+ // Determine the query parameters based on mode
+ const queryParams = isPast24HoursMode
+ ? {
+ // Past minutes approach
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
parameter,
limit,
+ minutes: periodTime === "previous" ? 48 * 60 : 24 * 60,
filters: useFilters ? filters : undefined,
- }).then((res) => res.json());
+ }
+ : {
+ // Regular date-based approach
+ ...getStartAndEndDate(timeToUse),
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ parameter,
+ limit,
+ filters: useFilters ? filters : undefined,
+ };
+
+ // Use a consistent query key format that includes the mode
+ const queryKey = [
+ parameter,
+ timeToUse,
+ site,
+ filters,
+ limit,
+ useFilters,
+ isPast24HoursMode ? "past-minutes" : "date-range",
+ ];
+
+ return useQuery({
+ queryKey,
+ queryFn: () => {
+ return authedFetch(`${BACKEND_URL}/single-col/${site}`, queryParams).then(
+ (res) => res.json()
+ );
},
staleTime: Infinity,
placeholderData: (_, query: any) => {
@@ -66,10 +92,10 @@ export function useSingleColRealtime({
limit?: number;
minutes?: number;
}): UseQueryResult<APIResponse<SingleColResponse[]>> {
- const { time, previousTime, site, filters } = useStore();
+ const { site } = useStore();
return useQuery({
- queryKey: [parameter, site, limit, minutes],
+ queryKey: [parameter, site, limit, minutes, "realtime"],
queryFn: () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return authedFetch(`${BACKEND_URL}/single-col/${site}`, {
diff --git a/client/src/api/analytics/userInfo.ts b/client/src/api/analytics/userInfo.ts
index 066cc0b7d..c8a7b8788 100644
--- a/client/src/api/analytics/userInfo.ts
+++ b/client/src/api/analytics/userInfo.ts
@@ -26,8 +26,6 @@ export function useUserInfo(siteId: number, userId: string) {
return useQuery<UserInfo>({
queryKey: ["user-info", userId, siteId],
queryFn: () => {
- console.info("Fetching user info");
-
return authedFetch(`${BACKEND_URL}/user/info/${userId}/${siteId}`)
.then((res) => res.json())
.then((res) => res.data);
diff --git a/client/src/api/analytics/userSessions.ts b/client/src/api/analytics/userSessions.ts
index a6e736cd2..f25c2fd8d 100644
--- a/client/src/api/analytics/userSessions.ts
+++ b/client/src/api/analytics/userSessions.ts
@@ -7,6 +7,7 @@ import {
} from "../../lib/store";
import { APIResponse } from "../types";
import { authedFetch, getStartAndEndDate } from "../utils";
+import { getQueryTimeParams } from "./utils";
export type UserSessionsResponse = {
session_id: string;
@@ -73,7 +74,12 @@ export type GetSessionsResponse = {
export function useGetSessionsInfinite(userId?: string) {
const { time, site, filters } = useStore();
- const { startDate, endDate } = getStartAndEndDate(time);
+ const isPast24HoursMode = time.mode === "last-24-hours";
+
+ // Get the appropriate time parameters
+ const timeParams = isPast24HoursMode
+ ? Object.fromEntries(new URLSearchParams(getQueryTimeParams(time)))
+ : getStartAndEndDate(time);
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
@@ -81,14 +87,32 @@ export function useGetSessionsInfinite(userId?: string) {
queryKey: ["sessions-infinite", time, site, filteredFilters, userId],
queryFn: ({ pageParam = 1 }) => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- return authedFetch(`${BACKEND_URL}/sessions/${site}`, {
- startDate: userId ? undefined : startDate,
- endDate: userId ? undefined : endDate,
+
+ // Use an object for request parameters so we can conditionally add fields
+ const requestParams: Record<string, any> = {
timezone,
filters: filteredFilters,
page: pageParam,
- userId,
- }).then((res) => res.json());
+ };
+
+ // Add userId if provided
+ if (userId) {
+ requestParams.userId = userId;
+ }
+
+ // Add time parameters
+ if (isPast24HoursMode) {
+ // Add minutes parameter for last-24-hours mode
+ Object.assign(requestParams, timeParams);
+ } else if (!userId) {
+ // Only add date parameters if not filtering by userId
+ requestParams.startDate = timeParams.startDate;
+ requestParams.endDate = timeParams.endDate;
+ }
+
+ return authedFetch(`${BACKEND_URL}/sessions/${site}`, requestParams).then(
+ (res) => res.json()
+ );
},
initialPageParam: 1,
getNextPageParam: (
@@ -150,17 +174,27 @@ export interface SessionPageviewsAndEvents {
}
export function useGetSessionDetailsInfinite(sessionId: string | null) {
- const { site } = useStore();
+ const { site, time } = useStore();
+ const isPast24HoursMode = time.mode === "last-24-hours";
+
+ // Get minutes for last-24-hours mode
+ const minutes = isPast24HoursMode ? 24 * 60 : undefined;
return useInfiniteQuery<APIResponse<SessionPageviewsAndEvents>>({
- queryKey: ["session-details-infinite", sessionId, site],
+ queryKey: ["session-details-infinite", sessionId, site, minutes],
queryFn: ({ pageParam = 0 }) => {
if (!sessionId) throw new Error("Session ID is required");
const limit = 100;
- return authedFetch(
- `${BACKEND_URL}/session/${sessionId}/${site}?limit=${limit}&offset=${pageParam}`
- ).then((res) => res.json());
+ // Build URL with query parameters
+ let url = `${BACKEND_URL}/session/${sessionId}/${site}?limit=${limit}&offset=${pageParam}`;
+
+ // Add minutes parameter for last-24-hours mode
+ if (isPast24HoursMode && minutes) {
+ url += `&minutes=${minutes}`;
+ }
+
+ return authedFetch(url).then((res) => res.json());
},
initialPageParam: 0,
getNextPageParam: (lastPage) => {
diff --git a/client/src/api/analytics/users.ts b/client/src/api/analytics/users.ts
index 9fb86e5a3..f70e53a8f 100644
--- a/client/src/api/analytics/users.ts
+++ b/client/src/api/analytics/users.ts
@@ -8,6 +8,7 @@ import {
} from "../../lib/store";
import { getStartAndEndDate, authedFetch } from "../utils";
import { APIResponse } from "../types";
+import { getQueryTimeParams } from "./utils";
export type UsersResponse = {
user_id: string;
@@ -35,7 +36,12 @@ export interface GetUsersOptions {
export function useGetUsers(options: GetUsersOptions) {
const { time, site } = useStore();
- const { startDate, endDate } = getStartAndEndDate(time);
+ const isPast24HoursMode = time.mode === "last-24-hours";
+
+ // Get the appropriate time parameters
+ const timeParams = isPast24HoursMode
+ ? Object.fromEntries(new URLSearchParams(getQueryTimeParams(time)))
+ : getStartAndEndDate(time);
const { page, pageSize, sortBy, sortOrder } = options;
const filteredFilters = getFilteredFilters(USER_PAGE_FILTERS);
@@ -60,16 +66,28 @@ export function useGetUsers(options: GetUsersOptions) {
queryFn: async () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- return authedFetch(`${BACKEND_URL}/users/${site}`, {
- startDate,
- endDate,
+ // Build request parameters
+ const requestParams: Record<string, any> = {
timezone,
filters: filteredFilters,
page,
pageSize,
sortBy,
sortOrder,
- }).then((res) => res.json());
+ };
+
+ // Add time parameters
+ if (isPast24HoursMode) {
+ // Add minutes parameter for last-24-hours mode
+ Object.assign(requestParams, timeParams);
+ } else {
+ requestParams.startDate = timeParams.startDate;
+ requestParams.endDate = timeParams.endDate;
+ }
+
+ return authedFetch(`${BACKEND_URL}/users/${site}`, requestParams).then(
+ (res) => res.json()
+ );
},
// Use default staleTime (0) for real-time data
staleTime: 0,
diff --git a/client/src/api/analytics/utils.ts b/client/src/api/analytics/utils.ts
index 69bf814f5..0f5355376 100644
--- a/client/src/api/analytics/utils.ts
+++ b/client/src/api/analytics/utils.ts
@@ -7,11 +7,20 @@ import { getStartAndEndDate } from "../utils";
* @returns URL query string with time parameters
*/
export function getQueryTimeParams(time: Time): string {
- const { startDate, endDate } = getStartAndEndDate(time);
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
-
const params = new URLSearchParams();
+ // Handle last-24-hours mode differently
+ if (time.mode === "last-24-hours") {
+ // Use minutes parameter instead of date range
+ params.append("minutes", "1440"); // 24 hours * 60 minutes
+ params.append("timezone", timezone);
+ return params.toString();
+ }
+
+ // Regular date-based approach for other modes
+ const { startDate, endDate } = getStartAndEndDate(time);
+
if (startDate) params.append("startDate", startDate);
if (endDate) params.append("endDate", endDate);
params.append("timezone", timezone);
diff --git a/client/src/api/utils.ts b/client/src/api/utils.ts
index f2aad6f24..d4de93fac 100644
--- a/client/src/api/utils.ts
+++ b/client/src/api/utils.ts
@@ -1,7 +1,4 @@
import { DateTime } from "luxon";
-import { APIResponse } from "./types";
-import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { BACKEND_URL } from "../lib/const";
import { Time } from "../components/DateSelector/types";
export function getStartAndEndDate(time: Time) {
@@ -29,6 +26,9 @@ export function getStartAndEndDate(time: Time) {
if (time.mode === "all-time") {
return { startDate: null, endDate: null };
}
+ if (time.mode === "last-24-hours") {
+ return { startDate: null, endDate: null };
+ }
return { startDate: time.day, endDate: time.day };
}
diff --git a/client/src/app/[site]/components/SubHeader/SubHeader.tsx b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
index 631e90afb..9a41f223d 100644
--- a/client/src/app/[site]/components/SubHeader/SubHeader.tsx
+++ b/client/src/app/[site]/components/SubHeader/SubHeader.tsx
@@ -94,6 +94,7 @@ export function SubHeader({
variant="outline"
size="icon"
onClick={goBack}
+ disabled={time.mode === "last-24-hours"}
className="rounded-r-none h-8 w-8 sm:h-9 sm:w-9"
>
<ChevronLeft />
diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
index 0919263ba..211b83b29 100644
--- a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
@@ -36,29 +36,30 @@ export function StandardSection({
parameter: filterParameter,
});
- const {
- data: previousData,
- isLoading: previousIsLoading,
- isFetching: previousIsFetching,
- } = useSingleCol({
- parameter: filterParameter,
- periodTime: "previous",
- });
+ // const {
+ // data: previousData,
+ // isLoading: previousIsLoading,
+ // isFetching: previousIsFetching,
+ // } = useSingleCol({
+ // parameter: filterParameter,
+ // periodTime: "previous",
+ // });
// Create combined loading state
- const loading = isLoading || previousIsLoading;
+ const loading = isLoading;
+ // const loading = isLoading || previousIsLoading;
// For potential additional features that use previous data
- const previousDataMap = useMemo(() => {
- return previousData?.data?.reduce((acc, curr) => {
- acc[getKey(curr)] = curr;
- return acc;
- }, {} as Record<string, SingleColResponse>);
- }, [previousData, getKey]);
+ // const previousDataMap = useMemo(() => {
+ // return previousData?.data?.reduce((acc, curr) => {
+ // acc[getKey(curr)] = curr;
+ // return acc;
+ // }, {} as Record<string, SingleColResponse>);
+ // }, [previousData, getKey]);
return (
<>
- {(isFetching || previousIsFetching) && (
+ {isFetching && (
<div className="absolute top-[-8px] left-0 w-full h-full">
<CardLoader />
</div>
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index 8d65228d9..bd7e76c96 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -72,7 +72,11 @@ export function Funnel({
<span>Conversion from previous step</span>
</div>
</div>
- <DateSelector time={time} setTime={setTime} />
+ <DateSelector
+ time={time}
+ setTime={setTime}
+ past24HoursEnabled={false}
+ />
</div>
{isError ? (
diff --git a/client/src/app/[site]/funnels/components/FunnelForm.tsx b/client/src/app/[site]/funnels/components/FunnelForm.tsx
index 939de5155..db4e81f4d 100644
--- a/client/src/app/[site]/funnels/components/FunnelForm.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelForm.tsx
@@ -61,7 +61,6 @@ export function FunnelForm({
saveError,
funnelData,
}: FunnelFormProps) {
- console.info(funnelData);
const [showFilters, setShowFilters] = useState(filters.length > 0);
// State to track which event steps have property filtering enabled
const [useProperties, setUseProperties] = useState<boolean[]>(() =>
diff --git a/client/src/app/[site]/goals/page.tsx b/client/src/app/[site]/goals/page.tsx
index ab4c88541..477033385 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -1,7 +1,10 @@
"use client";
import { useState } from "react";
-import { useGetGoals } from "../../../api/analytics/useGetGoals";
+import {
+ useGetGoals,
+ useGetGoalsPastMinutes,
+} from "../../../api/analytics/useGetGoals";
import { getStartAndEndDate } from "../../../api/utils";
import { NothingFound } from "../../../components/NothingFound";
import { GOALS_PAGE_FILTERS, useStore } from "../../../lib/store";
@@ -14,21 +17,20 @@ export default function GoalsPage() {
useSetPageTitle("Rybbit · Goals");
const { time, site } = useStore();
- const { startDate, endDate } = getStartAndEndDate(time);
+ const isPast24HoursMode = time.mode === "last-24-hours";
const [currentPage, setCurrentPage] = useState(1);
const pageSize = 9; // Show 9 cards (3x3 grid)
- // Handle the case where startDate or endDate might be null (for 'all-time' mode)
- const queryStartDate = startDate || "2020-01-01"; // Default fallback date
- const queryEndDate = endDate || new Date().toISOString().split("T")[0]; // Today
-
- // Fetch goals data with pagination
- const { data: goalsData, isLoading } = useGetGoals({
- startDate: queryStartDate,
- endDate: queryEndDate,
- page: currentPage,
- pageSize,
- });
+ // Use the appropriate hook based on the mode
+ const { data: goalsData, isLoading } = isPast24HoursMode
+ ? useGetGoalsPastMinutes({
+ page: currentPage,
+ pageSize,
+ })
+ : useGetGoals({
+ page: currentPage,
+ pageSize,
+ });
// Handle page change
const handlePageChange = (newPage: number) => {
diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsx
index 2118b15a3..af7cfca8b 100644
--- a/client/src/app/[site]/journeys/page.tsx
+++ b/client/src/app/[site]/journeys/page.tsx
@@ -435,7 +435,11 @@ export default function JourneysPage() {
<MobileSidebar />
</div>
<div className="flex justify-end items-center gap-2 mb-2">
- <DateSelector time={time} setTime={setTime} />
+ <DateSelector
+ time={time}
+ setTime={setTime}
+ past24HoursEnabled={false}
+ />
<Select
value={steps.toString()}
onValueChange={(value) => setSteps(Number(value))}
diff --git a/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx b/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
index a6ce314f0..4224d364a 100644
--- a/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/BucketSelection.tsx
@@ -12,6 +12,24 @@ import { DateTime } from "luxon";
import { Time } from "../../../../../components/DateSelector/types";
const getOptions = (time: Time) => {
+ if (time.mode === "last-24-hours") {
+ return (
+ <SelectContent>
+ <SelectItem size="sm" value="minute">
+ Minute
+ </SelectItem>
+ <SelectItem size="sm" value="five_minutes">
+ 5 Minutes
+ </SelectItem>
+ <SelectItem size="sm" value="fifteen_minutes">
+ 15 Minutes
+ </SelectItem>
+ <SelectItem size="sm" value="hour">
+ Hour
+ </SelectItem>
+ </SelectContent>
+ );
+ }
if (time.mode === "day") {
return (
<SelectContent>
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 26ffbf471..be52e56ee 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -2,7 +2,7 @@
import { nivoTheme } from "@/lib/nivo";
import { StatType, TimeBucket, useStore } from "@/lib/store";
import { ResponsiveLine, CustomLayer, CustomLayerProps } from "@nivo/line";
-import type { ScaleLinear } from '@nivo/scales'
+import type { ScaleLinear } from "@nivo/scales";
import { DateTime } from "luxon";
import { formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
import { APIResponse } from "../../../../../api/types";
@@ -10,16 +10,18 @@ import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGet
import { Time } from "../../../../../components/DateSelector/types";
import { useWindowSize } from "@uidotdev/usehooks";
-type DashedLineProps = Omit<CustomLayerProps, 'xScale' | 'yScale'> & {
- xScale: ScaleLinear<number>
- yScale: ScaleLinear<number>
-}
+type DashedLineProps = Omit<CustomLayerProps, "xScale" | "yScale"> & {
+ xScale: ScaleLinear<number>;
+ yScale: ScaleLinear<number>;
+};
export const formatter = Intl.NumberFormat("en", { notation: "compact" });
const getMax = (time: Time, bucket: TimeBucket) => {
const now = DateTime.now();
- if (time.mode === "day") {
+ if (time.mode === "last-24-hours") {
+ return DateTime.now().setZone("UTC").startOf("hour").toJSDate();
+ } else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day)
.endOf("day")
.minus({
@@ -62,7 +64,13 @@ const getMax = (time: Time, bucket: TimeBucket) => {
};
const getMin = (time: Time, bucket: TimeBucket) => {
- if (time.mode === "day") {
+ if (time.mode === "last-24-hours") {
+ return DateTime.now()
+ .setZone("UTC")
+ .minus({ hours: 24 })
+ .startOf("hour")
+ .toJSDate();
+ } else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day).startOf("day");
return dayDate.toJSDate();
} else if (time.mode === "week") {
@@ -115,37 +123,43 @@ export function Chart({
0
);
- const formattedData = data?.data
- ?.map((e, i) => {
- // filter out dates from the future
- if (DateTime.fromSQL(e.time).toUTC() > DateTime.now()) {
- return null;
- }
+ const formattedData =
+ data?.data
+ ?.map((e, i) => {
+ // Parse timestamp properly
+ const timestamp = DateTime.fromSQL(e.time).toUTC();
- return {
- x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
- y: e[selectedStat],
- previousY:
- i >= lengthDiff && previousData?.data?.[i - lengthDiff][selectedStat],
- currentTime: DateTime.fromSQL(e.time),
- previousTime:
- i >= lengthDiff
- ? DateTime.fromSQL(previousData?.data?.[i - lengthDiff]?.time ?? "")
- : undefined,
- };
- })
- .filter((e) => e !== null) || [];
+ // filter out dates from the future
+ if (timestamp > DateTime.now()) {
+ return null;
+ }
+
+ return {
+ x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
+ y: e[selectedStat],
+ previousY:
+ i >= lengthDiff &&
+ previousData?.data?.[i - lengthDiff][selectedStat],
+ currentTime: timestamp,
+ previousTime:
+ i >= lengthDiff
+ ? DateTime.fromSQL(
+ previousData?.data?.[i - lengthDiff]?.time ?? ""
+ ).toUTC()
+ : undefined,
+ };
+ })
+ .filter((e) => e !== null) || [];
const currentDayStr = DateTime.now().toISODate();
- const currentMonthStr = DateTime.now().toFormat('yyyy-MM-01');
- const shouldNotDisplay = (
- time.mode === 'all-time' || // do not display in all-time mode
- time.mode === 'year' || // do not display in year mode
- (time.mode === 'month' && time.month !== currentMonthStr) || // do not display in month mode if month is not current
- (time.mode === 'day' && time.day !== currentDayStr) || // do not display in day mode if day is not current
- (time.mode === 'range' && time.endDate !== currentDayStr) || // do not display in range mode if end date is not current day
- (time.mode === 'day' && (bucket === 'minute' || bucket === 'five_minutes')) // do not display in day mode if bucket is minute or five_minutes
- );
+ const currentMonthStr = DateTime.now().toFormat("yyyy-MM-01");
+ const shouldNotDisplay =
+ time.mode === "all-time" || // do not display in all-time mode
+ time.mode === "year" || // do not display in year mode
+ (time.mode === "month" && time.month !== currentMonthStr) || // do not display in month mode if month is not current
+ (time.mode === "day" && time.day !== currentDayStr) || // do not display in day mode if day is not current
+ (time.mode === "range" && time.endDate !== currentDayStr) || // do not display in range mode if end date is not current day
+ (time.mode === "day" && (bucket === "minute" || bucket === "five_minutes")); // do not display in day mode if bucket is minute or five_minutes
const displayDashed = formattedData.length >= 2 && !shouldNotDisplay;
const baseGradient = {
@@ -156,24 +170,30 @@ export function Chart({
const croppedData = formattedData.slice(0, -1);
// add original data and styles to chart
- const chartPropsData = [{
- id: "croppedData",
- data: displayDashed ? croppedData : formattedData,
- }];
- const chartPropsDefs = [{
- id: "croppedData",
- type: "linearGradient",
- colors: [
- { ...baseGradient, opacity: 1 },
- { offset: 100, color: baseGradient.color, opacity: 0 },
- ],
- }];
- const chartPropsFill = [{
- id: "croppedData",
- match: {
- id: "croppedData"
+ const chartPropsData = [
+ {
+ id: "croppedData",
+ data: displayDashed ? croppedData : formattedData,
},
- }];
+ ];
+ const chartPropsDefs = [
+ {
+ id: "croppedData",
+ type: "linearGradient",
+ colors: [
+ { ...baseGradient, opacity: 1 },
+ { offset: 100, color: baseGradient.color, opacity: 0 },
+ ],
+ },
+ ];
+ const chartPropsFill = [
+ {
+ id: "croppedData",
+ match: {
+ id: "croppedData",
+ },
+ },
+ ];
// add dashed data and styles to chart
if (displayDashed) {
@@ -192,7 +212,7 @@ export function Chart({
chartPropsFill.push({
id: "dashedData",
match: {
- id: "dashedData"
+ id: "dashedData",
},
});
}
@@ -208,7 +228,7 @@ export function Chart({
key={id.toString()}
d={
lineGenerator(
- data.map(d => ({
+ data.map((d) => ({
x: xScale(d.data.x as number),
y: yScale(d.data.y as number),
}))
@@ -223,7 +243,7 @@ export function Chart({
}
/>
));
- }
+ };
return (
<ResponsiveLine
@@ -258,22 +278,28 @@ export function Chart({
truncateTickAt: 0,
tickValues: Math.min(
maxTicks,
- time.mode === "day" ? 24 : Math.min(12, data?.data?.length ?? 0)
+ time.mode === "day" || time.mode === "last-24-hours"
+ ? 24
+ : Math.min(12, data?.data?.length ?? 0)
),
format: (value) => {
- if (time.mode === "day") {
- return DateTime.fromJSDate(value).toFormat("ha");
+ // Convert UTC date to local timezone for display
+ const localTime = DateTime.fromJSDate(value).toLocal();
+
+ if (time.mode === "last-24-hours" || time.mode === "day") {
+ return localTime.toFormat("ha");
} else if (time.mode === "range") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
} else if (time.mode === "week") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
} else if (time.mode === "month") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
} else if (time.mode === "year") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
} else if (time.mode === "all-time") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
}
+ return "";
},
}}
axisLeft={{
@@ -340,7 +366,8 @@ export function Chart({
"axes",
"areas",
"crosshair",
- (displayDashed ? DashedLine : "lines"),
+ displayDashed ? DashedLine : "lines",
+ // "lines",
"slices",
"points",
"mesh",
@@ -351,16 +378,19 @@ export function Chart({
}
const formatTime = (time: DateTime<boolean>, bucket: TimeBucket) => {
+ // Ensure time is in local timezone
+ const localTime = time.toLocal();
+
if (
bucket === "minute" ||
bucket === "five_minutes" ||
bucket === "ten_minutes" ||
bucket === "fifteen_minutes"
) {
- return time.toFormat("M/d h:mm a");
+ return localTime.toFormat("M/d h:mm a");
} else if (bucket === "hour") {
- return time.toFormat("M/d h a");
+ return localTime.toFormat("M/d h a");
} else {
- return time.toLocaleString();
+ return localTime.toLocaleString();
}
};
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index 991da1f58..24d8f9709 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -4,7 +4,11 @@ import { Tilt_Warp } from "next/font/google";
import Image from "next/image";
import Link from "next/link";
import { useGetOverview } from "../../../../../api/analytics/useGetOverview";
-import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
+import {
+ useGetOverviewBucketed,
+ useGetOverviewBucketedPastMinutes,
+ useGetOverviewBucketedPreviousPastMinutes,
+} from "../../../../../api/analytics/useGetOverviewBucketed";
import { authClient } from "../../../../../lib/auth";
import { useStore } from "../../../../../lib/store";
import { cn } from "../../../../../lib/utils";
@@ -32,12 +36,74 @@ export function MainSection() {
const { selectedStat, time, site, bucket } = useStore();
- const { data, isFetching, error } = useGetOverviewBucketed({ site, bucket });
+ // Use the past minutes API when in last-24-hours mode
+ const isPast24HoursMode = time.mode === "last-24-hours";
+
+ // Regular date-based queries
+ const {
+ data: regularData,
+ isFetching: isRegularFetching,
+ error: regularError,
+ } = useGetOverviewBucketed({
+ site,
+ bucket,
+ props: {
+ enabled: !isPast24HoursMode,
+ },
+ });
+
+ const {
+ data: regularPreviousData,
+ isFetching: isRegularPreviousFetching,
+ error: regularPreviousError,
+ } = useGetOverviewBucketed({
+ periodTime: "previous",
+ site,
+ bucket,
+ props: {
+ enabled: !isPast24HoursMode,
+ },
+ });
+
+ // Past minutes-based queries (for 24 hour mode)
+ const {
+ data: pastMinutesData,
+ isFetching: isPastMinutesFetching,
+ error: pastMinutesError,
+ } = useGetOverviewBucketedPastMinutes({
+ pastMinutes: 24 * 60,
+ site,
+ bucket,
+ props: {
+ enabled: isPast24HoursMode,
+ },
+ });
+
const {
- data: previousData,
- isFetching: isPreviousFetching,
- error: previousError,
- } = useGetOverviewBucketed({ periodTime: "previous", site, bucket });
+ data: pastMinutesPreviousData,
+ isFetching: isPastMinutesPreviousFetching,
+ error: pastMinutesPreviousError,
+ } = useGetOverviewBucketedPreviousPastMinutes({
+ pastMinutes: 24 * 60,
+ site,
+ bucket,
+ props: {
+ enabled: isPast24HoursMode,
+ },
+ });
+
+ // Combine the data based on the mode
+ const data = isPast24HoursMode ? pastMinutesData : regularData;
+ const previousData = isPast24HoursMode
+ ? pastMinutesPreviousData
+ : regularPreviousData;
+ const isFetching = isPast24HoursMode
+ ? isPastMinutesFetching
+ : isRegularFetching;
+ const isPreviousFetching = isPast24HoursMode
+ ? isPastMinutesPreviousFetching
+ : isRegularPreviousFetching;
+
const { isFetching: isOverviewFetching } = useGetOverview({ site });
const { isFetching: isOverviewFetchingPrevious } = useGetOverview({
site,
@@ -45,8 +111,8 @@ export function MainSection() {
});
const maxOfDataAndPreviousData = Math.max(
- Math.max(...(data?.data?.map((d) => d[selectedStat]) ?? [])),
- Math.max(...(previousData?.data?.map((d) => d[selectedStat]) ?? []))
+ Math.max(...(data?.data?.map((d: any) => d[selectedStat]) ?? [])),
+ Math.max(...(previousData?.data?.map((d: any) => d[selectedStat]) ?? []))
);
return (
@@ -64,7 +130,10 @@ export function MainSection() {
<div className="flex items-center space-x-4">
<Link
href={session.data ? "/" : "https://rybbit.io"}
- className={cn("text-lg font-semibold flex items-center gap-1.5 opacity-75", tilt_wrap.className)}
+ className={cn(
+ "text-lg font-semibold flex items-center gap-1.5 opacity-75",
+ tilt_wrap.className
+ )}
>
<Image src="/rybbit.png" alt="Rybbit" width={20} height={20} />
rybbit.io
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsx
index 7acf27726..461ca6437 100644
--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx
@@ -5,8 +5,14 @@ import { cn, formatSecondsAsMinutesAndSeconds } from "@/lib/utils";
import NumberFlow from "@number-flow/react";
import { TrendingDown, TrendingUp } from "lucide-react";
import { useState } from "react";
-import { useGetOverview } from "../../../../../api/analytics/useGetOverview";
-import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
+import {
+ useGetOverview,
+ useGetOverviewPastMinutes,
+} from "../../../../../api/analytics/useGetOverview";
+import {
+ useGetOverviewBucketed,
+ useGetOverviewBucketedPastMinutes,
+} from "../../../../../api/analytics/useGetOverviewBucketed";
import { StatType, useStore } from "../../../../../lib/store";
import { SparklinesChart } from "./SparklinesChart";
@@ -34,7 +40,12 @@ const ChangePercentage = ({
return (
<div
- className={cn("text-xs flex items-center gap-1", (reverseColor ? -change : change) > 0 ? "text-green-400" : "text-red-400")}
+ className={cn(
+ "text-xs flex items-center gap-1",
+ (reverseColor ? -change : change) > 0
+ ? "text-green-400"
+ : "text-red-400"
+ )}
>
{change > 0 ? (
<TrendingUp className="w-4 h-4" />
@@ -67,20 +78,58 @@ const Stat = ({
postfix?: string;
reverseColor?: boolean;
}) => {
- const { selectedStat, setSelectedStat, site, bucket } = useStore();
+ const { selectedStat, setSelectedStat, site, bucket, time } = useStore();
const [isHovering, setIsHovering] = useState(false);
+ const isPast24HoursMode = time.mode === "last-24-hours";
+
+ // Regular bucketed data for sparklines
+ const { data: regularData } = useGetOverviewBucketed({
+ site,
+ bucket,
+ props: {
+ enabled: !isPast24HoursMode,
+ },
+ });
- const { data, isFetching, error } = useGetOverviewBucketed({ site, bucket });
+ // Past minutes data for sparklines
+ const { data: pastMinutesData } = useGetOverviewBucketedPastMinutes({
+ pastMinutes: 24 * 60,
+ site,
+ bucket,
+ props: {
+ enabled: isPast24HoursMode,
+ },
+ });
+ // Use the appropriate data source based on mode
+ const data = isPast24HoursMode ? pastMinutesData : regularData;
+
+ // Filter and format sparklines data
const sparklinesData =
- data?.data?.map((d) => ({
- value: d[id],
- time: d.time,
- })) ?? [];
+ data?.data
+ ?.filter((d) => {
+ // For last-24-hours mode, ensure we only show data within the last 24 hours
+ if (isPast24HoursMode) {
+ const timestamp = new Date(d.time);
+ const now = new Date();
+ const twentyFourHoursAgo = new Date(
+ now.getTime() - 24 * 60 * 60 * 1000
+ );
+ return timestamp >= twentyFourHoursAgo && timestamp <= now;
+ }
+ return true;
+ })
+ .map((d: any) => ({
+ value: d[id],
+ time: d.time,
+ })) ?? [];
return (
<div
- className={cn("flex flex-col cursor-pointer border-r border-neutral-800 last:border-r-0 text-nowrap", selectedStat === id && "bg-neutral-850")}
+ className={cn(
+ "flex flex-col cursor-pointer border-r border-neutral-800 last:border-r-0 text-nowrap",
+ selectedStat === id && "bg-neutral-850"
+ )}
onClick={() => setSelectedStat(id)}
onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)}
@@ -126,15 +175,62 @@ const Stat = ({
};
export function Overview() {
- const { site } = useStore();
+ const { site, time } = useStore();
+ const isPast24HoursMode = time.mode === "last-24-hours";
+
+ // Regular time-based queries
const {
- data: overviewData,
- isFetching: isOverviewFetching,
- isLoading: isOverviewLoading,
- error: overviewError,
+ data: regularOverviewData,
+ isFetching: isRegularOverviewFetching,
+ isLoading: isRegularOverviewLoading,
+ error: regularOverviewError,
} = useGetOverview({ site });
- const { data: overviewDataPrevious, isLoading: isOverviewLoadingPrevious } =
- useGetOverview({ site, periodTime: "previous" });
+
+ const {
+ data: regularOverviewDataPrevious,
+ isLoading: isRegularOverviewLoadingPrevious,
+ } = useGetOverview({ site, periodTime: "previous" });
+
+ // Past minutes-based queries
+ const {
+ data: pastMinutesOverviewData,
+ isFetching: isPastMinutesOverviewFetching,
+ isLoading: isPastMinutesOverviewLoading,
+ error: pastMinutesOverviewError,
+ } = useGetOverviewPastMinutes({
+ site,
+ pastMinutes: 24 * 60,
+ });
+
+ // Past minutes-based queries for previous period
+ const {
+ data: pastMinutesOverviewDataPrevious,
+ isLoading: isPastMinutesOverviewLoadingPrevious,
+ } = useGetOverviewPastMinutes({
+ site,
+ pastMinutes: 48 * 60, // Use 48 hours instead of a isPrevious flag
+ });
+
+ // Combine the data based on the mode
+ const overviewData = isPast24HoursMode
+ ? pastMinutesOverviewData
+ : regularOverviewData;
+ const overviewDataPrevious = isPast24HoursMode
+ ? pastMinutesOverviewDataPrevious
+ : regularOverviewDataPrevious;
+
+ const isOverviewFetching = isPast24HoursMode
+ ? isPastMinutesOverviewFetching
+ : isRegularOverviewFetching;
+ const isOverviewLoading = isPast24HoursMode
+ ? isPastMinutesOverviewLoading
+ : isRegularOverviewLoading;
+ const isOverviewLoadingPrevious = isPast24HoursMode
+ ? isPastMinutesOverviewLoadingPrevious
+ : isRegularOverviewLoadingPrevious;
+ const overviewError = isPast24HoursMode
+ ? pastMinutesOverviewError
+ : regularOverviewError;
const isLoading = isOverviewLoading || isOverviewLoadingPrevious;
diff --git a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
index 5dc4bea9a..fbde033b5 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -9,7 +9,13 @@ import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGet
import { Time } from "../../../../../components/DateSelector/types";
const getMin = (time: Time) => {
- if (time.mode === "day") {
+ if (time.mode === "last-24-hours") {
+ return DateTime.now()
+ .setZone("UTC")
+ .minus({ hours: 48 })
+ .startOf("hour")
+ .toJSDate();
+ } else if (time.mode === "day") {
const dayDate = DateTime.fromISO(time.day).startOf("day");
return dayDate.toJSDate();
} else if (time.mode === "week") {
@@ -38,12 +44,22 @@ export function PreviousChart({
}) {
const { previousTime: time, selectedStat } = useStore();
- const formattedData = data?.data?.map((e) => ({
- x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
- y: e[selectedStat],
- }));
+ const size = (data?.data.length ?? 0 / 2) + 1;
+ const formattedData = data?.data
+ ?.map((e) => {
+ const timestamp = DateTime.fromSQL(e.time).toUTC();
+ return {
+ x: timestamp.toFormat("yyyy-MM-dd HH:mm:ss"),
+ y: e[selectedStat],
+ };
+ })
+ .slice(0, size);
- const min = useMemo(() => getMin(time), [data]);
+ const min = useMemo(() => getMin(time), [time]);
+ const max24Hours =
+ time.mode === "last-24-hours"
+ ? DateTime.now().setZone("UTC").minus({ hours: 24 }).toJSDate()
+ : undefined;
return (
<ResponsiveLine
@@ -61,6 +77,7 @@ export function PreviousChart({
precision: "second",
useUTC: true,
min,
+ max: max24Hours,
}}
yScale={{
type: "linear",
@@ -81,15 +98,18 @@ export function PreviousChart({
truncateTickAt: 0,
tickValues: 0,
format: (value) => {
- if (time.mode === "day") {
- return DateTime.fromJSDate(value).toFormat("ha");
+ const localTime = DateTime.fromJSDate(value).toLocal();
+
+ if (time.mode === "last-24-hours" || time.mode === "day") {
+ return localTime.toFormat("ha");
} else if (time.mode === "range") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
} else if (time.mode === "week") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
} else if (time.mode === "month") {
- return DateTime.fromJSDate(value).toFormat("MMM d");
+ return localTime.toFormat("MMM d");
}
+ return "";
},
}}
axisLeft={{
diff --git a/client/src/app/[site]/main/components/sections/Weekdays.tsx b/client/src/app/[site]/main/components/sections/Weekdays.tsx
index 03135fda5..cf1f18507 100644
--- a/client/src/app/[site]/main/components/sections/Weekdays.tsx
+++ b/client/src/app/[site]/main/components/sections/Weekdays.tsx
@@ -1,6 +1,9 @@
import { DateTime } from "luxon";
import { useMemo, useState } from "react";
-import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
+import {
+ useGetOverviewBucketed,
+ useGetOverviewBucketedPastMinutes,
+} from "../../../../../api/analytics/useGetOverviewBucketed";
import {
Tabs,
TabsList,
@@ -28,17 +31,39 @@ import { StatType, useStore } from "../../../../../lib/store";
import { cn } from "../../../../../lib/utils";
export function Weekdays() {
- const { site } = useStore();
+ const { site, time } = useStore();
const [metric, setMetric] = useState<StatType>("users");
+ // Use the past minutes API when in last-24-hours mode
+ const isPast24HoursMode = time.mode === "last-24-hours";
+
const { data, isFetching, error } = useGetOverviewBucketed({
site,
bucket: "hour",
+ props: {
+ enabled: !isPast24HoursMode,
+ },
});
+ // Past minutes-based queries (for 24 hour mode)
+ const {
+ data: past24HoursData,
+ isFetching: isPast24HoursFetching,
+ error: past24HoursError,
+ } = useGetOverviewBucketedPastMinutes({
+ pastMinutes: 24 * 60,
+ site,
+ bucket: "hour",
+ props: {
+ enabled: isPast24HoursMode,
+ },
+ });
+
+ const dataToUse = isPast24HoursMode ? past24HoursData : data;
+
// Generate aggregated data for the heatmap
const heatmapData = useMemo(() => {
- if (!data?.data) return [];
+ if (!dataToUse?.data) return [];
// Initialize a 2D array for days (0-6) and hours (0-23)
const aggregated: number[][] = Array(7)
@@ -51,7 +76,7 @@ export function Weekdays() {
.map(() => Array(24).fill(0));
// Process each data point
- data.data.forEach((item) => {
+ dataToUse.data.forEach((item) => {
if (!item || !item.time) return;
// Parse the timestamp
@@ -79,7 +104,7 @@ export function Weekdays() {
}
return aggregated;
- }, [data, metric]);
+ }, [dataToUse, metric]);
// Find max value for color intensity scaling
const maxValue = useMemo(() => {
@@ -264,7 +289,10 @@ export function Weekdays() {
<Tooltip key={day}>
<TooltipTrigger asChild>
<div
- className={cn("flex-1 mx-0.5 hover:ring-1 hover:ring-emerald-300 transition-all rounded-sm my-0.5", colorClass)}
+ className={cn(
+ "flex-1 mx-0.5 hover:ring-1 hover:ring-emerald-300 transition-all rounded-sm my-0.5",
+ colorClass
+ )}
/>
</TooltipTrigger>
<TooltipContent className="flex flex-col gap-1 p-2">
diff --git a/client/src/components/DateSelector/DateSelector.tsx b/client/src/components/DateSelector/DateSelector.tsx
index c0ebcd0ce..18d172624 100644
--- a/client/src/components/DateSelector/DateSelector.tsx
+++ b/client/src/components/DateSelector/DateSelector.tsx
@@ -24,6 +24,10 @@ const getLabel = (time: Time) => {
return `${startFormatted} - ${endFormatted}`;
}
+ if (time.mode === "last-24-hours") {
+ return "Past 24 Hours";
+ }
+
if (time.mode === "day") {
if (time.day === DateTime.now().toISODate()) {
return "Today";
@@ -75,9 +79,11 @@ const getLabel = (time: Time) => {
export function DateSelector({
time,
setTime,
+ past24HoursEnabled = true,
}: {
time: Time;
setTime: (time: Time) => void;
+ past24HoursEnabled?: boolean;
}) {
return (
<DropdownMenu>
@@ -99,6 +105,17 @@ export function DateSelector({
>
Today
</DropdownMenuItem>
+ {past24HoursEnabled && (
+ <DropdownMenuItem
+ onClick={() =>
+ setTime({
+ mode: "last-24-hours",
+ })
+ }
+ >
+ Last 24 Hours
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
onClick={() =>
setTime({
diff --git a/client/src/components/DateSelector/types.ts b/client/src/components/DateSelector/types.ts
index d898fb50c..8ea58d8d8 100644
--- a/client/src/components/DateSelector/types.ts
+++ b/client/src/components/DateSelector/types.ts
@@ -34,10 +34,15 @@ export type AllTimeMode = {
mode: "all-time";
};
+export type Past24HoursMode = {
+ mode: "last-24-hours";
+};
+
export type Time =
| DateMode
| DateRangeMode
| WeekMode
| MonthMode
| YearMode
- | AllTimeMode;
+ | AllTimeMode
+ | Past24HoursMode;
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index 055314399..c589e66c7 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -195,6 +195,11 @@ export const useStore = create<Store>((set) => ({
mode: "day",
day: DateTime.fromISO(time.day).minus({ days: 1 }).toISODate() ?? "",
};
+ } else if (time.mode === "last-24-hours") {
+ bucketToUse = "hour";
+ previousTime = {
+ mode: "last-24-hours",
+ };
} else if (time.mode === "range") {
const timeRangeLength =
DateTime.fromISO(time.endDate).diff(
diff --git a/client/src/lib/urlParams.ts b/client/src/lib/urlParams.ts
index 0a1f683b9..b6f825d6f 100644
--- a/client/src/lib/urlParams.ts
+++ b/client/src/lib/urlParams.ts
@@ -63,7 +63,9 @@ export const deserializeUrlToState = (
// Deserialize time
const timeMode = searchParams.get("timeMode") as Time["mode"] | null;
if (timeMode) {
- if (timeMode === "day") {
+ if (timeMode === "last-24-hours") {
+ result.time = { mode: "last-24-hours" };
+ } else if (timeMode === "day") {
const day = searchParams.get("day");
if (day) {
result.time = { mode: "day", day };
diff --git a/server/src/api/analytics/getEventNames.ts b/server/src/api/analytics/getEventNames.ts
index 4572a12d0..8c4769eda 100644
--- a/server/src/api/analytics/getEventNames.ts
+++ b/server/src/api/analytics/getEventNames.ts
@@ -17,10 +17,11 @@ export interface GetEventNamesRequest {
site: string;
};
Querystring: {
- startDate: string;
- endDate: string;
+ startDate?: string;
+ endDate?: string;
timezone: string;
filters?: string;
+ minutes?: string;
};
}
@@ -28,7 +29,7 @@ export async function getEventNames(
req: FastifyRequest<GetEventNamesRequest>,
res: FastifyReply
) {
- const { startDate, endDate, timezone, filters } = req.query;
+ const { startDate, endDate, timezone, filters, minutes } = req.query;
const site = req.params.site;
const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);
if (!userHasAccessToSite) {
@@ -36,7 +37,10 @@ export async function getEventNames(
}
const timeStatement = getTimeStatement({
- date: { startDate, endDate, timezone },
+ startDate,
+ endDate,
+ timezone,
+ minutes,
});
const filterStatement = filters ? getFilterStatement(filters) : "";
diff --git a/server/src/api/analytics/getEventProperties.ts b/server/src/api/analytics/getEventProperties.ts
index 8e1c2243a..df6d323a3 100644
--- a/server/src/api/analytics/getEventProperties.ts
+++ b/server/src/api/analytics/getEventProperties.ts
@@ -18,11 +18,12 @@ export interface GetEventPropertiesRequest {
site: string;
};
Querystring: {
- startDate: string;
- endDate: string;
+ startDate?: string;
+ endDate?: string;
timezone: string;
eventName: string;
filters?: string;
+ minutes?: string;
};
}
@@ -30,7 +31,8 @@ export async function getEventProperties(
req: FastifyRequest<GetEventPropertiesRequest>,
res: FastifyReply
) {
- const { startDate, endDate, timezone, eventName, filters } = req.query;
+ const { startDate, endDate, timezone, eventName, filters, minutes } =
+ req.query;
const site = req.params.site;
const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);
if (!userHasAccessToSite) {
@@ -42,7 +44,10 @@ export async function getEventProperties(
}
const timeStatement = getTimeStatement({
- date: { startDate, endDate, timezone },
+ startDate,
+ endDate,
+ timezone,
+ minutes,
});
const filterStatement = filters ? getFilterStatement(filters) : "";
diff --git a/server/src/api/analytics/getEvents.ts b/server/src/api/analytics/getEvents.ts
index dea4611b0..f0c5080ea 100644
--- a/server/src/api/analytics/getEvents.ts
+++ b/server/src/api/analytics/getEvents.ts
@@ -66,7 +66,7 @@ export async function getEvents(
// Get time and filter statements if parameters are provided
const timeStatement =
startDate || endDate
- ? getTimeStatement({ date: { startDate, endDate, timezone } })
+ ? getTimeStatement({ startDate, endDate, timezone })
: "AND timestamp > now() - INTERVAL 30 MINUTE"; // Default to last 30 minutes if no time range specified
const filterStatement = filters ? getFilterStatement(filters) : "";
diff --git a/server/src/api/analytics/getGoals.ts b/server/src/api/analytics/getGoals.ts
index 247d6c1ae..34e017288 100644
--- a/server/src/api/analytics/getGoals.ts
+++ b/server/src/api/analytics/getGoals.ts
@@ -40,14 +40,17 @@ export async function getGoals(
site: string;
};
Querystring: {
- startDate: string;
- endDate: string;
+ startDate?: string;
+ endDate?: string;
timezone: string;
filters?: string;
page?: string;
pageSize?: string;
sort?: string;
order?: "asc" | "desc";
+ minutes?: string;
+ pastMinutesStart?: string;
+ pastMinutesEnd?: string;
};
}>,
reply: FastifyReply
@@ -62,6 +65,9 @@ export async function getGoals(
pageSize = "10",
sort = "createdAt",
order = "desc",
+ minutes,
+ pastMinutesStart,
+ pastMinutesEnd,
} = request.query;
const pageNumber = parseInt(page, 10);
@@ -150,7 +156,12 @@ export async function getGoals(
// Build filter and time clauses for ClickHouse queries
const filterStatement = filters ? getFilterStatement(filters) : "";
const timeStatement = getTimeStatement({
- date: { startDate, endDate, timezone },
+ startDate,
+ endDate,
+ timezone,
+ minutes,
+ pastMinutesStart,
+ pastMinutesEnd,
});
// First, get the total number of unique sessions (denominator for conversion rate)
diff --git a/server/src/api/analytics/getOverview.ts b/server/src/api/analytics/getOverview.ts
index 58fa112a4..d0f2c8e93 100644
--- a/server/src/api/analytics/getOverview.ts
+++ b/server/src/api/analytics/getOverview.ts
@@ -34,7 +34,8 @@ const getQuery = ({
}) => {
const filterStatement = getFilterStatement(filters);
- return `SELECT
+ return `
+ SELECT
session_stats.sessions,
session_stats.pages_per_session,
session_stats.bounce_rate * 100 AS bounce_rate,
@@ -61,13 +62,12 @@ const getQuery = ({
WHERE
site_id = {siteId:Int32}
${filterStatement}
- ${getTimeStatement(
- pastMinutes
- ? { pastMinutes }
- : {
- date: { startDate, endDate, timezone },
- }
- )}
+ ${getTimeStatement({
+ startDate,
+ endDate,
+ timezone,
+ minutes: pastMinutes,
+ })}
GROUP BY session_id
)
) AS session_stats
@@ -81,13 +81,12 @@ const getQuery = ({
WHERE
site_id = {siteId:Int32}
${filterStatement}
- ${getTimeStatement(
- pastMinutes
- ? { pastMinutes }
- : {
- date: { startDate, endDate, timezone },
- }
- )}
+ ${getTimeStatement({
+ startDate,
+ endDate,
+ timezone,
+ minutes: pastMinutes,
+ })}
AND type = 'pageview'
) AS page_stats`;
};
diff --git a/server/src/api/analytics/getOverviewBucketed.ts b/server/src/api/analytics/getOverviewBucketed.ts
index 2f3c88f99..c623495d8 100644
--- a/server/src/api/analytics/getOverviewBucketed.ts
+++ b/server/src/api/analytics/getOverviewBucketed.ts
@@ -37,14 +37,16 @@ function getTimeStatementFill(
{
date,
pastMinutes,
+ pastMinutesRange,
}: {
date?: { startDate: string; endDate: string; timezone: string };
pastMinutes?: number;
+ pastMinutesRange?: { start: number; end: number };
},
bucket: TimeBucket
) {
const { params, bucket: validatedBucket } = validateTimeStatementFillParams(
- { date, pastMinutes },
+ { date, pastMinutes, pastMinutesRange },
bucket
);
@@ -73,6 +75,16 @@ function getTimeStatementFill(
)
) STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
}
+ // For specific past minutes range
+ if (params.pastMinutesRange) {
+ const { start, end } = params.pastMinutesRange;
+ return `WITH FILL FROM now() - INTERVAL ${SqlString.escape(
+ start
+ )} MINUTE TO now() - INTERVAL ${SqlString.escape(
+ end
+ )} MINUTE STEP INTERVAL ${bucketIntervalMap[validatedBucket]}`;
+ }
+ // For regular past minutes
if (params.pastMinutes) {
return `WITH FILL FROM now() - INTERVAL ${SqlString.escape(
params.pastMinutes
@@ -89,6 +101,8 @@ const getQuery = ({
site,
filters,
pastMinutes,
+ pastMinutesStart,
+ pastMinutesEnd,
}: {
startDate: string;
endDate: string;
@@ -97,11 +111,24 @@ const getQuery = ({
site: string;
filters: string;
pastMinutes?: number;
+ pastMinutesStart?: number;
+ pastMinutesEnd?: number;
}) => {
const filterStatement = getFilterStatement(filters);
const isAllTime = !startDate && !endDate;
+ const timeParams = pastMinutesEnd
+ ? {
+ pastMinutesRange: {
+ start: Number(pastMinutesStart),
+ end: Number(pastMinutesEnd),
+ },
+ }
+ : pastMinutes
+ ? { pastMinutes }
+ : { date: { startDate, endDate, timezone } };
+
const query = `
SELECT
session_stats.time AS time,
@@ -133,25 +160,12 @@ FROM
WHERE
site_id = {siteId:Int32}
${filterStatement}
- ${getTimeStatement(
- pastMinutes
- ? { pastMinutes }
- : {
- date: { startDate, endDate, timezone },
- }
- )}
+ ${getTimeStatement(timeParams)}
AND type = 'pageview'
GROUP BY session_id
)
GROUP BY time ORDER BY time ${
- isAllTime
- ? ""
- : getTimeStatementFill(
- pastMinutes
- ? { pastMinutes }
- : { date: { startDate, endDate, timezone } },
- bucket
- )
+ isAllTime ? "" : getTimeStatementFill(timeParams, bucket)
}
) AS session_stats
FULL JOIN
@@ -166,23 +180,10 @@ FULL JOIN
WHERE
site_id = {siteId:Int32}
${filterStatement}
- ${getTimeStatement(
- pastMinutes
- ? { pastMinutes }
- : {
- date: { startDate, endDate, timezone },
- }
- )}
+ ${getTimeStatement(timeParams)}
AND type = 'pageview'
GROUP BY time ORDER BY time ${
- isAllTime
- ? ""
- : getTimeStatementFill(
- pastMinutes
- ? { pastMinutes }
- : { date: { startDate, endDate, timezone } },
- bucket
- )
+ isAllTime ? "" : getTimeStatementFill(timeParams, bucket)
}
) AS page_stats
USING time
@@ -207,12 +208,22 @@ export async function getOverviewBucketed(
bucket: TimeBucket;
filters: string;
pastMinutes?: number;
+ pastMinutesStart?: number;
+ pastMinutesEnd?: number;
};
}>,
res: FastifyReply
) {
- const { startDate, endDate, timezone, bucket, filters, pastMinutes } =
- req.query;
+ const {
+ startDate,
+ endDate,
+ timezone,
+ bucket,
+ filters,
+ pastMinutes,
+ pastMinutesStart,
+ pastMinutesEnd,
+ } = req.query;
const site = req.params.site;
const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);
@@ -227,7 +238,9 @@ export async function getOverviewBucketed(
bucket,
site,
filters,
- pastMinutes: pastMinutes ? Number(pastMinutes) : undefined,
+ pastMinutes,
+ pastMinutesStart,
+ pastMinutesEnd,
});
try {
diff --git a/server/src/api/analytics/getSession.ts b/server/src/api/analytics/getSession.ts
index 37f136e8e..106144546 100644
--- a/server/src/api/analytics/getSession.ts
+++ b/server/src/api/analytics/getSession.ts
@@ -57,6 +57,7 @@ export interface GetSessionRequest {
Querystring: {
limit?: string;
offset?: string;
+ minutes?: string;
};
}
@@ -67,12 +68,21 @@ export async function getSession(
const { sessionId, site } = req.params;
const limit = req.query.limit ? parseInt(req.query.limit) : 100;
const offset = req.query.offset ? parseInt(req.query.offset) : 0;
+ const minutes = req.query.minutes ? parseInt(req.query.minutes) : undefined;
const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);
if (!userHasAccessToSite) {
return res.status(403).send({ error: "Forbidden" });
}
+ // Add time filter if minutes is provided
+ const timeFilter = minutes
+ ? `timestamp > now() - interval ${minutes} minute`
+ : "";
+
+ // Add the WHERE clause connector if timeFilter exists
+ const timeFilterWithConnector = timeFilter ? `AND ${timeFilter}` : "";
+
try {
// 1. First query: Get session data derived from events
const sessionQuery = `
@@ -101,6 +111,7 @@ FROM events
WHERE
site_id = {siteId:Int32}
AND session_id = {sessionId:String}
+ ${timeFilterWithConnector}
GROUP BY session_id
LIMIT 1
`;
@@ -113,6 +124,7 @@ FROM events
WHERE
site_id = {siteId:Int32}
AND session_id = {sessionId:String}
+ ${timeFilterWithConnector}
`;
// 3. Query to get paginated pageviews
@@ -131,6 +143,7 @@ FROM events
WHERE
site_id = {siteId:Int32}
AND session_id = {sessionId:String}
+ ${timeFilterWithConnector}
ORDER BY timestamp ASC
LIMIT {limit:Int32}
OFFSET {offset:Int32}
diff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.ts
index ad239127d..06855ea4f 100644
--- a/server/src/api/analytics/getSessions.ts
+++ b/server/src/api/analytics/getSessions.ts
@@ -38,12 +38,15 @@ export interface GetSessionsRequest {
site: string;
};
Querystring: {
- startDate: string;
- endDate: string;
+ startDate?: string;
+ endDate?: string;
timezone: string;
filters: string;
page: number;
userId?: string;
+ minutes?: string;
+ pastMinutesStart?: string;
+ pastMinutesEnd?: string;
};
}
@@ -51,7 +54,17 @@ export async function getSessions(
req: FastifyRequest<GetSessionsRequest>,
res: FastifyReply
) {
- const { startDate, endDate, timezone, filters, page, userId } = req.query;
+ const {
+ startDate,
+ endDate,
+ timezone,
+ filters,
+ page,
+ userId,
+ minutes,
+ pastMinutesStart,
+ pastMinutesEnd,
+ } = req.query;
const site = req.params.site;
const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);
if (!userHasAccessToSite) {
@@ -60,7 +73,12 @@ export async function getSessions(
const filterStatement = getFilterStatement(filters);
const timeStatement = getTimeStatement({
- date: { startDate, endDate, timezone },
+ startDate,
+ endDate,
+ timezone,
+ minutes,
+ pastMinutesStart,
+ pastMinutesEnd,
});
const query = `
diff --git a/server/src/api/analytics/getSingleCol.ts b/server/src/api/analytics/getSingleCol.ts
index 0505ba470..17401f3b3 100644
--- a/server/src/api/analytics/getSingleCol.ts
+++ b/server/src/api/analytics/getSingleCol.ts
@@ -40,13 +40,12 @@ const getQuery = (request: FastifyRequest<GenericRequest>) => {
request.query;
const filterStatement = getFilterStatement(filters);
- const timeStatement = getTimeStatement(
- minutes
- ? { pastMinutes: minutes }
- : {
- date: { startDate, endDate, timezone },
- }
- );
+ const timeStatement = getTimeStatement({
+ startDate,
+ endDate,
+ timezone,
+ minutes,
+ });
// Validate and sanitize the limit parameter
let validatedLimit: number | null = null;
diff --git a/server/src/api/analytics/getUsers.ts b/server/src/api/analytics/getUsers.ts
index b12b2cd99..29b3acfb4 100644
--- a/server/src/api/analytics/getUsers.ts
+++ b/server/src/api/analytics/getUsers.ts
@@ -28,14 +28,17 @@ export interface GetUsersRequest {
site: string;
};
Querystring: {
- startDate: string;
- endDate: string;
+ startDate?: string;
+ endDate?: string;
timezone: string;
filters: string;
page?: string;
pageSize?: string;
sortBy?: string;
sortOrder?: string;
+ minutes?: string;
+ pastMinutesStart?: string;
+ pastMinutesEnd?: string;
};
}
@@ -52,6 +55,9 @@ export async function getUsers(
pageSize = "20",
sortBy = "last_seen",
sortOrder = "desc",
+ minutes,
+ pastMinutesStart,
+ pastMinutesEnd,
} = req.query;
const site = req.params.site;
@@ -78,7 +84,12 @@ export async function getUsers(
// Generate filter statement and time statement
const filterStatement = getFilterStatement(filters);
const timeStatement = getTimeStatement({
- date: { startDate, endDate, timezone },
+ startDate,
+ endDate,
+ timezone,
+ minutes,
+ pastMinutesStart,
+ pastMinutesEnd,
});
const query = `
diff --git a/server/src/api/analytics/query-validation.ts b/server/src/api/analytics/query-validation.ts
index 8fb008c33..46180347d 100644
--- a/server/src/api/analytics/query-validation.ts
+++ b/server/src/api/analytics/query-validation.ts
@@ -88,29 +88,65 @@ const fillDateParamsSchema = z.object({
/**
* Schema for parameters to getTimeStatement() function
- * Either date or pastMinutes must be provided
+ * Either date, pastMinutes, or pastMinutesRange must be provided
*/
const timeStatementParamsSchema = z
.object({
- date: dateParamsSchema.optional(),
+ date: fillDateParamsSchema.optional(),
pastMinutes: z.number().nonnegative().optional(),
+ pastMinutesRange: z
+ .object({
+ start: z.number().nonnegative(),
+ end: z.number().nonnegative(),
+ })
+ .optional()
+ .refine((data) => !data || data.start > data.end, {
+ message: "start must be greater than end (start = older, end = newer)",
+ }),
})
- .refine((data) => data.date !== undefined || data.pastMinutes !== undefined, {
- message: "Either date or pastMinutes must be provided",
+ .refine(
+ (data) =>
+ data.date !== undefined ||
+ data.pastMinutes !== undefined ||
+ data.pastMinutesRange !== undefined,
+ {
+ message: "Either date, pastMinutes, or pastMinutesRange must be provided",
+ }
+ )
+ // Set default empty objects if schema validation fails
+ .catch({
+ date: undefined,
+ pastMinutes: undefined,
+ pastMinutesRange: undefined,
});
/**
* Schema for parameters to getTimeStatementFill() function
- * Either date or pastMinutes must be provided
+ * Either date, pastMinutes, or pastMinutesRange must be provided
*/
const timeStatementFillParamsSchema = z
.object({
date: fillDateParamsSchema.optional(),
pastMinutes: z.number().nonnegative().optional(),
+ pastMinutesRange: z
+ .object({
+ start: z.number().nonnegative(),
+ end: z.number().nonnegative(),
+ })
+ .optional()
+ .refine((data) => !data || data.start > data.end, {
+ message: "start must be greater than end (start = older, end = newer)",
+ }),
})
- .refine((data) => data.date !== undefined || data.pastMinutes !== undefined, {
- message: "Either date or pastMinutes must be provided",
- });
+ .refine(
+ (data) =>
+ data.date !== undefined ||
+ data.pastMinutes !== undefined ||
+ data.pastMinutesRange !== undefined,
+ {
+ message: "Either date, pastMinutes, or pastMinutesRange must be provided",
+ }
+ );
// =============================================================================
// BUCKET RELATED SCHEMAS
diff --git a/server/src/api/analytics/utils.ts b/server/src/api/analytics/utils.ts
index cb30a852b..bf045bcf3 100644
--- a/server/src/api/analytics/utils.ts
+++ b/server/src/api/analytics/utils.ts
@@ -7,37 +7,77 @@ import {
} from "./query-validation.js";
import SqlString from "sqlstring";
-export function getTimeStatement({
- date,
- pastMinutes,
-}: {
- date?: {
- startDate?: string;
- endDate?: string;
- timezone?: string;
- table?: "events" | "sessions";
- };
- pastMinutes?: number;
-}) {
- // Sanitize inputs with Zod
- const sanitized = validateTimeStatementParams({ date, pastMinutes });
+export function getTimeStatement(
+ params:
+ | {
+ date?: {
+ startDate?: string;
+ endDate?: string;
+ timezone?: string;
+ table?: "events" | "sessions";
+ };
+ pastMinutes?: number;
+ pastMinutesRange?: { start: number; end: number };
+ }
+ | {
+ startDate?: string;
+ endDate?: string;
+ timezone?: string;
+ minutes?: string | number;
+ pastMinutesStart?: string | number;
+ pastMinutesEnd?: string | number;
+ }
+) {
+ // Handle if raw query parameters are passed
+ if ("pastMinutesStart" in params || "minutes" in params) {
+ // Extract and normalize raw parameters
+ const {
+ startDate,
+ endDate,
+ timezone,
+ minutes,
+ pastMinutesStart,
+ pastMinutesEnd,
+ } = params;
+
+ // Convert to the internal format
+ const pastMinutesRange =
+ pastMinutesStart && pastMinutesEnd
+ ? {
+ start: Number(pastMinutesStart),
+ end: Number(pastMinutesEnd),
+ }
+ : undefined;
+
+ const normalizedParams = pastMinutesRange
+ ? { pastMinutesRange }
+ : minutes
+ ? { pastMinutes: Number(minutes) }
+ : startDate && endDate
+ ? { date: { startDate, endDate, timezone } }
+ : {};
+
+ // Call self with normalized parameters
+ return getTimeStatement(normalizedParams);
+ }
+
+ // Original function implementation with sanitized parameters
+ const sanitized = validateTimeStatementParams(params);
if (sanitized.date) {
- const { startDate, endDate, timezone, table } = sanitized.date;
+ const { startDate, endDate, timezone } = sanitized.date;
if (!startDate && !endDate) {
return "";
}
- const col = (table ?? "events") === "events" ? "timestamp" : "session_end";
-
// Use SqlString.escape for date and timezone values
- return `AND ${col} >= toTimeZone(
+ return `AND timestamp >= toTimeZone(
toStartOfDay(toDateTime(${SqlString.escape(
startDate
)}, ${SqlString.escape(timezone)})),
'UTC'
)
- AND ${col} < if(
+ AND timestamp < if(
toDate(${SqlString.escape(endDate)}) = toDate(now(), ${SqlString.escape(
timezone
)}),
@@ -50,12 +90,27 @@ export function getTimeStatement({
)
)`;
}
+
+ // Handle specific range of past minutes
+ if (sanitized.pastMinutesRange) {
+ const { start, end } = sanitized.pastMinutesRange;
+ return `AND timestamp > now() - interval ${SqlString.escape(
+ start
+ )} minute AND timestamp <= now() - interval ${SqlString.escape(
+ end
+ )} minute`;
+ }
+
+ // Handle standard past minutes
if (sanitized.pastMinutes) {
// Use SqlString.escape for pastMinutes (it handles numbers)
return `AND timestamp > now() - interval ${SqlString.escape(
sanitized.pastMinutes
)} minute`;
}
+
+ // If no valid time parameters were provided, return empty string
+ return "";
}
export async function processResults<T>(