Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

chore add datatable and challenge review table (#303)

bautistaaa2bfd047eb244
diff --git a/global.d.ts b/global.d.ts
index 371e5834..2347b3e2 100644
--- a/global.d.ts
+++ b/global.d.ts
@@ -2,4 +2,4 @@ declare module '*.md' {
const text: string;
export default text;
}
-
+declare module '*.png';
diff --git a/package.json b/package.json
index 0c3cf613..1e1c4f3d 100644
--- a/package.json
+++ b/package.json
@@ -40,6 +40,7 @@
"@radix-ui/react-tooltip": "^1.0.6",
"@t3-oss/env-nextjs": "^0.6.0",
"@tanstack/react-query": "^4.29.25",
+ "@tanstack/react-table": "^8.9.3",
"@types/lodash": "^4.14.195",
"@uiw/react-md-editor": "^3.23.3",
"class-variance-authority": "^0.6.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 120ff0ff..1e26ad7b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -82,6 +82,9 @@ dependencies:
'@tanstack/react-query':
specifier: ^4.29.25
+ '@tanstack/react-table':
+ specifier: ^8.9.3
'@types/lodash':
specifier: ^4.14.195
version: 4.14.195
@@ -2196,6 +2199,23 @@ packages:
use-sync-external-store: 1.2.0([email protected])
dev: false
+ resolution: {integrity: sha512-Ng9rdm3JPoSCi6cVZvANsYnF+UoGVRxflMb270tVj0+LjeT/ZtZ9ckxF6oLPLcKesza6VKBqtdF9mQ+vaz24Aw==}
+ engines: {node: '>=12'}
+ peerDependencies:
+ react: '>=16'
+ react-dom: '>=16'
+ dependencies:
+ '@tanstack/table-core': 8.9.3
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ dev: false
+
+ /@tanstack/[email protected]:
+ resolution: {integrity: sha512-NpHZBoHTfqyJk0m/s/+CSuAiwtebhYK90mDuf5eylTvgViNOujiaOaxNDxJkQQAsVvHWZftUGAx1EfO1rkKtLg==}
+ engines: {node: '>=12'}
+ dev: false
+
resolution: {integrity: sha512-Vqm22aZrCvCd6I5g1SvpW151jfqwTzEZ7XJ3yZ6xaZG31nUEOEyzzVImjRcsN8Wi/QyPxId/x8GTtgIbsy8kEw==}
dev: false
diff --git a/prisma/challenges.mock.ts b/prisma/challenges.mock.ts
index af0b0fab..ca4861bd 100644
--- a/prisma/challenges.mock.ts
+++ b/prisma/challenges.mock.ts
@@ -65,7 +65,7 @@ export async function loadChallengesFromTypeChallenge() {
id: idNum,
name: title,
description: README,
- status: ChallengeStatus.ACTIVE,
+ status: Math.floor(Math.random() * 2) > 0 ? ChallengeStatus.PENDING : ChallengeStatus.ACTIVE,
prompt: `// TEST CASE START\n${testData}\n\n// CODE START\n${prompt}`,
difficulty: difficulty === 'warm' ? 'BEGINNER' : (difficulty.toUpperCase() as Difficulty),
shortDescription: README.slice(0, 100),
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index da7b3f5e..bdc8d2af 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -29,7 +29,6 @@ enum RoleTypes {
enum UserStatus {
BANNED
ACTIVE // can post, comment, vote, etc
- PENDING // must finish x number of challenges to be active
}
enum ReportStatus {
@@ -39,6 +38,7 @@ enum ReportStatus {
}
enum ChallengeStatus {
+ DECLINED
BANNED
PENDING
ACTIVE
@@ -104,7 +104,7 @@ model User {
/// this is the twitter URL that shows up on the profile page
userLinks UserLink[]
- status UserStatus @default(PENDING)
+ status UserStatus @default(ACTIVE)
banReason String? @db.MediumText
accounts Account[]
diff --git a/src/app/admin/challenge/[challengeId]/challenge-review.action.ts b/src/app/admin/challenge/[challengeId]/challenge-review.action.ts
new file mode 100644
index 00000000..f3b6f337
--- /dev/null
+++ b/src/app/admin/challenge/[challengeId]/challenge-review.action.ts
@@ -0,0 +1,42 @@
+'use server';
+
+import { RoleTypes } from '@prisma/client';
+import { prisma } from '~/server/db';
+
+export async function approveChallenge(challengeId: number, userId: string, isUserACreator: boolean) {
+ return prisma.$transaction([
+ prisma.challenge.update({
+ where: {
+ id: challengeId,
+ },
+ data: {
+ status: 'ACTIVE',
+ },
+ }),
+ ...(isUserACreator
+ ? [
+ prisma.role.create({
+ data: {
+ user: {
+ connect: {
+ id: userId,
+ },
+ },
+ role: RoleTypes.ADMIN,
+ },
+ }),
+ ]
+ : []),
+ ]);
+}
+
+export async function denyChallenge(challengeId: number) {
+ return prisma.challenge.update({
+ where: {
+ id: challengeId,
+ },
+ data: {
+ status: 'DECLINED',
+ },
+ });
+}
diff --git a/src/app/admin/challenge/[challengeId]/challenge-review.tsx b/src/app/admin/challenge/[challengeId]/challenge-review.tsx
new file mode 100644
index 00000000..aea8729b
--- /dev/null
+++ b/src/app/admin/challenge/[challengeId]/challenge-review.tsx
@@ -0,0 +1,94 @@
+'use client';
+
+import Link from 'next/link';
+import { Button } from '~/components/ui/button';
+import { CodeEditor } from '~/components/ui/code-editor';
+import { DifficultyBadge } from '~/components/ui/difficulty-badge';
+import { Markdown } from '~/components/ui/markdown';
+import Text from '~/components/ui/typography/typography';
+import { UserBadge } from '~/components/ui/user-badge';
+import { approveChallenge, denyChallenge } from './challenge-review.action';
+import type { ChallengeToReview } from './page';
+import { useToast } from '~/components/ui/use-toast';
+import { useRouter } from 'next/navigation';
+import { useSession } from 'next-auth/react';
+import { useMemo } from 'react';
+
+interface Props {
+ challenge: ChallengeToReview;
+}
+export function ChallengeReview({ challenge }: Props) {
+ const router = useRouter();
+ const { data: session } = useSession();
+ const { toast } = useToast();
+ const isUserACreator = useMemo(
+ () => session?.user.role.includes('CREATOR') ?? false,
+ [session?.user.role],
+ );
+ const handleApproveChallenge = async () => {
+ console.log(challenge.id);
+ try {
+ await approveChallenge(challenge.id, challenge.userId, isUserACreator);
+ toast({
+ variant: 'success',
+ title: 'Challenge Approved Successfully',
+ });
+ router.push('/admin');
+ } catch {
+ toast({
+ variant: 'destructive',
+ title: 'Something went wrong',
+ });
+ }
+ };
+
+ const handleDenyChallenge = async () => {
+ try {
+ await denyChallenge(challenge.id);
+ toast({
+ variant: 'success',
+ title: 'Challenge Denied Successfully',
+ });
+ router.push('/admin');
+ } catch {
+ toast({
+ variant: 'destructive',
+ title: 'Something went wrong',
+ });
+ }
+ };
+
+ return (
+ <div className="flex h-full flex-col px-4">
+ <div className="mb-5">
+ <Text intent="h2">{challenge.name}</Text>
+ <div className="mb-3 flex gap-4">
+ <DifficultyBadge difficulty={challenge.difficulty} />
+ <UserBadge username={challenge.user.name} />
+ </div>
+ <div className="font-semibold">Short Description</div>
+ <div>{challenge.shortDescription}</div>
+ </div>
+
+ <div className="flex h-full gap-4">
+ <div className="w-[500px] rounded-l-2xl rounded-r-xl border border-zinc-300 bg-white p-4 dark:border-zinc-700 dark:bg-zinc-800">
+ <Markdown>{challenge.description}</Markdown>
+ </div>
+ <div className="flex-1 rounded-l-xl rounded-r-2xl border border-zinc-300 dark:border-zinc-700">
+ <CodeEditor value={challenge.prompt} />
+ </div>
+ </div>
+ <div className="flex justify-end gap-3 p-4">
+ <Link href="/admin">
+ <Button variant="ghost">Cancel</Button>
+ </Link>
+ <Button variant="destructive" onClick={handleDenyChallenge}>
+ Deny
+ </Button>
+ <Button className="bg-green-300 dark:bg-green-700" onClick={handleApproveChallenge}>
+ Approve
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/admin/challenge/[challengeId]/page.tsx b/src/app/admin/challenge/[challengeId]/page.tsx
new file mode 100644
index 00000000..9d4c39d3
--- /dev/null
+++ b/src/app/admin/challenge/[challengeId]/page.tsx
@@ -0,0 +1,32 @@
+import { prisma } from '~/server/db';
+import { ChallengeReview } from './challenge-review';
+
+interface Props {
+ params: {
+ challengeId: string;
+ };
+}
+
+export default async function ChallengeReviewPage({ params: { challengeId } }: Props) {
+ const challenge = await getChallengeToReview(+challengeId);
+ return <ChallengeReview challenge={challenge} />;
+}
+
+export type ChallengeToReview = NonNullable<Awaited<ReturnType<typeof getChallengeToReview>>>;
+async function getChallengeToReview(id: number) {
+ return prisma.challenge.findFirstOrThrow({
+ where: {
+ id,
+ },
+ include: {
+ user: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ orderBy: {
+ createdAt: 'desc'
+ }
+ });
+}
diff --git a/src/app/admin/page.tsx b/src/app/admin/page.tsx
index 548a4699..1f440997 100644
--- a/src/app/admin/page.tsx
+++ b/src/app/admin/page.tsx
@@ -3,7 +3,8 @@ import { RoleTypes } from '@prisma/client';
import { Lock } from 'lucide-react';
import React from 'react';
import { getBannedUsers } from '~/components/admin/admin.actions';
-import Reports2 from '~/components/admin/reports';
+import { ChallengeReviews } from '~/components/admin/challenge-reviews';
+import { Reports } 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';
@@ -41,7 +42,7 @@ const View = async () => {
const firstPage = await getInfiniteReports();
return (
- <div className="m-8 flex flex-col space-y-4 container">
+ <div className="container 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>
@@ -59,7 +60,13 @@ const View = async () => {
Reports
</TabsTrigger>
<TabsTrigger
- className="rounded-l-2xl rounded-r-lg duration-300 data-[state=active]:bg-border"
+ className="duration-300 data-[state=active]:bg-border"
+ value="challengeReviews"
+ >
+ Challenge Reviews
+ </TabsTrigger>
+ <TabsTrigger
+ className="rounded-l-lg rounded-r-2xl duration-300 data-[state=active]:bg-border"
value="users"
>
Users
@@ -67,12 +74,15 @@ const View = async () => {
</TabsList>
<TabsContent value="reports">
<React.Suspense fallback={<>Loading...</>}>
- <Reports2 initialReports={firstPage}/>
+ <Reports initialReports={firstPage} />
</React.Suspense>
</TabsContent>
<TabsContent value="users">
<BannedUsers data={allBannedUsers} />
</TabsContent>
+ <TabsContent value="challengeReviews">
+ <ChallengeReviews />
+ </TabsContent>
</Tabs>
</div>
</div>
diff --git a/src/app/api/challenge-reviews/route.ts b/src/app/api/challenge-reviews/route.ts
new file mode 100644
index 00000000..36586f0f
--- /dev/null
+++ b/src/app/api/challenge-reviews/route.ts
@@ -0,0 +1,38 @@
+import { NextResponse } from 'next/server';
+import { prisma } from '~/server/db';
+
+export async function GET(request: Request) {
+ const { searchParams } = new URL(request.url);
+ const page = Number(searchParams.get('page')) ?? 1;
+ const size = Number(searchParams.get('size')) ?? 10;
+
+ const [count, data] = await getChallenges(page, size);
+ const pageCount = Math.ceil(count / size);
+
+ return NextResponse.json([pageCount, data]);
+}
+
+export type ChallengeReviewData = Awaited<ReturnType<typeof getChallenges>>;
+async function getChallenges(page: number, size: number) {
+ return prisma.$transaction([
+ prisma.challenge.count({
+ where: {
+ status: 'PENDING',
+ },
+ }),
+ prisma.challenge.findMany({
+ skip: page * size,
+ take: size,
+ where: {
+ status: 'PENDING',
+ },
+ include: {
+ user: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ }),
+ ]);
+}
diff --git a/src/components/admin/challenge-reviews/columns.tsx b/src/components/admin/challenge-reviews/columns.tsx
new file mode 100644
index 00000000..29ed7a7f
--- /dev/null
+++ b/src/components/admin/challenge-reviews/columns.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import type { Challenge } from '@prisma/client';
+import { type ColumnDef } from '@tanstack/react-table';
+
+export const columns: ColumnDef<Challenge>[] = [
+ {
+ accessorKey: 'name',
+ header: 'Name',
+ },
+ {
+ accessorKey: 'difficulty',
+ header: 'Difficulty',
+ },
+ {
+ accessorKey: 'shortDescription',
+ header: 'Description',
+ },
+ {
+ accessorKey: 'user.name',
+ header: 'Created By',
+ },
+ {
+ accessorKey: 'createdAt',
+ header: 'Created On',
+ cell: (info) => new Date(info.getValue() as Date).toLocaleDateString(),
+ },
+];
diff --git a/src/components/admin/challenge-reviews/data-table.tsx b/src/components/admin/challenge-reviews/data-table.tsx
new file mode 100644
index 00000000..1314e8fd
--- /dev/null
+++ b/src/components/admin/challenge-reviews/data-table.tsx
@@ -0,0 +1,148 @@
+'use client';
+
+import type { Challenge } from '@prisma/client';
+import { useQuery } from '@tanstack/react-query';
+import {
+ type PaginationState,
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+ type ColumnDef,
+} from '@tanstack/react-table';
+import { useRouter } from 'next/navigation';
+import { useMemo, useState } from 'react';
+import type { ChallengeReviewData } from '~/app/api/challenge-reviews/route';
+import { Button } from '~/components/ui/button';
+
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '~/components/ui/table';
+import { getBaseUrl } from '~/utils/getBaseUrl';
+
+interface Props {
+ columns: ColumnDef<Challenge>[];
+}
+
+export function DataTable({ columns }: Props) {
+ const router = useRouter();
+ const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
+ pageIndex: 0,
+ pageSize: 20,
+ });
+
+ const fetchDataOptions = {
+ page: pageIndex,
+ size: pageSize,
+ };
+
+ const data = useQuery(['data', fetchDataOptions], () => getChallengeReviews(fetchDataOptions), {
+ keepPreviousData: true,
+ });
+
+ const pagination = useMemo(
+ () => ({
+ pageIndex,
+ pageSize,
+ }),
+ [pageIndex, pageSize],
+ );
+
+ const table = useReactTable({
+ data: data?.data?.[1] ?? [],
+ columns,
+ pageCount: data?.data?.[0] ?? -1,
+ getCoreRowModel: getCoreRowModel(),
+ state: {
+ pagination,
+ },
+ onPaginationChange: setPagination,
+ manualPagination: true,
+ });
+
+ if (data.isLoading) return null;
+
+ return (
+ <div className="w-full rounded-md border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => {
+ return (
+ <TableHead key={header.id}>
+ {header.isPlaceholder
+ ? null
+ : flexRender(header.column.columnDef.header, header.getContext())}
+ </TableHead>
+ );
+ })}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow
+ key={row.id}
+ data-state={row.getIsSelected() && 'selected'}
+ onClick={() => router.push(`/admin/challenge/${row.original.id}`)}
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="h-24 text-center">
+ No results.
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ <div className="flex items-center justify-between p-4">
+ <div className="flex items-center gap-1">
+ <div>Page</div>
+ <strong>
+ {table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
+ </strong>
+ </div>
+ <div className="space-x-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ >
+ Previous
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ >
+ Next
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+async function getChallengeReviews(options: {
+ page: number;
+ size: number;
+}): Promise<ChallengeReviewData> {
+ return fetch(
+ `${getBaseUrl()}/api/challenge-reviews?page=${options.page}&size=${options.size}`,
+ ).then((res) => res.json());
+}
diff --git a/src/components/admin/challenge-reviews/index.tsx b/src/components/admin/challenge-reviews/index.tsx
new file mode 100644
index 00000000..47311f3b
--- /dev/null
+++ b/src/components/admin/challenge-reviews/index.tsx
@@ -0,0 +1,10 @@
+import { columns } from './columns';
+import { DataTable } from './data-table';
+
+export async function ChallengeReviews() {
+ return (
+ <div className="">
+ <DataTable columns={columns} />
+ </div>
+ );
+}
diff --git a/src/components/admin/reports.tsx b/src/components/admin/reports.tsx
index 9d310cd2..206316b1 100644
--- a/src/components/admin/reports.tsx
+++ b/src/components/admin/reports.tsx
@@ -1,4 +1,6 @@
'use client';
+import { useInfiniteQuery } from '@tanstack/react-query';
+import { useRouter } from 'next/navigation';
import React from 'react';
import {
Table,
@@ -8,17 +10,14 @@ import {
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 { getInfiniteReports, type InfiniteReports } from '../report/report.action';
import Pagination from '../ui/pagination';
export interface ReportsProps {
initialReports: InfiniteReports;
}
-export default function Reports2({ initialReports }: ReportsProps) {
-
+export function Reports({ initialReports }: ReportsProps) {
const router = useRouter();
const [page, setPage] = React.useState(0);
@@ -38,12 +37,10 @@ export default function Reports2({ initialReports }: ReportsProps) {
b,
) => (a?.metadata.hasNextPage ? a?.metadata?.lastCursor : false),
initialData: {
- pages: [
- initialReports
- ],
- pageParams: [null]
+ pages: [initialReports],
+ pageParams: [null],
},
- enabled: enableInfinite
+ enabled: enableInfinite,
},
);
@@ -56,8 +53,7 @@ export default function Reports2({ initialReports }: ReportsProps) {
<header className="flex justify-end">
<Pagination
onChange={(e) => {
- if(!e.detail.pageLoaded)
- fetchNextPage().then(() => setPage(e.detail.page - 1));
+ if (!e.detail.pageLoaded) fetchNextPage().then(() => setPage(e.detail.page - 1));
else setPage(e.detail.page - 1);
}}
totalPages={data?.pages.length}
@@ -87,7 +83,9 @@ export default function Reports2({ initialReports }: ReportsProps) {
<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 key={`issues-${i.id}`} className="rounded-full bg-zinc-800 px-3 py-1">
+ {i.type}
+ </div>
))}
</div>
</TableCell>
diff --git a/src/components/challenge/submissions/overview.tsx b/src/components/challenge/submissions/overview.tsx
index 1f800287..164ffe92 100644
--- a/src/components/challenge/submissions/overview.tsx
+++ b/src/components/challenge/submissions/overview.tsx
@@ -74,6 +74,6 @@ export function SubmissionOverview({ submissionId }: Props) {
);
}
-function getSubmission(id: string) {
+async function getSubmission(id: string) {
return fetch(`${getBaseUrl()}/api/submissions/${id}`).then((res) => res.json());
}
diff --git a/src/components/explore/explore-card.tsx b/src/components/explore/explore-card.tsx
index ab624e46..319fdd11 100644
--- a/src/components/explore/explore-card.tsx
+++ b/src/components/explore/explore-card.tsx
@@ -2,12 +2,12 @@ import { Circle, Diamond, MessageCircle, Plus, Sparkle, ThumbsUp, Triangle } fro
import { getRelativeTime } from '~/utils/relativeTime';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card';
-import { type ExploreChallengeData } from './';
+import { type ExploreChallengeFetcher } from './';
import { DifficultyBadge } from '../ui/difficulty-badge';
interface ExploreCardProps {
challenge: Pick<
- ExploreChallengeData[0],
+ Awaited<ReturnType<ExploreChallengeFetcher>>[0],
'difficulty' | 'name' | 'shortDescription' | 'user' | '_count' | 'updatedAt'
>;
}
diff --git a/src/components/explore/index.tsx b/src/components/explore/index.tsx
index ef0dcabb..1eb8d12e 100644
--- a/src/components/explore/index.tsx
+++ b/src/components/explore/index.tsx
@@ -30,7 +30,7 @@ export async function Explore() {
);
}
-export type ExploreChallengeData = Awaited<ReturnType<typeof getEasyChallenges>>;
+export type ExploreChallengeFetcher = typeof getEasyChallenges;
// TODO: this is trash
async function getEasyChallenges() {
return prisma.challenge.findMany({
diff --git a/src/components/explore/section.tsx b/src/components/explore/section.tsx
index ed2e5b48..5ef41cff 100644
--- a/src/components/explore/section.tsx
+++ b/src/components/explore/section.tsx
@@ -2,14 +2,14 @@ import Link from 'next/link';
import { ExploreCard } from './explore-card';
-import type { ExploreChallengeData } from '.';
+import type { ExploreChallengeFetcher } from '.';
import type { Difficulty } from '@prisma/client';
import { Button } from '../ui/button';
import { ChevronRight } from 'lucide-react';
interface Props {
title: string;
- fetcher: () => Promise<ExploreChallengeData>;
+ fetcher: ExploreChallengeFetcher;
}
const difficultyToNumber: Record<Difficulty, number> = {
diff --git a/src/components/report/report.action.ts b/src/components/report/report.action.ts
index 8bf7ca48..9a63f740 100644
--- a/src/components/report/report.action.ts
+++ b/src/components/report/report.action.ts
@@ -153,9 +153,9 @@ export async function getReports(lastCursor?: number, take = 25) {
_count: {
select: {
vote: true,
- }
- }
- }
+ },
+ },
+ },
},
user: true,
reporter: true,
diff --git a/src/components/ui/navigation.tsx b/src/components/ui/navigation.tsx
index 405e3faf..5e805f4c 100644
--- a/src/components/ui/navigation.tsx
+++ b/src/components/ui/navigation.tsx
@@ -129,7 +129,9 @@ export function Navigation() {
<header className="w-full">
<nav
className={`flex h-14 items-center ${
- pathname.includes('/challenge') ? 'px-4' : 'container '
+ pathname.startsWith('/challenge') || pathname.startsWith('/admin/challenge')
+ ? 'px-4'
+ : 'container '
}`}
>
<div className="flex w-full items-center justify-between">
diff --git a/src/components/wizard/ChallengeCardEditor.tsx b/src/components/wizard/ChallengeCardEditor.tsx
index 9e10b252..d243dc87 100644
--- a/src/components/wizard/ChallengeCardEditor.tsx
+++ b/src/components/wizard/ChallengeCardEditor.tsx
@@ -2,7 +2,7 @@
import { useWatch } from 'react-hook-form';
import type { WizardForm } from '.';
-import type { ExploreChallengeData } from '../explore';
+import type { ExploreChallengeFetcher } from '../explore';
import { ExploreCard } from '../explore/explore-card';
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from '../ui/form';
import { Input } from '../ui/input';
@@ -20,7 +20,7 @@ export function ChallengeCardEditor({ form }: Props) {
const shortDescription = useWatch({ control: form.control, name: 'shortDescription' });
const data: Pick<
- ExploreChallengeData[0],
+ Awaited<ReturnType<ExploreChallengeFetcher>>[0],
'difficulty' | 'name' | 'shortDescription' | 'user' | '_count' | 'updatedAt'
> = {
difficulty,
@@ -60,6 +60,7 @@ export function ChallengeCardEditor({ form }: Props) {
</FormControl>
<SelectContent>
<SelectItem value="BEGINNER">BEGINNER</SelectItem>
+ <SelectItem value="EASY">EASY</SelectItem>
<SelectItem value="MEDIUM">MEDIUM</SelectItem>
<SelectItem value="HARD">HARD</SelectItem>
<SelectItem value="EXTREME">EXTREME</SelectItem>
diff --git a/src/components/wizard/Summary.tsx b/src/components/wizard/Summary.tsx
index 49d89f2d..d42c58fb 100644
--- a/src/components/wizard/Summary.tsx
+++ b/src/components/wizard/Summary.tsx
@@ -1,8 +1,15 @@
-export function Summary() {
+interface Props {
+ isUserACreator: boolean;
+}
+export function Summary({ isUserACreator }: Props) {
return (
<div className="flex h-full flex-col items-center justify-center">
<div className="mb-5 text-center text-5xl font-bold text-gray-900 dark:text-gray-100">
- Thanks for creating a challenge! Submit it to the community for review.
+ {isUserACreator ? (
+ <>Thanks for creating a challenge! Submit it to share with the community.</>
+ ) : (
+ <>Thanks for creating a challenge! Submit it to the community for review.</>
+ )}
</div>
</div>
);
diff --git a/src/components/wizard/create.action.ts b/src/components/wizard/create.action.ts
index cde2ac2c..fe0f7931 100644
--- a/src/components/wizard/create.action.ts
+++ b/src/components/wizard/create.action.ts
@@ -4,7 +4,7 @@ import { prisma } from '~/server/db';
import { getServerAuthSession } from '~/server/auth';
import { type CreateChallengeSchema } from '.';
-export async function uploadChallenge(data: CreateChallengeSchema) {
+export async function uploadChallenge(data: CreateChallengeSchema, isUserACreator: boolean) {
const session = await getServerAuthSession();
if (!session) {
@@ -15,6 +15,8 @@ export async function uploadChallenge(data: CreateChallengeSchema) {
data: {
...data,
userId: session.user.id,
+ // if a user has the creator role already then their challenges dont need to be approved anymore
+ ...(isUserACreator ? { status: 'ACTIVE' } : {}),
},
select: {
id: true,
diff --git a/src/components/wizard/index.tsx b/src/components/wizard/index.tsx
index ed460fd7..90070e7c 100644
--- a/src/components/wizard/index.tsx
+++ b/src/components/wizard/index.tsx
@@ -16,6 +16,7 @@ import { uploadChallenge } from './create.action';
import DEFAULT_CHALLENGE_TEMPLATE from './default-challenge.md';
import DEFAULT_DESCRIPTION from './default-description.md';
import type { TsErrors } from '../challenge/code-panel';
+import { useSession } from 'next-auth/react';
export const enum STEPS {
ChallengeCard,
@@ -66,10 +67,16 @@ export type WizardForm = UseFormReturn<CreateChallengeSchema>;
export function Wizard() {
const router = useRouter();
+ const { data: session } = useSession();
const [step, setStep] = useState(0);
const [rendered, setRendered] = useState(false);
const [tsErrors, setTsErrors] = useState<TsErrors>([[], [], [], []]);
+ const isUserACreator = useMemo(
+ () => session?.user.role.includes('CREATOR') ?? false,
+ [session?.user.role],
+ );
+
const hasTsErrors = useMemo(() => tsErrors.some((e) => e.length), [tsErrors]);
const form = useForm<CreateChallengeSchema>({
resolver: zodResolver(createChallengeSchema),
@@ -101,9 +108,15 @@ export function Wizard() {
};
async function onSubmit(data: CreateChallengeSchema) {
- const { id } = await uploadChallenge(data);
+ const { id } = await uploadChallenge(data, isUserACreator);
+
+ router.refresh();
- router.push(`/challenge/${id}`);
+ if (isUserACreator) {
+ router.push(`/challenge/${id}`);
+ } else {
+ router.push(`/explore}`);
+ }
}
return (
@@ -125,7 +138,7 @@ export function Wizard() {
{step === STEPS.TestCases && (
<TestCasesEditor form={form} hasTsErrors={hasTsErrors} setTsErrors={setTsErrors} />
)}
- {step === 3 && <Summary />}
+ {step === 3 && <Summary isUserACreator={isUserACreator} />}
</form>
</Form>
)}