Skip to content

Commit

Permalink
Unique Users Graph
Browse files Browse the repository at this point in the history
  • Loading branch information
ishaan812 committed Jul 1, 2024
1 parent ae22328 commit 979b08e
Show file tree
Hide file tree
Showing 3 changed files with 127 additions and 3 deletions.
30 changes: 27 additions & 3 deletions packages/nextjs/app/analytics/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import { useEffect, useState } from "react";
import {
Box,
Button,
ButtonGroup,
Container,
FormControl,
Grid,
Expand All @@ -28,6 +30,7 @@ import {
getTotalInteractions,
getTotalInteractionsGraph,
getUniqueUsers,
getUniqueUsersGraph,
} from "~~/services/analytics/getAnalytics";

const AnalyticsPage = () => {
Expand All @@ -37,6 +40,8 @@ const AnalyticsPage = () => {
const [uniqueInteractions, setUniqueInteractions] = useState<number>();
const [top5Journeys, settop5Journeys] = useState<any[]>([]);
const [totalInteractionsGraph, setTotalInteractionsGraph] = useState<any[]>([]);
const [uniqueUsersGraph, setUniqueUsersGraph] = useState<any[]>([]);
const [selectedChart, setSelectedChart] = useState("users");

const formatDate = (date: Date) => {
const month = String(date.getMonth() + 1).padStart(2, "0");
Expand Down Expand Up @@ -71,9 +76,12 @@ const AnalyticsPage = () => {
setUniqueInteractions(data);
});
getTotalInteractionsGraph(start, journeyId).then(data => {
console.log(data);
setTotalInteractionsGraph(data);
});
getUniqueUsersGraph(start, journeyId).then(data => {
console.log(data);
setUniqueUsersGraph(data);
});
}, [dateRange, journeyId]);

useEffect(() => {
Expand Down Expand Up @@ -137,9 +145,25 @@ const AnalyticsPage = () => {
</Grid>
<Box sx={{ my: 4 }}>
<Typography variant="h6" style={{ fontWeight: "bold" }}>
Interactions Over Time
Chart Type
</Typography>
<LineChart data={totalInteractionsGraph} />
<ButtonGroup variant="contained" sx={{ mb: 4 }}>
<Button onClick={() => setSelectedChart("interactions")} disabled={selectedChart === "interactions"}>
Total Interactions Over Time
</Button>
<Button onClick={() => setSelectedChart("users")} disabled={selectedChart === "users"}>
Unique Users Over Time
</Button>
</ButtonGroup>
{selectedChart === "users" ? (
<Box>
<LineChart data={totalInteractionsGraph} />
</Box>
) : (
<Box>
<LineChart data={uniqueUsersGraph} />
</Box>
)}
</Box>
<Box sx={{ my: 4 }}>
<Typography variant="h6" style={{ fontWeight: "bold" }}>
Expand Down
73 changes: 73 additions & 0 deletions packages/nextjs/app/api/analytics/unique_fids/graph/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { NextRequest, NextResponse } from "next/server";
import Analytics from "~~/model/analytics";
import connectDB from "~~/services/connectDB";

type DateFilter = {
$gte?: Date;
$lte?: Date;
};

export async function GET(request: NextRequest) {
await connectDB();
const { searchParams } = new URL(request.url);
const startDate = searchParams.get("startDate");
const frameId = searchParams.get("frameId");
const journeyId = searchParams.get("journeyId");
const dateFilter: DateFilter = {};
console.log(startDate, frameId, journeyId);
if (startDate) {
dateFilter.$gte = new Date(startDate);
}
const query: any = {};
if (startDate) {
query.createdAt = dateFilter;
}
if (frameId) {
query.frameId = frameId;
}
if (journeyId) {
query.journeyId = journeyId;
}
const aggregationPipeline = [
{
$match: query,
},
{
$group: {
_id: {
date: {
$dateToString: {
format: "%Y-%m-%d",
date: "$createdAt",
},
},
fid: "$fid", // assuming the unique identifier is stored in the 'fid' field
},
},
},
{
$group: {
_id: "$_id.date",
count: { $sum: 1 },
},
},
{
$project: {
date: "$_id",
count: 1,
_id: 0,
},
},
{
$sort: { date: 1 } as any,
},
];
const results = await Analytics.aggregate(aggregationPipeline).exec();
console.log(results);
// write a loop iterating from startDate to endDate and filling in the missing dates with 0
return new NextResponse(JSON.stringify(results), {
headers: {
"Content-Type": "application/json",
},
});
}
27 changes: 27 additions & 0 deletions packages/nextjs/services/analytics/getAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,30 @@ export const getTotalInteractionsGraph = async (startDate: string, journeyId = "
}
return finalGraph;
};

export const getUniqueUsersGraph = async (startDate: string, journeyId = "") => {
let queryparams = "?startDate=" + startDate;
if (journeyId !== "") {
queryparams += `&journeyId=${journeyId}`;
}
const res = await fetch(`/api/analytics/unique_fids/graph` + queryparams);
const data = await res.json();
const finalGraph = [];
const currentDate = new Date(startDate);
const endDateObj = new Date();
const adjustedDateObj = new Date(endDateObj.getTime() + 1 * 24 * 60 * 60 * 1000);
while (currentDate <= adjustedDateObj) {
const dateStr = currentDate.toISOString().split("T")[0];
const entry = data.find((entry: any) => {
const entryDateStr = new Date(entry.date).toISOString().split("T")[0];
return entryDateStr === dateStr;
});
if (entry) {
finalGraph.push(entry);
} else {
finalGraph.push({ date: dateStr, count: 0 });
}
currentDate.setDate(currentDate.getDate() + 1);
}
return finalGraph;
}

0 comments on commit 979b08e

Please sign in to comment.