Connect, collaborate, and grow with a community of TypeScript developers
feat: moderation page and few actions. (#149)
Ayusha4ebd3b59a48
diff --git a/package.json b/package.jsonindex a0e5f016..2046dc49 100644--- a/package.json+++ b/package.json@@ -30,6 +30,7 @@"@radix-ui/react-label": "^2.0.2","@radix-ui/react-navigation-menu": "^1.1.3","@radix-ui/react-popover": "^1.0.6",+ "@radix-ui/react-scroll-area": "^1.0.4","@radix-ui/react-select": "^1.2.2","@radix-ui/react-separator": "^1.0.3","@radix-ui/react-slot": "^1.0.2",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1987cec0..727f5516 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -52,6 +52,9 @@ dependencies:'@radix-ui/react-popover':specifier: ^1.0.6version: 1.0.6(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-scroll-area':+ specifier: ^1.0.4+ version: 1.0.4(@types/[email protected])(@types/[email protected])([email protected])([email protected])'@radix-ui/react-select':specifier: ^1.2.2version: 1.2.2(@types/[email protected])(@types/[email protected])([email protected])([email protected])@@ -1547,6 +1550,35 @@ packages:react-dom: 18.2.0([email protected])dev: false+ /@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-OIClwBkwPG+FKvC4OMTRaa/3cfD069nkKFFL/TQzRzaO42Ce5ivKU9VMKgT7UU6UIkjcQqKBrDOIzWtPGw6e6w==}+ peerDependencies:+ '@types/react': '*'+ '@types/react-dom': '*'+ react: ^16.8 || ^17.0 || ^18.0+ react-dom: ^16.8 || ^17.0 || ^18.0+ peerDependenciesMeta:+ '@types/react':+ optional: true+ '@types/react-dom':+ optional: true+ dependencies:+ '@babel/runtime': 7.22.5+ '@radix-ui/number': 1.0.1+ '@radix-ui/primitive': 1.0.1+ '@radix-ui/react-compose-refs': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-direction': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-presence': 1.0.1(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])+ '@radix-ui/react-use-callback-ref': 1.0.1(@types/[email protected])([email protected])+ '@radix-ui/react-use-layout-effect': 1.0.1(@types/[email protected])([email protected])+ '@types/react': 18.2.8+ '@types/react-dom': 18.2.4+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+/@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]):resolution: {integrity: sha512-zI7McXr8fNaSrUY9mZe4x/HC0jTLY9fWNhO1oLWYMQGDXuV4UCivIGTxwioSzO0ZCYX9iSLyWmAh/1TOmX3Cnw==}peerDependencies:diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 68b16b93..b7af3c38 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -26,12 +26,18 @@ enum RoleTypes {MODERATOR}-enum Status {+enum UserStatus {BANNEDACTIVE // can post, comment, vote, etcPENDING // must finish x number of challenges to be active}+enum ReportStatus {+ PENDING+ CLEARED+ DISMISSED+}+// Necessary for Next authmodel Account {id String @id @default(cuid())@@ -69,26 +75,33 @@ model Role {}model User {- id String @id @default(uuid())- name String?- email String? @unique- roles Role[]- status Status @default(PENDING)- emailVerified DateTime?- createdAt DateTime @default(now())- image String?- accounts Account[]- sessions Session[]- challenge Challenge[]- vote Vote[]- solution Solution[]- report Report[]- bookmark Bookmark[]- sharedSolution SharedSolution[]- comment ChallengeComment[]- reply ChallengeReply[]- solutionComment SolutionComment[]- solutionReply SolutionReply[]+ id String @id @default(uuid())++ name String?+ email String? @unique+ emailVerified DateTime?+ image String?+ roles Role[]++ status UserStatus @default(PENDING)+ banReason String? @db.MediumText++ accounts Account[]+ sessions Session[]+ challenge Challenge[]+ vote Vote[]+ solution Solution[]+ report Report[] @relation(name: "report_author")+ moderatedReports Report[] @relation(name: "moderated_reports")+ bookmark Bookmark[]+ sharedSolution SharedSolution[]+ comment ChallengeComment[]+ reply ChallengeReply[]+ solutionComment SolutionComment[]+ solutionReply SolutionReply[]++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt}model VerificationToken {@@ -100,22 +113,25 @@ model VerificationToken {}model Challenge {- id Int @id @default(autoincrement())- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ id Int @id @default(autoincrement())+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAtdifficulty Difficultyname String- description String @db.MediumText+ description String @db.MediumTextshortDescription String- prompt String @db.MediumText- user User @relation(fields: [userId], references: [id])- userId String- vote Vote[]- solution Solution[]- comment ChallengeComment[]- report Report[]- bookmark Bookmark[]- sharedSolution SharedSolution[]+ prompt String @db.MediumText+ disabled Boolean @default(false)++ user User @relation(fields: [userId], references: [id])+ userId String++ vote Vote[]+ solution Solution[]+ comment ChallengeComment[]+ report Report[]+ bookmark Bookmark[]+ sharedSolution SharedSolution[]@@index([userId])}@@ -224,16 +240,26 @@ model SolutionReply {}model Report {- id Int @id @default(autoincrement())- user User @relation(fields: [userId], references: [id])- userId String+ id Int @id @default(autoincrement())++ author User @relation(fields: [authorId], references: [id], name: "report_author")+ authorId String+challenge Challenge @relation(fields: [challengeId], references: [id])challengeId Int- text String- derogatory Boolean @default(false)- unclear Boolean @default(false)- @@index([userId])+ text String @db.MediumText+ derogatory Boolean @default(false)+ unclear Boolean @default(false)+ status ReportStatus @default(PENDING)++ moderator User? @relation(fields: [moderatorId], references: [id], name: "moderated_reports")+ moderatorId String?++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([authorId])@@index([challengeId])}diff --git a/src/app/admin/page.tsx b/src/app/admin/page.tsxindex 724e6f54..336006c7 100644--- a/src/app/admin/page.tsx+++ b/src/app/admin/page.tsx@@ -1,5 +1,9 @@import { RoleTypes } from '@prisma/client';import { Lock } from 'lucide-react';+import { getBannedUsers, getReports } from '~/components/admin/admin.actions';+import { ReportDetails } from '~/components/admin/reports';+import { BannedUsers } from '~/components/admin/users';+import { Tabs, TabsContent, TabsList, TabsTrigger } from '~/components/ui/tabs';import { getServerAuthSession } from '~/server/auth';async function Admin() {@@ -12,12 +16,12 @@ async function Admin() {return (<div>- <div className="flex flex-col items-center justify-center gap-4">+ <div className="flex flex-col gap-4">{isModOrAdmin ? (- <ModerationView />+ <View />) : (<div- className="flex w-full flex-col items-center justify-center space-y-2"+ className="flex w-full flex-col items-center justify-center space-y-2 min-h-[calc(100dvh-112px)]"// TODO: i bet there is a css/tw way to do this, @Nikita can fix in 2msstyle={{ minHeight: 'calc(100dvh - 112px)' }}>@@ -32,16 +36,43 @@ async function Admin() {);}-const ModerationView = async () => {- const session = await getServerAuthSession();- const roles = session?.user.role ?? [];+const View = async () => {+ const allReports = await getReports();+ const allBannedUsers = await getBannedUsers();return (- <div>- <p className="text-center text-2xl text-white">Moderation View</p>- <div className="m-8">- Roles:- <div>{JSON.stringify(roles)}</div>+ <div className="m-8 flex flex-col space-y-4">+ <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>+ <p className="max-w-[40ch] text-start text-sm text-neutral-400 dark:text-neutral-600">+ A view of all the reports & users.+ </p>+ </div>+ <div className="flex flex-col space-y-2">+ <Tabs defaultValue="reports" className="space-x-4">+ <TabsList className="rounded-full border border-border bg-background">+ <TabsTrigger+ className="rounded-l-2xl rounded-r-lg duration-300 data-[state=active]:bg-border"+ value="reports"+ >+ Reports+ </TabsTrigger>+ <TabsTrigger+ className="rounded-l-2xl rounded-r-lg duration-300 data-[state=active]:bg-border"+ value="users"+ >+ Users+ </TabsTrigger>+ </TabsList>+ <TabsContent value="reports">+ <ReportDetails data={allReports} />+ </TabsContent>+ <TabsContent value="users">+ <BannedUsers data={allBannedUsers} />+ </TabsContent>+ </Tabs>+ </div></div></div>);diff --git a/src/components/admin/admin.actions.tsx b/src/components/admin/admin.actions.tsxnew file mode 100644index 00000000..d0ead649--- /dev/null+++ b/src/components/admin/admin.actions.tsx@@ -0,0 +1,169 @@+'use server';++import { getServerSession } from 'next-auth';+import { authOptions } from '~/server/auth';+import { prisma } from '~/server/db';++export type AdminReportDetails = Awaited<ReturnType<typeof getReports>>;++/**+ * The function fetches all the reports along+ * with challenge and the user.+ */+export async function getReports() {+ return prisma.report.findMany({+ include: {+ challenge: {+ include: {+ user: true,+ },+ },+ author: true,+ moderator: true,+ },+ });+}++export type AdminBannedUsers = Awaited<ReturnType<typeof getBannedUsers>>;++/**+ * The function fetches all the banned+ * user's.+ */+export async function getBannedUsers() {+ return prisma.user.findMany({+ where: {+ status: 'BANNED',+ },+ });+}++/**+ * The function deletes a challenge & updates+ * the report to indicate the status of `CLEARED`.+ * @param challengeId The id of the challenge.+ * @param reportId The id of the report.+ * @returns+ */+export async function disableChallenge(challengeId: number, reportId: number) {+ const session = await getServerSession(authOptions);+ try {+ await prisma.$transaction([+ prisma.challenge.update({+ where: {+ id: challengeId,+ },+ data: {+ disabled: true,+ },+ }),+ prisma.report.update({+ where: {+ id: reportId,+ },+ data: {+ status: 'CLEARED',+ moderatorId: session?.user.id,+ },+ }),+ ]);+ } catch (e) {+ console.log(e);+ return 'uh_oh';+ }+}++/**+ * The function updates the report to indicate+ * a status of `DISMISSED`.+ * @param reportId The id of the report.+ * @returns+ */+export async function dismissReport(reportId: number) {+ const session = await getServerSession(authOptions);+ return prisma.report.update({+ where: {+ id: reportId,+ },+ data: {+ status: 'DISMISSED',+ moderatorId: session?.user.id,+ },+ });+}++/**+ * The function updates the user to indicate a status+ * of `BANNED`.+ * @param userId The id of the user.+ * @param reportId The id of the report.+ * @returns+ */+export async function banUser(userId: string, reportId: number, banReason?: string) {+ const session = await getServerSession(authOptions);++ try {+ await prisma.$transaction([+ prisma.user.update({+ where: {+ id: userId,+ },+ data: {+ status: 'BANNED',+ banReason: banReason,+ },+ }),+ prisma.challenge.updateMany({+ where: {+ userId: userId,+ },+ data: {+ disabled: true,+ },+ }),+ prisma.session.deleteMany({+ where: {+ userId: userId,+ },+ }),+ prisma.report.update({+ where: {+ id: reportId,+ },+ data: {+ status: 'CLEARED',+ moderatorId: session?.user.id,+ },+ }),+ ]);+ } catch (e) {+ console.log(e);+ return 'uh_oh';+ }+}+/**+ * The function lifts the ban off the user i.e. updates+ * the status to `ACTIVE`.+ * @param userId The id of the user.+ * @returns+ */+export async function unbanUser(userId: string) {+ return prisma.$transaction([+ prisma.challenge.updateMany({+ where: {+ userId: userId,+ },+ data: {+ disabled: false,+ },+ }),+ prisma.user.update({+ where: {+ id: userId,+ },+ data: {+ status: 'ACTIVE',+ },+ }),+ ]);+}diff --git a/src/components/admin/reports.tsx b/src/components/admin/reports.tsxnew file mode 100644index 00000000..fdf29225--- /dev/null+++ b/src/components/admin/reports.tsx@@ -0,0 +1,311 @@+'use client';++import { formatDistance } from 'date-fns';+import { EyeOff, Gavel, X } from 'lucide-react';+import { useSession } from 'next-auth/react';+import { useRouter } from 'next/navigation';+import { useState } from 'react';+import {+ banUser,+ disableChallenge,+ dismissReport,+ type AdminReportDetails,+} from '~/components/admin/admin.actions';+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';++interface ReportsProps {+ data: AdminReportDetails;+}+export const ReportDetails = ({ data }: ReportsProps) => {+ // State+ 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);++ toast({+ title: 'Success',+ description: <p>The user {username ? '@' + username + ' ' : ''}successfully banned.</p>,+ variant: 'success',+ });+ }+ } catch (e) {+ } finally {+ router.refresh();+ setDialogOpen(false);+ }+ }++ 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);+ }+ }++ async function handleDismissReport() {+ try {+ if (selectedIssue) {+ await dismissReport(selectedIssue.id);+ }+ } catch (e) {+ } finally {+ router.refresh();+ setDialogOpen(false);+ }+ }++ 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>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Challenge Name</TableHead>+ <TableHead>Reported By</TableHead>+ <TableHead>At</TableHead>+ <TableHead>Reason</TableHead>+ <TableHead>Tags</TableHead>+ <TableHead>Status</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 = formatDistance(report.createdAt, Date.now(), {+ addSuffix: true,+ includeSeconds: true,+ });+ const absoluteTime = new Intl.DateTimeFormat('en-US', {+ dateStyle: 'medium',+ timeStyle: 'medium',+ }).format(report.createdAt);++ return (+ <TableRow+ onClick={() => {+ setSelectedIssue(report);+ setDialogOpen(true);+ }}+ className="hover:cursor-pointer"+ key={reportIdx}+ >+ <TableCell title={challengeName}>+ {challengeName.length > 10+ ? challengeName.substring(0, 10) + '...'+ : challengeName}+ </TableCell>+ <TableCell>@{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>+ );+ })}+ </TableBody>+ </Table>+ <Dialog open={dialogOpen} onOpenChange={(e) => setDialogOpen(!e)}>+ {/* max-w-xl is not the best solution, the dialog width need fixing with the markdown. */}+ <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>+ <TypographyP>@{selectedIssue?.challenge.user.name}</TypographyP>+ </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={() => {+ void 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={() => {+ void handleDisableChallenge();+ }}+ className="flex items-center justify-center gap-2"+ >+ <EyeOff className="h-4 w-4" />+ Disable Challenge+ </Button>+ <Button+ onClick={() => {+ void 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>+ );+};diff --git a/src/components/admin/users.tsx b/src/components/admin/users.tsxnew file mode 100644index 00000000..3e82a894--- /dev/null+++ b/src/components/admin/users.tsx@@ -0,0 +1,108 @@+'use client';++import { formatDistance } from 'date-fns';+import { useRouter } from 'next/navigation';+import { unbanUser, type AdminBannedUsers } from '~/components/admin/admin.actions';+import { ActionMenu } from '../ui/action-menu';+import { Badge } from '../ui/badge';+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';+import { TypographyH3 } from '../ui/typography/h3';+import { toast } from '../ui/use-toast';++interface BannedUsersProps {+ data: AdminBannedUsers;+}++export const BannedUsers = ({ data }: BannedUsersProps) => {+ // State+ const router = useRouter();++ // Functions+ async function handleUserUnban(user: (typeof data)[number]) {+ try {+ await unbanUser(user.id);+ toast({+ title: 'Unbanned',+ description: `The user ${user.name ? '@' + user.name + ' ' : ''}was successfully unbanned.`,+ });+ } catch (e) {+ toast({+ title: 'Something went wrong.',+ variant: 'destructive',+ description: `The user ${user.name ? '@' + user.name + ' ' : ''}could not be unbanned.`,+ });+ } finally {+ router.refresh();+ }+ }++ return (+ <div className="flex flex-col gap-2">+ <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> total bans.+ </span>+ </div>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Username</TableHead>+ <TableHead>Status</TableHead>+ <TableHead>At</TableHead>+ <TableHead>Reason</TableHead>+ <TableHead></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {data.map((user, userIdx) => {+ const username = user.name;+ const status = user.status;+ const relativeTime = formatDistance(user.updatedAt, Date.now(), {+ addSuffix: true,+ includeSeconds: true,+ });+ const absoluteTime = new Intl.DateTimeFormat('en-US', {+ dateStyle: 'medium',+ timeStyle: 'medium',+ }).format(user.updatedAt);+ const banReason = user.banReason;+ return (+ <TableRow key={userIdx}>+ <TableCell title={username ?? ''}>@{username}</TableCell>+ <TableCell>+ <Badge>{status}</Badge>+ </TableCell>+ <TableCell title={absoluteTime}>{relativeTime}</TableCell>+ <TableCell title={banReason ?? ''}>+ {banReason+ ? banReason.length > 15+ ? banReason.substring(0, 10)+ : banReason+ : 'N/A'}+ </TableCell>+ <TableCell>+ <ActionMenu+ items={[+ {+ key: 'unban',+ label: 'Unban',+ icon: 'Unlock',+ },+ ]}+ onChange={(item) => {+ if (item.key === 'unban') {+ // any better workarounds for void?+ void handleUserUnban(user);+ }+ }}+ />+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ );+};diff --git a/src/components/challenge/description/index.tsx b/src/components/challenge/description/index.tsxindex c8a1d6a9..88df01ba 100644--- a/src/components/challenge/description/index.tsx+++ b/src/components/challenge/description/index.tsx@@ -90,36 +90,43 @@ export function Description({ challenge }: Props) {});async function onSubmit(data: FormValues) {- const response = await addReport(challenge.id, session?.data?.user?.id as string, data);- if (response === 'created') {- toast({- title: 'Feedback Sent',- variant: 'success',- description: (- <p>- Thank you for submitting this feedback. Someone from our moderator team will be- reviewing it shortly.- </p>- ),- });- } else if (response === 'report_already_made') {- toast({- title: 'Report already made',- description: (- <p>- You have already made a report about this challenge. We are still reviewing the- question.- </p>- ),- });- } else if (response === 'not_logged_in') {+ try {+ const response = await addReport(challenge.id, session?.data?.user?.id as string, data);+ if (response === 'created') {+ toast({+ title: 'Feedback Sent',+ variant: 'success',+ description: (+ <p>+ Thank you for submitting this feedback. Someone from our moderator team will be+ reviewing it shortly.+ </p>+ ),+ });+ } else if (response === 'report_already_made') {+ toast({+ title: 'Report already made',+ description: (+ <p>+ You have already made a report about this challenge. We are still reviewing the+ question.+ </p>+ ),+ });+ } else if (response === 'not_logged_in') {+ toast({+ title: 'You are not loggeed in',+ description: <p>Please log in to make this report.</p>,+ });+ }+ setDialogOpen(false);+ } catch (e) {toast({- title: 'You are not loggeed in',- description: <p>Please log in to make this report.</p>,+ title: 'Something went wrong.',+ variant: 'destructive',+ description: <p>An error was encountered while trying to make a report.</p>,});}-- setDialogOpen(false);}return (<>diff --git a/src/components/challenge/report.action.ts b/src/components/challenge/report.action.tsindex 5639e6e6..02970c49 100644--- a/src/components/challenge/report.action.ts+++ b/src/components/challenge/report.action.ts@@ -14,7 +14,7 @@ export async function addReport(challengeId: number, userId: string, data: FormVconst report = await prisma.report.findMany({where: {challengeId,- userId,+ authorId: userId,},});if (report.length > 0) {@@ -25,7 +25,7 @@ export async function addReport(challengeId: number, userId: string, data: FormVawait prisma.report.create({data: {challengeId,- userId,+ authorId: userId,text: data.comments,unclear: data.examples,derogatory: data.derogatory,diff --git a/src/components/explore/index.tsx b/src/components/explore/index.tsxindex bc05fcbf..ceb7d411 100644--- a/src/components/explore/index.tsx+++ b/src/components/explore/index.tsx@@ -1,6 +1,6 @@+import { Suspense } from 'react';import { prisma } from '~/server/db';import { ExploreSection } from './section';-import { Suspense } from 'react';import { ExploreSectionSkeleton } from './section-skeleton';export async function Explore() {@@ -32,6 +32,9 @@ export async function Explore() {export type ExploreChallengeData = Awaited<ReturnType<typeof getExploreChallengeData>>;async function getExploreChallengeData() {return prisma.challenge.findMany({+ where: {+ disabled: false,+ },include: {_count: {select: { vote: true },diff --git a/src/components/ui/scroll-area.tsx b/src/components/ui/scroll-area.tsxnew file mode 100644index 00000000..3d400bd7--- /dev/null+++ b/src/components/ui/scroll-area.tsx@@ -0,0 +1,46 @@+'use client';++import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';+import * as React from 'react';++import { cn } from '~/utils/cn';++const ScrollArea = React.forwardRef<+ React.ElementRef<typeof ScrollAreaPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>+>(({ className, children, ...props }, ref) => (+ <ScrollAreaPrimitive.Root+ ref={ref}+ className={cn('relative overflow-hidden', className)}+ {...props}+ >+ <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">+ {children}+ </ScrollAreaPrimitive.Viewport>+ <ScrollBar />+ <ScrollAreaPrimitive.Corner />+ </ScrollAreaPrimitive.Root>+));+ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;++const ScrollBar = React.forwardRef<+ React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,+ React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>+>(({ className, orientation = 'vertical', ...props }, ref) => (+ <ScrollAreaPrimitive.ScrollAreaScrollbar+ ref={ref}+ orientation={orientation}+ className={cn(+ 'flex touch-none select-none transition-colors',+ orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent p-[1px]',+ orientation === 'horizontal' && 'h-2.5 border-t border-t-transparent p-[1px]',+ className,+ )}+ {...props}+ >+ <ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />+ </ScrollAreaPrimitive.ScrollAreaScrollbar>+));+ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;++export { ScrollArea, ScrollBar };