Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import useSWRImmutable from "swr/immutable";
import type {
StatsByDayResponse,
StatsByDayQuery,
} from "@/app/api/user/stats/day/route";
} from "@/app/api/user/stats/day/controller";
import { LoadingContent } from "@/components/LoadingContent";
import { Skeleton } from "@/components/ui/skeleton";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type {
StatsByWeekResponse,
StatsByWeekParams,
} from "@/app/api/user/stats/by-period/route";
} from "@/app/api/user/stats/by-period/controller";
import { DetailedStatsFilter } from "@/app/(app)/[emailAccountId]/stats/DetailedStatsFilter";
import { getDateRangeParams } from "@/app/(app)/[emailAccountId]/stats/params";

Expand Down
2 changes: 1 addition & 1 deletion apps/web/app/(app)/[emailAccountId]/stats/StatsChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import useSWR from "swr";
import type {
StatsByDayQuery,
StatsByDayResponse,
} from "@/app/api/user/stats/day/route";
} from "@/app/api/user/stats/day/controller";
import { LoadingContent } from "@/components/LoadingContent";
import { Skeleton } from "@/components/ui/skeleton";

Expand Down
2 changes: 1 addition & 1 deletion apps/web/app/(app)/[emailAccountId]/stats/StatsSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
import type {
StatsByWeekParams,
StatsByWeekResponse,
} from "@/app/api/user/stats/by-period/route";
} from "@/app/api/user/stats/by-period/controller";
import { getDateRangeParams } from "./params";
import { formatStat } from "@/utils/stats";
import { StatsCards } from "@/components/StatsCards";
Expand Down
124 changes: 124 additions & 0 deletions apps/web/app/api/user/stats/by-period/controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import format from "date-fns/format";
import { z } from "zod";
import sumBy from "lodash/sumBy";
import { zodPeriod } from "@inboxzero/tinybird";
import prisma from "@/utils/prisma";
import { Prisma } from "@prisma/client";

export const statsByWeekParams = z.object({
period: zodPeriod,
fromDate: z.coerce.number().nullish(),
toDate: z.coerce.number().nullish(),
});
export type StatsByWeekParams = z.infer<typeof statsByWeekParams>;
export type StatsByWeekResponse = Awaited<ReturnType<typeof getStatsByPeriod>>;

export async function getStatsByPeriod(
options: StatsByWeekParams & {
emailAccountId: string;
},
) {
// Get all stats in a single query
const stats = await getEmailStatsByPeriod(options);

// Transform stats to match the expected format
const formattedStats = stats.map((stat) => {
const startOfPeriodFormatted = format(stat.startOfPeriod, "LLL dd, y");

return {
startOfPeriod: startOfPeriodFormatted,
All: Number(stat.totalCount),
Sent: Number(stat.sentCount),
Read: Number(stat.readCount),
Unread: Number(stat.unread),
Unarchived: Number(stat.inboxCount),
Archived: Number(stat.notInbox),
};
});

// Calculate totals
const totalAll = sumBy(stats, (stat) => Number(stat.totalCount));
const totalInbox = sumBy(stats, (stat) => Number(stat.inboxCount));
const totalRead = sumBy(stats, (stat) => Number(stat.readCount));
const totalSent = sumBy(stats, (stat) => Number(stat.sentCount));

return {
result: formattedStats,
allCount: totalAll,
inboxCount: totalInbox,
readCount: totalRead,
sentCount: totalSent,
};
}

