diff --git a/src/components/admin/AdminPageModal.tsx b/src/components/admin/AdminPageModal.tsx index f68f81bc..13229bf9 100644 --- a/src/components/admin/AdminPageModal.tsx +++ b/src/components/admin/AdminPageModal.tsx @@ -1,5 +1,5 @@ import { Modal, Box, Typography, Switch } from "@mui/joy"; -import { ReactNode } from "react"; +import { ReactNode, useEffect, useState } from "react"; // Interface for Modal Props interface AdminPageModalProps { @@ -9,6 +9,7 @@ interface AdminPageModalProps { modalDesc: string; switchLabel?: string; switchAction?: () => void; + switchCondition?: () => Promise; extraNodes?: ReactNode[]; } @@ -40,8 +41,34 @@ export default function AdminPageModal({ modalDesc, switchLabel, switchAction, + switchCondition, extraNodes: extraNode, }: AdminPageModalProps) { + const [isChecked, setIsChecked] = useState(false); + + // If a switchCondition is set, handle it as a checked condition for the toggle itself + useEffect(() => { + const handleSwitchCondition = async () => { + if (!switchCondition) return; + const fetchedCheckState = await switchCondition(); + setIsChecked(fetchedCheckState); + }; + handleSwitchCondition(); + }, [switchCondition]); + + const handleSwitchChange = async () => { + const nextChecked = !isChecked; + + setIsChecked(nextChecked); + + try { + await switchAction?.(); + } catch (error) { + setIsChecked(!nextChecked); + throw error; + } + }; + return ( } + endDecorator={} > {switchLabel} diff --git a/src/components/admin/ContractOverrideList.tsx b/src/components/admin/ContractOverrideList.tsx index 08ef46f9..a2d6586a 100644 --- a/src/components/admin/ContractOverrideList.tsx +++ b/src/components/admin/ContractOverrideList.tsx @@ -1,5 +1,62 @@ -export {} +import { Box, Button, List, ListItem, Typography } from "@mui/joy"; +import { useEffect, useState } from "react"; +import { getProfiles } from "../../utils/getProfiles"; +import { StudentRecord } from "../../types"; +import { supabase } from "../../supabaseClient"; -// export default function ContractOverrideList { +const boxStyles = { + bgcolor: "#b2f2bb", + border: "2px solid", + borderColor: "#006400", + borderRadius: 2, + p: 2, +}; -// } \ No newline at end of file +export default function ContractOverrideList() { + const [profilesWithOverrides, setProfilesWithOverrides] = useState(); + + useEffect(() => { + const fetchProfileWithOverrides = async () => { + const profiles = await getProfiles("contract_override", "true", "eq"); + setProfilesWithOverrides(profiles); + }; + fetchProfileWithOverrides(); + }, []); + + const disableOverride = async (profile_id: string) => { + const { error } = await supabase + .from("profiles") + .update({ contract_override: false }) + .eq("profile_id", `${profile_id}`); + + if (error) { + throw Error(error.message); + } + + // remove the profile from the local list + setProfilesWithOverrides((prev) => prev?.filter((p) => p.profile_id !== profile_id)); + }; + + return ( + + Students with Write Access Overrides + + {profilesWithOverrides && profilesWithOverrides.length > 0 ? ( + profilesWithOverrides.map((profile, idx) => ( + + + {profile.username} + + + + )) + ) : ( + No Students Found with Overrides + )} + + + ); +} diff --git a/src/components/layout/UpperNavBar.tsx b/src/components/layout/UpperNavBar.tsx index 45645719..b00b124d 100644 --- a/src/components/layout/UpperNavBar.tsx +++ b/src/components/layout/UpperNavBar.tsx @@ -5,6 +5,7 @@ import { List as ListIcon } from '@phosphor-icons/react'; import ProfileAvatar from '../profile/ProfileAvatar'; import { ALL_PFPS } from '../profile/UserInfo'; import { Session } from '@supabase/supabase-js'; +import { StudentRecord } from '../../types'; interface Props { openDrawer: () => void; @@ -16,7 +17,7 @@ interface Props { sessionRemainingSeconds: number; endSession: () => void; sessionId: string | null; - userData: { name: string; pfp_id: number } | null; + userData: StudentRecord | null; isAdmin: boolean; signOut: () => void; setActiveSession: (param: boolean) => void; @@ -86,7 +87,7 @@ export default function UpperNavBar({ ) : ( <> )} - {userData?.name ?? 'Profile'} + {userData?.username ?? 'Profile'} diff --git a/src/components/profile/UserInfo.tsx b/src/components/profile/UserInfo.tsx index 1e00d832..888d5c0f 100644 --- a/src/components/profile/UserInfo.tsx +++ b/src/components/profile/UserInfo.tsx @@ -4,7 +4,7 @@ import { supabase } from "../../supabaseClient"; import { Button, Stack, Typography } from "@mui/joy"; import { useOutletContext } from "react-router-dom"; import ProfileAvatar from "./ProfileAvatar"; -import { UserData } from "../../types"; +import { StudentRecord } from "../../types"; // TODO: maybe get these dynamically? export const ALL_PFPS = [ @@ -15,7 +15,7 @@ export const ALL_PFPS = [ "thumbs-up-pfp.png" ] -export default function UserInfo({ userData, refetchProfile }: { userData: UserData | null, refetchProfile: Function }) { +export default function UserInfo({ userData, refetchProfile }: { userData: StudentRecord | null, refetchProfile: Function }) { const [isUpdating, setIsUpdating] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); @@ -146,7 +146,7 @@ export default function UserInfo({ userData, refetchProfile }: { userData: UserD height={pfpHeight} width={pfpWidth} /> - { userData?.name && {userData.name} } + { userData?.username && {userData.username} } diff --git a/src/components/profile/contract/Contract.tsx b/src/components/profile/contract/Contract.tsx index 732d4839..2dc15135 100644 --- a/src/components/profile/contract/Contract.tsx +++ b/src/components/profile/contract/Contract.tsx @@ -5,10 +5,11 @@ import ContractEdit from "./ContractEdit"; import { supabase } from "../../../supabaseClient"; import { Session } from "@supabase/supabase-js"; import { useOutletContext } from "react-router-dom"; +import { fetchContractPerms } from "../../../utils/contractPerms"; interface ContractProps { categoriesData: CategoryData[]; - profileData?: StudentRecord + profileData?: StudentRecord; } export default function Contract({ categoriesData, profileData }: ContractProps) { @@ -25,7 +26,7 @@ export default function Contract({ categoriesData, profileData }: ContractProps) const profileId = profileData?.profile_id ?? session?.user.id; if (!profileId) { - throw Error("Error: No session or profile_id has been defined"); + throw Error("Error: No session or profile_id has been defined"); } // if the categoriesData changes, update the problem count @@ -122,6 +123,7 @@ export default function Contract({ categoriesData, profileData }: ContractProps) setContract={setContract} featureMap={featureMap} problemCountByCategory={problemCountByCategory} + profileData={profileData} /> ); @@ -136,6 +138,7 @@ interface ContractModalProps { onSave: () => Promise; featureMap: Record; problemCountByCategory: Record; + profileData?: StudentRecord; } function ContractModal({ @@ -147,8 +150,25 @@ function ContractModal({ onSave, featureMap, problemCountByCategory, + profileData }: ContractModalProps) { const [isUpdating, setIsUpdating] = useState(false); + const [isReadOnly, setIsReadOnly] = useState(false); + + useEffect(() => { + const checkIfReadOnly = async () => { + try { + if(profileData && profileData.contract_override === true){ + setIsReadOnly(false) + } else { + setIsReadOnly(await fetchContractPerms()); + } + } catch (error) { + console.error("Contract read-only setting could not be loaded", error); + } + }; + checkIfReadOnly(); + }, [profileData]); /** * This function enforces a max and min of submitted values @@ -234,9 +254,20 @@ function ContractModal({ ) : ( - + <> + {isReadOnly && ( + + CONTRACT IS SET TO READ-ONLY + + )} + + )} diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts index 67b34908..8d38cc2a 100644 --- a/src/hooks/useAuth.ts +++ b/src/hooks/useAuth.ts @@ -1,11 +1,11 @@ import { useState, useEffect, useCallback } from 'react'; import { supabase } from '../supabaseClient'; import { type Session } from '@supabase/supabase-js'; -import { UserData } from '../types'; +import { StudentRecord } from '../types'; interface UseAuthReturn { session: Session | null; - userData: UserData | null; + userData: StudentRecord | null; isAdmin: boolean; isRecoverySession: boolean; fetchProfile: () => Promise; @@ -13,7 +13,7 @@ interface UseAuthReturn { export default function useAuth(): UseAuthReturn { const [session, setSession] = useState(null); - const [userData, setUserData] = useState(null); + const [userData, setUserData] = useState(null); const [isAdmin, setIsAdmin] = useState(false); const [isRecoverySession, setIsRecoverySession] = useState(false); @@ -71,11 +71,11 @@ export default function useAuth(): UseAuthReturn { if (!session) return; const { data } = await supabase .from('profiles') - .select('username, pfp_id') + .select() .eq('profile_id', session.user.id) .single(); if (data) { - setUserData({ name: data.username, pfp_id: data.pfp_id }); + setUserData({...data}); } }, [session]); diff --git a/src/routes/Account.tsx b/src/routes/Account.tsx index f6d00ce8..3501d900 100644 --- a/src/routes/Account.tsx +++ b/src/routes/Account.tsx @@ -11,7 +11,7 @@ import OtherStats from "../components/profile/progress/other-stats/OtherStats"; import { useOutletContext } from "react-router-dom"; import SessionReflections from "../components/profile/sessions/SessionReflections"; import useActivityTracker from "../hooks/useActivityTracker"; -import { UserData } from "../types"; +import { StudentRecord } from "../types"; /** * The `Account` component handles everything related to the profile page. @@ -19,7 +19,7 @@ import { UserData } from "../types"; */ export default function Account({ session }: { session: Session }) { const { refetchProfile } = useOutletContext<{ refetchProfile: () => Promise }>(); - const { userData } = useOutletContext<{ userData: UserData | null }>(); + const { userData } = useOutletContext<{ userData: StudentRecord }>(); // Change "reflections" into something else const [view, setView] = useState<"reflections" | "activity" | "sessions">("reflections"); @@ -58,7 +58,7 @@ export default function Account({ session }: { session: Session }) { Contract - + diff --git a/src/routes/AdminPage.tsx b/src/routes/AdminPage.tsx index 78faddf2..6ac70dd5 100644 --- a/src/routes/AdminPage.tsx +++ b/src/routes/AdminPage.tsx @@ -6,6 +6,8 @@ import CategoryPasswordForm from "../components/admin/CategoryPasswordForm"; import { ListProtectedCategories } from "../components/admin/ListProtectedCategories"; import { useLoaderData } from "react-router-dom"; import { SearchBar } from "../components/admin/SearchBar"; +import { fetchContractPerms, updateContractPerms } from "../utils/contractPerms"; +import ContractOverrideList from "../components/admin/ContractOverrideList"; // Defines the data in the modal interface ModalMetaData { @@ -33,8 +35,8 @@ export default function AdminPage() { const links: ModalMetaData[] = [ { title: "View Student Information", - desc: "Enter the email/student id of the student you want to a detailed view of", - extraNodes: [] + desc: "Enter the username of the student you want to a detailed view of", + extraNodes: [], }, { title: "Toggle Public/Test Questions", @@ -44,7 +46,12 @@ export default function AdminPage() { { title: "Modify Global Contract Permissions", desc: "Below is a switch that toggles the contract to be read-only globally. This does not apply for student who have contract overrides enabled.", - switch: { switchLabel: "Toggle Read-Only Mode", switchAction: () => ({}) }, + switch: { + switchLabel: "Toggle Read-Only Mode", + switchCondition: () => fetchContractPerms(), + switchAction: () => updateContractPerms(), + }, + extraNodes: [] }, ]; @@ -67,7 +74,7 @@ export default function AdminPage() { gap: 1.5, border: "10px, solid ,#d4ff99", padding: "100px", - marginTop: "5%" + marginTop: "5%", }} > @@ -90,6 +97,7 @@ export default function AdminPage() { modalDesc={activeModal.desc} switchLabel={activeModal.switch?.switchLabel} switchAction={activeModal.switch?.switchAction} + switchCondition={activeModal.switch?.switchCondition} extraNodes={activeModal.extraNodes} /> )} diff --git a/src/routes/PasswordProtected.tsx b/src/routes/PasswordProtected.tsx index 8830fdda..81d2a03e 100644 --- a/src/routes/PasswordProtected.tsx +++ b/src/routes/PasswordProtected.tsx @@ -43,7 +43,7 @@ export default function PasswordProtected({ order, setOrder, orderBy, - setOrderBy + setOrderBy, }: ProblemListProps) { const [passwordValue, setPasswordValue] = useState(""); const [error, setError] = useState(""); @@ -51,16 +51,20 @@ export default function PasswordProtected({ const handleClick = async () => { //Generate a hash and compare it w/ the user entered password - const hashedUserPassword = await hashPassword(passwordValue) + const hashedUserPassword = await hashPassword(passwordValue); - const { data, error } = await supabase.from("settings").select(); + const { data: actualPassword, error } = await supabase + .from("settings") + .select("value") + .eq("key", "test-password") + .single(); if (error) { setError("Failed to fetch password. Please try again."); return; } - if (hashedUserPassword === data?.[0]?.value) { + if (hashedUserPassword === actualPassword.value) { handleUnlock(); } else { setError("Incorrect password. Please try again."); diff --git a/src/routes/StudentAnalytics.tsx b/src/routes/StudentAnalytics.tsx index f7d012ec..7b9ff6fd 100644 --- a/src/routes/StudentAnalytics.tsx +++ b/src/routes/StudentAnalytics.tsx @@ -1,4 +1,4 @@ -import { Box, Stack, Typography } from "@mui/joy"; +import { Box, Card, Divider, Stack, Switch, Typography } from "@mui/joy"; import CategoriesBarGraph from "../components/profile/progress/CategoriesBarGraph"; import HeatMap from "../components/profile/progress/heatmap/HeatMap"; import ActivityGraph from "../components/profile/progress/ActivityGraph"; @@ -8,59 +8,86 @@ import { getProfiles } from "../utils/getProfiles"; import { useLoaderData } from "react-router-dom"; import useActivityTracker from "../hooks/useActivityTracker"; import Contract from "../components/profile/contract/Contract"; +import { useState } from "react"; +import { supabase } from "../supabaseClient"; const containerStyles = { minHeight: "100vh", + px: { xs: 2, md: 4 }, + py: { xs: 2, md: 3 }, + background: "linear-gradient(180deg, #feffed 0%, #fff7d9 100%)", +}; + +const pageStyles = { + width: "100%", + maxWidth: 1500, + mx: "auto", display: "flex", flexDirection: "column", - pt: 3, - pb: 4, - px: 2, - gap: 4, + gap: 3, +}; + +const heroStyles = { + display: "flex", + alignItems: { xs: "flex-start", md: "center" }, + justifyContent: "space-between", + gap: 2, + flexWrap: "wrap", + p: { xs: 2, md: 3 }, + borderRadius: "xl", + backgroundColor: "rgba(255, 255, 255, 0.72)", + border: "1px solid rgba(0, 0, 0, 0.08)", + boxShadow: "0 20px 60px rgba(31, 41, 55, 0.08)", }; const titleStyles = { - fontSize: "2rem", - textAlign: "center", + fontSize: { xs: "1.7rem", md: "2.2rem" }, + textAlign: { xs: "left", md: "center" }, + lineHeight: 1.05, + fontWeight: 800, }; const contentStyles = { - flex: 1, - display: "flex", - gap: 4, - alignItems: "flex-start", - justifyContent: "space-between", + display: "grid", + gridTemplateColumns: { xs: "1fr", lg: "300px minmax(0, 1fr)" }, + gap: { xs: 2, lg: 3 }, + alignItems: "start", }; const leftPanelStyles = { - flex: "0 0 220px", display: "flex", flexDirection: "column", - justifyContent: "space-between", - alignItems: "center", - p: 3, - pb: 2, - minHeight: 160, - backgroundColor: "#f7f0dc", - borderRadius: "lg", - border: "1px solid", - borderColor: "rgba(0, 0, 0, 0.08)", + gap: 2, + p: 2.5, + borderRadius: "xl", + backgroundColor: "rgba(255, 255, 255, 0.8)", + border: "1px solid rgba(0, 0, 0, 0.08)", + boxShadow: "0 18px 40px rgba(31, 41, 55, 0.08)", }; const studentInfoStyles = { width: "100%", - textAlign: "center", + display: "flex", + flexDirection: "column", + gap: 0.75, }; const rightPanelStyles = { - flex: 1, display: "flex", - justifyContent: "flex-end", + minWidth: 0, }; const graphStackStyles = { width: "100%", - maxWidth: 960, + gap: 2.25, +}; + +const graphCardStyles = { + p: { xs: 1.5, md: 2 }, + borderRadius: "xl", + backgroundColor: "rgba(255, 255, 255, 0.82)", + border: "1px solid rgba(0, 0, 0, 0.08)", + boxShadow: "0 18px 40px rgba(31, 41, 55, 0.06)", }; export async function profileLoader({ params }: any): Promise { @@ -79,34 +106,96 @@ export function StudentAnalytics() { return ( - - Student Analytics: ({profileData.username}) - - - + + + + Student Analytics + + + Control Panel for User: {profileData.username} + + + + - - Student ID: {profileData.student_id ?? "No Student ID Found"} + + {profileData.username ?? "No Username Found"} - - Student Name: {profileData.username ?? "No Username Found"} + + Last updated: {new Date(profileData.updated_at).toLocaleDateString()} - + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - ); } + +function ContractOverrideSwitch({ profileData }: { profileData: StudentRecord }) { + const [isChecked, setIsChecked] = useState(!!profileData.contract_override); + + const handleToggle = async () => { + const nextChecked = !isChecked; + + setIsChecked(nextChecked); + const { error } = await supabase + .from("profiles") + .update({ contract_override: nextChecked }) + .eq("profile_id", profileData.profile_id); + + if (error) { + setIsChecked(!nextChecked); + throw Error(error.message); + } + }; + + return ( + + + + Contract Override + + + Temporarily bypass the read-only contract lock for this student. + + + } + > + Readonly override + + + ); +} diff --git a/src/types.ts b/src/types.ts index 0164fbe0..dd290ee5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -8,6 +8,7 @@ export interface StudentRecord { student_id: number; is_admin: boolean; pfp_id: number; + contract_override: boolean; } export interface CategoryData { @@ -19,7 +20,8 @@ export interface CategoryData { } export interface AdminSwitch { - switchLabel: string + switchLabel: string; + switchCondition: () => Promise; switchAction: () => void; } diff --git a/src/utils/contractPerms.ts b/src/utils/contractPerms.ts new file mode 100644 index 00000000..cb51d801 --- /dev/null +++ b/src/utils/contractPerms.ts @@ -0,0 +1,33 @@ +import { supabase } from "../supabaseClient"; + +/** + * Toggles the contract read-only setting and updates the db + */ +export async function updateContractPerms() { + const contractStatusBool = await fetchContractPerms(); + const { error } = await supabase + .from("settings") + .update({ value: !contractStatusBool }) + .eq("key", "contract-read-only"); + + if (error) { + throw Error(error.message); + } +} + +/** + * Function the value of the read-only values of the contract + */ +export async function fetchContractPerms() { + const { data, error } = await supabase + .from("settings") + .select("value") + .eq("key", "contract-read-only"); + + if (error) { + throw Error(error.message); + } + const contractStatusBool = data?.[0].value === "true"; + + return contractStatusBool; +} diff --git a/src/utils/getProfiles.ts b/src/utils/getProfiles.ts index 457859ed..2ca99211 100644 --- a/src/utils/getProfiles.ts +++ b/src/utils/getProfiles.ts @@ -33,5 +33,5 @@ export async function getProfiles( throw error; } - return data as StudentRecord[] | null; + return data as StudentRecord[]; }