File size: 2,033 Bytes
81d1e4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import prisma from "../../config/database";

export class AnalyticsService {
  async track(page: string, visitorIp?: string, userAgent?: string, referer?: string) {
    return await prisma.analytics.create({
      data: { page, visitorIp, userAgent, referer },
    });
  }

  async getDashboard() {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const thisMonth = new Date(today.getFullYear(), today.getMonth(), 1);

    try {
      const [visitorsToday, monthlyVisitors, totalPageViews, recentViews, topProjects] =
        await Promise.all([
          prisma.analytics.groupBy({
            by: ["visitorIp"],
            where: { createdAt: { gte: today } },
          }),
          prisma.analytics.groupBy({
            by: ["visitorIp"],
            where: { createdAt: { gte: thisMonth } },
          }),
          prisma.analytics.count(),
          prisma.analytics.findMany({
            orderBy: { createdAt: "desc" },
            take: 100,
          }),
          prisma.analytics.groupBy({
            by: ["page"],
            _count: { id: true },
            where: { page: { startsWith: "/projects" } },
            orderBy: { _count: { id: "desc" } },
            take: 5,
          }),
        ]);

      let dailyVisitors: any[] = [];
      try {
        dailyVisitors = await prisma.$queryRaw`
          SELECT DATE("createdAt") as date, COUNT(DISTINCT "visitorIp") as count
          FROM "Analytics"
          WHERE "createdAt" >= ${thisMonth}
          GROUP BY DATE("createdAt")
          ORDER BY date DESC
        `;
      } catch {
        dailyVisitors = [];
      }

      return {
        visitorsToday: visitorsToday.length,
        monthlyVisitors: monthlyVisitors.length,
        totalPageViews,
        dailyVisitors,
        topProjects,
        recentViews,
      };
    } catch {
      return {
        visitorsToday: 0,
        monthlyVisitors: 0,
        totalPageViews: 0,
        dailyVisitors: [],
        topProjects: [],
        recentViews: [],
      };
    }
  }
}