Skip to content
Merged
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
4 changes: 2 additions & 2 deletions apps/web/app/(app)/[emailAccountId]/stats/MainStatChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as React from "react";
import { parse, format } from "date-fns";
import { Card, CardContent } from "@/components/ui/card";
import type { ChartConfig } from "@/components/ui/chart";
import type { StatsByWeekResponse } from "@/app/api/user/stats/by-period/route";
import type { StatsByPeriodResponse } from "@/app/api/user/stats/by-period/controller";
import { BarChart } from "@/app/(app)/[emailAccountId]/stats/BarChart";
import { COLORS } from "@/utils/colors";

Expand All @@ -26,7 +26,7 @@ function getActiveChart(activChart: keyof typeof chartConfig): string[] {
}

export function MainStatChart(props: {
data: StatsByWeekResponse;
data: StatsByPeriodResponse;
period: "day" | "week" | "month" | "year";
}) {
const [activeChart, setActiveChart] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ import { BarChart } from "./BarChart";
import type { ChartConfig } from "@/components/ui/chart";
import { COLORS } from "@/utils/colors";
import { cn } from "@/utils";
import type {
GetResponseTimeResponse,
ResponseTimeParams,
} from "@/app/api/user/stats/response-time/route";
import type { ResponseTimeQuery } from "@/app/api/user/stats/response-time/validation";
import type { ResponseTimeResponse } from "@/app/api/user/stats/response-time/controller";
import { isDefined } from "@/utils/types";
import { pluralize } from "@/utils/string";

Expand All @@ -29,9 +27,9 @@ export function ResponseTimeAnalytics({
dateRange,
refreshInterval,
}: ResponseTimeAnalyticsProps) {
const params: ResponseTimeParams = getDateRangeParams(dateRange);
const params: ResponseTimeQuery = getDateRangeParams(dateRange);

const { data, isLoading, error } = useOrgSWR<GetResponseTimeResponse>(
const { data, isLoading, error } = useOrgSWR<ResponseTimeResponse>(
`/api/user/stats/response-time?${new URLSearchParams(params as Record<string, string>)}`,
{ refreshInterval },
);
Expand Down
10 changes: 4 additions & 6 deletions apps/web/app/(app)/[emailAccountId]/stats/StatsSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import type { DateRange } from "react-day-picker";
import { useOrgSWR } from "@/hooks/useOrgSWR";
import { LoadingContent } from "@/components/LoadingContent";
import { Skeleton } from "@/components/ui/skeleton";
import type {
StatsByWeekParams,
StatsByWeekResponse,
} from "@/app/api/user/stats/by-period/route";
import type { StatsByPeriodQuery } from "@/app/api/user/stats/by-period/validation";
import type { StatsByPeriodResponse } from "@/app/api/user/stats/by-period/controller";
import { getDateRangeParams } from "./params";
import { MainStatChart } from "@/app/(app)/[emailAccountId]/stats/MainStatChart";

Expand All @@ -18,13 +16,13 @@ export function StatsSummary(props: {
}) {
const { dateRange, period } = props;

const params: StatsByWeekParams = {
const params: StatsByPeriodQuery = {
period,
...getDateRangeParams(dateRange),
};

const { data, isLoading, error } = useOrgSWR<
StatsByWeekResponse,
StatsByPeriodResponse,
{ error: string }
>(
`/api/user/stats/by-period?${new URLSearchParams(
Expand Down
96 changes: 96 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,96 @@
import { format } from "date-fns/format";
import sumBy from "lodash/sumBy";
import prisma from "@/utils/prisma";
import { Prisma } from "@/generated/prisma/client";
import type { StatsByPeriodQuery } from "@/app/api/user/stats/by-period/validation";

export type StatsByPeriodResponse = Awaited<
ReturnType<typeof getStatsByPeriod>
>;

async function getEmailStatsByPeriod(
options: StatsByPeriodQuery & { 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)}`);
}

// Using raw query with properly typed parameters
type StatsResult = {
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[]>`
SELECT
DATE_TRUNC(${Prisma.raw(`'${period}'`)}, date) AS "startOfPeriod",
COUNT(*) AS "totalCount",
SUM(CASE WHEN inbox = true THEN 1 ELSE 0 END) AS "inboxCount",
SUM(CASE WHEN inbox = false THEN 1 ELSE 0 END) AS "notInbox",
SUM(CASE WHEN read = true THEN 1 ELSE 0 END) AS "readCount",
SUM(CASE WHEN read = false THEN 1 ELSE 0 END) AS unread,
SUM(CASE WHEN sent = true THEN 1 ELSE 0 END) AS "sentCount"
FROM "EmailMessage"
${whereClause}${dateClause}
GROUP BY "startOfPeriod"
ORDER BY "startOfPeriod"
`;
}

export async function getStatsByPeriod(
options: StatsByPeriodQuery & {
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,
};
}
105 changes: 3 additions & 102 deletions apps/web/app/api/user/stats/by-period/route.ts
Original file line number Diff line number Diff line change
@@ -1,113 +1,14 @@
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 "@/generated/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)}`);
}

// Using raw query with properly typed parameters
type StatsResult = {
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[]>`
SELECT
DATE_TRUNC(${Prisma.raw(`'${period}'`)}, date) AS "startOfPeriod",
COUNT(*) AS "totalCount",
SUM(CASE WHEN inbox = true THEN 1 ELSE 0 END) AS "inboxCount",
SUM(CASE WHEN inbox = false THEN 1 ELSE 0 END) AS "notInbox",
SUM(CASE WHEN read = true THEN 1 ELSE 0 END) AS "readCount",
SUM(CASE WHEN read = false THEN 1 ELSE 0 END) AS unread,
SUM(CASE WHEN sent = true THEN 1 ELSE 0 END) AS "sentCount"
FROM "EmailMessage"
${whereClause}${dateClause}
GROUP BY "startOfPeriod"
ORDER BY "startOfPeriod"
`;
}

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 } from "./controller";
import { statsByPeriodQuerySchema } from "@/app/api/user/stats/by-period/validation";

export const GET = withEmailAccount(
async (request) => {
const emailAccountId = request.auth.emailAccountId;

const { searchParams } = new URL(request.url);
const params = statsByWeekParams.parse({
const params = statsByPeriodQuerySchema.parse({
period: searchParams.get("period") || "week",
fromDate: searchParams.get("fromDate"),
toDate: searchParams.get("toDate"),
Expand Down
9 changes: 9 additions & 0 deletions apps/web/app/api/user/stats/by-period/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { z } from "zod";
import { zodPeriod } from "@inboxzero/tinybird";

export const statsByPeriodQuerySchema = z.object({
period: zodPeriod,
fromDate: z.coerce.number().nullish(),
toDate: z.coerce.number().nullish(),
});
Comment on lines +4 to +8
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 | 🟠 Major

Add validation to reject NaN and ensure valid timestamps.

z.coerce.number() can produce NaN from invalid input (e.g., "abc"), which passes validation but creates Invalid Date downstream in the controller.

Apply this diff:

 export const statsByPeriodQuerySchema = z.object({
   period: zodPeriod,
-  fromDate: z.coerce.number().nullish(),
-  toDate: z.coerce.number().nullish(),
+  fromDate: z.coerce.number().finite().nullish(),
+  toDate: z.coerce.number().finite().nullish(),
 });
📝 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
export const statsByPeriodQuerySchema = z.object({
period: zodPeriod,
fromDate: z.coerce.number().nullish(),
toDate: z.coerce.number().nullish(),
});
export const statsByPeriodQuerySchema = z.object({
period: zodPeriod,
fromDate: z.coerce.number().finite().nullish(),
toDate: z.coerce.number().finite().nullish(),
});
🤖 Prompt for AI Agents
In apps/web/app/api/user/stats/by-period/validation.ts around lines 4 to 8, the
z.coerce.number() fields can produce NaN from invalid input which then becomes
Invalid Date downstream; update fromDate and toDate to reject NaN and ensure
they are valid timestamps by adding a refinement (after coercion) that checks
Number.isFinite(value) and that the value is an integer and within a sensible
timestamp range (e.g., > 0, optionally <= Date.now()), returning a clear error
message on failure so malformed inputs are rejected at validation time.

export type StatsByPeriodQuery = z.infer<typeof statsByPeriodQuerySchema>;
Loading
Loading