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

Admin fixes #28

Merged
merged 46 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
6fe350f
style player avatar and submit button
tydolla00 Dec 6, 2024
0f044e5
Show multiple stats for games correctly
Shargrove09 Dec 12, 2024
56bef72
Did this validation ever even work
Shargrove09 Dec 12, 2024
87cea7a
Temporarily enable fields that are filled by getYtVid to fix submissi…
Shargrove09 Dec 13, 2024
444f108
Seed additional game stats
Shargrove09 Dec 13, 2024
2f80b9f
Change statName to enum
Shargrove09 Dec 13, 2024
bc99a5b
Merge branch 'main' of https://github.com/tydolla00/Project-RDC into …
tydolla00 Dec 14, 2024
920e295
Fix issue constraint issue due to seeding inserts
Shargrove09 Dec 15, 2024
8a575b1
refactor form to use react 19 hooks
tydolla00 Dec 16, 2024
bdb137c
remove provider from contexts.
tydolla00 Dec 16, 2024
ba4d71a
add react compiler support
tydolla00 Dec 16, 2024
7c9c5e7
fix build errors
tydolla00 Dec 16, 2024
eb7fff8
Add RL Score
Shargrove09 Dec 19, 2024
3eb9395
Test multi stat names
Shargrove09 Dec 20, 2024
492c6b7
Time to leetcode
Shargrove09 Dec 22, 2024
cb92e80
cleanup page
tydolla00 Dec 24, 2024
1750224
PlayerStats load in at once
Shargrove09 Dec 24, 2024
5fa2379
Merge branch 'admin-fixes' of https://github.com/tydolla00/Project-RD…
tydolla00 Dec 24, 2024
3cb04bc
temp fix for messed of types
tydolla00 Dec 24, 2024
7f3b53a
update db models, to include timestamps and additional statnames.
tydolla00 Dec 24, 2024
ed4a5d6
in-progress: add neon serverless edge runtime support for prisma
tydolla00 Dec 24, 2024
5254d04
Merge branch 'main' of https://github.com/tydolla00/Project-RDC into …
tydolla00 Dec 24, 2024
52ed6cd
update packages to latest version
tydolla00 Dec 24, 2024
c5952a3
show data on rocket league screen
tydolla00 Dec 24, 2024
0e86f21
fix build errors
tydolla00 Dec 24, 2024
13498b7
Merge branch 'main' of https://github.com/tydolla00/Project-RDC into …
tydolla00 Dec 24, 2024
6309e10
merge
tydolla00 Dec 24, 2024
576a128
Merge branch 'admin-fixes' of https://github.com/tydolla00/Project-RD…
tydolla00 Dec 24, 2024
424631b
fix build error
tydolla00 Dec 24, 2024
c22c68a
T_Day stat shouldnt be included in every match
Shargrove09 Dec 24, 2024
52c2fb6
add functions for retrieving data.
tydolla00 Dec 24, 2024
2388460
begin handling error logic.
tydolla00 Dec 25, 2024
e7a81f9
Merge branch 'react-19-form-upgrades' of https://github.com/tydolla00…
tydolla00 Dec 25, 2024
aae5bc2
add todo's and fix issue with date
tydolla00 Dec 25, 2024
efeb4b8
update todos
tydolla00 Dec 26, 2024
4f9dad0
Merge branch 'rocket-league-ui' of https://github.com/tydolla00/Proje…
tydolla00 Dec 26, 2024
d90ccd7
removing todos by logging to posthog
tydolla00 Dec 26, 2024
48a2eed
fix build errors
tydolla00 Dec 26, 2024
b8a37a9
performance improvements
tydolla00 Dec 28, 2024
aae41d3
Merge branch 'main' of https://github.com/tydolla00/Project-RDC into …
tydolla00 Dec 28, 2024
46ee12e
playerstatmanager refactor
tydolla00 Dec 29, 2024
40b5094
implement v2 of form submission.
tydolla00 Dec 29, 2024
0d8501a
add auth to actions. "Treat actions as public http endpoints"
tydolla00 Dec 30, 2024
e039fd7
wip: add ability to upload json to fill form. All praise the AI overl…
tydolla00 Dec 31, 2024
27cb7b9
paste in json form progress and fixing build errors.
tydolla00 Jan 13, 2025
d756d3f
comment about broken videosession db call.
tydolla00 Jan 13, 2025
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
2 changes: 1 addition & 1 deletion prisma/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const connectionString = config.DATABASE_URL;

const pool = new Pool({ connectionString });
const adapter = new PrismaNeon(pool);
const prisma = global.prisma || new PrismaClient({ adapter });
const prisma = global.prisma || new PrismaClient({ adapter, log: ["query"] });

if (process.env.NODE_ENV === "development") global.prisma = prisma;