async function getEmailStatsByPeriod(
options: StatsByWeekParams & { emailAccountId: string },
) {
const { period, fromDate, toDate, emailAccountId } = options;

// Build date conditions without starting with AND
const dateConditions: Prisma.Sql[] = [];
if (fromDate) {
dateConditions.push(Prisma.sql`date >= ${new Date(fromDate)}`);
}
if (toDate) {
dateConditions.push(Prisma.sql`date <= ${new Date(toDate)}`);
}

const dateFormat =
period === "day"
? "YYYY-MM-DD"
: period === "week"
? "YYYY-WW"
: period === "month"
? "YYYY-MM"
: "YYYY";

// Using raw query with properly typed parameters
type StatsResult = {
period_group: string;
startOfPeriod: Date;
totalCount: bigint;
inboxCount: bigint;
readCount: bigint;
sentCount: bigint;
unread: bigint;
notInbox: bigint;
};

// Create WHERE clause properly
const whereClause = Prisma.sql`WHERE "emailAccountId" = ${emailAccountId}`;
const dateClause =
dateConditions.length > 0
? Prisma.sql` AND ${Prisma.join(dateConditions, " AND ")}`
: Prisma.sql``;

// Convert period and dateFormat to string literals in PostgreSQL
return prisma.$queryRaw<StatsResult[]>`
WITH stats AS (
SELECT
TO_CHAR(date, ${Prisma.raw(`'${dateFormat}'`)}) AS period_group,
DATE_TRUNC(${Prisma.raw(`'${period}'`)}, date) AS start_of_period,
COUNT(*) AS total_count,
SUM(CASE WHEN inbox = true THEN 1 ELSE 0 END) AS inbox_count,
SUM(CASE WHEN inbox = false THEN 1 ELSE 0 END) AS not_inbox,
SUM(CASE WHEN read = true THEN 1 ELSE 0 END) AS read_count,
SUM(CASE WHEN read = false THEN 1 ELSE 0 END) AS unread,
SUM(CASE WHEN sent = true THEN 1 ELSE 0 END) AS sent_count
FROM "EmailMessage"
${whereClause}${dateClause}
GROUP BY period_group, start_of_period
ORDER BY start_of_period
)
SELECT
period_group,
start_of_period AS "startOfPeriod",
total_count AS "totalCount",
inbox_count AS "inboxCount",
not_inbox AS "notInbox",
read_count AS "readCount",
unread,
sent_count AS "sentCount"
FROM stats
`;
}
128 changes: 4 additions & 124 deletions apps/web/app/api/user/stats/by-period/route.ts
Original file line number Diff line number Diff line change
@@ -1,129 +1,9 @@
import { NextResponse } from "next/server";
import format from "date-fns/format";
import { z } from "zod";
import sumBy from "lodash/sumBy";
import { zodPeriod } from "@inboxzero/tinybird";
import { withEmailAccount } from "@/utils/middleware";
import prisma from "@/utils/prisma";
import { Prisma } from "@prisma/client";

const statsByWeekParams = z.object({
period: zodPeriod,
fromDate: z.coerce.number().nullish(),
toDate: z.coerce.number().nullish(),
});
export type StatsByWeekParams = z.infer<typeof statsByWeekParams>;
export type StatsByWeekResponse = Awaited<ReturnType<typeof getStatsByPeriod>>;

async function getEmailStatsByPeriod(
options: StatsByWeekParams & { emailAccountId: string },
) {
const { period, fromDate, toDate, emailAccountId } = options;

// Build date conditions without starting with AND
const dateConditions: Prisma.Sql[] = [];
if (fromDate) {
dateConditions.push(Prisma.sql`date >= ${new Date(fromDate)}`);
}
if (toDate) {
dateConditions.push(Prisma.sql`date <= ${new Date(toDate)}`);
}

const dateFormat =
period === "day"
? "YYYY-MM-DD"
: period === "week"
? "YYYY-WW"
: period === "month"
? "YYYY-MM"
: "YYYY";

// Using raw query with properly typed parameters
type StatsResult = {
period_group: string;
startOfPeriod: Date;
totalCount: bigint;
inboxCount: bigint;
readCount: bigint;
sentCount: bigint;
unread: bigint;
notInbox: bigint;
};

// Create WHERE clause properly
const whereClause = Prisma.sql`WHERE "emailAccountId" = ${emailAccountId}`;
const dateClause =
dateConditions.length > 0
? Prisma.sql` AND ${Prisma.join(dateConditions, " AND ")}`
: Prisma.sql``;

// Convert period and dateFormat to string literals in PostgreSQL
return prisma.$queryRaw<StatsResult[]>`
WITH stats AS (
SELECT
TO_CHAR(date, ${Prisma.raw(`'${dateFormat}'`)}) AS period_group,
DATE_TRUNC(${Prisma.raw(`'${period}'`)}, date) AS start_of_period,
COUNT(*) AS total_count,
SUM(CASE WHEN inbox = true THEN 1 ELSE 0 END) AS inbox_count,
SUM(CASE WHEN inbox = false THEN 1 ELSE 0 END) AS not_inbox,
SUM(CASE WHEN read = true THEN 1 ELSE 0 END) AS read_count,
SUM(CASE WHEN read = false THEN 1 ELSE 0 END) AS unread,
SUM(CASE WHEN sent = true THEN 1 ELSE 0 END) AS sent_count
FROM "EmailMessage"
${whereClause}${dateClause}
GROUP BY period_group, start_of_period
ORDER BY start_of_period
)
SELECT
period_group,
start_of_period AS "startOfPeriod",
total_count AS "totalCount",
inbox_count AS "inboxCount",
not_inbox AS "notInbox",
read_count AS "readCount",
unread,
sent_count AS "sentCount"
FROM stats
`;
}

