Connect, collaborate, and grow with a community of TypeScript developers
feat(admin): Adds in new page for reporting (#218)
Jim Burbridge7b04446b3569
diff --git a/src/app/admin/report/[id]/actions.tsx b/src/app/admin/report/[id]/actions.tsxnew file mode 100644index 00000000..4e17e2bc--- /dev/null+++ b/src/app/admin/report/[id]/actions.tsx@@ -0,0 +1,134 @@+'use client';++import { type Challenge, type User, type Vote } from '@prisma/client';+import {+ Dialog,+ DialogContent,+ DialogTitle,+ DialogDescription,+ DialogFooter,+ DialogHeader,+} from '~/components/ui/dialog';+import { useRouter } from 'next/navigation';+import { useState } from 'react';+import {+ banUser,+ disableChallenge,+ dismissChallengeReport,+} 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';++export default function ReportActions({+ moderatorId,+ moderator,+ challenge,+ reportId,+}: {+ moderatorId: string | null;+ moderator: { name: string | null } | null;+ challenge: Challenge & { user: User; vote: Vote[] };+ reportId: number;+}) {+ const [banReason, setBanReason] = useState('');+ const [ban, setBan] = useState(false);+ const router = useRouter();++ async function handleDisableChallenge(challengeId: number, reportId: number) {+ try {+ await disableChallenge(challengeId, reportId);+ } catch (e) {+ toast({+ title: 'Error',+ variant: 'destructive',+ description: <p>An error occurred. Please try again later.s</p>,+ });+ }+ }++ async function handleBanUser(userId: string, reportId: number, banReason?: string) {+ try {+ await banUser(userId, reportId, banReason);+ toast({+ title: 'Success',+ description: <p>User banned successfully.</p>,+ });+ router.push('/admin');+ } catch (e) {+ toast({+ title: 'Error',+ variant: 'destructive',+ description: <p>An error occurred. Please try again later.s</p>,+ });+ }+ }++ async function handleDismissReport(reportId: number) {+ try {+ await dismissChallengeReport(reportId);+ toast({+ title: 'Success',+ description: <p>Dismissed successfully.</p>,+ });+ router.push('/admin');+ } catch (e) {+ toast({+ title: 'Error',+ variant: 'destructive',+ description: <p>An error occurred. Please try again later.s</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)}+ >+ Disable Challenge+ </Button>+ <Button disabled={moderatorId !== null} onClick={() => handleDismissReport(reportId)}>+ Dismiss Report+ </Button>+ <Dialog open={ban} onOpenChange={() => setBan(false)}>+ <DialogContent className="sm:max-w-[425px]">+ <form+ onSubmit={(e) => {+ e.preventDefault();+ handleBanUser(challenge.user.id, reportId, banReason);+ }}+ >+ <DialogHeader>+ <DialogTitle>Ban Reason</DialogTitle>+ <DialogDescription>+ Give some details for why the user is being banned+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 py-4">+ <Label htmlFor="reason">Reason</Label>+ <Textarea+ id="reason"+ value={banReason}+ onChange={(e) => setBanReason(e.target.value)}+ />+ </div>+ <DialogFooter>+ <Button type="button" variant="secondary" onClick={() => setBan(false)}>+ Cancel+ </Button>+ <Button type="submit" variant="destructive">+ Ban+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/src/app/admin/report/[id]/loading.tsx b/src/app/admin/report/[id]/loading.tsxnew file mode 100644index 00000000..07b4dd51--- /dev/null+++ b/src/app/admin/report/[id]/loading.tsx@@ -0,0 +1,3 @@+export default function ReportIdLoading() {+ return <>Loading...</>;+}diff --git a/src/app/admin/report/[id]/page.tsx b/src/app/admin/report/[id]/page.tsxnew file mode 100644index 00000000..dc9eaefd--- /dev/null+++ b/src/app/admin/report/[id]/page.tsx@@ -0,0 +1,125 @@+import { prisma } from '~/server/db';+import { redirect } from 'next/navigation';+import Text from '~/components/ui/typography/typography';+import Link from 'next/link';+import { Markdown } from '~/components/ui/markdown';+import Editor from '~/components/ui/editor';+import { UserBadge } from '~/components/ui/user-badge';+import { AlertCircle, ThumbsUp } from 'lucide-react';+import { Alert, AlertDescription, AlertTitle } from '~/components/ui/alert';+import ReportActions from './actions';+import { getChallenge } from '~/components/admin/admin.actions';++export interface Props {+ params: {+ id: string;+ };+}++export default async function (props: Props) {+ const idNum = Number(props.params.id);+ // Double check that we have a number, redirect out if we don't+ if (isNaN(idNum)) {+ return redirect('/admin');+ }+ // Grab the items.+ const {+ author,+ challenge,+ derogatory,+ id,+ moderatorId,+ moderator,+ createdAt,+ updatedAt,+ unclear,+ text,+ status,+ } = await getChallenge(idNum);++ return (+ <div className="container">+ <div className="sticky top-0 z-50 flex items-center justify-between bg-background/80">+ <Text intent="h1" color="primary">+ Challenge Report+ </Text>+ <ReportActions+ reportId={id}+ moderatorId={moderatorId}+ moderator={moderator}+ challenge={challenge}+ />+ </div>++ <Text intent="h2" className="mt-6">+ Report information+ </Text>++ {moderator && (+ <Alert className="mt-4" variant="destructive">+ <div className="flex items-center gap-2">+ <AlertCircle className="h-[1.25rem]" />+ <AlertTitle>Action already taken</AlertTitle>+ </div>++ <AlertDescription>+ Moderator @{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>++ <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 intent="h2" className="mt-6">+ Challenge information+ </Text>++ <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">+ <Editor value={challenge.prompt} />+ </div>+ </section>+ </div>+ );+}diff --git a/src/app/admin/report/[id]/report.action.ts b/src/app/admin/report/[id]/report.action.tsnew file mode 100644index 00000000..54395f5c--- /dev/null+++ b/src/app/admin/report/[id]/report.action.ts@@ -0,0 +1,18 @@+import { prisma } from '~/server/db';+export async function getReports() {+ const challengeReports = await prisma.challengeReport.findMany({+ include: {+ challenge: {+ include: {+ user: true,+ },+ },+ author: true,+ },+ });+ const otherReports = await prisma.commentReport.findMany();+ return {+ challengeReports,+ otherReports,+ };+}diff --git a/src/app/admin/report/page.tsx b/src/app/admin/report/page.tsxnew file mode 100644index 00000000..0931d338--- /dev/null+++ b/src/app/admin/report/page.tsx@@ -0,0 +1,11 @@+import { getChallengeReports } from '~/components/admin/admin.actions';++export default async function ReportPage() {+ const reports = await getChallengeReports();+ return (+ <div>+ Reports table here. List all+ {reports.length}+ </div>+ );+}diff --git a/src/app/challenge/[id]/solutions/[solutionId]/page.tsx b/src/app/challenge/[id]/solutions/[solutionId]/page.tsxindex 32d41579..a996fae2 100644--- a/src/app/challenge/[id]/solutions/[solutionId]/page.tsx+++ b/src/app/challenge/[id]/solutions/[solutionId]/page.tsx@@ -22,7 +22,7 @@ async function getSolution(solutionId: string) {},include: {challenge: true,- user: true+ user: true,},});diff --git a/src/app/page.tsx b/src/app/page.tsxindex 2ea073a5..0560d045 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -1,7 +1,7 @@import Head from 'next/head';import { Footsies } from '~/components/ui/footsies';-export default function Index() {+export default async function Index() {return (<><Head>diff --git a/src/components/admin/admin.actions.tsx b/src/components/admin/admin.actions.tsxindex 85fec4e6..1fc6df97 100644--- a/src/components/admin/admin.actions.tsx+++ b/src/components/admin/admin.actions.tsx@@ -46,30 +46,25 @@ export async function getBannedUsers() {*/export async function disableChallenge(challengeId: number, reportId: number) {const session = await getServerAuthSession();- try {- await prisma.$transaction([- prisma.challenge.update({- where: {- id: challengeId,- },- data: {- visibility: 'HIDDEN',- },- }),- prisma.challengeReport.update({- where: {- id: reportId,- },- data: {- status: 'CLEARED',- moderatorId: session?.user.id,- },- }),- ]);- } catch (e) {- console.log(e);- return 'uh_oh';- }+ await prisma.$transaction([+ prisma.challenge.update({+ where: {+ id: challengeId,+ },+ data: {+ visibility: 'HIDDEN',+ },+ }),+ prisma.challengeReport.update({+ where: {+ id: reportId,+ },+ data: {+ status: 'CLEARED',+ moderatorId: session?.user.id,+ },+ }),+ ]);}/**@@ -101,44 +96,39 @@ export async function dismissChallengeReport(reportId: number) {export async function banUser(userId: string, reportId: number, banReason?: string) {const session = await getServerAuthSession();- try {- await prisma.$transaction([- prisma.user.update({- where: {- id: userId,- },- data: {- status: 'BANNED',- banReason: banReason,- },- }),- prisma.challenge.updateMany({- where: {- userId: userId,- },- data: {- visibility: 'HIDDEN',- },- }),- prisma.session.deleteMany({- where: {- userId: userId,- },- }),- prisma.challengeReport.update({- where: {- id: reportId,- },- data: {- status: 'CLEARED',- moderatorId: session?.user.id,- },- }),- ]);- } catch (e) {- console.log(e);- return 'uh_oh';- }+ await prisma.$transaction([+ prisma.user.update({+ where: {+ id: userId,+ },+ data: {+ status: 'BANNED',+ banReason: banReason,+ },+ }),+ prisma.challenge.updateMany({+ where: {+ userId: userId,+ },+ data: {+ visibility: 'HIDDEN',+ },+ }),+ prisma.session.deleteMany({+ where: {+ userId: userId,+ },+ }),+ prisma.challengeReport.update({+ where: {+ id: reportId,+ },+ data: {+ status: 'CLEARED',+ moderatorId: session?.user.id,+ },+ }),+ ]);}/*** The function lifts the ban off the user i.e. updates@@ -166,3 +156,25 @@ export async function unbanUser(userId: string) {}),]);}++export async function getChallenge(id: number) {+ return prisma.challengeReport.findFirstOrThrow({+ where: {+ id,+ },+ include: {+ author: true,+ moderator: {+ select: {+ name: true,+ },+ },+ challenge: {+ include: {+ user: true,+ vote: true,+ },+ },+ },+ });+}diff --git a/src/components/admin/reports.tsx b/src/components/admin/reports.tsxindex 7a042f8c..f3ef50f3 100644--- a/src/components/admin/reports.tsx+++ b/src/components/admin/reports.tsx@@ -24,7 +24,6 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '.import { Textarea } from '../ui/textarea';import { TypographyH3 } from '../ui/typography/h3';import { toast } from '../ui/use-toast';-interface ReportsProps {data: AdminReportDetails;}@@ -135,7 +134,7 @@ export const ReportDetails = ({ data }: ReportsProps) => {<TableRowonClick={() => {setSelectedIssue(report);- setDialogOpen(true);+ router.push(`/admin/report/${report.id}`);}}className="hover:cursor-pointer"key={reportIdx}diff --git a/src/components/challenge/description/index.tsx b/src/components/challenge/description/index.tsxindex f991cdd6..f509cd2f 100644--- a/src/components/challenge/description/index.tsx+++ b/src/components/challenge/description/index.tsx@@ -135,9 +135,9 @@ export function Description({ challenge }: Props) {return (<><div className="flex items-baseline justify-between">- <TypographyH3 className="mb-2 font-medium flex items-center gap-2">- {challenge.name}- </TypographyH3>+ <TypographyH3 className="mb-2 flex items-center gap-2 font-medium">+ {challenge.name}+ </TypographyH3><Dialog><DialogTrigger><ActionMenudiff --git a/src/components/ui/alert.tsx b/src/components/ui/alert.tsxnew file mode 100644index 00000000..71f90e5e--- /dev/null+++ b/src/components/ui/alert.tsx@@ -0,0 +1,49 @@+import * as React from 'react';+import { cva, type VariantProps } from 'class-variance-authority';++import { cn } from '~/utils/cn';++const alertVariants = cva(+ 'relative w-full rounded-lg border p-4 [&:has(svg)]:pl-11 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground',+ {+ variants: {+ variant: {+ default: 'bg-background text-foreground',+ destructive:+ 'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive bg-red-100',+ },+ },+ defaultVariants: {+ variant: 'default',+ },+ },+);++const Alert = React.forwardRef<+ HTMLDivElement,+ React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>+>(({ className, variant, ...props }, ref) => (+ <div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} />+));+Alert.displayName = 'Alert';++const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(+ ({ className, ...props }, ref) => (+ <h5+ ref={ref}+ className={cn('mb-1 font-medium leading-none tracking-tight', className)}+ {...props}+ />+ ),+);+AlertTitle.displayName = 'AlertTitle';++const AlertDescription = React.forwardRef<+ HTMLParagraphElement,+ React.HTMLAttributes<HTMLParagraphElement>+>(({ className, ...props }, ref) => (+ <div ref={ref} className={cn('text-sm [&_p]:leading-relaxed', className)} {...props} />+));+AlertDescription.displayName = 'AlertDescription';++export { Alert, AlertTitle, AlertDescription };diff --git a/src/components/ui/avatar.tsx b/src/components/ui/avatar.tsxindex 6496ce85..5e54c995 100644--- a/src/components/ui/avatar.tsx+++ b/src/components/ui/avatar.tsx@@ -45,4 +45,3 @@ const AvatarFallback = React.forwardRef<AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;export { Avatar, AvatarImage, AvatarFallback };-diff --git a/src/components/ui/editor.tsx b/src/components/ui/editor.tsxnew file mode 100644index 00000000..f62e4a9c--- /dev/null+++ b/src/components/ui/editor.tsx@@ -0,0 +1,32 @@+'use client';+import Editor, { loader } from '@monaco-editor/react';+import { useTheme } from 'next-themes';++export interface EditorProps {+ value: string;+}++loader.config({+ paths: {+ vs: '/vs',+ },+});+/**+ * @description Used as a read-only monaco editor. Respects theme values, disables minimap.+ */+export default function ReadOnlyEditor({ value }: EditorProps) {+ const { theme } = useTheme();+ return (+ <Editor+ value={value}+ theme={theme === 'light' ? 'vs' : 'vs-dark'}+ defaultLanguage="typescript"+ options={{+ readOnly: true,+ minimap: {+ enabled: false,+ },+ }}+ />+ );+}diff --git a/src/components/ui/markdown.tsx b/src/components/ui/markdown.tsxindex b37576db..c3426d3a 100644--- a/src/components/ui/markdown.tsx+++ b/src/components/ui/markdown.tsx@@ -34,9 +34,10 @@ function removeHtmlComments(): Transformer {};}-export function Markdown({ children }: { children: string }) {+export function Markdown({ children, className }: { children: string; className?: string }) {return (<ReactMarkdown+ className={className}remarkPlugins={[removeHtmlComments, remarkGfm]}components={{h1: ({ className, ...props }) => (