Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: New Record Notification #654

Merged
merged 7 commits into from
Aug 18, 2023
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
107 changes: 102 additions & 5 deletions packages/app/src/app/result/loaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { safeLoader } from "@/lib/safeLoader";
import { getCurrentUser } from "@/lib/session";
import { formatDate } from "@/lib/utils";
import { Result, Snippet } from "@prisma/client";
import { Decimal } from "@prisma/client/runtime/library";
import { race } from "cypress/types/bluebird";
import { redirect } from "next/navigation";
import "server-only";
import { z } from "zod";
Expand Down Expand Up @@ -111,15 +113,32 @@ export async function getCurrentRaceResult(resultId: string) {
redirect("/auth");
}

const raceResults = await prisma.result.findUnique({
where: {
id: resultId,
},
});
const raceResults = await safeLoadCurrentResults(resultId);

return raceResults;
}

const safeLoadCurrentResults = safeLoader({
outputValidation: z
.object({
id: z.string(),
snippetId: z.string(),
accuracy: z.number(),
cpm: z.number(),
errorCount: z.number(),
takenTime: z.string(),
}),
loader: async (resultId: string) => {
const results = await prisma.result.findUnique({
where: {
id: resultId,
},
});

return convertDecimalsToNumbers(results);
},
});

export async function getSnippetVote(snippetId: string) {
const user = await getCurrentUser();

Expand Down Expand Up @@ -207,3 +226,81 @@ export async function getUserSnippetPlacement(snippetId?: Snippet["id"]) {

return allResults.findIndex((r) => r.id === usersResult.id) + 1;
}

export const getBestCPM = safeLoader({
outputValidation: z
.object({
id: z.string(),
cpm: z.number(),
user: z.object({
id: z.string(),
}),
}),
loader: async (snippetId: any, raceID: string) => {
const user = await getCurrentUser();

if (!user) return null;

const results = await prisma.result.findFirst({
where: {
userId: user.id,
snippetId: snippetId,
NOT: {
id: raceID,
},
},
orderBy: {
cpm: "desc",
},
distinct: ["userId"],
include: {
user: {
select: {
id: true,
},
},
},
});

return convertDecimalsToNumbers(results);
},
});

export const getBestAccuracy = safeLoader({
outputValidation: z
.object({
id: z.string(),
accuracy: z.number(),
user: z.object({
id: z.string(),
}),
}),
loader: async (snippetId: any, raceID: string) => {
const user = await getCurrentUser();

if (!user) return null;

const results = await prisma.result.findFirst({
where: {
userId: user.id,
snippetId: snippetId,
NOT: {
id: raceID,
},
},
orderBy: {
accuracy: "desc",
},
distinct: ["userId"],
include: {
user: {
select: {
id: true,
},
},
},
});

return convertDecimalsToNumbers(results);
},
});
43 changes: 43 additions & 0 deletions packages/app/src/app/result/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { getCurrentUser } from "@/lib/session";
import {
getUserResultsForSnippet,
getCurrentRaceResult,
getBestCPM,
ParsedRacesResult,
getSnippetVote,
getBestAccuracy,
} from "./loaders";

// Components
Expand All @@ -24,6 +26,7 @@ import { TopTable } from "./topten";
import { RaceAchievementBadges } from "./race-achievement-badges";
import { ResultChart } from "./result-chart";
import HistoryChart from "./history-chart";
import { pushNotification } from "@/lib/notification";

type ResultPageProps = {
searchParams: {
Expand Down Expand Up @@ -100,6 +103,46 @@ async function AuthenticatedPage({ resultId, user }: AuthenticatedPageProps) {
},
];

const bestCPMRace = await getBestCPM(currentRaceResult.snippetId, currentRaceResult.id);

if (bestCPMRace && bestCPMRace?.cpm < currentRaceResult.cpm) {
const notificationData = {
notification: {
title: "New Record!",
description: "You just achvied your highest CPM!",
ctaUrl: "/dashboard/races",
},
userId: user.id,
};

try {
await pushNotification(notificationData);
console.log("Best CPM notification sent successfully!");
} catch (error) {
console.error("Error sending notification:", error);
}
}

const bestAccuracy = await getBestAccuracy(currentRaceResult.snippetId, currentRaceResult.id);

if (bestAccuracy && bestAccuracy?.accuracy < currentRaceResult.accuracy) {
const notificationData = {
notification: {
title: "New Record!",
description: "You just achvied your highest accuracy!",
ctaUrl: "/dashboard/races",
},
userId: user.id,
};

try {
await pushNotification(notificationData);
console.log("Best accuracy notification sent successfully!");
} catch (error) {
console.error("Error sending notification:", error);
}
}

return (
<main className="w-auto mb-32 lg:mb-40">
<div className="flex flex-col justify-center gap-4 mt-5">
Expand Down
Loading