add charts and reset stats function

This commit is contained in:
2025-04-01 14:30:40 +02:00
parent 46d10d6ef4
commit 96a3497aea
7 changed files with 589 additions and 66 deletions
+29
View File
@@ -207,4 +207,33 @@ export async function pinPageToRoot(prevState: any, fromData: FormData) {
};
}
}
export async function deletePageStats(prevState: any, formData: FormData) {
const schema = z.object({
uuid: z.string().uuid()
});
const data = schema.safeParse({
uuid: formData.get("uuid")
});
if (!data.success) {
return {
message: "Invalid data",
error: data.error.flatten().fieldErrors,
};
}
await prisma.stat.deleteMany({
where: {
pageUuid: data.data.uuid
}
});
revalidatePath(`/~/dash/${data.data.uuid}`);
return {
message: "Stats deleted",
};
}
+128
View File
@@ -0,0 +1,128 @@
'use server'
import prisma from "../../prisma/prisma";
export async function getDailyStats(pageUuid: string) {
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
const dailyStats = await prisma.stat.groupBy({
by: ['accessedAt'],
where: {
pageUuid: pageUuid,
accessedAt: {
gte: sevenDaysAgo
}
},
_count: {
uuid: true
},
orderBy: {
accessedAt: 'asc'
}
});
// Group by date only (ignoring time)
const groupedByDate = dailyStats.reduce((acc, stat) => {
const date = stat.accessedAt.toISOString().split('T')[0];
if (!acc[date]) {
acc[date] = {
date: stat.accessedAt.toISOString(),
clicks: 0
};
}
acc[date].clicks += stat._count.uuid;
return acc;
}, {} as Record<string, { date: string; clicks: number }>);
return Object.values(groupedByDate);
}
export async function getPageData(uuid: string) {
return await prisma.page.findUnique({
where: { uuid: uuid },
include: {
pinnedPage: true,
redirectPage: true,
customPage: true,
stat: { orderBy: { accessedAt: "desc" } },
_count: {
select: { stat: true }
}
}
});
}
export async function getPageStats(uuid: string) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const [stats, clicksToday, lastVisit] = await Promise.all([
prisma.stat.groupBy({
by: ['hash', 'userAgent'],
where: {
pageUuid: uuid
},
_count: {
uuid: true
},
_max: {
accessedAt: true
},
orderBy: {
_max: {
accessedAt: "desc"
}
}
}),
prisma.stat.count({
where: {
pageUuid: uuid,
accessedAt: {
gte: today
}
}
}),
prisma.stat.findFirst({
where: {
pageUuid: uuid
},
orderBy: {
accessedAt: 'desc'
}
})
]);
return {
stats,
clicksToday,
lastVisit: lastVisit?.accessedAt
};
}
export async function getCustomPageData(customPageUuid: string) {
const [linkPages, linkBlocks] = await Promise.all([
prisma.redirectPage.findMany({
include: { page: true }
}),
prisma.linkBlock.findMany({
where: {
customPageUuid: customPageUuid
},
orderBy: {
order: "asc"
},
include: {
redirectPage: { include: { page: true } }
}
})
]);
const shortcodes = linkPages.map((p) => p.page.shortcode);
return {
linkPages,
linkBlocks,
shortcodes
};
}
+28 -63
View File
@@ -9,6 +9,9 @@ import { hashToColor } from "@/utils";
import PinPageToRootForm from "@/components/forms/pinPageToRootForm";
import { ArrowTopRightOnSquareIcon, BookmarkIcon } from "@heroicons/react/24/solid";
import QRCode from "@/components/QRCode";
import ResetStatsForm from "@/components/forms/resetStatsForm";
import LineChart from "@/components/LineChart";
import { getDailyStats, getPageData, getPageStats, getCustomPageData } from "@/actions/stats";
interface PageProps {
params: Promise<{
@@ -17,68 +20,25 @@ interface PageProps {
}
export default async function DetailedStats({ params }: PageProps) {
const { uuid } = await params;
const page = await prisma.page.findUnique({
where: { uuid: uuid },
include: {
pinnedPage: true,
redirectPage: true,
customPage: true,
stat: { orderBy: { accessedAt: "desc" } },
_count: {
select: { stat: true }
}
}
});
// group stats by hash
const stats = await prisma.stat.groupBy({
by: ['hash', 'userAgent'],
where: {
pageUuid: uuid
},
_count: {
uuid: true
},
_max: {
accessedAt: true
},
orderBy: {
_max: {
accessedAt: "desc"
}
}
});
const [page, pageStats] = await Promise.all([
getPageData(uuid),
getPageStats(uuid)
]);
if (!page) {
redirect("/~/dash");
//return notFound();
}
const redirectPage = page.redirectPage[0];
const customPage = page.customPage[0];
// get shortcodes if the page is a custom page to use in the link block form
const linkPages = customPage ? await prisma.redirectPage.findMany({ include: { page: true } }) : undefined
const shortcodes = linkPages ? linkPages.map((p) => p.page.shortcode) : undefined
// get custom page data if needed
const customPageData = customPage ? await getCustomPageData(customPage.uuid) : undefined;
// get link blocks if the page is a custom page
const linkBlocks = customPage ? await prisma.linkBlock.findMany({
where: {
customPageUuid: customPage.uuid
},
orderBy: {
order: "asc"
},
include: {
redirectPage: { include: { page: true } }
}
}) : undefined;
// Get chart data using server action
const chartData = await getDailyStats(uuid);
return (
<div>
@@ -125,23 +85,28 @@ export default async function DetailedStats({ params }: PageProps) {
<QRCode url={page.shortcode} />
</div>
{customPage ? <CustomPageDashboard customPage={customPage} linkBlocks={linkBlocks || []} shortcodes={shortcodes || []} /> : ""}
{customPage ? <CustomPageDashboard customPage={customPage} linkBlocks={customPageData?.linkBlocks || []} shortcodes={customPageData?.shortcodes || []} /> : ""}
<h2 className="mt-10">Visitors</h2>
<p className="my-2">All visits (not unique): {page._count.stat}</p>
<div className="flex justify-between items-center mt-10">
<h2 className="m-0">Stats</h2>
<div className="ml-auto">
<ResetStatsForm uuid={page.uuid} />
</div>
</div>
<p className="my-2">Clicks today: {pageStats.clicksToday}</p>
<p className="my-2">Last visit: {pageStats.lastVisit?.toLocaleString()}</p>
<p className="my-2">Unique visitors: {pageStats.stats.length}</p>
<p className="my-2">All clicks: {page._count.stat}</p>
{stats.map((stat) => (<div className="zebra" key={stat.hash}>
<h3 className="mt-10">Last 7 Days</h3>
<LineChart data={chartData} />
<h3 className="mt-10">All Visits</h3>
{pageStats.stats.map((stat) => (<div className="zebra" key={stat.hash}>
<p style={{ color: hashToColor(stat.hash) }}>{stat.userAgent}</p>
<p>Visits: {"" + stat._count.uuid}</p>
<p>Last Visit: {stat._max.accessedAt?.toDateString()}</p>
<p>Last Visit: {stat._max.accessedAt?.toLocaleString()}</p>
</div>))}
{/* <h2>All Visits</h2>
{page.stat.map((stat) => (<div className="my-5" key={stat.uuid}>
<p>{stat.accessedAt.toDateString()}</p>
<p>{stat.userAgent}</p>
<p style={{ color: hashToColor(stat.hash) }}>{stat.hash}</p>
</div>))} */}
</div>
);
}
+47
View File
@@ -0,0 +1,47 @@
"use client"
import { LineChart as RechartsLineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
interface LineChartProps {
data: {
date: string;
clicks: number;
}[];
}
export default function LineChart({ data }: LineChartProps) {
return (
<div className="w-full h-[300px] mt-5">
<ResponsiveContainer width="100%" height="100%">
<RechartsLineChart data={data}>
<CartesianGrid strokeDasharray="3 3" stroke="#374151" />
<XAxis
dataKey="date"
stroke="#9CA3AF"
tickFormatter={(value: string) => new Date(value).toLocaleDateString()}
/>
<YAxis
stroke="#9CA3AF"
allowDecimals={false}
/>
<Tooltip
contentStyle={{
backgroundColor: '#1F2937',
border: 'none',
borderRadius: '0.5rem',
color: '#9CA3AF'
}}
labelFormatter={(value: string) => new Date(value).toLocaleDateString()}
/>
<Line
type="monotone"
dataKey="clicks"
stroke="#10B981"
strokeWidth={2}
dot={{ fill: '#10B981', strokeWidth: 2 }}
/>
</RechartsLineChart>
</ResponsiveContainer>
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
"use client"
import { deletePageStats } from "@/actions/page_actions";
import { useActionState, useEffect } from "react";
import SubmitButton from "../SubmitButton";
import { handleToast } from "@/utils";
import { ArrowPathIcon } from "@heroicons/react/24/solid";
export default function ResetStatsForm({ uuid }: { uuid: string }) {
const initialState = {
message: "",
error: {}
};
const [state, formAction] = useActionState(deletePageStats, initialState);
useEffect(() => { handleToast(state); }, [state]);
return (
<form action={formAction}>
<input type="hidden" name="uuid" value={uuid} />
<SubmitButton><ArrowPathIcon className="button-icon" /></SubmitButton>
</form>
);
}