Skip to content

Commit

Permalink
Changes
Browse files Browse the repository at this point in the history
  • Loading branch information
ishaan812 committed Jun 30, 2024
1 parent 82d426a commit 2d56f9c
Show file tree
Hide file tree
Showing 12 changed files with 126 additions and 84 deletions.
99 changes: 67 additions & 32 deletions packages/nextjs/app/analytics/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,20 @@ import {
ListItem,
ListItemText,
MenuItem,
Paper,
Select,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Typography,
} from "@mui/material";
import LineChart from "~~/components/analytics/LineChart";
import {
getTop5Frames,
getTop5Journeys,
getTotalInteractions,
getTotalInteractionsGraph,
getUniqueUsers,
Expand All @@ -28,7 +35,7 @@ const AnalyticsPage = () => {
const [journeyId, setJourneyId] = useState("");
const [totalInteractions, setTotalInteractions] = useState<number>();
const [uniqueInteractions, setUniqueInteractions] = useState<number>();
const [top5Frames, setTop5Frames] = useState<any[]>([]);
const [top5Journeys, settop5Journeys] = useState<any[]>([]);
const [totalInteractionsGraph, setTotalInteractionsGraph] = useState<any[]>([]);

const formatDate = (date: Date) => {
Expand All @@ -37,6 +44,35 @@ const AnalyticsPage = () => {
const year = date.getFullYear();
return `${month}-${day}-${year}`;
};
useEffect(() => {
const getDateRange = () => {
const today = new Date();
const actualToday = new Date(today.getDate() + 1);
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
const lastWeek = new Date(today);
lastWeek.setDate(today.getDate() - 7);
const lastMonth = new Date(today);
lastMonth.setMonth(today.getMonth() - 1);
switch (dateRange) {
case "last-day":
return { start: formatDate(yesterday), end: formatDate(actualToday) };
case "last-7-days":
return { start: formatDate(lastWeek), end: formatDate(actualToday) };
case "last-30-days":
return { start: formatDate(lastMonth), end: formatDate(actualToday) };
default:
return { start: formatDate(lastWeek), end: formatDate(actualToday) };
}
};
const { start, end } = getDateRange();
getTotalInteractions(start, end, journeyId).then(data => setTotalInteractions(data));
getUniqueUsers(start, end, journeyId).then(data => setUniqueInteractions(data));
getTotalInteractionsGraph(start, end, journeyId).then(data => {
setTotalInteractionsGraph(data);
});
}, [dateRange, journeyId]);

useEffect(() => {
const getDateRange = () => {
const today = new Date();
Expand All @@ -58,11 +94,8 @@ const AnalyticsPage = () => {
}
};
const { start, end } = getDateRange();
getTotalInteractions(start, end, journeyId).then(data => setTotalInteractions(data));
getUniqueUsers(start, end, journeyId).then(data => setUniqueInteractions(data));
getTop5Frames(start, end).then((data: any[]) => setTop5Frames(data));
getTotalInteractionsGraph(start, end, journeyId).then(data => setTotalInteractionsGraph(data));
}, [dateRange, journeyId]);
getTop5Journeys(start, end).then((data: any[]) => settop5Journeys(data));
}, [dateRange]);

return (
<Container>
Expand Down Expand Up @@ -107,32 +140,34 @@ const AnalyticsPage = () => {
</Box>
<Box sx={{ my: 4 }}>
<Typography variant="h6" style={{ fontWeight: "bold" }}>
Top 5 Frames
Top 5 Journeys
</Typography>
<List>
<ListItem key={0}>
<ListItemText
primary={
<Typography variant="subtitle1" style={{ fontWeight: "bold" }}>
Frame ID
</Typography>
}
/>
<ListItemText
primary={
<Typography variant="subtitle1" style={{ fontWeight: "bold" }}>
Count
</Typography>
}
/>
</ListItem>
{top5Frames.map((frame, index) => (
<ListItem key={index}>
<ListItemText primary={frame._id} />
<ListItemText primary={frame.count} />
</ListItem>
))}
</List>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>
<Typography variant="subtitle1" style={{ fontWeight: "bold" }}>
Journey Name
</Typography>
</TableCell>
<TableCell>
<Typography variant="subtitle1" style={{ fontWeight: "bold" }}>
Interactions
</Typography>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{top5Journeys.map((frame, index) => (
<TableRow key={index}>
<TableCell>{frame.journeyName}</TableCell>
<TableCell>{frame.count}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Box>
</Box>
</Container>
Expand Down
18 changes: 0 additions & 18 deletions packages/nextjs/app/api/analytics/top5frames/route.ts

This file was deleted.

23 changes: 23 additions & 0 deletions packages/nextjs/app/api/analytics/top5journeys/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { NextResponse } from "next/server";
import Analytics from "~~/model/analytics";
import Journey from "~~/model/journey";
import connectDB from "~~/services/connectDB";

export async function GET() {
await connectDB();
const topJourneys = await Analytics.aggregate([
{ $group: { _id: "$journeyId", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 5 },
]).exec();

for (const journey of topJourneys) {
const journeyBody = await Journey.findById(journey._id);
journey.journeyName = journeyBody?.name;
}
return new NextResponse(JSON.stringify(topJourneys), {
headers: {
"Content-Type": "application/json",
},
});
}
1 change: 0 additions & 1 deletion packages/nextjs/app/api/frame/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export async function GET(req: NextRequest, { params }: { params: { id: string }
await connectDB();
const frame_id = params.id;
const frame = await Frame.findById(frame_id);
console.log(frame);
if (!frame) {
return new NextResponse(JSON.stringify({ message: "Frame not found" }), { status: 404 });
}
Expand Down
1 change: 0 additions & 1 deletion packages/nextjs/app/api/journey/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ export async function GET() {
export async function POST(req: NextRequest) {
await connectDB();
const payload = await req.json();
console.log(payload);
const journey = new Journey(payload);
await journey.save();
return new NextResponse(JSON.stringify(journey));
Expand Down
33 changes: 17 additions & 16 deletions packages/nextjs/app/api/orchestrator/[frameId]/route.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { FrameRequest, getFrameHtmlResponse } from "@coinbase/onchainkit";
import { APP_URL } from "~~/constants";
import Analytics from "~~/model/analytics";
import connectDB from "~~/services/connectDB";
import { getFrameAtServer } from "~~/services/frames";

const storeAnalytics = async (body: FrameRequest, state: any) => {
const analyticsEntry = new Analytics({
journeyId: state?.journeyId || "",
frameId: state?.frameId || "",
journeyId: state?.journey_id || "",
frameId: state?.frame_id || "",
fid: body.untrustedData.fid,
buttonClicked: body.untrustedData.buttonIndex || 0,
inputtedText: body.untrustedData.inputText || "",
timestamp: body.untrustedData.timestamp,
});
analyticsEntry.save();
await analyticsEntry.save();
console.log(analyticsEntry);
};

async function getResponse(req: NextRequest): Promise<NextResponse> {
await connectDB();
const url = req.nextUrl.pathname;
const frameId = url.replace(`/api/orchestrator`, "");
const body = await req.json();
console.log("GETTTTTING HIT")
// const state = JSON.parse(decodeURIComponent(body.untrustedData.state as string));

console.log("body", body);
const state = JSON.parse(decodeURIComponent(body.untrustedData.state as string));
console.log("state", state);
// Creating Analytics for the frame asynchronously
// storeAnalytics(body, state).catch(err => console.error("Error Saving Analytics", err));
storeAnalytics(body, state).catch(err => console.error("Error Saving Analytics", err));
// Adding State for Button Press and Inputted Text on last frame
// const stateUpdate = {
// ...state,
// [`${frameId}ButtonPressed`]: body.untrustedData.buttonIndex,
// [`${frameId}InputtedText`]: body.untrustedData.inputText,
// };
state.frame_id = frameId;
const stateUpdate = {
...state,
[`${frameId}ButtonPressed`]: body.untrustedData.buttonIndex,
[`${frameId}InputtedText`]: body.untrustedData.inputText,
};
const dbFrame = await getFrameAtServer(frameId);
if (!dbFrame) {
return new NextResponse(JSON.stringify({ message: "Frame not found" }), { status: 404 });
}
const nextFrame = dbFrame.frameJson;
// nextFrame.state = {
// ...stateUpdate,
// };
nextFrame.state = {
...stateUpdate,
};
return new NextResponse(getFrameHtmlResponse(nextFrame));
}

Expand Down
6 changes: 3 additions & 3 deletions packages/nextjs/components/FramesSidebar.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { DEFAULT_FRAME } from "~~/constants";
import { useProductJourney } from "~~/providers/ProductProvider";
import { getFrameById } from "~~/services/frames";
import { GetDefaultFrame } from "~~/services/frames/frameGetters";
import { Frame } from "~~/types/commontypes";

const thumbnailImageStyle = {
Expand Down Expand Up @@ -35,7 +35,7 @@ const thumbnailActiveStyle = {
backgroundColor: "#c0c0c0",
};
function FrameSidebar() {
const { productQuery, frame, setFrame, setCurrentFrame, createFrame } = useProductJourney();
const { productQuery, productID, frame, setFrame, setCurrentFrame, createFrame } = useProductJourney();
const [frames, setFrames] = useState<Frame[] | undefined>(undefined);
const [currentFrameId, setCurrentFrameId] = useState<string>(frame?._id as string);
useEffect(() => {
Expand All @@ -53,7 +53,7 @@ function FrameSidebar() {
const onCreate = async () => {
await createFrame.mutateAsync({
name: "Frame",
frameJson: DEFAULT_FRAME,
frameJson: await GetDefaultFrame(productID),
});
};
if (!frames) return null;
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/components/analytics/LineChart.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react";
import Chart from "react-apexcharts";

const LineChart = ({ data }) => {
const LineChart = ({ data }: { data: any }) => {
// Prepare data for ApexCharts
const series = [
{
Expand Down
4 changes: 2 additions & 2 deletions packages/nextjs/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FrameMetadataType } from "@coinbase/onchainkit";
import { Abi } from "viem";

export const APP_URL = "https://950a-103-216-213-71.ngrok-free.app";
export const APP_URL = "http://localhost:3000";
export const txFrame = {
buttons: [
{
Expand Down Expand Up @@ -708,4 +708,4 @@ export const ABI: Abi = [
},
];
export const contract = "0x059ee9bde2aff94d0e6ad396ec0ec7d27bff6dc8";
export const myAddress = "0x027fe3f132403c1b59ddaba14b576d15865f69c0"
export const myAddress = "0x027fe3f132403c1b59ddaba14b576d15865f69c0";
7 changes: 3 additions & 4 deletions packages/nextjs/services/analytics/getAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@ export const getUniqueUsers = async (startDate: string, endDate: string, journey
if (journeyId !== "") {
queryparams = `?startDate=${startDate}&endDate=${endDate}&journeyId=${journeyId}`;
}
console.log("Query", queryparams);
const res = await fetch(`/api/analytics/unique_fids` + queryparams);
const data = await res.json();
console.log("unique", data);
return data.uniqueFids;
};

export const getTop5Frames = async (startDate: string, endDate: string) => {
export const getTop5Journeys = async (startDate: string, endDate: string) => {
const queryparams = "?startDate=" + startDate + "&endDate=" + endDate;
const res = await fetch(`/api/analytics/top5frames` + queryparams);
const res = await fetch(`/api/analytics/top5journeys` + queryparams);
const data = await res.json();
console.log(data);
return data;
};

Expand Down
8 changes: 2 additions & 6 deletions packages/nextjs/services/frames.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { APP_URL, DEFAULT_FRAME } from "~~/constants";
import { Frame, Journey } from "~~/types/commontypes";
import { GetDefaultFrame } from "./frames/frameGetters";

export const getFrameById = async (id: string) => {
try {
Expand Down Expand Up @@ -52,11 +53,6 @@ export const createFrame = async (frame: Omit<Frame, "_id">) => {
};

export const createJourney = async (journey: Partial<Journey>) => {
const frame = await createFrame({
frameJson: DEFAULT_FRAME,
name: "Frame 1",
});
journey.frames = [frame._id];
try {
const response = await fetch(`/api/journey`, {
method: "POST",
Expand All @@ -67,7 +63,7 @@ export const createJourney = async (journey: Partial<Journey>) => {
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
};
return response.json();
} catch (error: any) {
console.error(error);
Expand Down
8 changes: 8 additions & 0 deletions packages/nextjs/services/frames/frameGetters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { FrameMetadataType } from "@coinbase/onchainkit";
import { DEFAULT_FRAME } from "~~/constants";

export const GetDefaultFrame = async (journey_id: string) => {
let frame: FrameMetadataType = DEFAULT_FRAME;
frame.state.journey_id = journey_id;
return frame;
};

0 comments on commit 2d56f9c

Please sign in to comment.