🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
rearrange apis
Bill Yang0e95a8876811
diff --git a/client/src/api/admin/auth.ts b/client/src/api/admin/auth.tsnew file mode 100644index 000000000..0f0f32f1a--- /dev/null+++ b/client/src/api/admin/auth.ts@@ -0,0 +1,29 @@+import { useQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { authedFetch } from "../utils";++type GetOrganizationMembersResponse = {+ data: {+ id: string;+ role: string;+ userId: string;+ organizationId: string;+ createdAt: string;+ user: {+ id: string;+ name: string | null;+ email: string;+ };+ }[];+};++export const useOrganizationMembers = (organizationId: string) => {+ return useQuery<GetOrganizationMembersResponse>({+ queryKey: ["organization-members", organizationId],+ queryFn: () =>+ authedFetch(+ `${BACKEND_URL}/list-organization-members/${organizationId}`+ ).then((res) => res.json()),+ staleTime: Infinity,+ });+};diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.tsnew file mode 100644index 000000000..4edeb383c--- /dev/null+++ b/client/src/api/admin/sites.ts@@ -0,0 +1,53 @@+import { useQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { authedFetch, useGenericQuery } from "../utils";++export type GetSitesResponse = {+ siteId: number;+ name: string;+ domain: string;+ createdAt: string;+ updatedAt: string;+ createdBy: string;+}[];++export function useGetSites() {+ return useGenericQuery<GetSitesResponse>("get-sites");+}++export function addSite(domain: string, name: string, organizationId: string) {+ return authedFetch(`${BACKEND_URL}/add-site`, {+ method: "POST",+ body: JSON.stringify({+ domain,+ name,+ organizationId,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ });+}++export function deleteSite(siteId: number) {+ return authedFetch(`${BACKEND_URL}/delete-site/${siteId}`, {+ method: "POST",+ });+}++export function changeSiteDomain(siteId: number, newDomain: string) {+ return authedFetch(`${BACKEND_URL}/change-site-domain`, {+ method: "POST",+ body: JSON.stringify({+ siteId,+ newDomain,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ });+}++export function useSiteHasData(siteId: string) {+ return useGenericQuery<boolean>(`site-has-data/${siteId}`);+}diff --git a/client/src/api/admin/subscription.ts b/client/src/api/admin/subscription.tsnew file mode 100644index 000000000..f4c642f70--- /dev/null+++ b/client/src/api/admin/subscription.ts@@ -0,0 +1,53 @@+import { useQuery } from "@tanstack/react-query";+import { authClient } from "../../lib/auth";++export type Subscription = {+ id: string;+ status: "active" | "trialing" | "canceled" | "incomplete" | "past_due";+ plan: string;+ stripeCustomerId?: string;+ stripeSubscriptionId?: string;+ trialStart?: Date;+ trialEnd?: string | null | Date;+ createdAt?: Date;+ updatedAt?: Date;+ cancelAt?: string | null;+ canceledAt?: Date | null;+ periodStart?: Date | string;+ periodEnd?: Date | string;+ cancelAtPeriodEnd: boolean;+ referenceId?: string;+ limits?: {+ events: number;+ [key: string]: any;+ };+ seats?: number;+ metadata?: Record<string, any>;+};++export function useSubscription() {+ return useQuery({+ queryKey: ["subscription"],+ queryFn: async () => {+ try {+ const { data, error } = await authClient.subscription.list();++ if (error) {+ throw new Error(error.message);+ }++ // Find the active subscription+ const activeSubscription =+ data?.find(+ (sub) => sub.status === "active" || sub.status === "trialing"+ ) || null;++ // Ensure the returned data has the correct shape for our frontend+ return activeSubscription as Subscription | null;+ } catch (error) {+ console.error("Failed to fetch subscription:", error);+ throw error;+ }+ },+ });+}diff --git a/client/src/api/analytics/useGetOverview.ts b/client/src/api/analytics/useGetOverview.tsnew file mode 100644index 000000000..c5a3c78a7--- /dev/null+++ b/client/src/api/analytics/useGetOverview.ts@@ -0,0 +1,54 @@+import { useQuery } from "@tanstack/react-query";+import { useStore } from "../../lib/store";+import { authedFetch, getStartAndEndDate } from "../utils";+import { BACKEND_URL } from "../../lib/const";++export type GetOverviewResponse = {+ sessions: number;+ pageviews: number;+ users: number;+ pages_per_session: number;+ bounce_rate: number;+ session_duration: number;+};++type PeriodTime = "current" | "previous";++export function useGetOverview({+ periodTime,+ past24Hours,+ site,+}: {+ periodTime?: PeriodTime;+ past24Hours?: boolean;+ site?: number | string;+}) {+ const { time, previousTime, filters } = useStore();+ const timeToUse = periodTime === "previous" ? previousTime : time;+ const { startDate, endDate } = getStartAndEndDate(timeToUse);++ return useQuery({+ queryKey: ["overview", timeToUse, site, filters, past24Hours],+ queryFn: () => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return authedFetch(+ `${BACKEND_URL}/overview?${startDate ? `startDate=${startDate}&` : ""}${+ endDate ? `endDate=${endDate}&` : ""+ }timezone=${timezone}&site=${site}&filters=${JSON.stringify(filters)}${+ past24Hours ? `&past24Hours=${past24Hours}` : ""+ }`+ ).then((res) => res.json());+ },+ staleTime: Infinity,+ 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;+ },+ });+}diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/useGetOverviewBucketed.tsnew file mode 100644index 000000000..f86aa4b31--- /dev/null+++ b/client/src/api/analytics/useGetOverviewBucketed.ts@@ -0,0 +1,67 @@+import { UseQueryResult, useQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { APIResponse } from "../types";+import { getStartAndEndDate, authedFetch } from "../utils";+import { useStore } from "../../lib/store";++type PeriodTime = "current" | "previous";++export type GetOverviewBucketedResponse = {+ time: string;+ pageviews: number;+ sessions: number;+ pages_per_session: number;+ bounce_rate: number;+ session_duration: number;+ users: number;+}[];++export function useGetOverviewBucketed({+ periodTime,+ past24Hours,+ site,+}: {+ periodTime?: PeriodTime;+ past24Hours?: boolean;+ site?: number | string;+}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {+ const { time, previousTime, bucket, filters } = useStore();++ const timeToUse = periodTime === "previous" ? previousTime : time;++ const { startDate, endDate } = getStartAndEndDate(timeToUse);++ return useQuery({+ queryKey: [+ "overview-bucketed",+ timeToUse,+ bucket,+ site,+ filters,+ past24Hours,+ ],+ queryFn: () => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return authedFetch(+ `${BACKEND_URL}/overview-bucketed?${+ startDate ? `startDate=${startDate}&` : ""+ }${+ endDate ? `endDate=${endDate}&` : ""+ }timezone=${timezone}&bucket=${bucket}&site=${site}&filters=${JSON.stringify(+ filters+ )}${past24Hours ? `&past24Hours=${past24Hours}` : ""}`+ ).then((res) => res.json());+ },+ 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,+ });+}diff --git a/client/src/api/analytics/useLiveUserCount.ts b/client/src/api/analytics/useLiveUserCount.tsnew file mode 100644index 000000000..791a45edc--- /dev/null+++ b/client/src/api/analytics/useLiveUserCount.ts@@ -0,0 +1,15 @@+import { useQuery } from "@tanstack/react-query";+import { useStore } from "../../lib/store";+import { BACKEND_URL } from "../../lib/const";+import { authedFetch } from "../utils";++export function useGetLiveUsercount() {+ const { site } = useStore();+ return useQuery({+ queryKey: ["live-user-count", site],+ queryFn: () =>+ authedFetch(`${BACKEND_URL}/live-user-count/${site}`).then((res) =>+ res.json()+ ),+ });+}diff --git a/client/src/api/analytics/useSingleCol.ts b/client/src/api/analytics/useSingleCol.tsnew file mode 100644index 000000000..895ed1030--- /dev/null+++ b/client/src/api/analytics/useSingleCol.ts@@ -0,0 +1,56 @@+import { useQuery, UseQueryResult } from "@tanstack/react-query";+import { FilterParameter, useStore } from "../../lib/store";+import { APIResponse } from "../types";+import { BACKEND_URL } from "../../lib/const";+import { getStartAndEndDate, authedFetch } from "../utils";++type PeriodTime = "current" | "previous";++export type SingleColResponse = {+ value: string;+ count: number;+ percentage: number;+};++export function useSingleCol({+ parameter,+ limit = 10000,+ periodTime,+ useFilters = true,+}: {+ parameter: FilterParameter;+ limit?: number;+ periodTime?: PeriodTime;+ useFilters?: boolean;+}): 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],+ queryFn: () => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return authedFetch(+ `${BACKEND_URL}/single-col?${+ startDate ? `startDate=${startDate}&` : ""+ }${+ endDate ? `endDate=${endDate}&` : ""+ }timezone=${timezone}&site=${site}¶meter=${parameter}${+ limit ? `&limit=${limit}` : ""+ }${useFilters ? `&filters=${JSON.stringify(filters)}` : ""}`+ ).then((res) => res.json());+ },+ staleTime: Infinity,+ 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;+ },+ });+}diff --git a/client/src/api/analytics/userSessions.ts b/client/src/api/analytics/userSessions.tsnew file mode 100644index 000000000..fcd2db981--- /dev/null+++ b/client/src/api/analytics/userSessions.ts@@ -0,0 +1,90 @@+import { useQuery, useInfiniteQuery } from "@tanstack/react-query";+import { BACKEND_URL } from "../../lib/const";+import { useStore } from "../../lib/store";+import { APIResponse } from "../types";+import { getStartAndEndDate, authedFetch } from "../utils";++export type UserSessionsResponse = {+ session_id: string;+ browser: string;+ operating_system: string;+ device_type: string;+ country: string;+ firstTimestamp: string;+ lastTimestamp: string;+ duration: number; // Duration in seconds+ pageviews: {+ pathname: string;+ querystring: string;+ title: string;+ timestamp: string;+ referrer: string;+ }[];+}[];++export function useGetUserSessions(userId: string) {+ const { time, site, filters } = useStore();+ const { startDate, endDate } = getStartAndEndDate(time);++ return useQuery({+ queryKey: ["user-sessions", userId, time, site, filters],+ queryFn: () => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ return authedFetch(+ `${BACKEND_URL}/user/${userId}/sessions?${+ startDate ? `startDate=${startDate}&` : ""+ }${+ endDate ? `endDate=${endDate}&` : ""+ }timezone=${timezone}&site=${site}&filters=${JSON.stringify(filters)}`+ ).then((res) => res.json());+ },+ staleTime: Infinity,+ });+}++type GetSessionsResponse = {+ session_id: string;+ user_id: string;+ country: string;+ iso_3166_2: string;+ language: string;+ device_type: string;+ browser: string;+ operating_system: string;+ referrer: string;+ last_pageview_timestamp: string;+ pageviews: number;+}[];++export function useGetSessionsInfinite() {+ const { time, site, filters } = useStore();+ const { startDate, endDate } = getStartAndEndDate(time);++ return useInfiniteQuery<APIResponse<GetSessionsResponse>>({+ queryKey: ["sessions-infinite", time, site, filters],+ queryFn: ({ pageParam = 1 }) => {+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ let url = `${BACKEND_URL}/sessions?${+ startDate ? `startDate=${startDate}&` : ""+ }${+ endDate ? `endDate=${endDate}&` : ""+ }timezone=${timezone}&site=${site}&filters=${JSON.stringify(+ filters+ )}&page=${pageParam}`;++ return authedFetch(url).then((res) => res.json());+ },+ initialPageParam: 1,+ getNextPageParam: (+ lastPage: APIResponse<GetSessionsResponse>,+ allPages+ ) => {+ // If we have data and it's a full page (100 items), there might be more+ if (lastPage?.data && lastPage.data.length === 100) {+ return allPages.length + 1;+ }+ return undefined;+ },+ staleTime: Infinity,+ });+}diff --git a/client/src/api/api.ts b/client/src/api/api.tsdeleted file mode 100644index 040832d9a..000000000--- a/client/src/api/api.ts+++ /dev/null@@ -1,412 +0,0 @@-import { authClient } from "@/lib/auth";-import {- useInfiniteQuery,- useQuery,- UseQueryResult,-} from "@tanstack/react-query";-import { BACKEND_URL } from "../lib/const";-import { FilterParameter, useStore } from "../lib/store";-import { authedFetch, getStartAndEndDate } from "./utils";--export type APIResponse<T> = {- data: T;- error?: string;-};--export function useGetLiveUsercount() {- const { site } = useStore();- return useQuery({- queryKey: ["live-user-count", site],- queryFn: () =>- authedFetch(`${BACKEND_URL}/live-user-count/${site}`).then((res) =>- res.json()- ),- });-}--type PeriodTime = "current" | "previous";--export type SingleColResponse = {- value: string;- count: number;- percentage: number;-};--export function useSingleCol({- parameter,- limit = 10000,- periodTime,- useFilters = true,-}: {- parameter: FilterParameter;- limit?: number;- periodTime?: PeriodTime;- useFilters?: boolean;-}): 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],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return authedFetch(- `${BACKEND_URL}/single-col?${- startDate ? `startDate=${startDate}&` : ""- }${- endDate ? `endDate=${endDate}&` : ""- }timezone=${timezone}&site=${site}¶meter=${parameter}${- limit ? `&limit=${limit}` : ""- }${useFilters ? `&filters=${JSON.stringify(filters)}` : ""}`- ).then((res) => res.json());- },- staleTime: Infinity,- 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;- },- });-}--export function useGenericQuery<T>(- endpoint: string-): UseQueryResult<APIResponse<T>> {- return useQuery({- queryKey: [endpoint],- queryFn: () => {- return authedFetch(`${BACKEND_URL}/${endpoint}`).then((res) =>- res.json()- );- },- staleTime: Infinity,- });-}--export type GetOverviewBucketedResponse = {- time: string;- pageviews: number;- sessions: number;- pages_per_session: number;- bounce_rate: number;- session_duration: number;- users: number;-}[];--export function useGetOverviewBucketed({- periodTime,- past24Hours,- site,-}: {- periodTime?: PeriodTime;- past24Hours?: boolean;- site?: number | string;-}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {- const { time, previousTime, bucket, filters } = useStore();-- const timeToUse = periodTime === "previous" ? previousTime : time;-- const { startDate, endDate } = getStartAndEndDate(timeToUse);-- return useQuery({- queryKey: [- "overview-bucketed",- timeToUse,- bucket,- site,- filters,- past24Hours,- ],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return authedFetch(- `${BACKEND_URL}/overview-bucketed?${- startDate ? `startDate=${startDate}&` : ""- }${- endDate ? `endDate=${endDate}&` : ""- }timezone=${timezone}&bucket=${bucket}&site=${site}&filters=${JSON.stringify(- filters- )}${past24Hours ? `&past24Hours=${past24Hours}` : ""}`- ).then((res) => res.json());- },- 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,- });-}--export type GetOverviewResponse = {- sessions: number;- pageviews: number;- users: number;- pages_per_session: number;- bounce_rate: number;- session_duration: number;-};--export function useGetOverview({- periodTime,- past24Hours,- site,-}: {- periodTime?: PeriodTime;- past24Hours?: boolean;- site?: number | string;-}) {- const { time, previousTime, filters } = useStore();- const timeToUse = periodTime === "previous" ? previousTime : time;- const { startDate, endDate } = getStartAndEndDate(timeToUse);-- return useQuery({- queryKey: ["overview", timeToUse, site, filters, past24Hours],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return authedFetch(- `${BACKEND_URL}/overview?${startDate ? `startDate=${startDate}&` : ""}${- endDate ? `endDate=${endDate}&` : ""- }timezone=${timezone}&site=${site}&filters=${JSON.stringify(filters)}${- past24Hours ? `&past24Hours=${past24Hours}` : ""- }`- ).then((res) => res.json());- },- staleTime: Infinity,- 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;- },- });-}--export type GetSitesResponse = {- siteId: number;- name: string;- domain: string;- createdAt: string;- updatedAt: string;- createdBy: string;-}[];--export function useGetSites() {- return useGenericQuery<GetSitesResponse>("get-sites");-}--export function addSite(domain: string, name: string, organizationId: string) {- return authedFetch(`${BACKEND_URL}/add-site`, {- method: "POST",- body: JSON.stringify({- domain,- name,- organizationId,- }),- headers: {- "Content-Type": "application/json",- },- });-}--export function deleteSite(siteId: number) {- return authedFetch(`${BACKEND_URL}/delete-site/${siteId}`, {- method: "POST",- });-}--export function changeSiteDomain(siteId: number, newDomain: string) {- return authedFetch(`${BACKEND_URL}/change-site-domain`, {- method: "POST",- body: JSON.stringify({- siteId,- newDomain,- }),- headers: {- "Content-Type": "application/json",- },- });-}--export function useSiteHasData(siteId: string) {- return useGenericQuery<boolean>(`site-has-data/${siteId}`);-}--// Updated type for grouped sessions from the API-export type UserSessionsResponse = {- session_id: string;- browser: string;- operating_system: string;- device_type: string;- country: string;- firstTimestamp: string;- lastTimestamp: string;- duration: number; // Duration in seconds- pageviews: {- pathname: string;- querystring: string;- title: string;- timestamp: string;- referrer: string;- }[];-}[];--export function useGetUserSessions(userId: string) {- const { time, site, filters } = useStore();- const { startDate, endDate } = getStartAndEndDate(time);-- return useQuery({- queryKey: ["user-sessions", userId, time, site, filters],- queryFn: () => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- return authedFetch(- `${BACKEND_URL}/user/${userId}/sessions?${- startDate ? `startDate=${startDate}&` : ""- }${- endDate ? `endDate=${endDate}&` : ""- }timezone=${timezone}&site=${site}&filters=${JSON.stringify(filters)}`- ).then((res) => res.json());- },- staleTime: Infinity,- });-}--type GetSessionsResponse = {- session_id: string;- user_id: string;- country: string;- iso_3166_2: string;- language: string;- device_type: string;- browser: string;- operating_system: string;- referrer: string;- last_pageview_timestamp: string;- pageviews: number;-}[];--export function useGetSessionsInfinite() {- const { time, site, filters } = useStore();- const { startDate, endDate } = getStartAndEndDate(time);-- return useInfiniteQuery<APIResponse<GetSessionsResponse>>({- queryKey: ["sessions-infinite", time, site, filters],- queryFn: ({ pageParam = 1 }) => {- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;- let url = `${BACKEND_URL}/sessions?${- startDate ? `startDate=${startDate}&` : ""- }${- endDate ? `endDate=${endDate}&` : ""- }timezone=${timezone}&site=${site}&filters=${JSON.stringify(- filters- )}&page=${pageParam}`;-- return authedFetch(url).then((res) => res.json());- },- initialPageParam: 1,- getNextPageParam: (- lastPage: APIResponse<GetSessionsResponse>,- allPages- ) => {- // If we have data and it's a full page (100 items), there might be more- if (lastPage?.data && lastPage.data.length === 100) {- return allPages.length + 1;- }- return undefined;- },- staleTime: Infinity,- });-}--type GetOrganizationMembersResponse = {- data: {- id: string;- role: string;- userId: string;- organizationId: string;- createdAt: string;- user: {- id: string;- name: string | null;- email: string;- };- }[];-};--export const useOrganizationMembers = (organizationId: string) => {- return useQuery<GetOrganizationMembersResponse>({- queryKey: ["organization-members", organizationId],- queryFn: () =>- authedFetch(- `${BACKEND_URL}/list-organization-members/${organizationId}`- ).then((res) => res.json()),- staleTime: Infinity,- });-};--// Subscription types-export type Subscription = {- id: string;- status: "active" | "trialing" | "canceled" | "incomplete" | "past_due";- plan: string;- stripeCustomerId?: string;- stripeSubscriptionId?: string;- trialStart?: Date;- trialEnd?: string | null | Date;- createdAt?: Date;- updatedAt?: Date;- cancelAt?: string | null;- canceledAt?: Date | null;- periodStart?: Date | string;- periodEnd?: Date | string;- cancelAtPeriodEnd: boolean;- referenceId?: string;- limits?: {- events: number;- [key: string]: any;- };- seats?: number;- metadata?: Record<string, any>;-};--export function useSubscription() {- return useQuery({- queryKey: ["subscription"],- queryFn: async () => {- try {- const { data, error } = await authClient.subscription.list();-- if (error) {- throw new Error(error.message);- }-- // Find the active subscription- const activeSubscription =- data?.find(- (sub) => sub.status === "active" || sub.status === "trialing"- ) || null;-- // Ensure the returned data has the correct shape for our frontend- return activeSubscription as Subscription | null;- } catch (error) {- console.error("Failed to fetch subscription:", error);- throw error;- }- },- });-}diff --git a/client/src/api/hooks.ts b/client/src/api/hooks.tsindex d5da41325..cb2169ee9 100644--- a/client/src/api/hooks.ts+++ b/client/src/api/hooks.ts@@ -1,6 +1,6 @@import { useQuery } from "@tanstack/react-query";import { BACKEND_URL } from "../lib/const";-import { useGetSites } from "./api";+import { useGetSites } from "./admin/sites";import { authedFetch } from "./utils";export function useGetSiteMetadata(siteId: string | number) {diff --git a/client/src/api/types.ts b/client/src/api/types.tsnew file mode 100644index 000000000..2bbaece24--- /dev/null+++ b/client/src/api/types.ts@@ -0,0 +1,4 @@+export type APIResponse<T> = {+ data: T;+ error?: string;+};diff --git a/client/src/api/utils.ts b/client/src/api/utils.tsindex 20825a05a..66e914a39 100644--- a/client/src/api/utils.ts+++ b/client/src/api/utils.ts@@ -1,5 +1,8 @@import { Time } from "@/lib/store";import { DateTime } from "luxon";+import { APIResponse } from "./types";+import { useQuery, UseQueryResult } from "@tanstack/react-query";+import { BACKEND_URL } from "../lib/const";export function getStartAndEndDate(time: Time) {if (time.mode === "range") {@@ -35,3 +38,17 @@ export async function authedFetch(url: string, opts: RequestInit = {}) {...opts,});}++export function useGenericQuery<T>(+ endpoint: string+): UseQueryResult<APIResponse<T>> {+ return useQuery({+ queryKey: [endpoint],+ queryFn: () => {+ return authedFetch(`${BACKEND_URL}/${endpoint}`).then((res) =>+ res.json()+ );+ },+ staleTime: Infinity,+ });+}diff --git a/client/src/app/[site]/Header/Header.tsx b/client/src/app/[site]/Header/Header.tsxindex bfc7ce696..86b356cb1 100644--- a/client/src/app/[site]/Header/Header.tsx+++ b/client/src/app/[site]/Header/Header.tsx@@ -5,7 +5,8 @@ import { ChartBarDecreasing, ChartLine, Radio, User } from "lucide-react";import Link from "next/link";import { usePathname } from "next/navigation";import { SiteSettings } from "../../../components/SiteSettings/SiteSettings";-import { useGetLiveUsercount, useGetSites } from "../../../api/api";+import { useGetSites } from "../../../api/admin/sites";+import { useGetLiveUsercount } from "../../../api/analytics/useLiveUserCount";export function Header() {const { data } = useGetLiveUsercount();diff --git a/client/src/app/[site]/components/NoData.tsx b/client/src/app/[site]/components/NoData.tsxindex a281315d4..4d109331a 100644--- a/client/src/app/[site]/components/NoData.tsx+++ b/client/src/app/[site]/components/NoData.tsx@@ -1,6 +1,6 @@import { CodeSnippet } from "../../../components/CodeSnippet";import { Card, CardContent, CardHeader } from "../../../components/ui/card";-import { GetSitesResponse } from "../../../api/api";+import { GetSitesResponse } from "../../../api/admin/sites";import { BACKEND_URL } from "../../../lib/const";export function NoData({diff --git a/client/src/app/[site]/components/SubHeader/Filters/ValueFilter.tsx b/client/src/app/[site]/components/SubHeader/Filters/ValueFilter.tsxindex b83334d26..547499548 100644--- a/client/src/app/[site]/components/SubHeader/Filters/ValueFilter.tsx+++ b/client/src/app/[site]/components/SubHeader/Filters/ValueFilter.tsx@@ -4,29 +4,12 @@ import { useMemo, useState } from "react";import { Button } from "../../../../../components/ui/button";-import { ChevronsUpDown, Plus } from "lucide-react";-import { getCountryName } from "../../../../../lib/utils";-import {- Command,- CommandEmpty,- CommandGroup,- CommandInput,- CommandItem,- CommandList,-} from "../../../../../components/ui/command";--import {- Popover,- PopoverContent,- PopoverTrigger,-} from "../../../../../components/ui/popover";-import { FilterParameter, addFilter } from "../../../../../lib/store";-import { useSingleCol } from "../../../../../api/api";import { MultiSelect } from "../../../../../components/MultiSelect";+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";interface ValueFilterProps {parameter: FilterParameter;diff --git a/client/src/app/[site]/components/SubHeader/SubHeader.tsx b/client/src/app/[site]/components/SubHeader/SubHeader.tsxindex ec7791f8b..006702a18 100644--- a/client/src/app/[site]/components/SubHeader/SubHeader.tsx+++ b/client/src/app/[site]/components/SubHeader/SubHeader.tsx@@ -7,7 +7,7 @@ import { ChevronLeft, ChevronRight } from "lucide-react";import { DateTime } from "luxon";import { usePathname } from "next/navigation";-import { useGetSites } from "../../../../api/api";+import { useGetSites } from "../../../../api/admin/sites";import { DateSelector } from "./DateSelector";const canGoForward = (time: Time) => {diff --git a/client/src/app/[site]/components/shared/StandardCard.tsx b/client/src/app/[site]/components/shared/StandardCard.tsxindex c7fa9a867..fd06aca4d 100644--- a/client/src/app/[site]/components/shared/StandardCard.tsx+++ b/client/src/app/[site]/components/shared/StandardCard.tsx@@ -20,7 +20,10 @@ import { ReactNode, useMemo } from "react";import { addFilter, FilterParameter } from "../../../../lib/store";import { formatter } from "../../../../lib/utils";import { SquareArrowOutUpRight } from "lucide-react";-import { SingleColResponse, useSingleCol } from "../../../../api/api";+import {+ SingleColResponse,+ useSingleCol,+} from "../../../../api/analytics/useSingleCol";export function StandardCard({title,diff --git a/client/src/app/[site]/layout.tsx b/client/src/app/[site]/layout.tsxindex 759f1a65d..5f10cf3cb 100644--- a/client/src/app/[site]/layout.tsx+++ b/client/src/app/[site]/layout.tsx@@ -4,7 +4,7 @@ import { useEffect } from "react";import { useStore } from "../../lib/store";import { useSyncStateWithUrl } from "../../lib/urlParams";import { Header } from "./Header/Header";-import { useSiteHasData } from "../../api/api";+import { useSiteHasData } from "../../api/admin/sites";import { useGetSiteMetadata } from "../../api/hooks";import { NoData } from "./components/NoData";diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsxindex 7d615566d..68b9e909d 100644--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx@@ -1,10 +1,11 @@"use client";-import { APIResponse, GetOverviewBucketedResponse } from "@/api/api";import { nivoTheme } from "@/lib/nivo";import { StatType, Time, TimeBucket, useStore } from "@/lib/store";import { ResponsiveLine } from "@nivo/line";import { DateTime } from "luxon";import { formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";+import { APIResponse } from "../../../../../api/types";+import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";export const formatter = Intl.NumberFormat("en", { notation: "compact" });diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsxindex 46fa40f82..0ea126508 100644--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx@@ -1,11 +1,12 @@"use client";import { Card, CardContent, CardLoader } from "@/components/ui/card";-import { useGetOverview, useGetOverviewBucketed } from "@/api/api";import { BucketSelection } from "./BucketSelection";import { Chart } from "./Chart";import { Overview } from "./Overview";import { PreviousChart } from "./PreviousChart";import { useStore } from "../../../../../lib/store";+import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";+import { useGetOverview } from "../../../../../api/analytics/useGetOverview";export function MainSection() {const { selectedStat, time, site } = useStore();diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsxindex 285e131c5..0cbba9c6b 100644--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx@@ -2,9 +2,9 @@import { Badge } from "@/components/ui/badge";import { Skeleton } from "@/components/ui/skeleton";-import { useGetOverview } from "@/api/api";import { cn, formatSecondsAsMinutesAndSeconds, formatter } from "@/lib/utils";import { StatType, useStore } from "../../../../../lib/store";+import { useGetOverview } from "../../../../../api/analytics/useGetOverview";const ChangePercentage = ({current,diff --git a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsxindex 8f5ea612e..7c4ee5981 100644--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx@@ -1,10 +1,11 @@"use client";-import { APIResponse, GetOverviewBucketedResponse } from "@/api/api";import { nivoTheme } from "@/lib/nivo";import { Time, useStore } from "@/lib/store";import { ResponsiveLine } from "@nivo/line";import { DateTime } from "luxon";import { useMemo } from "react";+import { APIResponse } from "../../../../../api/types";+import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";const getMin = (time: Time) => {if (time.mode === "day") {diff --git a/client/src/app/[site]/main/components/sections/Chloropleth.tsx b/client/src/app/[site]/main/components/sections/Chloropleth.tsxindex bf81fb325..1b0058078 100644--- a/client/src/app/[site]/main/components/sections/Chloropleth.tsx+++ b/client/src/app/[site]/main/components/sections/Chloropleth.tsx@@ -1,12 +1,12 @@"use client";-import { useSingleCol } from "@/api/api";import { scaleLinear } from "d3-scale";import { Feature, FeatureCollection } from "geojson";import { LatLngExpression } from "leaflet";import "leaflet/dist/leaflet.css";import dynamic from "next/dynamic";import { useEffect, useMemo, useState } from "react";+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";const MapContainer = dynamic(() => import("react-leaflet").then((mod) => mod.MapContainer),diff --git a/client/src/app/[site]/main/components/sections/Map.tsx b/client/src/app/[site]/main/components/sections/Map.tsxindex e63858998..cf4647ca0 100644--- a/client/src/app/[site]/main/components/sections/Map.tsx+++ b/client/src/app/[site]/main/components/sections/Map.tsx@@ -11,10 +11,10 @@ import * as CountryFlags from "country-flag-icons/react/3x2";import { scaleLinear } from "d3-scale";import React, { useEffect, useMemo, useState } from "react";import { GeoJSON, MapContainer, useMapEvent } from "react-leaflet";-import { useSingleCol } from "@/api/api";import { Layer } from "leaflet";import { Feature, GeoJsonObject } from "geojson";import "leaflet/dist/leaflet.css";+import { useSingleCol } from "../../../../../api/analytics/useSingleCol";const countriesGeoUrl = "/countries.json";const subdivisionsGeoUrl = "/subdivisions.json";diff --git a/client/src/app/[site]/main/components/sections/Pages.tsx b/client/src/app/[site]/main/components/sections/Pages.tsxindex 1ddfea0e2..6ee046223 100644--- a/client/src/app/[site]/main/components/sections/Pages.tsx+++ b/client/src/app/[site]/main/components/sections/Pages.tsx@@ -1,6 +1,6 @@"use client";-import { GetSitesResponse } from "@/api/api";+import { GetSitesResponse } from "@/api/admin/sites";import { StandardCard } from "../../../components/shared/StandardCard";export function Pages({diff --git a/client/src/app/[site]/main/page.tsx b/client/src/app/[site]/main/page.tsxindex 5926116ef..2821f6fb7 100644--- a/client/src/app/[site]/main/page.tsx+++ b/client/src/app/[site]/main/page.tsx@@ -1,5 +1,5 @@"use client";-import { useSiteHasData } from "../../../api/api";+import { useSiteHasData } from "../../../api/admin/sites";import { useGetSiteMetadata } from "../../../api/hooks";import { useStore } from "../../../lib/store";import { NoData } from "../components/NoData";diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsxindex f3c08a8ef..47d723c54 100644--- a/client/src/app/[site]/sessions/page.tsx+++ b/client/src/app/[site]/sessions/page.tsx@@ -1,9 +1,9 @@"use client";-import { useGetSessionsInfinite } from "@/api/api";import { useMemo } from "react";import SessionsTable from "./components/SessionsTable";import { SubHeader } from "../components/SubHeader/SubHeader";+import { useGetSessionsInfinite } from "../../../api/analytics/userSessions";export default function SessionsPage() {const {diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsxindex d4569c3f1..cf42087de 100644--- a/client/src/app/[site]/user/[userId]/page.tsx+++ b/client/src/app/[site]/user/[userId]/page.tsx@@ -1,6 +1,5 @@"use client";-import { UserSessionsResponse, useGetUserSessions } from "@/api/api";import { useParams } from "next/navigation";import { Skeleton } from "@/components/ui/skeleton";import { Browser } from "../../components/shared/icons/Browser";@@ -10,6 +9,10 @@ import { getCountryName } from "@/lib/utils";import { useGetSiteMetadata } from "../../../../api/hooks";import { useStore } from "../../../../lib/store";import { DateTime } from "luxon";+import {+ useGetUserSessions,+ UserSessionsResponse,+} from "../../../../api/analytics/userSessions";// Helper function to format duration in seconds to a readable formatconst formatDuration = (seconds: number): string => {@@ -60,7 +63,6 @@ export default function UserPage() {const { site } = useStore();const { siteMetadata, isLoading: isLoadingSiteMetadata } =useGetSiteMetadata(site);- console.info(data);// Sessions are now pre-grouped by the serverconst groupedSessions = data?.data || [];diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsxindex ae8f4a622..062f4cf01 100644--- a/client/src/app/components/AddSite.tsx+++ b/client/src/app/components/AddSite.tsx@@ -12,7 +12,7 @@ import {import { useState, useEffect } from "react";import { Label } from "../../components/ui/label";import { Input } from "../../components/ui/input";-import { addSite, useGetSites } from "../../api/api";+import { addSite, useGetSites } from "../../api/admin/sites";import { Alert, AlertDescription, AlertTitle } from "../../components/ui/alert";import {AlertCircle,diff --git a/client/src/app/page.tsx b/client/src/app/page.tsxindex 95db42c34..fc3ea155e 100644--- a/client/src/app/page.tsx+++ b/client/src/app/page.tsx@@ -2,7 +2,7 @@import { useState, useEffect } from "react";import { SiteCard } from "../components/SiteCard";-import { useGetSites } from "../api/api";+import { useGetSites } from "../api/admin/sites";import { authClient } from "../lib/auth";import { AddSite } from "./components/AddSite";import { CreateOrganizationDialog } from "./components/CreateOrganizationDialog";diff --git a/client/src/app/settings/organizations/page.tsx b/client/src/app/settings/organizations/page.tsxindex 57874e0a8..8f106f94c 100644--- a/client/src/app/settings/organizations/page.tsx+++ b/client/src/app/settings/organizations/page.tsx@@ -14,7 +14,6 @@ import {TableHeader,TableRow,} from "../../../components/ui/table";-import { useOrganizationMembers } from "../../../api/api";import { authClient } from "../../../lib/auth";// Import the separated dialog components@@ -23,6 +22,7 @@ import { EditOrganizationDialog } from "./components/EditOrganizationDialog";import { InviteMemberDialog } from "./components/InviteMemberDialog";import { RemoveMemberDialog } from "./components/RemoveMemberDialog";import { useUserOrganizations } from "../../../api/hooks";+import { useOrganizationMembers } from "../../../api/admin/auth";// Types for our componentexport type Organization = {diff --git a/client/src/app/settings/subscription/components/ChangePlanDialog.tsx b/client/src/app/settings/subscription/components/ChangePlanDialog.tsxindex 5572cc395..bd2ac4375 100644--- a/client/src/app/settings/subscription/components/ChangePlanDialog.tsx+++ b/client/src/app/settings/subscription/components/ChangePlanDialog.tsx@@ -9,9 +9,9 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";-import { Subscription } from "@/api/api";import { AlertCircle, Shield, Zap } from "lucide-react";import { useEffect, useState } from "react";+import { Subscription } from "@/api/admin/subscription";interface ChangePlanDialogProps {showUpgradeDialog: boolean;diff --git a/client/src/app/settings/subscription/components/CurrentPlanCard.tsx b/client/src/app/settings/subscription/components/CurrentPlanCard.tsxindex 667f4fb22..d0d7d6d2c 100644--- a/client/src/app/settings/subscription/components/CurrentPlanCard.tsx+++ b/client/src/app/settings/subscription/components/CurrentPlanCard.tsx@@ -11,7 +11,7 @@ import {import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";import { Progress } from "@/components/ui/progress";import { Separator } from "@/components/ui/separator";-import { Subscription } from "@/api/api";+import { Subscription } from "@/api/admin/subscription";import { PlanTemplate, formatDate } from "../utils/planUtils";import { AlertCircle, ArrowRight, X } from "lucide-react";diff --git a/client/src/app/settings/subscription/page.tsx b/client/src/app/settings/subscription/page.tsxindex f1d20fe98..5df7c4d0a 100644--- a/client/src/app/settings/subscription/page.tsx+++ b/client/src/app/settings/subscription/page.tsx@@ -1,9 +1,6 @@"use client";-import { useRouter } from "next/navigation";-import { useState } from "react";import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";-import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import {Card,@@ -14,17 +11,19 @@ import {CardTitle,} from "@/components/ui/card";import { Skeleton } from "@/components/ui/skeleton";-import { useSubscription } from "@/api/api";+import { STRIPE_PRICES } from "@/lib/stripe";import { AlertCircle, ArrowRight } from "lucide-react";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { useSubscription } from "../../../api/admin/subscription";import { authClient } from "../../../lib/auth";-import { CurrentPlanCard } from "./components/CurrentPlanCard";-import { PlanFeaturesCard } from "./components/PlanFeaturesCard";import { ChangePlanDialog } from "./components/ChangePlanDialog";+import { CurrentPlanCard } from "./components/CurrentPlanCard";import { ErrorDialog } from "./components/ErrorDialog";import { HelpSection } from "./components/HelpSection";-import { getPlanDetails } from "./utils/planUtils";+import { PlanFeaturesCard } from "./components/PlanFeaturesCard";import { DEFAULT_EVENT_LIMIT, DEFAULT_USAGE } from "./utils/constants";-import { STRIPE_PRICES } from "@/lib/stripe";+import { getPlanDetails } from "./utils/planUtils";export default function SubscriptionPage() {const router = useRouter();diff --git a/client/src/components/SiteCard.tsx b/client/src/components/SiteCard.tsxindex c86304167..47ff456c0 100644--- a/client/src/components/SiteCard.tsx+++ b/client/src/components/SiteCard.tsx@@ -1,10 +1,11 @@-import { useGetOverview, useGetOverviewBucketed } from "@/api/api";import { ArrowRight } from "lucide-react";import Link from "next/link";import { SiteSessionChart } from "./SiteSessionChart";import { SiteSettings } from "./SiteSettings/SiteSettings";import { Button } from "./ui/button";import { Skeleton } from "./ui/skeleton";+import { useGetOverviewBucketed } from "../api/analytics/useGetOverviewBucketed";+import { useGetOverview } from "../api/analytics/useGetOverview";interface SiteCardProps {siteId: number;diff --git a/client/src/components/SiteSessionChart.tsx b/client/src/components/SiteSessionChart.tsxindex 33bafe44b..42a0a763a 100644--- a/client/src/components/SiteSessionChart.tsx+++ b/client/src/components/SiteSessionChart.tsx@@ -2,8 +2,8 @@ import { nivoTheme } from "@/lib/nivo";import { ResponsiveLine } from "@nivo/line";import { DateTime } from "luxon";import { useMemo } from "react";-import { GetOverviewBucketedResponse } from "../api/api";import { formatter } from "../lib/utils";+import { GetOverviewBucketedResponse } from "../api/analytics/useGetOverviewBucketed";interface SiteSessionChartProps {data: GetOverviewBucketedResponse;diff --git a/client/src/components/SiteSettings/SiteSettings.tsx b/client/src/components/SiteSettings/SiteSettings.tsxindex 3194be512..2e0773bc7 100644--- a/client/src/components/SiteSettings/SiteSettings.tsx+++ b/client/src/components/SiteSettings/SiteSettings.tsx@@ -35,7 +35,7 @@ import {deleteSite,GetSitesResponse,useGetSites,-} from "@/api/api";+} from "@/api/admin/sites";import { BACKEND_URL } from "@/lib/const";import { useGetSiteMetadata } from "../../api/hooks";