Connect, collaborate, and grow with a community of TypeScript developers
feat(admin): update ui/ux for the reports page (#288)
Jim Burbridgeeddae54d59e1
diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 475d080c..2f37fba1 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -123,6 +123,8 @@ model User {updatedAt DateTime @updatedAtreports Report[] @relation("reporter")reportsAbout Report[] @relation("reported_user")+ moderated Report[] @relation("report_moderator")+}model VerificationToken {@@ -308,12 +310,19 @@ model Report {solutionId Int?solution SharedSolution? @relation(fields: [solutionId], references: [id])+ moderatorId String?+ moderator User? @relation("report_moderator", fields: [moderatorId], references: [id])++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+@@unique([id])@@index([commentId])@@index([reporterId])@@index([userId])@@index([challengeId])@@index([solutionId])+ @@index([moderatorId])}enum CommentRoot {diff --git a/src/app/admin/page.tsx b/src/app/admin/page.tsxindex bb6791e5..548a4699 100644--- a/src/app/admin/page.tsx+++ b/src/app/admin/page.tsx@@ -1,8 +1,11 @@+'use server';import { RoleTypes } from '@prisma/client';import { Lock } from 'lucide-react';-import { getBannedUsers, getChallengeReports } from '~/components/admin/admin.actions';-import { ReportDetails } from '~/components/admin/reports';+import React from 'react';+import { getBannedUsers } from '~/components/admin/admin.actions';+import Reports2 from '~/components/admin/reports';import { BannedUsers } from '~/components/admin/users';+import { getInfiniteReports } from '~/components/report/report.action';import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';import { getServerAuthSession } from '~/server/auth';@@ -33,11 +36,12 @@ async function Admin() {}const View = async () => {- const allReports = await getChallengeReports();const allBannedUsers = await getBannedUsers();+ // This needs done because server functions are dumb and this throws A LOT of errors otherwise.+ const firstPage = await getInfiniteReports();return (- <div className="m-8 flex flex-col space-y-4">+ <div className="m-8 flex flex-col space-y-4 container"><div className="space-y-2"><div className="mx-2 flex flex-col"><p className="text-2xl font-semibold text-black dark:text-white">Moderation</p>@@ -62,7 +66,9 @@ const View = async () => {</TabsTrigger></TabsList><TabsContent value="reports">- <ReportDetails data={allReports} />+ <React.Suspense fallback={<>Loading...</>}>+ <Reports2 initialReports={firstPage}/>+ </React.Suspense></TabsContent><TabsContent value="users"><BannedUsers data={allBannedUsers} />diff --git a/src/app/admin/report/[id]/actions.tsx b/src/app/admin/report/[id]/actions.tsxindex cfb7087d..93b19232 100644--- a/src/app/admin/report/[id]/actions.tsx+++ b/src/app/admin/report/[id]/actions.tsx@@ -1,6 +1,6 @@'use client';-import { type Challenge, type User, type Vote } from '@prisma/client';+import { type User } from '@prisma/client';import {Dialog,DialogContent,@@ -10,46 +10,81 @@ import {DialogHeader,} from '~/components/ui/dialog';import { useRouter } from 'next/navigation';-import { useState } from 'react';+import { useMemo, useState } from 'react';import {banUser,+ deleteComment,+ deleteSolution,disableChallenge,- dismissChallengeReport,+ dismissReport,} from '~/components/admin/admin.actions';import { Button } from '~/components/ui/button';import { Label } from '~/components/ui/label';import { Textarea } from '~/components/ui/textarea';import { toast } from '~/components/ui/use-toast';+import { type ReportWithInfo } from './report.action';-export default function ReportActions({- moderatorId,- challenge,- reportId,-}: {- moderatorId: string | null;- moderator: { name: string | null } | null;- challenge: Challenge & { user: User; vote: Vote[] };- reportId: number;-}) {+export interface ReportActionsProps {+ report: NonNullable<ReportWithInfo>;+}+// export type ReportActionsProps = UserReportActionProps | ChallengeReportActionProps | SolutionReportActionProps | CommentReportActionProps;++export interface ReportActionsBase {+ moderator?: User;+ user: User;+}++export default function ReportActions({ report }: ReportActionsProps) {const [banReason, setBanReason] = useState('');const [ban, setBan] = useState(false);const router = useRouter();+ const user = useMemo(() => {+ switch (report.type) {+ case 'USER':+ return report.user as User;+ case 'CHALLENGE':+ return report?.challenge?.user as User;+ case 'COMMENT':+ return report?.comment?.user as User;+ case 'SOLUTION':+ return report.solution?.user as User;+ }+ }, [report]);++ async function handleDeleteComment(commentId: number, reportId: number) {+ try {+ await deleteComment(commentId, reportId);+ toast({+ title: 'Success',+ description: <p>Comment deleted successfully</p>,+ });+ router.push('/admin/report');+ } catch (e) {+ toast({+ title: 'Error',+ variant: 'destructive',+ description: <p>An error occurred. Please try again later.</p>,+ });+ }+ }+async function handleDisableChallenge(challengeId: number, reportId: number) {try {await disableChallenge(challengeId, reportId);+ router.push('/admin/report');} catch (e) {toast({title: 'Error',variant: 'destructive',- description: <p>An error occurred. Please try again later.s</p>,+ description: <p>An error occurred. Please try again later</p>,});}}async function handleBanUser(userId: string, reportId: number, banReason?: string) {try {- await banUser(userId, reportId, banReason);+ await banUser(report.userId as string, reportId, banReason);toast({title: 'Success',description: <p>User banned successfully.</p>,@@ -59,48 +94,92 @@ export default function ReportActions({toast({title: 'Error',variant: 'destructive',- description: <p>An error occurred. Please try again later.s</p>,+ description: <p>An error occurred. Please try again later</p>,});}}async function handleDismissReport(reportId: number) {try {- await dismissChallengeReport(reportId);+ await dismissReport(reportId);toast({title: 'Success',description: <p>Dismissed successfully.</p>,});router.push('/admin');} catch (e) {+ console.error(e);toast({title: 'Error',variant: 'destructive',- description: <p>An error occurred. Please try again later.s</p>,+ description: <p>An error occurred. Please try again later</p>,+ });+ }+ }++ async function handleRemoveSolution(solutionId: number) {+ const response = await deleteSolution(solutionId, report.id);+ if (response === 'ok') {+ toast({+ title: 'Successfully removed solution',+ });+ router.push('/admin');+ } else {+ toast({+ title: 'Error',+ description: <p>Something has gone wrong. Please try again later.</p>,});}}return (<div className="flex gap-2">- <Button variant="destructive" disabled={moderatorId !== null} onClick={() => setBan(true)}>- Ban @{challenge.user.name}- </Button><Button- disabled={moderatorId !== null}- onClick={() => handleDisableChallenge(challenge.id, reportId)}+ variant="destructive"+ disabled={report.moderatorId !== null}+ onClick={() => setBan(true)}>- Disable Challenge+ Ban @{user.name}</Button>- <Button disabled={moderatorId !== null} onClick={() => handleDismissReport(reportId)}>++ {report.type === 'CHALLENGE' && (+ <Button+ disabled={report.moderatorId !== null}+ onClick={() => handleDisableChallenge(report.challengeId as number, report.id)}+ >+ Disable Challenge+ </Button>+ )}++ {report.type === 'SOLUTION' && (+ <Button+ disabled={report.moderator !== null}+ onClick={() => handleRemoveSolution(report.solutionId as number)}+ >+ Remove Solution+ </Button>+ )}++ {report.type === 'COMMENT' && (+ <Button+ disabled={report.moderatorId !== null}+ onClick={() => handleDeleteComment(report.commentId as number, report.id)}+ variant="destructive"+ >+ Delete Comment+ </Button>+ )}++ <Button disabled={report.moderatorId !== null} onClick={() => handleDismissReport(report.id)}>Dismiss Report</Button>+<Dialog open={ban} onOpenChange={() => setBan(false)}><DialogContent className="sm:max-w-[425px]"><formonSubmit={(e) => {e.preventDefault();- handleBanUser(challenge.user.id, reportId, banReason);+ handleBanUser('', report.id, banReason);}}><DialogHeader>diff --git a/src/app/admin/report/[id]/loading.tsx b/src/app/admin/report/[id]/loading.tsxindex 07b4dd51..c2b0855a 100644--- a/src/app/admin/report/[id]/loading.tsx+++ b/src/app/admin/report/[id]/loading.tsx@@ -1,3 +1,9 @@+import { LoaderIcon } from 'lucide-react';+export default function ReportIdLoading() {- return <>Loading...</>;+ return (+ <div className="container text-center">+ <LoaderIcon className="animate-spin duration-1000 ease-in-out spin-in" />+ </div>+ );}diff --git a/src/app/admin/report/[id]/page.tsx b/src/app/admin/report/[id]/page.tsxindex ec458dbd..a9e92491 100644--- a/src/app/admin/report/[id]/page.tsx+++ b/src/app/admin/report/[id]/page.tsx@@ -1,14 +1,15 @@-import { AlertCircle, ThumbsUp } from 'lucide-react';+import { AlertCircle, ChevronLeft } from 'lucide-react';import Link from 'next/link';import { redirect } from 'next/navigation';-import { getChallenge } from '~/components/admin/admin.actions';import { Alert, AlertDescription, AlertTitle } from '~/components/ui/alert';-import { CodeEditor } from '~/components/ui/code-editor';import { Markdown } from '~/components/ui/markdown';import Text from '~/components/ui/typography/typography';-import { UserBadge } from '~/components/ui/user-badge';import ReportActions from './actions';-+import ChallengeReport from '~/components/report/types/challenge.report';+import CommentReport from '~/components/report/types/comment.report';+import UserReportUi from '~/components/report/types/user.report';+import SolutionReport from '~/components/report/types/solution.report';+import { getReport, type ReportWithInfo } from './report.action';export interface Props {params: {id: string;@@ -21,29 +22,55 @@ const Report = async function (props: Props) {if (isNaN(idNum)) {return redirect('/admin');}- // Grab the items.- const { author, challenge, derogatory, id, moderatorId, moderator, unclear, text } =- await getChallenge(idNum);++ const report = await getReport(idNum);++ if (!report) return redirect('/admin');++ let title = '';++ switch (report.type) {+ case 'USER':+ title = 'User Report';+ break;+ case 'CHALLENGE':+ title = 'Challenge Report';+ break;+ case 'COMMENT':+ title = 'Comment Report';+ break;+ case 'SOLUTION':+ title = 'Solution Report';+ break;+ }++ const ReportEl = (report: NonNullable<ReportWithInfo>) => {+ switch (report.type) {+ case 'CHALLENGE':+ return <ChallengeReport report={report} />;+ case 'COMMENT':+ return <CommentReport report={report} />;+ case 'SOLUTION':+ return <SolutionReport report={report} />;+ case 'USER':+ return <UserReportUi report={report} />;+ }+ };return (<div className="container ">+ <Link href="/admin" className="inline-flex gap-2">+ {' '}+ <ChevronLeft /> <span>Back to reports</span>+ </Link><div className="sticky top-0 z-50 flex items-center justify-between bg-background/80"><Text intent="h1" color="primary">- Challenge Report+ {title}</Text>- <ReportActions- reportId={id}- moderatorId={moderatorId}- moderator={moderator}- challenge={challenge}- />+ <ReportActions report={report} /></div>- <Text intent="h2" className="mt-6">- Report information- </Text>-- {moderator && (+ {report?.moderator && (<Alert className="mt-4" variant="destructive"><div className="flex items-center gap-2"><AlertCircle className="h-[1.25rem]" />@@ -51,63 +78,40 @@ const Report = async function (props: Props) {</div><AlertDescription>- Moderator @{moderator.name} took action on this case already.+ Moderator @{report?.moderator.name} took action on this case already.</AlertDescription></Alert>)}- <Text className="mt-4" intent="leading">- Reporter{' '}- <Link className="text-gray-400 hover:underline" href={`/@${author.name}`}>- @{author.name}- </Link>{' '}- says that this challenge:{' '}- </Text>-- <ul className="list-disc pl-8">- {derogatory && <li>Is derogatory</li>}- {unclear && <li>Is unclear</li>}- {!(derogatory || unclear) && <li>Has some other issue (see comments below)</li>}- </ul>+ <div className="wrapper mt-4 flex flex-col gap-4 md:flex-row">+ <section className="order-2 flex-grow md:order-1">{ReportEl(report)}</section>+ <aside className="order-1 flex-shrink-0 md:order-2 md:w-1/3 lg:w-[30%]">+ <Text intent="h2" className="mt-6">+ Information+ </Text>- <section className="my-4">- <Text weight="semi">Other comments by reporter</Text>- <div className="mt-4 rounded-lg bg-zinc-200 p-4 text-gray-800 dark:bg-zinc-800 dark:text-white">- <Markdown>{text || '__No additional comments given__'}</Markdown>- </div>- </section>+ <Text className="mt-4" intent="leading">+ Reporter{' '}+ <Link className="text-gray-400 hover:underline" href={`/@${report?.reporter.name}`}>+ @{report?.reporter.name}+ </Link>{' '}+ says that this challenge includes:{' '}+ </Text>- <Text intent="h2" className="mt-6">- Challenge information- </Text>+ <ul className="list-disc pl-8">+ {report.issues.map((issue) => (+ <li key={`issue-${issue.id}`}>{issue.type}</li>+ ))}+ </ul>- <section className="mt-6 flex flex-wrap gap-4 md:flex-nowrap">- <div className="w-full rounded-lg p-4 dark:bg-muted/90 md:w-1/2">- <Text intent="h3">{challenge.name}</Text>- <Text className="mt-2">- Created at:{' '}- {challenge.createdAt.toLocaleString('en-US', {- dateStyle: 'medium',- timeStyle: 'medium',- })}- </Text>- <Text intent="body">- Last updated on:{' '}- {challenge.updatedAt.toLocaleString('en-US', {- dateStyle: 'medium',- timeStyle: 'medium',- })}- </Text>- <UserBadge username={challenge.user.name || 'No author found'} />- <div className="my-2 flex gap-4">- <ThumbsUp /> {challenge.vote.length}- </div>- <Markdown className="mt-4">{challenge.description}</Markdown>- </div>- <div className="w-full md:w-1/2">- <CodeEditor value={challenge.prompt} />- </div>- </section>+ <section className="my-4">+ <Text weight="semi">Other comments by reporter</Text>+ <div className="mt-4 rounded-lg bg-zinc-200 p-4 text-gray-800 dark:bg-zinc-800 dark:text-white">+ <Markdown>{report?.text || '_No additional comments given_'}</Markdown>+ </div>+ </section>+ </aside>+ </div></div>);};diff --git a/src/app/admin/report/[id]/report.action.ts b/src/app/admin/report/[id]/report.action.tsindex d6d2cf31..842093ea 100644--- a/src/app/admin/report/[id]/report.action.ts+++ b/src/app/admin/report/[id]/report.action.ts@@ -1,4 +1,5 @@import { prisma } from '~/server/db';+export async function getReports() {const challengeReports = await prisma.report.findMany({where: {@@ -22,3 +23,67 @@ export async function getReports() {otherReports,};}++export type ReportWithInfo = Awaited<ReturnType<typeof getReport>>;++export async function getReport(idNum: number) {+ return prisma.report.findFirst({+ where: {+ id: +idNum,+ },+ orderBy: {+ type: 'asc',+ },+ include: {+ challenge: {+ include: {+ user: true,+ },+ },+ comment: {+ include: {+ user: true,+ rootChallenge: true,+ rootSolution: true,+ },+ },+ issues: true,+ reporter: true,+ solution: {+ include: {+ user: true,+ },+ },+ user: true,+ moderator: true,+ },+ });+}++export async function getReportedUserInformation(userId: string) {+ return await prisma.user.findFirst({+ where: {+ id: userId,+ },+ include: {+ comment: {+ take: 10,+ orderBy: {+ createdAt: 'desc',+ },+ },+ sharedSolution: {+ take: 5,+ orderBy: {+ createdAt: 'desc',+ },+ },+ challenge: {+ take: 5,+ orderBy: {+ createdAt: 'asc',+ },+ },+ },+ });+}diff --git a/src/app/admin/report/page.tsx b/src/app/admin/report/page.tsxdeleted file mode 100644index 3b1814ca..00000000--- a/src/app/admin/report/page.tsx+++ /dev/null@@ -1,72 +0,0 @@-import React from 'react';-import { prisma } from '~/server/db';-import { ReportType } from '@prisma/client';-import Text from '~/components/ui/typography/typography';-import { cva } from 'class-variance-authority';--export const dynamic = 'force-dynamic';--async function getReports() {- return prisma.report.findMany({- include: {- challenge: true,- user: true,- reporter: true,- issues: true,- comment: true,- solution: true,- },- take: 25,- });-}--const f = cva('border p-4 rounded-xl', {- variants: {- type: {- [ReportType.CHALLENGE]: 'border-orange-400',- [ReportType.USER]: 'border-green-300',- [ReportType.COMMENT]: 'border-yellow-400',- [ReportType.SOLUTION]: 'border-pink-300',- },- },- defaultVariants: {- type: 'USER',- },-});--export default async function ReportPage() {- const reports = await getReports();-- const bob = reports.reduce((all, cur) => {- if (!all[cur.type]) all[cur.type] = [];- all[cur.type].push(cur);- return all;- }, {} as Record<ReportType, (typeof reports)[0][]>);-- return (- <div className="container">- {Object.entries(bob).map(([key, reports]) => {- return (- <div key={`types-${key}`}>- <header className="mb-4">- <Text intent="h1">{key}</Text>- </header>- <section>- {reports.map((report) => (- <div className={f({ type: report.type })} key={`report-${report.id}`}>- Reported By:- {report.reporter.name} <br />- {report.type === 'CHALLENGE' && report.challenge && report.challenge.name}- <br />- User being reported:- {report.type === 'USER' && report.user && report.user.name}- <br />- </div>- ))}- </section>- </div>- );- })}- </div>- );-}diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex 63080209..061ced5d 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -26,8 +26,8 @@ export default function RootLayout({ children }: { children: React.ReactNode })<body className={`${inter.className} flex flex-col`}><Providers><Navigation />- <main className="flex-1">- <div className="h-full">{children}</div>+ <main className="flex flex-1 flex-col">+ <div className="flex h-full flex-col">{children}</div></main><Toaster /></Providers>diff --git a/src/components/admin/admin.actions.tsx b/src/components/admin/admin.actions.tsxindex 00b78384..3431ea61 100644--- a/src/components/admin/admin.actions.tsx+++ b/src/components/admin/admin.actions.tsx@@ -56,6 +56,25 @@ export async function getChallengeReports() {export type AdminBannedUsers = Awaited<ReturnType<typeof getBannedUsers>>;+export async function deleteComment(commentId: number, reportId: number) {+ return prisma.$transaction([+ prisma.comment.delete({+ where: {+ id: commentId,+ },+ }),+ prisma.report.update({+ where: {+ id: reportId,+ },+ data: {+ status: 'CLEARED',+ updatedAt: new Date(),+ },+ }),+ ]);+}+/*** The function fetches all the banned* user's.@@ -86,13 +105,14 @@ export async function disableChallenge(challengeId: number, reportId: number) {visibility: 'HIDDEN',},}),- prisma.challengeReport.update({+ prisma.report.update({where: {id: reportId,},data: {status: 'CLEARED',moderatorId: session?.user.id,+ updatedAt: new Date(),},}),]);@@ -104,19 +124,44 @@ export async function disableChallenge(challengeId: number, reportId: number) {* @param reportId The id of the report.* @returns*/-export async function dismissChallengeReport(reportId: number) {+export async function dismissReport(reportId: number) {const session = await getServerAuthSession();- return prisma.challengeReport.update({+ return prisma.report.update({where: {id: reportId,},data: {status: 'DISMISSED',moderatorId: session?.user.id,+ updatedAt: new Date(),},});}+export async function deleteSolution(solutionId: number, reportId: number) {+ try {+ await prisma.$transaction([+ prisma.sharedSolution.delete({+ where: {+ id: solutionId,+ },+ }),+ prisma.report.update({+ where: {+ id: reportId,+ },+ data: {+ status: 'CLEARED',+ updatedAt: new Date(),+ },+ }),+ ]);+ return 'ok';+ } catch (e) {+ return 'failed';+ }+}+/*** The function updates the user to indicate a status* of `BANNED`.@@ -150,13 +195,14 @@ export async function banUser(userId: string, reportId: number, banReason?: striuserId: userId,},}),- prisma.challengeReport.update({+ prisma.report.update({where: {id: reportId,},data: {status: 'CLEARED',moderatorId: session?.user.id,+ updatedAt: new Date(),},}),]);@@ -189,22 +235,17 @@ export async function unbanUser(userId: string) {}export async function getChallenge(id: number) {- return prisma.challengeReport.findFirstOrThrow({+ return prisma.challenge.findFirstOrThrow({where: {id,},include: {- author: true,- moderator: {+ _count: {select: {- name: true,- },- },- challenge: {- include: {- user: true,vote: true,- },+ bookmark: true,+ comment: true,+ }},},});diff --git a/src/components/admin/reports.tsx b/src/components/admin/reports.tsxindex 43fc228f..9d310cd2 100644--- a/src/components/admin/reports.tsx+++ b/src/components/admin/reports.tsx@@ -1,311 +1,106 @@'use client';--import { EyeOff, Gavel, X } from 'lucide-react';-import { useSession } from 'next-auth/react';-import { useRouter } from 'next/navigation';-import { useState } from 'react';+import React from 'react';import {- banUser,- disableChallenge,- dismissChallengeReport,- type AdminReportDetails,-} from '~/components/admin/admin.actions';-import { getRelativeTime } from '~/utils/relativeTime';-import { Badge } from '../ui/badge';-import { Button } from '../ui/button';-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card';-import { Dialog, DialogContent } from '../ui/dialog';-import { Label } from '../ui/label';-import { Markdown } from '../ui/markdown';-import { TypographyP } from '../ui/paragraph';-import { ScrollArea } from '../ui/scroll-area';-import { Separator } from '../ui/separator';-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';-import { Textarea } from '../ui/textarea';-import { TypographyH3 } from '../ui/typography/h3';-import { toast } from '../ui/use-toast';-import { UserBadge } from '../ui/user-badge';+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '~/components/ui/table';+import { useRouter } from 'next/navigation';+import { useInfiniteQuery } from '@tanstack/react-query';+import { getInfiniteReports, type InfiniteReports, type ReportsData } from '../report/report.action';+import Pagination from '../ui/pagination';-interface ReportsProps {- data: AdminReportDetails;+export interface ReportsProps {+ initialReports: InfiniteReports;}-export const ReportDetails = ({ data }: ReportsProps) => {- // State++export default function Reports2({ initialReports }: ReportsProps) {+const router = useRouter();- const session = useSession();- const [dialogOpen, setDialogOpen] = useState(false);- const [selectedIssue, setSelectedIssue] = useState<AdminReportDetails[number]>();- const [banReason, setBanReason] = useState('');- const handledReports = data.filter((report) => report.moderatorId === session.data?.user.id);- // TODO: will add them to a dropdown later.- const [isDismissedHidden, _setIsDismissedHidden] = useState(false);- const [isClearedHidden, _setIsClearedHidden] = useState(false);- // Functions- async function handleUserBan() {- try {- if (selectedIssue) {- const username = selectedIssue.challenge.user.name;- await banUser(selectedIssue?.challenge.userId, selectedIssue?.id, banReason);+ const [page, setPage] = React.useState(0);+ const [enableInfinite, setEnableInfinite] = React.useState(false);- toast({- title: 'Success',- description: <p>The user {username ? '@' + username + ' ' : ''}successfully banned.</p>,- variant: 'success',- });- }- } catch (e) {- } finally {- router.refresh();- setDialogOpen(false);- }- }+ const { data, hasNextPage, fetchNextPage } = useInfiniteQuery(+ ['reports'],+ async ({ pageParam }) => {+ const data = await getInfiniteReports(pageParam);+ return data;+ },+ {+ suspense: true,+ getNextPageParam: (+ a,- async function handleDisableChallenge() {- try {- if (selectedIssue) {- await disableChallenge(selectedIssue?.challengeId, selectedIssue?.id);- toast({- title: 'Success',- description: <p>The challenge was successfully disabled.</p>,- variant: 'success',- });- }- } catch (e) {- toast({- title: 'Something went wrong.',- description: <p>An error was encountered while trying to disable the challenge</p>,- variant: 'destructive',- });- } finally {- router.refresh();- setDialogOpen(false);- }- }+ b,+ ) => (a?.metadata.hasNextPage ? a?.metadata?.lastCursor : false),+ initialData: {+ pages: [+ initialReports+ ],+ pageParams: [null]+ },+ enabled: enableInfinite+ },+ );- async function handleDismissReport() {- try {- if (selectedIssue) {- await dismissChallengeReport(selectedIssue.id);- }- } catch (e) {- } finally {- router.refresh();- setDialogOpen(false);- }- }+ React.useEffect(() => {+ setEnableInfinite(true);+ }, []);return (- <div className="flex flex-col gap-4">- <div className="flex w-full flex-col justify-start gap-4 rounded-md border-2 p-5 md:flex-row md:items-center">- <TypographyH3>Statistics</TypographyH3>- <span className="text-sm text-neutral-400 dark:text-neutral-600">- <strong>{data.length}</strong> reports.- </span>- <span className="text-sm text-neutral-400 dark:text-neutral-600">- <strong>{handledReports.length}</strong> reports handled by you.- </span>- </div>+ <section className="data-table">+ <header className="flex justify-end">+ <Pagination+ onChange={(e) => {+ if(!e.detail.pageLoaded)+ fetchNextPage().then(() => setPage(e.detail.page - 1));+ else setPage(e.detail.page - 1);+ }}+ totalPages={data?.pages.length}+ hasNextPage={hasNextPage}+ currentPage={0 + 1}+ />+ </header><Table><TableHeader><TableRow>- <TableHead>Challenge Name</TableHead>- <TableHead>Reported By</TableHead>- <TableHead>At</TableHead>- <TableHead>Reason</TableHead>- <TableHead>Tags</TableHead>+ <TableHead>Type</TableHead>+ <TableHead>Reporter</TableHead><TableHead>Status</TableHead>+ <TableHead>Info</TableHead>+ <TableHead>Tags</TableHead>+ <TableHead>Created at</TableHead>+ <TableHead>Updated at</TableHead></TableRow></TableHeader><TableBody>- {data.map((report, reportIdx) => {- // 1. Checks.- if (isDismissedHidden && report.status === 'DISMISSED') return;- if (isClearedHidden && report.status === 'CLEARED') return;-- // 2. Local State- const challengeName = report.challenge.name;- const text = report.text;- const relativeTime = getRelativeTime(report.createdAt);- const absoluteTime = new Intl.DateTimeFormat('en-US', {- dateStyle: 'medium',- timeStyle: 'medium',- }).format(report.createdAt);-- return (- <TableRow- onClick={() => {- setSelectedIssue(report);- router.push(`/admin/report/${report.id}`);- }}- className="hover:cursor-pointer"- key={reportIdx}- >- <TableCell title={challengeName}>- {challengeName.length > 10- ? challengeName.substring(0, 10) + '...'- : challengeName}- </TableCell>- <TableCell>- <UserBadge username={report.author.name} />- </TableCell>- <TableCell title={absoluteTime}>{relativeTime}</TableCell>- <TableCell title={text}>- {text.length > 15 ? text.substring(0, 10) : text}- </TableCell>- <TableCell className="flex flex-wrap gap-2">- {report.derogatory && <Badge variant="destructive">Derogatory</Badge>}- {report.unclear && <Badge variant="outline">Unclear</Badge>}- </TableCell>- <TableCell>- {report.status === 'PENDING' && <Badge variant="secondary">Pending</Badge>}- {report.status === 'DISMISSED' && <Badge variant="outline">Dismissed</Badge>}- {report.status === 'CLEARED' && <Badge>Cleared</Badge>}- </TableCell>- </TableRow>- );- })}+ {data?.pages?.[page]?.data.map((tr) => (+ <TableRow key={`report-${tr.id}`} onClick={() => router.push(`/admin/report/${tr.id}`)}>+ <TableCell>{tr.type}</TableCell>+ <TableCell>{tr.reporter.name}</TableCell>+ <TableCell>{tr.status}</TableCell>+ <TableCell>{tr.text.slice(0, 100)}</TableCell>+ <TableCell>+ <div className="flex flex-wrap gap-2">+ {tr.issues.map((i) => (+ <div key={`issues-${i.id}`} className="rounded-full bg-zinc-800 px-3 py-1">{i.type}</div>+ ))}+ </div>+ </TableCell>+ <TableCell>+ {tr.createdAt.toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' })}+ </TableCell>+ <TableCell>+ {tr.updatedAt.toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' })}+ </TableCell>+ </TableRow>+ ))}</TableBody></Table>-- {selectedIssue && (- <Dialog open={dialogOpen} onOpenChange={(e) => setDialogOpen(!e)}>- <DialogContent className="max-w-xl">- <ScrollArea className="h-[500px]">- <div className="flex flex-col gap-4">- <Card>- <CardHeader>- <CardTitle>Challenge</CardTitle>- <CardDescription>A detailed description of the challenge.</CardDescription>- </CardHeader>- <CardContent>- <div className="flex flex-col space-y-2">- <div className="flex flex-col space-y-2">- <h5 className="text-sm text-neutral-400 dark:text-neutral-600">Name</h5>- <TypographyP>{selectedIssue.challenge.name}</TypographyP>- </div>- <div className="flex flex-col space-y-2">- <h5 className="text-sm text-neutral-400 dark:text-neutral-600">- Description- </h5>- <div className="prose-invert flex-1 leading-8 prose-h3:text-xl">- {/* todo: fix the width overflow because of markdown component. */}-- <Markdown>- {selectedIssue.challenge.description ?? 'Not Specified.'}- </Markdown>- </div>- </div>- <div className="flex flex-col space-y-2">- <h5 className="text-sm text-neutral-400 dark:text-neutral-600">- Created By- </h5>- <UserBadge username={selectedIssue.challenge.user.name} />- </div>- </div>- </CardContent>- </Card>- <Card>- <CardHeader>- <CardTitle>Report</CardTitle>- <CardDescription>A detailed description of the report.</CardDescription>- </CardHeader>- <CardContent>- <div className="flex flex-col space-y-2">- <div className="flex flex-col space-y-2">- <h5 className="text-sm text-neutral-400 dark:text-neutral-600">Reason</h5>- <TypographyP>- {selectedIssue.text && selectedIssue.text.length > 0- ? selectedIssue.text- : 'Not Specified.'}- </TypographyP>- </div>- <div className="flex flex-col space-y-2">- <h5 className="text-sm text-neutral-400 dark:text-neutral-600">Tags</h5>- <div className="flex flex-wrap gap-2">- {selectedIssue.derogatory && (- <Badge variant="destructive">Derogatory</Badge>- )}- {selectedIssue.unclear && <Badge variant="outline">Unclear</Badge>}- </div>- </div>- </div>- </CardContent>- </Card>- {selectedIssue.moderator && (- <Card>- <CardHeader>- <CardTitle>Activity</CardTitle>- <CardDescription>An account of activity on the report.</CardDescription>- </CardHeader>- <CardContent>- <div className="flex flex-col space-y-2">- <div className="flex flex-col space-y-2">- <h5 className="text-sm text-neutral-400 dark:text-neutral-600">- Handled By- </h5>- <TypographyP>@{selectedIssue.moderator.name}</TypographyP>- </div>- <div className="flex flex-col space-y-2">- <h5 className="text-sm text-neutral-400 dark:text-neutral-600">At</h5>- <div className="flex">- {new Intl.DateTimeFormat('en-US', {- dateStyle: 'medium',- timeStyle: 'medium',- }).format(selectedIssue.updatedAt)}- </div>- </div>- </div>- </CardContent>- </Card>- )}- <div className="flex flex-col space-y-2">- <div className="flex flex-col gap-2">- <Label htmlFor="ban_reason">Ban Reason</Label>- <Textarea- className="max-w-xl"- id="ban_reason"- placeholder="An optional ban reason..."- value={banReason}- onChange={(e) => {- setBanReason(e.target.value);- }}- />- </div>- <Button- variant={'destructive'}- onClick={handleUserBan}- className="flex items-center justify-center gap-2"- >- <Gavel className="h-4 w-4" />- Ban @{selectedIssue?.challenge.user.name}- </Button>- <Separator />- <div className="flex flex-col gap-2">- <Button- variant={'outline'}- onClick={() => {- handleDisableChallenge();- }}- className="flex items-center justify-center gap-2"- >- <EyeOff className="h-4 w-4" />- Disable Challenge- </Button>- <Button- onClick={handleDismissReport}- className="flex items-center justify-center gap-2"- >- <X className="h-4 w-4" />- Dismiss Report- </Button>- </div>- </div>- </div>- </ScrollArea>- </DialogContent>- </Dialog>- )}- </div>+ </section>);-};+}diff --git a/src/components/admin/reports/index.ts b/src/components/admin/reports/index.tsnew file mode 100644index 00000000..e69de29bdiff --git a/src/components/challenge/code-panel/index.tsx b/src/components/challenge/code-panel/index.tsxindex b67ed9e4..b0d11097 100644--- a/src/components/challenge/code-panel/index.tsx+++ b/src/components/challenge/code-panel/index.tsx@@ -116,7 +116,7 @@ export const CodePanel = (props: Props) => {strict: true,target: monaco.languages.typescript.ScriptTarget.ESNext,strictNullChecks: true,- })+ });if (!monaco.editor.getModel(monaco.Uri.parse(LIB_URI))) {monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, LIB_URI);diff --git a/src/components/challenge/comments/comment.action.ts b/src/components/challenge/comments/comment.action.tsindex 3dec5552..79237869 100644--- a/src/components/challenge/comments/comment.action.ts+++ b/src/components/challenge/comments/comment.action.ts@@ -22,6 +22,8 @@ export type SolutionComment = Omit<export async function addComment(comment: ChallengeComment | SolutionComment) {const session = await getServerAuthSession();+ if (!session?.user.id) return 'unauthorized';+ if (comment.text.length === 0) return 'text_is_empty';if (!session?.user.id) return 'unauthorized';if (comment.text.length === 0) return 'text_is_empty';diff --git a/src/components/challenge/comments/comment.tsx b/src/components/challenge/comments/comment.tsxindex 4448f7df..978f286c 100644--- a/src/components/challenge/comments/comment.tsx+++ b/src/components/challenge/comments/comment.tsx@@ -12,6 +12,7 @@ import CommentDeleteDialog from './delete';interface CommentProps {comment: ChallengeRouteData['comment'][number];+ readonly?: boolean;}const commentReportSchema = z@@ -35,7 +36,7 @@ const commentReportSchema = zexport type CommentReportSchemaType = z.infer<typeof commentReportSchema>;-const Comment = ({ comment }: CommentProps) => {+const Comment = ({ comment, readonly = false }: CommentProps) => {async function copyPathNotifyUser() {try {await copyCommentUrlToClipboard();@@ -78,42 +79,39 @@ const Comment = ({ comment }: CommentProps) => {</TooltipContent></Tooltip></div>-- <div className="flex flex-wrap items-center justify-end gap-2">- <div- onClick={() => {- copyPathNotifyUser();- }}- className="flex cursor-pointer items-center gap-1 text-neutral-500 duration-200 hover:text-neutral-400 hover:underline"- >- <Share className="h-3 w-3" />- <small className="font-md text-sm leading-none">Share</small>+ {!readonly && (+ <div className="flex flex-wrap items-center justify-end gap-2">+ <div+ onClick={() => {+ copyPathNotifyUser();+ }}+ className="flex cursor-pointer items-center gap-1 text-neutral-500 duration-200 hover:text-neutral-400 hover:underline"+ >+ <Share className="h-3 w-3" />+ <small className="font-md text-sm leading-none">Share</small>+ </div>+ {/* TODO: make dis work */}+ <button className="flex cursor-pointer items-center gap-1 text-sm text-neutral-500 duration-200 hover:text-neutral-400 hover:underline dark:text-neutral-500 dark:hover:text-neutral-400">+ <Reply className="h-3 w-3" />+ Reply+ </button>+ {/* TODO: make dis work */}+ {isAuthor ? (+ <CommentDeleteDialog comment={comment} asChild>+ <button className="flex cursor-pointer items-center gap-1 text-sm text-neutral-500 duration-200 hover:text-neutral-400 hover:underline dark:text-neutral-500 dark:hover:text-neutral-400">+ <Trash2 className="h-3 w-3" />+ Delete+ </button>+ </CommentDeleteDialog>+ ) : (+ <ReportDialog reportType="COMMENT" commentId={comment.id}>+ <button className="flex cursor-pointer items-center text-sm text-neutral-400 duration-200 hover:text-neutral-500 hover:underline dark:text-neutral-600 dark:hover:text-neutral-500">+ Report+ </button>+ </ReportDialog>+ )}</div>- {/* TODO: make dis work */}- <button className="flex cursor-pointer items-center gap-1 text-sm text-neutral-500 duration-200 hover:text-neutral-400 hover:underline dark:text-neutral-500 dark:hover:text-neutral-400">- <Reply className="h-3 w-3" />- Reply- </button>- {isAuthor ? (- <CommentDeleteDialog comment={comment} asChild>- <button className="flex cursor-pointer items-center gap-1 text-sm text-neutral-500 duration-200 hover:text-neutral-400 hover:underline dark:text-neutral-500 dark:hover:text-neutral-400">- <Trash2 className="h-3 w-3" />- Delete- </button>- </CommentDeleteDialog>- ) : (- <ReportDialog reportType="COMMENT" commentId={comment.id}>- <button- onClick={() => {- // do somehting- }}- className="flex cursor-pointer items-center text-sm text-neutral-400 duration-200 hover:text-neutral-500 hover:underline dark:text-neutral-600 dark:hover:text-neutral-500"- >- Report- </button>- </ReportDialog>- )}- </div>+ )}</div><p className="w-full break-words pl-[1px] text-sm">{/* TODO: <code></code> is <Markdown /> does not wrap long lines causing overflow */}diff --git a/src/components/challenge/comments/getCommentRouteData.ts b/src/components/challenge/comments/getCommentRouteData.tsindex 70d807fd..08817e65 100644--- a/src/components/challenge/comments/getCommentRouteData.ts+++ b/src/components/challenge/comments/getCommentRouteData.ts@@ -37,6 +37,9 @@ export async function getInfiniteComments({ challengeId, lastCursor }: QueryParawhere: {rootChallengeId: challengeId,},+ cursor: {+ id: last.id,+ },}).then((f) => f.length > 0): false;diff --git a/src/components/challenge/solutions/submit-solution.tsx b/src/components/challenge/solutions/submit-solution.tsxindex 18067684..5de7e42d 100644--- a/src/components/challenge/solutions/submit-solution.tsx+++ b/src/components/challenge/solutions/submit-solution.tsx@@ -2,7 +2,7 @@ import { Plus } from 'lucide-react';import { Button } from '~/components/ui/button';interface Props {- disabled: boolean+ disabled: boolean;setView: (view: 'editor' | 'list') => void;}diff --git a/src/components/report/index.tsx b/src/components/report/index.tsxindex b7e6af80..f3d0f008 100644--- a/src/components/report/index.tsx+++ b/src/components/report/index.tsx@@ -59,7 +59,13 @@ export default function ReportDialog({| ReportCommentDialogProps| ReportSolutionDialogProps>) {- const { handleSubmit, register, control, setValue } = useForm({+ const {+ handleSubmit,+ formState: { errors },+ register,+ control,+ setValue,+ } = useForm({defaultValues: {derogatory: false,unclear: false,@@ -90,220 +96,222 @@ export default function ReportDialog({}return (- <div>- <Dialog- open={show}- onOpenChange={(e) => {- setShow(e);- }}- >- <DialogTrigger asChild={triggerAsChild}>{children}</DialogTrigger>- <DialogContent>- <form- onSubmit={handleSubmit(async (e) => {- let args = {} as UserReport | ChallengeReport | CommentReport | SolutionReport;- switch (reportType) {- case 'CHALLENGE':- args = {- ...props,- text: e.comments,- type: reportType,- } as ChallengeReport;- break;- case 'COMMENT':- args = {- ...props,- text: e.comments,- type: reportType,- } as CommentReport;- break;- case 'USER':- args = {- ...props,- text: e.comments,- type: reportType,- } as UserReport;- break;- case 'SOLUTION':- args = {- ...props,- text: e.comments,- type: reportType,- } as SolutionReport;- }+ <Dialog+ open={show}+ onOpenChange={(e) => {+ setShow(e);+ }}+ >+ <DialogTrigger asChild={triggerAsChild}>{children}</DialogTrigger>+ <DialogContent>+ <form+ onSubmit={handleSubmit(async (e) => {+ let args = {} as UserReport | ChallengeReport | CommentReport | SolutionReport;+ switch (reportType) {+ case 'CHALLENGE':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as ChallengeReport;+ break;+ case 'COMMENT':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as CommentReport;+ break;+ case 'USER':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as UserReport;+ break;+ case 'SOLUTION':+ args = {+ ...props,+ text: e.comments,+ type: reportType,+ } as SolutionReport;+ }- // This shit is like... extra jank.- const issues = Object.entries(e).reduce((all, [key, value]) => {- if (key === 'comments') return all;- if (value)- all.push({- type: key.toUpperCase() as IssueType,- });- return all;- }, [] as { type: IssueType }[]);+ // This shit is like... extra jank.+ const issues = Object.entries(e).reduce((all, [key, value]) => {+ if (key === 'comments') return all;+ if (value)+ all.push({+ type: key.toUpperCase() as IssueType,+ });+ return all;+ }, [] as { type: IssueType }[]);- const value = await addReport({- ...args,- issues,- });+ const value = await addReport({+ ...args,+ issues,+ });- switch (value) {- case 'already_exists':- toast({- title: 'Already reported',- description: <p>You have already made a report with this information.</p>,- });- break;- case 'created':- toast({- title: 'Created',- variant: 'success',- description: <p>A report has been made.</p>,- });- break;- case 'not_logged_in':- toast({- title: 'Not Logged In',- variant: 'destructive',- description: <p>You must be logged in to make a report.</p>,- });- }- setShow(false);- })}- >- <DialogHeader>- <DialogTitle>{desc}</DialogTitle>- <DialogDescription>- Please be as thorough in your report as you can.- </DialogDescription>- </DialogHeader>- <div className="mt-4 flex flex-col gap-2">- <Text intent="leading">Please select all that apply:</Text>- <FormField- name="derogatory"- render={() => (- <FormItem>- <div className="flex items-center gap-2">- <Checkbox- {...register('derogatory')}- onCheckedChange={(e) => setValue('derogatory', e as boolean)}- />- <div>Derogatory</div>- </div>- </FormItem>- )}- control={control}- />- <FormField- name="derogatory"- render={() => (- <FormItem>- <div className="flex items-center gap-2">- <Checkbox- {...register('bullying')}- onCheckedChange={(e) => setValue('bullying', e as boolean)}- />- <div>Bullying</div>- </div>- </FormItem>- )}- control={control}- />- <FormField- name="hateSpeech"- render={() => (- <FormItem>- <div className="flex items-center gap-2">- <Checkbox- {...register('hateSpeech')}- onCheckedChange={(e) => setValue('hateSpeech', e as boolean)}- />- <div>Hate speech</div>- </div>- </FormItem>- )}- control={control}- />- <FormField- name="spam"- render={() => (- <FormItem>- <div className="flex items-center gap-2">- <Checkbox- {...register('spam')}- onCheckedChange={(e) => setValue('spam', e as boolean)}- />- <div>Spam</div>- </div>- </FormItem>- )}- control={control}- />+ switch (value) {+ case 'already_exists':+ toast({+ title: 'Already reported',+ description: <p>You have already made a report with this information.</p>,+ });+ break;+ case 'created':+ toast({+ title: 'Created',+ variant: 'success',+ description: <p>A report has been made.</p>,+ });+ break;+ case 'not_logged_in':+ toast({+ title: 'Not Logged In',+ variant: 'destructive',+ description: <p>You must be logged in to make a report.</p>,+ });+ }+ setShow(false);+ })}+ >+ <DialogHeader>+ <DialogTitle>{desc}</DialogTitle>+ <DialogDescription>Please be as thorough in your report as you can.</DialogDescription>+ </DialogHeader>+ <div className="mt-4 flex flex-col gap-2">+ <Text intent="leading">Please select all that apply:</Text>+ <FormField+ name="derogatory"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="derogatory"+ {...register('derogatory')}+ onCheckedChange={(e) => setValue('derogatory', e as boolean)}+ />+ <label htmlFor="derogatory">Derogatory</label>+ </div>+ </FormItem>+ )}+ control={control}+ />+ <FormField+ name="derogatory"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="bullying"+ {...register('bullying')}+ onCheckedChange={(e) => setValue('bullying', e as boolean)}+ />+ <label htmlFor="bullying">Bullying</label>+ </div>+ </FormItem>+ )}+ control={control}+ />+ <FormField+ name="hateSpeech"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="hateSpeech"+ {...register('hateSpeech')}+ onCheckedChange={(e) => setValue('hateSpeech', e as boolean)}+ />+ <label htmlFor="hateSpeech">Hate speech</label>+ </div>+ </FormItem>+ )}+ control={control}+ />+ <FormField+ name="spam"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="spam"+ {...register('spam')}+ onCheckedChange={(e) => setValue('spam', e as boolean)}+ />+ <label htmlFor="spam">Spam</label>+ </div>+ </FormItem>+ )}+ control={control}+ />+ <FormField+ name="threat"+ render={({ field }) => (+ <FormItem>+ <div className="flex items-center gap-2">+ <Checkbox+ id="threat"+ {...register('threat')}+ onCheckedChange={(e) => setValue('threat', e as boolean)}+ />+ <label htmlFor="threat">Threat of violence</label>+ </div>+ </FormItem>+ )}+ control={control}+ />+ {reportType === 'CHALLENGE' && (<FormField- name="threat"- render={() => (+ name="unclear"+ render={({ field }) => (<FormItem><div className="flex items-center gap-2"><Checkbox- {...register('threat')}- onCheckedChange={(e) => setValue('threat', e as boolean)}+ id="unclear"+ {...register('unclear')}+ onCheckedChange={(e) => setValue('unclear', e as boolean)}/>- <div>Threat of violence</div>+ <label htmlFor="unclear">Unclear</label></div></FormItem>)}control={control}/>- {reportType === 'CHALLENGE' && (- <FormField- name="unclear"- render={() => (- <FormItem>- <div className="flex items-center gap-2">- <Checkbox- {...register('unclear')}- onCheckedChange={(e) => setValue('unclear', e as boolean)}- />- <div>Unclear</div>- </div>- </FormItem>- )}- control={control}- />- )}+ )}- <FormField- name="comments"- render={() => (- <FormItem className="my-3">- <div className="flex flex-col gap-3">- <div>Other information</div>- <Textarea- {...register('comments')}- placeholder="Any extra information to help our moderator team when reviewing this report."- />- </div>- </FormItem>- )}- control={control}- />- </div>+ <FormField+ name="comments"+ render={({ field }) => (+ <FormItem className="my-3">+ <div className="flex flex-col gap-3">+ <div>Other information</div>+ <Textarea+ {...register('comments')}+ placeholder="Any extra information to help our moderator team when reviewing this report."+ />+ </div>+ </FormItem>+ )}+ control={control}+ />+ </div>- <DialogFooter>- <Button- variant="outline"- onClick={(e) => {- e.preventDefault();- setShow(false);- }}- >- Cancel- </Button>- <Button type="submit">Send report</Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- </div>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={(e) => {+ e.preventDefault();+ setShow(false);+ }}+ >+ Cancel+ </Button>+ <Button type="submit">Send report</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>);}diff --git a/src/components/report/report.action.ts b/src/components/report/report.action.tsindex 40985714..6cfe8552 100644--- a/src/components/report/report.action.ts+++ b/src/components/report/report.action.ts@@ -11,22 +11,54 @@ export type ReportBase = {export type ChallengeReport = Omit<Report,- 'id' | 'type' | 'userId' | 'commentId' | 'reporterId' | 'status' | 'solutionId'+ | 'id'+ | 'type'+ | 'userId'+ | 'commentId'+ | 'reporterId'+ | 'status'+ | 'solutionId'+ | 'updatedAt'+ | 'createdAt'> & { type: 'CHALLENGE' } & ReportBase;export type UserReport = Omit<Report,- 'id' | 'type' | 'challengeId' | 'commentId' | 'reporterId' | 'status' | 'solutionId'+ | 'id'+ | 'type'+ | 'challengeId'+ | 'commentId'+ | 'reporterId'+ | 'status'+ | 'solutionId'+ | 'updatedAt'+ | 'createdAt'> & { type: 'USER' } & ReportBase;export type CommentReport = Omit<Report,- 'id' | 'type' | 'challengeId' | 'userId' | 'reporterId' | 'status' | 'solutionId'+ | 'id'+ | 'type'+ | 'challengeId'+ | 'userId'+ | 'reporterId'+ | 'status'+ | 'solutionId'+ | 'updatedAt'+ | 'createdAt'> & { type: 'COMMENT' } & ReportBase;export type SolutionReport = Omit<Report,- 'id' | 'type' | 'challengeId' | 'userId' | 'reporterId' | 'status' | 'commentId'+ | 'id'+ | 'type'+ | 'challengeId'+ | 'userId'+ | 'reporterId'+ | 'status'+ | 'commentId'+ | 'updatedAt'+ | 'createdAt'> & { type: 'SOLUTION' } & ReportBase;/**@@ -62,7 +94,7 @@ export async function addReport(};break;}- console.info('HAAAAAAAA', report.type, reporter.user.id, filterData);+const alreadyReported = await prisma.report.findFirst({where: {type: report.type,@@ -77,6 +109,7 @@ export async function addReport(await prisma.report.create({data: {reporterId: reporter.user.id,+ updatedAt: new Date(),...report,issues: {createMany: {@@ -90,6 +123,61 @@ export async function addReport(return 'created';}+export type ReportsData = Awaited<ReturnType<typeof getReports>>;+export type InfiniteReports = Awaited<ReturnType<typeof getInfiniteReports>>;++export async function getInfiniteReports(lastCursor?: number) {+ const reports = await getReports(lastCursor);+ const nextCursor = reports.at(-1)?.id;++ let hasNextCursor = false;+ if (nextCursor) {+ const nextPage = await getReports(nextCursor);+ if (nextPage.length > 0) hasNextCursor = true;+ }++ return {+ data: reports,+ metadata: {+ hasNextPage: hasNextCursor,+ lastCursor: hasNextCursor ? nextCursor : null,+ },+ };+}++export async function getReports(lastCursor?: number, take = 25) {+ return prisma.report.findMany({+ include: {+ challenge: {+ include: {+ _count: {+ select: {+ vote: true,+ }+ }+ }+ },+ user: true,+ reporter: true,+ issues: true,+ comment: true,+ solution: true,+ },+ take,+ ...(lastCursor && {+ skip: 1,+ cursor: {+ id: lastCursor,+ },+ }),+ orderBy: [+ {+ status: 'asc',+ },+ ],+ });+}+export async function addChallengeReport(challengeId: number, userId: string, data: FormValues) {if (userId === undefined) return 'not_logged_in';@@ -100,7 +188,6 @@ export async function addChallengeReport(challengeId: number, userId: string, da},});if (report.length > 0) {- console.info(report);return 'report_already_made';}@@ -116,3 +203,34 @@ export async function addChallengeReport(challengeId: number, userId: string, dareturn 'created';}++export async function getReportedUserInformation(userId: string) {+ return await prisma.user.findFirstOrThrow({+ where: {+ id: userId,+ },+ include: {+ comment: {+ take: 10,+ include: {+ user: true,+ },+ orderBy: {+ createdAt: 'desc',+ },+ },+ sharedSolution: {+ take: 5,+ orderBy: {+ createdAt: 'desc',+ },+ },+ challenge: {+ take: 5,+ orderBy: {+ createdAt: 'asc',+ },+ },+ },+ });+}diff --git a/src/components/report/types/challenge.report.tsx b/src/components/report/types/challenge.report.tsxnew file mode 100644index 00000000..30ecb60e--- /dev/null+++ b/src/components/report/types/challenge.report.tsx@@ -0,0 +1,42 @@+import { ThumbsUp } from 'lucide-react';+import { type ReportWithInfo } from '~/app/admin/report/[id]/report.action';+import { getChallenge } from '~/components/admin/admin.actions';+import { CodeEditor } from '~/components/ui/code-editor';++import { Markdown } from '~/components/ui/markdown';+import Text from '~/components/ui/typography/typography';+import { UserBadge } from '~/components/ui/user-badge';+export interface ChallengeReportProps {+ report: NonNullable<ReportWithInfo>;+}+export default async function ChallengeReport({ report }: ChallengeReportProps) {+ if (!report.challenge || !report.challengeId) return null;+ const challengeInfo = await getChallenge(report.challengeId);+ return (+ <section className="mt-6 flex flex-grow flex-col gap-4 overflow-auto md:flex-nowrap">+ <div className="w-full rounded-lg p-4 dark:bg-muted/90">+ <Text intent="h3">{report.challenge.name}</Text>+ <Text className="mt-2">+ Created at:{' '}+ {report.challenge.createdAt.toLocaleString('en-US', {+ dateStyle: 'medium',+ timeStyle: 'medium',+ })}+ </Text>+ <Text intent="body">+ Last updated on:{' '}+ {report.challenge.updatedAt.toLocaleString('en-US', {+ dateStyle: 'medium',+ timeStyle: 'medium',+ })}+ </Text>+ <UserBadge username={report.challenge.user.name || 'No author found'} />+ <div className="my-2 flex gap-4">+ <ThumbsUp /> {challengeInfo._count.vote}+ </div>+ <Markdown className="mt-4">{report.challenge.description}</Markdown>+ </div>+ <CodeEditor value={report.challenge.prompt} height={'50vh'} />+ </section>+ );+}diff --git a/src/components/report/types/comment.report.tsx b/src/components/report/types/comment.report.tsxnew file mode 100644index 00000000..19ac9d46--- /dev/null+++ b/src/components/report/types/comment.report.tsx@@ -0,0 +1,31 @@+import Link from 'next/link';+import { type ReportWithInfo } from '~/app/admin/report/[id]/report.action';+import Comment from '~/components/challenge/comments/comment';++export default function CommentReport({ report }: { report: NonNullable<ReportWithInfo> }) {+ if (report.type !== 'COMMENT' || report.commentId === null || !report.comment) return null;++ return (+ <div>+ <header>+ Commented on{' '}+ <Link+ className="rounded-full bg-zinc-800 px-2 py-1 text-blue-600 dark:text-blue-400"+ href={`/${report.comment.rootType.toLowerCase()}/${+ report.comment.rootChallengeId || report.comment.rootSolutionId+ }`}+ >+ <div className="mr-2 inline-block rounded-full bg-primary-foreground px-2 text-white">+ {report.comment.rootType}+ </div>+ {report.comment.rootType === 'CHALLENGE'+ ? report.comment?.rootChallenge?.name+ : report.comment?.rootSolution?.title}+ </Link>+ </header>+ <section className="mt-4 rounded-lg bg-zinc-800">+ <Comment comment={report.comment} readonly />+ </section>+ </div>+ );+}diff --git a/src/components/report/types/solution.report.tsx b/src/components/report/types/solution.report.tsxnew file mode 100644index 00000000..f4b334c1--- /dev/null+++ b/src/components/report/types/solution.report.tsx@@ -0,0 +1,47 @@+'use server';++import Link from 'next/link';+import { type ReportWithInfo } from '~/app/admin/report/[id]/report.action';+import { Markdown } from '~/components/ui/markdown';+import Text from '~/components/ui/typography/typography';+import { prisma } from '~/server/db';++async function getSolutionChallenge(challengeId: number) {+ return prisma.challenge.findFirstOrThrow({+ where: {+ id: challengeId,+ },+ });+}++export default async function SolutionReport({ report }: { report: NonNullable<ReportWithInfo> }) {+ if (report.type !== 'SOLUTION' || !report.solution) return null;++ const challenge = await getSolutionChallenge(report.solution.challengeId || -1);++ return (+ <div className="rounded-lg border border-slate-700 bg-zinc-800 p-3">+ <header className="mb-4 border-b border-zinc-600 py-4">+ <Text intent="h1">{report.solution.title}</Text>+ Solution for:{' '}+ <Link+ className="text-blue-600 dark:text-blue-400"+ href={`/challenge/${challenge.id}`}+ target="_blank"+ rel="noreferrer"+ >+ {challenge.name}+ </Link>{' '}+ <br />+ Created at{' '}+ {report.solution.createdAt.toLocaleString(undefined, {+ dateStyle: 'medium',+ timeStyle: 'short',+ })}+ </header>+ <section>+ <Markdown>{report.solution.description}</Markdown>+ </section>+ </div>+ );+}diff --git a/src/components/report/types/user.report.tsx b/src/components/report/types/user.report.tsxnew file mode 100644index 00000000..6469d58c--- /dev/null+++ b/src/components/report/types/user.report.tsx@@ -0,0 +1,116 @@+'use server';++import { type ReportWithInfo } from '~/app/admin/report/[id]/report.action';+import Comment from '~/components/challenge/comments/comment';+import { Expandable } from '~/components/ui/expandable';+import { Markdown } from '~/components/ui/markdown';+import Text from '~/components/ui/typography/typography';+import { getReportedUserInformation } from '../report.action';++interface UserReportProps {+ report: NonNullable<ReportWithInfo>;+}++export default async function UserReportUi({ report }: UserReportProps) {+ if (!report.userId) return null;+ const userInfo = await getReportedUserInformation(report.userId);+ return (+ <div>+ <Text intent="h3">+ Most Recent Comments <small>(10)</small>+ </Text>++ <div className="mt-4 flex flex-col gap-4">+ {userInfo.comment &&+ userInfo.comment.map((m) => (+ <div key={`comment-${m.id}`} className="rounded border border-zinc-700 bg-zinc-800 p-2">+ <Comment readonly comment={m} />+ </div>+ ))}++ {userInfo.comment && userInfo.comment.length === 0 && (+ <div className="mb-6 flex justify-center">No comments on record</div>+ )}+ </div>++ <Text intent="h3" className="mt-4">+ Most Recent challenges <small>(5)</small>{' '}+ </Text>++ <div className="mt-4 flex flex-col gap-4">+ {userInfo.challenge && userInfo.challenge.length === 0 && (+ <div className="text-center">No recent challenges.</div>+ )}+ {userInfo.challenge &&+ userInfo.challenge.map((ch, i) => (+ <Expandable+ open={i === 0}+ key={`challenge-${ch.id}`}+ className="rounded-xl border border-slate-600 p-3"+ header={+ <header className="flex w-full flex-col items-baseline justify-between gap-4 md:flex-row">+ <Text intent="h2">{ch.name}</Text>+ <div className="flex flex-wrap gap-2 text-xs md:flex-nowrap">+ <div className="rounded-full bg-slate-300 px-3 py-1 text-gray-800">+ <span className="font-semibold">Created at: </span>+ {ch.createdAt.toLocaleString(undefined, {+ dateStyle: 'medium',+ timeStyle: 'short',+ })}+ </div>+ <div className="rounded-full bg-slate-300 px-3 py-1 text-gray-800">+ <span className="font-semibold">Updated at: </span>+ {ch.updatedAt.toLocaleString(undefined, {+ dateStyle: 'medium',+ timeStyle: 'short',+ })}+ </div>+ </div>+ </header>+ }+ >+ <div className="mt-4 rounded-lg bg-zinc-800 p-4" key={`challenge-${ch.id}`}>+ <section className="mb-4 border-b border-slate-500 pb-4">+ <div className="font-semibold">Short description</div>+ <Markdown>{ch.shortDescription}</Markdown>+ </section>+ <Markdown>{ch.description}</Markdown>+ </div>+ </Expandable>+ ))}+ </div>++ <Text intent="h3" className="my-4">+ Most recent solutions <small>(5)</small>+ </Text>++ {userInfo.sharedSolution && (+ <div className="flex flex-col gap-4">+ {userInfo.sharedSolution.map((f) => (+ <div+ key={`solution-${f.id}`}+ className="text:primary-foreground rounded-xl border bg-zinc-800 p-4"+ >+ <header className="flex justify-between">+ <Text intent="h2" weight="bold">+ {f.title}+ </Text>+ <div>+ {f.createdAt.toLocaleString(undefined, {+ dateStyle: 'medium',+ timeStyle: 'medium',+ })}+ </div>+ </header>+ <section>+ <Markdown>{f.description}</Markdown>+ </section>+ </div>+ ))}+ </div>+ )}++ {userInfo?.sharedSolution?.length === 0 && <div className="mb-6">No solutions on record</div>}+ </div>+ );+}diff --git a/src/components/ui/code-editor.tsx b/src/components/ui/code-editor.tsxindex 699da189..beeb88b5 100644--- a/src/components/ui/code-editor.tsx+++ b/src/components/ui/code-editor.tsx@@ -22,6 +22,7 @@ interface Props extends EditorProps {options?: monaco.editor.IStandaloneEditorConstructionOptions;value: string;}+export function CodeEditor({ onChange, onMount, options, value, ...props }: Props) {const { theme } = useTheme();const editorTheme = theme === 'light' ? 'vs' : 'vs-dark';@@ -40,6 +41,7 @@ export function CodeEditor({ onChange, onMount, options, value, ...props }: Propreturn (<Editor+ {...props}theme={editorTheme}options={editorOptions}defaultLanguage="typescript"diff --git a/src/components/ui/expandable.tsx b/src/components/ui/expandable.tsxnew file mode 100644index 00000000..05f41f01--- /dev/null+++ b/src/components/ui/expandable.tsx@@ -0,0 +1,23 @@+'use client';+import clsx from 'clsx';+import React from 'react';++export interface ExpandableProps extends React.HTMLProps<HTMLDetailsElement> {+ header: React.ReactNode;+}++export function Expandable({+ header,+ children,+ className,+ ...props+}: React.PropsWithChildren<ExpandableProps>) {+ return (+ <details className={clsx('expandable', className)} {...props}>+ <summary className="cursor-pointer [&::marker]:hidden [&::marker]:content-none">+ {header}+ </summary>+ <section>{children}</section>+ </details>+ );+}diff --git a/src/components/ui/pagination.tsx b/src/components/ui/pagination.tsxnew file mode 100644index 00000000..7012852f--- /dev/null+++ b/src/components/ui/pagination.tsx@@ -0,0 +1,80 @@+import { ChevronLeft, ChevronRight } from 'lucide-react';+import { useMemo } from 'react';++export interface OnPageChangePayload {+ page: number;+ pageLoaded: boolean;+}++export interface PaginationProps {+ hasNextPage?: boolean;+ totalPages?: number;+ currentPage?: number;+ onChange: (e: CustomEvent<OnPageChangePayload>) => void;+}++export default function Pagination({+ hasNextPage = false,+ totalPages = 1,+ currentPage = 1,+ onChange,+}: PaginationProps) {+ const fuck = useMemo(() => {+ const length = totalPages > 5 ? 5 : totalPages;+ const initial = Array.from({ length }, (_, i) => i + 1);+ if (totalPages > 5) {+ [initial[1], initial[2], initial[3], initial[4]] = [+ currentPage - 1,+ currentPage,+ currentPage + 1,+ totalPages,+ ];+ }+ return initial;+ }, [currentPage, totalPages, hasNextPage]);++ return (+ <div className="pagination justify-baseline flex gap-2">+ <div className="prev">+ <button+ disabled={currentPage === 1}+ onClick={() =>+ onChange(+ new CustomEvent('page:change', {+ detail: {+ page: currentPage - 1,+ pageLoaded: true,+ },+ }),+ )+ }+ >+ <ChevronLeft />+ </button>+ </div>+ {fuck.map((page, i) => (+ <button key={`pagination-${page}`}>+ {page}+ {i === fuck.length - 1 && hasNextPage && '+'}+ </button>+ ))}+ <div className="next">+ <button+ disabled={!hasNextPage && currentPage === totalPages}+ onClick={() =>+ onChange(+ new CustomEvent('page:change', {+ detail: {+ page: currentPage + 1,+ pageLoaded: hasNextPage && currentPage !== totalPages,+ },+ }),+ )+ }+ >+ <ChevronRight />+ </button>+ </div>+ </div>+ );+}diff --git a/src/components/ui/typography/typography.tsx b/src/components/ui/typography/typography.tsxindex 3c022bce..048c3d6b 100644--- a/src/components/ui/typography/typography.tsx+++ b/src/components/ui/typography/typography.tsx@@ -33,9 +33,9 @@ const styles = cva<{body: 'text-md text-slate-800 dark:text-slate-100',leading: 'text-[1.125rem] font-medium',title: 'text-[8rem] font-bold',- h1: 'text-[2rem] font-bold',- h2: 'text-[1.5rem] font-semibold',- h3: 'font-bold italic text-[1.25rem]',+ h1: 'text-[2rem] font-bold [&>small]:text-[0.7em] [&>small]:dark:text-slate-400 [&>small]:text-slate-600',+ h2: 'text-[1.5rem] font-semibold [&>small]:text-[0.7em] [&>small]:dark:text-slate-400 [&>small]:text-slate-600',+ h3: 'font-bold italic text-[1.25rem] [&>small]:text-[0.7em] [&>small]:dark:text-slate-400 [&>small]:text-slate-600',},weight: {bold: 'font-bold',diff --git a/src/components/user/dashboard/user-header.tsx b/src/components/user/dashboard/user-header.tsxindex fe9022d1..45247b67 100644--- a/src/components/user/dashboard/user-header.tsx+++ b/src/components/user/dashboard/user-header.tsx@@ -1,6 +1,7 @@'use client';import Text from '~/components/ui/typography/typography';+import { UserData } from './index';import { type User } from '@prisma/client';import ReportDialog from '~/components/report';import { ActionMenu } from '~/components/ui/action-menu';