async function getStatsByPeriod(
options: StatsByWeekParams & {
emailAccountId: string;
},
) {
// Get all stats in a single query
const stats = await getEmailStatsByPeriod(options);

// Transform stats to match the expected format
const formattedStats = stats.map((stat) => {
const startOfPeriodFormatted = format(stat.startOfPeriod, "LLL dd, y");

return {
startOfPeriod: startOfPeriodFormatted,
All: Number(stat.totalCount),
Sent: Number(stat.sentCount),
Read: Number(stat.readCount),
Unread: Number(stat.unread),
Unarchived: Number(stat.inboxCount),
Archived: Number(stat.notInbox),
};
});

// Calculate totals
const totalAll = sumBy(stats, (stat) => Number(stat.totalCount));
const totalInbox = sumBy(stats, (stat) => Number(stat.inboxCount));
const totalRead = sumBy(stats, (stat) => Number(stat.readCount));
const totalSent = sumBy(stats, (stat) => Number(stat.sentCount));

return {
result: formattedStats,
allCount: totalAll,
inboxCount: totalInbox,
readCount: totalRead,
sentCount: totalSent,
};
}
import {
getStatsByPeriod,
statsByWeekParams,
} from "@/app/api/user/stats/by-period/controller";

export const GET = withEmailAccount(async (request) => {
const emailAccountId = request.auth.emailAccountId;
Expand Down
76 changes: 76 additions & 0 deletions apps/web/app/api/user/stats/day/controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { z } from "zod";
import type { gmail_v1 } from "@googleapis/gmail";
import { dateToSeconds } from "@/utils/date";
import { getMessages } from "@/utils/gmail/message";

export const statsByDayQuery = z.object({
type: z.enum(["inbox", "sent", "archived"]),
});
export type StatsByDayQuery = z.infer<typeof statsByDayQuery>;
export type StatsByDayResponse = Awaited<
ReturnType<typeof getPastSevenDayStats>
>;

const DAYS = 7;

export async function getPastSevenDayStats(
options: {
emailAccountId: string;
gmail: gmail_v1.Gmail;
} & StatsByDayQuery,
) {
const today = new Date();
const sevenDaysAgo = new Date(
today.getFullYear(),
today.getMonth(),
today.getDate() - (DAYS - 1), // include today in stats
);
Comment on lines +22 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider timezone handling for date calculations

The date calculation logic doesn't account for timezone differences, which could lead to incorrect day boundaries for users in different timezones.

Consider using a timezone-aware date library or explicitly handling the user's timezone:

-  const today = new Date();
-  const sevenDaysAgo = new Date(
-    today.getFullYear(),
-    today.getMonth(),
-    today.getDate() - (DAYS - 1), // include today in stats
-  );
+  // Consider accepting timezone as parameter or using user's timezone
+  const today = new Date();
+  const sevenDaysAgo = new Date(
+    today.getFullYear(),
+    today.getMonth(),
+    today.getDate() - (DAYS - 1), // include today in stats
+  );

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/web/app/api/user/stats/day/controller.ts around lines 22 to 27, the
current date calculation does not handle timezones, which can cause incorrect
day boundaries for users in different timezones. To fix this, use a
timezone-aware date library like date-fns-tz or moment-timezone to calculate
today and sevenDaysAgo based on the user's timezone, or explicitly adjust the
date objects to the correct timezone before performing date arithmetic.

// const cachedStats = await getAllStats({ email })

const lastSevenDaysCountsArray = await Promise.all(
Array.from({ length: DAYS }, (_, i) => {
const date = new Date(sevenDaysAgo);
date.setDate(date.getDate() + i);
return date;
}).map(async (date) => {
const dateString = `${date.getDate()}/${date.getMonth() + 1}`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix date format inconsistency

The date formatting here uses DD/MM format, but the validation schema in apps/web/app/api/v1/stats/validation.ts (line 73) expects "Date in YYYY-MM-DD format". This inconsistency could cause issues for API consumers.

Apply this fix to use consistent date formatting:

-      const dateString = `${date.getDate()}/${date.getMonth() + 1}`;
+      const dateString = date.toISOString().split('T')[0]; // YYYY-MM-DD format
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const dateString = `${date.getDate()}/${date.getMonth() + 1}`;
const dateString = date.toISOString().split('T')[0]; // YYYY-MM-DD format
🤖 Prompt for AI Agents
In apps/web/app/api/user/stats/day/controller.ts at line 36, the date string is
formatted as DD/MM, which conflicts with the expected YYYY-MM-DD format defined
in the validation schema at apps/web/app/api/v1/stats/validation.ts line 73.
Update the dateString assignment to format the date as YYYY-MM-DD by extracting
the full year, month (adding 1), and day, and concatenating them with hyphens to
ensure consistency with the validation schema.


// let count = cachedStats?.[dateString]
let count: number | undefined = undefined;

if (typeof count !== "number") {
const query = getQuery(options.type, date);

const messages = await getMessages(options.gmail, {
query,
maxResults: 500,
});
Comment on lines +44 to +47
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Make maxResults configurable and add error handling

The hardcoded maxResults: 500 should be configurable, and Gmail API calls lack error handling which could cause unhandled promise rejections.

+const DEFAULT_MAX_RESULTS = 500;
+
 export async function getPastSevenDayStats(
   options: {
     emailAccountId: string;
     gmail: gmail_v1.Gmail;
+    maxResults?: number;
   } & StatsByDayQuery,
 ) {
   // ... existing code ...
   
-        const messages = await getMessages(options.gmail, {
-          query,
-          maxResults: 500,
-        });
+        try {
+          const messages = await getMessages(options.gmail, {
+            query,
+            maxResults: options.maxResults ?? DEFAULT_MAX_RESULTS,
+          });
+          count = messages.messages?.length || 0;
+        } catch (error) {
+          console.error(`Failed to fetch messages for ${dateString}:`, error);
+          count = 0; // or throw error based on requirements
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const messages = await getMessages(options.gmail, {
query,
maxResults: 500,
});
// Add at top of file
const DEFAULT_MAX_RESULTS = 500;
export async function getPastSevenDayStats(
options: {
emailAccountId: string;
gmail: gmail_v1.Gmail;
maxResults?: number;
} & StatsByDayQuery,
) {
// ... existing code ...
try {
const messages = await getMessages(options.gmail, {
query,
maxResults: options.maxResults ?? DEFAULT_MAX_RESULTS,
});
count = messages.messages?.length || 0;
} catch (error) {
console.error(`Failed to fetch messages for ${dateString}:`, error);
count = 0; // or rethrow based on requirements
}
// ... rest of function ...
}
🤖 Prompt for AI Agents
In apps/web/app/api/user/stats/day/controller.ts around lines 44 to 47, the
maxResults parameter for getMessages is hardcoded to 500 and there is no error
handling for the Gmail API call. Refactor the code to accept maxResults as a
configurable parameter, possibly passed via options or environment variables.
Wrap the getMessages call in a try-catch block to handle any errors gracefully
and prevent unhandled promise rejections, logging or returning an appropriate
error response.


count = messages.messages?.length || 0;
}

return {
date: dateString,
Emails: count,
};
}),
);

return lastSevenDaysCountsArray;
}

function getQuery(type: StatsByDayQuery["type"], date: Date) {
const startOfDayInSeconds = dateToSeconds(date);
const endOfDayInSeconds = startOfDayInSeconds + 86400;

const dateRange = `after:${startOfDayInSeconds} before:${endOfDayInSeconds}`;

switch (type) {
case "inbox":
return `in:inbox ${dateRange}`;
case "sent":
return `in:sent ${dateRange}`;
case "archived":
return `-in:inbox -in:sent ${dateRange}`;
}
}
Loading
Loading