Expand Down
14 changes: 9 additions & 5 deletions prisma/lib/admin.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { unstable_cache } from "next/cache";
import prisma from "../db";
// Should only do this once in the EntryCreator I think
export const getRDCMembers = async () => {
const members = await prisma.player.findMany();

return members;
};
export const getAllSessions = unstable_cache(
async () =>
await prisma.videoSession.findMany({
include: { Game: { select: { gameName: true } } },
}),
undefined,
{ revalidate: 604800, tags: ["getAllSessions"] }, // 1 week
);
13 changes: 9 additions & 4 deletions prisma/lib/games.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"use server";

import { unstable_cache } from "next/cache";
import prisma from "../db";
import { StatName } from "@prisma/client";
Expand All @@ -10,12 +12,15 @@ import { getSumOfStat } from "@prisma/client/sql";
* Fetches all games from the database.
* @returns all game records including gameName and gameId
*/
export const getAllGames = function () {
return unstable_cache(async () => await prisma.game.findMany(), undefined, {
export const getAllGames = unstable_cache(
async () => await prisma.game.findMany(),
undefined,
{
tags: ["getAllGames"],
revalidate: false,
})();
};
},
);

export const getSumPerStat = async (playerId: number, statName: StatName) =>
await prisma.$queryRawTyped(getSumOfStat(playerId, statName));
/**
Expand Down
6 changes: 5 additions & 1 deletion src/app/(routes)/(groups)/games/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import GolfWithFriends from "./_components/golfwithfriends";
// ? Force non specified routes to return 404
export const dynamicParams = false; // true | false,

// TODO May need to revalidathPath/Tag after updating data.
// TODO May need to revalidatePath/Tag after updating data.

export async function generateStaticParams() {
const games = await getAllGames();
Expand Down Expand Up @@ -66,6 +66,10 @@ export default async function Page({
);
}

const Sessions = () => {
// TODO This will be a table with all of the currently submitted sessions for a game. Show the name. url, and thumbnail.
};

// const Average = ({
// }: {
// }) => {
Expand Down
2 changes: 1 addition & 1 deletion src/app/(routes)/(groups)/members/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default async function Page({
<CardTitle>Chart</CardTitle>
</CardHeader>
</Card>
<div className="mt-10 flex gap-10">
<div className="mt-10 flex flex-wrap gap-10">
<Card className="h-64 flex-1">
<CardHeader>
<CardTitle>Chart</CardTitle>
Expand Down
29 changes: 20 additions & 9 deletions src/app/(routes)/admin/_components/EntryCreatorForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Player } from "@prisma/client";
import SetManager from "./SetManager";
import { insertNewSessionFromAdmin } from "@/app/actions/adminAction";
import {
insertNewSessionFromAdmin,
insertNewSessionV2,
} from "@/app/actions/adminAction";
import { Form } from "@/components/ui/form";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
Expand All @@ -13,6 +16,9 @@ import { AdminFormProps } from "../_utils/form-helpers";
import { useAdmin } from "@/lib/adminContext";
import { useFormStatus } from "react-dom";
import { SessionInfo } from "./SessionInfo";
import { errorCodes } from "@/lib/constants";
import { signOut } from "@/auth";
import { revalidateTag } from "next/cache";

interface Props {
rdcMembers: Player[];
Expand Down Expand Up @@ -67,17 +73,22 @@ const EntryCreatorForm = (props: AdminFormProps) => {
data,
stringified: JSON.stringify(data, null, 2),
});
console.time();
const { error: err } = await insertNewSessionFromAdmin(data);
// const { error: err } = await insertNewSessionV2(data);
console.timeEnd();
console.log(err);

// data.date = new Date(data.date);
// console.log("Date Type in submit:", typeof data.date);
const err = await insertNewSessionFromAdmin(data);
if (err === null)
toast.error("Video already submitted", { richColors: true });
else toast.success("Session successfully created.", { richColors: true });
if (err)
err === errorCodes.NotAuthenticated
? await signOut({ redirectTo: "/" })
: toast.error(err, { richColors: true });
else {
toast.success("Session successfully created.", { richColors: true });
revalidateTag("getAllSessions");
}
};

// console.log("Date Type:", typeof getValues().date);

/**
* Handles errors that occur during form submission.
*
Expand Down
17 changes: 11 additions & 6 deletions src/app/(routes)/admin/_components/GameDropDownForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
"use client";
import { Check, ChevronsUpDown } from "lucide-react";
import { Control, ControllerRenderProps } from "react-hook-form";
import {
Control,
ControllerRenderProps,
UseFormResetField,
} from "react-hook-form";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
Expand All @@ -24,24 +28,24 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { getGames } from "@/app/actions/adminAction";
import { Game } from "@prisma/client";
import { useState, useEffect } from "react";
import { FormValues } from "../_utils/form-helpers";
import { getAllGames } from "../../../../../prisma/lib/games";

const GameDropDownForm = ({
control,
reset,
}: {
control: Control<FormValues>;
field: ControllerRenderProps<FormValues>;
reset: UseFormResetField<FormValues>;
}) => {
const [testGames, setTestGames] = useState<Game[]>([]);

useEffect(() => {
const fetchGames = async () => {
// TODO I'm so confused how this is working lol we shouldn't be able to access prisma on the client.
// This should be fetched on the server and then passed down as a prop.
const games = await getGames();
const games = await getAllGames();
setTestGames(games);
};
fetchGames();
Expand All @@ -53,7 +57,7 @@ const GameDropDownForm = ({
name="game"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Game</FormLabel>
<FormLabel className="w-fit">Game</FormLabel>
<Popover>
<PopoverTrigger asChild>
<FormControl>
Expand Down Expand Up @@ -88,6 +92,7 @@ const GameDropDownForm = ({
key={game.gameId}
onSelect={() => {
field.onChange(game.gameName);
reset("sets");
}}
>
{game.gameName}
Expand Down
2 changes: 1 addition & 1 deletion src/app/(routes)/admin/_components/MatchManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const MatchManager = (props: Props) => {
});
const players = getValues(`players`);

const statName = "MK8_POS";
const statName = "MK8_POS"; // ! TODO Can we remove this

/**
* Handles create new match button click.
Expand Down
86 changes: 52 additions & 34 deletions src/app/(routes)/admin/_components/PlayerStatManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { v4 as uuidv4 } from "uuid";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { useAdmin } from "@/lib/adminContext";
import { StatNames } from "../../../../../prisma/lib/utils";
import { FormValues } from "../_utils/form-helpers";
import { StatNames } from "../../../../../prisma/lib/utils";

interface Props {
player: Player;
Expand All @@ -33,56 +33,74 @@ const PlayerStatManager = (props: Props) => {
control,
});

const [loading, setLoading] = useState(true);
// const [loading, setLoading] = useState(true);
const { gameStats } = useAdmin();

// TODO: Move to PlayerSessionManager or above

useEffect(() => {
console.log(
"All Player Sessions: ",
getValues(`sets.${setIndex}.matches.${matchIndex}.playerSessions`),
let ignore = false;
const matchFields = getValues(
`sets.${setIndex}.matches.${matchIndex}.playerSessions.${playerSessionIndex}.playerStats`,
);
gameStats.forEach((stat) => {
const isMatch = matchFields.some((f) => f.stat === stat.statName); // Need to do this in dev because useEffect renders twice.
if (!ignore && !isMatch)
append({ statId: uuidv4(), stat: stat.statName, statValue: "" });
});

// Returns all the playerStats for the match
const getPlayerSessionStats = () => {
const values = getValues();
console.log(" Get PlayerSessionStats Values: ", values);
const playerSession =
values.sets[setIndex].matches[matchIndex].playerSessions[
playerSessionIndex
];
console.log("PlayerSessionStatGet: ", playerSession.playerStats);
return playerSession.playerStats;
return () => {
ignore = true;
};
}, [gameStats, append]);
// useEffect(() => {
// console.log(
// "All Player Sessions: ",
// getValues(`sets.${setIndex}.matches.${matchIndex}.playerSessions`),
// );

const fetchGameStats = async () => {
const existingStats = getPlayerSessionStats();
gameStats.forEach((stat) => {
const statExists = existingStats.some(
(existingStat) => existingStat.stat === stat.statName,
);
// Ducttape fix to stop useEffect double render from
// doubling playerStat fields
if (!statExists && stat.statName !== StatNames.RLDay) {
append({ statId: uuidv4(), stat: stat.statName, statValue: "" });
}
});
setLoading(false);
};
fetchGameStats();
}, [append, getValues, matchIndex, playerSessionIndex, setIndex, gameStats]);
// // Returns all the playerStats for the match
// const getPlayerSessionStats = () => {
// const values = getValues();
// console.log(" Get PlayerSessionStats Values: ", values);
// const playerSession =
// values.sets[setIndex].matches[matchIndex].playerSessions[
// playerSessionIndex
// ];
// console.log("PlayerSessionStatGet: ", playerSession.playerStats);
// return playerSession.playerStats;
// };

// const fetchGameStats = async () => {
// console.log("Fetching game stats");
// const existingStats = getPlayerSessionStats();
// gameStats.forEach((stat) => {
// const statExists = existingStats.some(
// (existingStat) => existingStat.stat === stat.statName,
// );
// // Ducttape fix to stop useEffect double render from
// // doubling playerStat fields
// if (!statExists) {
// append({ statId: uuidv4(), stat: stat.statName, statValue: "" });
// }
// });
// setLoading(false);
// };
// fetchGameStats();
// }, [append, getValues, matchIndex, playerSessionIndex, setIndex, gameStats]);

console.log("PlayerStatManagerFields: ", fields);
console.log("Loading: ", loading);
// console.log("PlayerStatManagerFields: ", fields);
// console.log("Loading: ", loading);

// TODO Fix bug, when changing the games doesn't remove stale inputs
return (
<>
{fields.map((field, index: number) => {
return (
<div key={field.id} className="my-4 flex gap-3">
<span className="sr-only">{field.stat}</span>
<Input
className="h-full max-w-xs"
className="max-w-xs"
placeholder={field.stat}
type="text"
{...register(
Expand Down
Loading
Loading