Connect, collaborate, and grow with a community of TypeScript developers
feat: Unified report and comment interfaces (#265)
Jim Burbridge11d4cf434020
diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 30a1bc7b..a807879b 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -114,18 +114,15 @@ model User {challengeReports ChallengeReport[] @relation(name: "authored_challenge_reports")moderatedChallengeReports ChallengeReport[] @relation(name: "moderated_challenge_reports")- commentReports CommentReport[] @relation(name: "authored_comment_reports")- moderatedCommentReports CommentReport[] @relation(name: "moderated_comment_reports")bookmark Bookmark[]sharedSolution SharedSolution[]- comment ChallengeComment[]- reply ChallengeReply[]- solutionComment SolutionComment[]- solutionReply SolutionReply[]+ comment Comment[]- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ reports Report[] @relation("reporter")+ reportsAbout Report[] @relation("reported_user")}model VerificationToken {@@ -155,10 +152,11 @@ model Challenge {vote Vote[]submission Submission[]- comment ChallengeComment[]+ comment Comment[]report ChallengeReport[]bookmark Bookmark[]sharedSolution SharedSolution[]+ Report Report[] @relation("report_challenge")@@index([userId])}@@ -191,7 +189,8 @@ model SharedSolution {userId String?challenge Challenge? @relation(fields: [challengeId], references: [id])challengeId Int?- solutionComment SolutionComment[]+ solutionComment Comment[]+ Report Report[]@@index([userId])@@index([challengeId])@@ -213,64 +212,6 @@ model Submission {@@index([challengeId])}-model ChallengeComment {- id Int @id @default(autoincrement())- createdAt DateTime @default(now())- user User @relation(fields: [userId], references: [id])- userId String- challenge Challenge @relation(fields: [challengeId], references: [id])- challengeId Int- text String @db.VarChar(1000)- visibility Visibility @default(VISIBLE)- replies ChallengeReply[]- CommentReport CommentReport[]-- @@index([userId])- @@index([challengeId])-}--model ChallengeReply {- id Int @id @default(autoincrement())- createdAt DateTime @default(now())- user User @relation(fields: [userId], references: [id])- userId String- comment ChallengeComment @relation(fields: [commentId], references: [id])- commentId Int- text String-- @@index([userId])- @@index([commentId])-}--model SolutionComment {- id Int @id @default(autoincrement())- createdAt DateTime @default(now())- user User @relation(fields: [userId], references: [id])- userId String- solution SharedSolution @relation(fields: [solutionId], references: [id])- solutionId Int- text String @db.VarChar(1000)- visibility Visibility @default(VISIBLE)- solutionReply SolutionReply[]- CommentReport CommentReport[]-- @@index([userId])- @@index([solutionId])-}--model SolutionReply {- id Int @id @default(autoincrement())- createdAt DateTime @default(now())- user User @relation(fields: [userId], references: [id])- userId String- solution SolutionComment @relation(fields: [solutionId], references: [id])- solutionId Int- text String-- @@index([userId])- @@index([solutionId])-}-model ChallengeReport {id Int @id @default(autoincrement())@@ -301,48 +242,106 @@ model ChallengeReport {@@index([moderatorId])}-model CommentReport {- id Int @id @default(autoincrement())-- // meta information- text String? @db.MediumText- status ReportStatus @default(PENDING)+model Bookmark {+ id Int @id @default(autoincrement())+ user User @relation(fields: [userId], references: [id])+ userId String+ challenge Challenge? @relation(fields: [challengeId], references: [id])+ challengeId Int?- // report types- threats Boolean @default(false)- hateSpeech Boolean @default(false)- spam Boolean @default(false)- bullying Boolean @default(false)+ @@index([userId])+ @@index([challengeId])+}- // user info- author User @relation(fields: [authorId], references: [id], name: "authored_comment_reports")- authorId String- moderator User? @relation(fields: [moderatorId], references: [id], name: "moderated_comment_reports")- moderatorId String?+enum ReportType {+ CHALLENGE+ USER+ COMMENT+ SOLUTION+}- // attached comments- challengeComment ChallengeComment? @relation(fields: [challengeCommentId], references: [id])- challengeCommentId Int?- solutionComment SolutionComment? @relation(fields: [solutionCommendId], references: [id])- solutionCommendId Int?+enum IssueType {+ DEROGATORY+ OTHER+ UNCLEAR+ BULLYING+ SPAM+ HATESPEECH+ THREAT+}- // time- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+model ReportIssue {+ id Int @id @default(autoincrement())+ reportId Int+ report Report @relation(fields: [reportId], references: [id])+ type IssueType- @@index([moderatorId])- @@index([authorId])- @@index([challengeCommentId])- @@index([solutionCommendId])+ @@unique([id])+ @@index([reportId])}-model Bookmark {- id Int @id @default(autoincrement())- user User @relation(fields: [userId], references: [id])- userId String- challenge Challenge? @relation(fields: [challengeId], references: [id])+model Report {+ // Base table info+ id Int @id @default(autoincrement())++ text String @db.MediumText++ type ReportType+ status ReportStatus+ issues ReportIssue[]++ // Reporter information+ reporterId String+ reporter User @relation("reporter", fields: [reporterId], references: [id])++ // reported User Info+ userId String?+ user User? @relation("reported_user", fields: [userId], references: [id])++ // reported Challenge InfochallengeId Int?+ challenge Challenge? @relation("report_challenge", fields: [challengeId], references: [id])+ commentId Int?+ comment Comment? @relation("report_comment", fields: [commentId], references: [id])++ solutionId Int?+ solution SharedSolution? @relation(fields: [solutionId], references: [id])++ @@unique([id])+ @@index([commentId])+ @@index([reporterId])@@index([userId])@@index([challengeId])+ @@index([solutionId])+}++enum CommentRoot {+ SOLUTION+ CHALLENGE+}++model Comment {+ id Int @id @default(autoincrement())+ text String @db.MediumText+ parentId Int?++ userId String+ user User @relation(fields: [userId], references: [id])++ rootType CommentRoot @default(CHALLENGE)++ rootChallengeId Int?+ rootChallenge Challenge? @relation(fields: [rootChallengeId], references: [id])++ rootSolutionId Int?+ rootSolution SharedSolution? @relation(fields: [rootSolutionId], references: [id])+ Report Report[] @relation("report_comment")++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([rootSolutionId])+ @@index([rootChallengeId])+ @@index([userId])}diff --git a/src/app/admin/report/[id]/report.action.ts b/src/app/admin/report/[id]/report.action.tsindex 54395f5c..8623c115 100644--- a/src/app/admin/report/[id]/report.action.ts+++ b/src/app/admin/report/[id]/report.action.ts@@ -1,16 +1,22 @@import { prisma } from '~/server/db';export async function getReports() {- const challengeReports = await prisma.challengeReport.findMany({+ const challengeReports = await prisma.report.findMany({+ where: {+ type: 'CHALLENGE',+ },include: {challenge: {include: {user: true,},},- author: true,},});- const otherReports = await prisma.commentReport.findMany();+ const otherReports = await prisma.report.findMany({+ where: {+ type: {not: 'CHALLENGE'},+ }+ });return {challengeReports,otherReports,diff --git a/src/app/admin/report/page.tsx b/src/app/admin/report/page.tsxindex b2ebe540..73d88dfa 100644--- a/src/app/admin/report/page.tsx+++ b/src/app/admin/report/page.tsx@@ -1,15 +1,78 @@-import { RoleTypes } from '@prisma/client';-import { getServerAuthSession } from '~/server/auth';-import { redirect } from 'next/navigation';+import { getChallengeReports } from '~/components/admin/admin.actions';+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 default async function ListReportPage() {- const session = await getServerAuthSession();- const roles = session?.user?.role ?? [];- const isMod = roles.includes(RoleTypes.ADMIN) || roles.includes(RoleTypes.MODERATOR);+export const dynamic = 'force-dynamic';- if (!isMod) {- return redirect('/');+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();- return <div>I am amazing</div>;+ 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/challenge/[id]/getChallengeRouteData.ts b/src/app/challenge/[id]/getChallengeRouteData.tsindex 69e84d92..81210484 100644--- a/src/app/challenge/[id]/getChallengeRouteData.ts+++ b/src/app/challenge/[id]/getChallengeRouteData.ts@@ -25,14 +25,18 @@ export const getChallengeRouteData = cache(async (id: string, session: Session |},},comment: {+ where: {+ rootType: 'CHALLENGE',+ rootChallengeId: +id,+ },+ include: {+ user: true,+ },orderBy: [{createdAt: 'desc',},],- include: {- user: true,- },},},});diff --git a/src/app/challenge/[id]/solutions/[solutionId]/page.tsx b/src/app/challenge/[id]/solutions/[solutionId]/page.tsxindex a35b60b2..55ca0da1 100644--- a/src/app/challenge/[id]/solutions/[solutionId]/page.tsx+++ b/src/app/challenge/[id]/solutions/[solutionId]/page.tsx@@ -23,8 +23,19 @@ async function getSolution(solutionId: string) {include: {challenge: true,user: true,+},});- return solution;+ const f = await prisma.comment.findMany({+ where: {+ rootType: 'SOLUTION',+ rootSolutionId: +solutionId+ }+ });++ return {+ ...solution,+ jimComments: f,+ };}diff --git a/src/components/admin/admin.actions.tsx b/src/components/admin/admin.actions.tsxindex 1fc6df97..28ce02ec 100644--- a/src/components/admin/admin.actions.tsx+++ b/src/components/admin/admin.actions.tsx@@ -1,10 +1,36 @@'use server';+import { type Report, type Prisma } from '@prisma/client';import { getServerAuthSession } from '~/server/auth';import { prisma } from '~/server/db';export type AdminReportDetails = Awaited<ReturnType<typeof getChallengeReports>>;+// FML this was obnoxious to do+export type ChallengeInfo = {type: 'CHALLENGE'} & Omit<Report, 'id' | 'userId' | 'type' | 'status'>;+export type UserInfo = {type: 'USER'} & Omit<Report, 'id' | 'challengeId' | 'type' | 'status'>;++/**+ *+ * @param info the info needed to create the Report instance+ * @param issues any issues types that are connected to this.+ * @returns the newly created report information.+ */+export async function addReport(info: ChallengeInfo | UserInfo, issues: Prisma.ReportIssueCreateManyReportInput[] = [{ type: 'OTHER' }]) {++ return prisma.report.create({+ data: {+ status: 'PENDING',+ ...info,+ issues: {+ createMany: {+ data: issues+ },+ }+ },+ });+}+/*** The function fetches all the reports along* with challenge and the user.diff --git a/src/components/challenge/comments/comment.action.ts b/src/components/challenge/comments/comment.action.tsindex 4f4abfd3..3281aef0 100644--- a/src/components/challenge/comments/comment.action.ts+++ b/src/components/challenge/comments/comment.action.ts@@ -1,68 +1,28 @@'use server';-import { getServerSession } from 'next-auth';-import { type CommentReportSchemaType } from '~/components/challenge/comments/comment';-import { authOptions, getServerAuthSession } from '~/server/auth';+import { type Prisma } from '@prisma/client';+import { getServerAuthSession } from '~/server/auth';import { prisma } from '~/server/db';-/**- * The function creates a comments with given- * text and challenge id.- * @param challengeId The challenge Id.- * @param text The comment text.- */-export async function addChallengeComment(challengeId: number, text: string) {- const session = await getServerAuthSession();+export type ChallengeComment = Omit<Prisma.CommentCreateManyInput, 'rootType' | 'rootSolutionId' | 'userId' > & { rootType: 'CHALLENGE' };- // 1. Checks.- if (!session?.user.id) return 'unauthorized';- if (text.length === 0) return 'text_is_empty';-- // 2. Create a new comment.- return await prisma.challengeComment.create({- data: {- challengeId,- text,- userId: session.user.id,- },- });-}+export type SolutionComment = Omit<Prisma.CommentCreateManyInput, 'rootType' | 'rootChallengeId' | 'userId'> & { rootType: 'SOLUTION' }/**- * Creates a new report on a challenge comment with a- * few parameters describing the report.- * @param formValues Accepts {@link CommentReportSchemaType}.- * @param commentId The comment id.- * @returns+ *+ * @param comment a Challenge or Solution-based comment.+ * @returns the prisma create response.*/-export async function reportChallengeComment(- formValues: CommentReportSchemaType,- commentId: number,-) {- const session = await getServerSession(authOptions);- const { bullying, hate_speech, spam, text, threat } = formValues;-- // 1. Checks.- if (!session?.user.id) return 'unauthorized';+export async function addComment(comment: ChallengeComment | SolutionComment) {+ const session = await getServerAuthSession();- // 2. If report already exist's return.- const report = await prisma.commentReport.findFirst({- where: {- challengeCommentId: commentId,- },- });- if (report) return 'already_exists';+ if(!session?.user.id) return 'unauthorized';+ if(comment.text.length === 0) return 'text_is_empty';- // 3. Create new report.- return await prisma.commentReport.create({+ return await prisma.comment.create({data: {- authorId: session.user.id,- bullying: bullying,- hateSpeech: hate_speech,- spam: spam,- threats: threat,- text: text,- challengeCommentId: commentId,- },+ ...comment,+ userId: session.user.id+ }});}diff --git a/src/components/challenge/comments/comment.tsx b/src/components/challenge/comments/comment.tsxindex 1b40b8ce..978d6e2f 100644--- a/src/components/challenge/comments/comment.tsx+++ b/src/components/challenge/comments/comment.tsx@@ -1,22 +1,15 @@'use client';-import { zodResolver } from '@hookform/resolvers/zod';-import { Delete, Trash2, Reply, Share } from 'lucide-react';+import { Trash2, Reply, Share } from 'lucide-react';import { useState } from 'react';-import { useForm } from 'react-hook-form';import { z } from 'zod';import type { ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';-import { Dialog, DialogContent, DialogHeader, DialogTitle } from '~/components/ui/dialog';import { getRelativeTime } from '~/utils/relativeTime';-import { Button } from '~/components/ui/button';-import { Checkbox } from '~/components/ui/checkbox';-import { Form, FormField, FormItem } from '~/components/ui/form';-import { Textarea } from '~/components/ui/textarea';-import { TypographyLarge } from '~/components/ui/typography/large';-import { toast } from '~/components/ui/use-toast';-import { reportChallengeComment } from './comment.action';import { Tooltip, TooltipContent, TooltipTrigger } from '~/components/ui/tooltip';import { UserBadge } from '~/components/ui/user-badge';import { useSession } from 'next-auth/react';+import { toast } from '~/components/ui/use-toast';+import ReportDialog from '~/components/report';+interface CommentProps {comment: ChallengeRouteData['comment'][number];@@ -46,18 +39,6 @@ export type CommentReportSchemaType = z.infer<typeof commentReportSchema>;const Comment = ({ comment }: CommentProps) => {const [dialogOpen, setDialogOpen] = useState(false);- const form = useForm<CommentReportSchemaType>({- resolver: zodResolver(commentReportSchema),- mode: 'onChange',- defaultValues: {- bullying: false,- hate_speech: false,- spam: false,- text: '',- threat: false,- },- });-async function copyPathNotifyUser() {try {await copyCommentUrlToClipboard();@@ -80,40 +61,6 @@ const Comment = ({ comment }: CommentProps) => {await navigator.clipboard.writeText(`${window.location.href}/comment/${comment.id}`);}- async function handleCommentReport(data: CommentReportSchemaType) {- try {- const res = await reportChallengeComment(data, comment.id);- if (res === 'unauthorized') {- toast({- title: 'Unauthorized',- variant: 'destructive',- description: <p>You're not authorized to perform the action.</p>,- });- } else if (res === 'already_exists') {- toast({- title: 'Already Reported',- description: <p>The comment you're trying to report has already been reported.</p>,- });- } else {- toast({- title: 'Reported',- variant: 'success',- description: <p>The comment has successfully been reported.</p>,- });- setDialogOpen(false);- form.reset();- }- } catch (e) {- toast({- title: 'Uh Oh!',- variant: 'destructive',- description: <p>There was an error while trying to report the comment.</p>,- });- }- }-- const text = form.watch('text');-const loggedinUser = useSession();const isAuthor = loggedinUser.data?.user?.id === comment.user.id;@@ -155,16 +102,21 @@ const Comment = ({ comment }: CommentProps) => {Delete</button>) : (- <button- onClick={() => {- setDialogOpen(true);- }}- 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"+ <ReportDialog+ reportType="COMMENT"+ commentId={comment.id}>- Report- </button>+ <button+ onClick={() => {+ setDialogOpen(true);+ }}+ 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">@@ -172,172 +124,6 @@ const Comment = ({ comment }: CommentProps) => {{/* <Markdown>{comment.text}</Markdown> */}{comment.text}</p>- <Dialog- open={dialogOpen}- onOpenChange={() => {- setDialogOpen(!dialogOpen);- }}- >- {/* TODO: make a separate component */}- <DialogContent className="max-w-lg">- <DialogHeader>- <DialogTitle>Report Comment</DialogTitle>- </DialogHeader>- <div className="space-y-2">- <div className="flex flex-col space-y-2 rounded-3xl border p-3 dark:bg-zinc-900">- {/* TODO: use comment template component inside this new separate component */}- <div className="flex items-center gap-1">- <UserBadge username={comment.user.name} />- <Tooltip>- <span className="text-sm text-neutral-500">- {getRelativeTime(comment.createdAt)}- </span>- <TooltipContent className="rounded-xl">- <span className="text-white-500 text-sm">- {comment.createdAt.toLocaleString()}- </span>- </TooltipContent>- </Tooltip>- </div>- <p className="max-h-[30vh] overflow-y-auto">{comment.text}</p>- </div>-- <Form {...form}>- {/* eslint-disable-next-line @typescript-eslint/no-misused-promises */}- <form onSubmit={form.handleSubmit(handleCommentReport)}>- <div className="py-2">- <TypographyLarge>Issues</TypographyLarge>- </div>- <div className="flex flex-col space-y-2 px-2">- <FormField- control={form.control}- name="bullying"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-4">- <Checkbox- id="bullying"- checked={field.value as boolean}- onCheckedChange={(e) => {- if (typeof e === 'boolean') {- field.onChange(e);- }- }}- />- <label htmlFor="bullying">The comment suggests bullying.</label>- </div>- </FormItem>- );- }}- />- <FormField- control={form.control}- name="hate_speech"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-4">- <Checkbox- id="hate_speech"- checked={field.value as boolean}- onCheckedChange={(e) => {- if (typeof e === 'boolean') {- field.onChange(e);- }- }}- />- <label htmlFor="hate_speech">The comment suggests hate speech.</label>- </div>- </FormItem>- );- }}- />- <FormField- control={form.control}- name="spam"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-4">- <Checkbox- id="spam"- checked={field.value as boolean}- onCheckedChange={(e) => {- if (typeof e === 'boolean') {- field.onChange(e);- }- }}- />- <label htmlFor="spam">The comment suggests spam.</label>- </div>- </FormItem>- );- }}- />- <FormField- control={form.control}- name="threat"- render={({ field }) => {- return (- <FormItem>- <div className="flex items-center gap-4">- <Checkbox- id="threat"- checked={field.value as boolean}- onCheckedChange={(e) => {- if (typeof e === 'boolean') {- field.onChange(e);- }- }}- />- <label htmlFor="threat">The comment suggests threat/s.</label>- </div>- </FormItem>- );- }}- />- <FormField- control={form.control}- name="text"- render={({ field }) => {- return (- <FormItem>- <div className="flex flex-row items-center gap-2">- <label className="-ml-2" htmlFor="text">- <TypographyLarge>Other</TypographyLarge>- </label>- {text !== undefined && text.length > 0 && (- <Delete- className="h-5 w-5 hover:cursor-pointer"- onClick={() => {- form.setValue('text', '');- }}- />- )}- </div>- <Textarea value={field.value} onChange={field.onChange} />- </FormItem>- );- }}- />- {form.formState.errors.text?.message && (- <p className={'text-sm font-medium text-destructive'}>- {form.formState.errors.text.message}- </p>- )}- </div>-- <div className="flex pt-4">- <Button type="submit" className="w-full">- Report- </Button>- </div>- </form>- </Form>- </div>- </DialogContent>- </Dialog></div>);};diff --git a/src/components/challenge/comments/getCommentRouteData.ts b/src/components/challenge/comments/getCommentRouteData.tsindex f3bda685..81588252 100644--- a/src/components/challenge/comments/getCommentRouteData.ts+++ b/src/components/challenge/comments/getCommentRouteData.ts@@ -10,10 +10,11 @@ interface QueryParams {}export async function getInfiniteComments({ challengeId, take = 10, lastCursor }: QueryParams) {- const results = await prisma.challengeComment.findMany({- where: { challengeId },- include: { user: true },- take,+ const results = await prisma.comment.findMany({+ where: {+ rootType: 'CHALLENGE',+ rootChallengeId: challengeId,+ },...(lastCursor && {skip: 1,cursor: {@@ -23,36 +24,24 @@ export async function getInfiniteComments({ challengeId, take = 10, lastCursor }orderBy: {createdAt: 'desc',},+ include: {+ user: true,+ }});- if (results.length == 0) {- return {- data: [],- metaData: {- lastCursor: null,- hasNextPage: false,- },- };- }-- const lastPostInResults = results[results.length - 1];- const cursor = lastPostInResults?.id;-- const nextPage = await prisma.challengeComment.findMany({- where: { challengeId },- include: { user: true },- take,- skip: 1,- cursor: {- id: cursor,- },- });-+ const last = results.at(-1);+ const hasNextPage = last && last.id ?+ await prisma.comment.findMany({+ where: {+ rootChallengeId: challengeId,+ }+ }).then(f => f.length > 0) : false;+return {data: results,metaData: {- lastCursor: cursor,- hasNextPage: nextPage.length > 0,- },+ lastCursor: last ? last.id : null,+ hasNextPage,+ }};}diff --git a/src/components/challenge/comments/index.tsx b/src/components/challenge/comments/index.tsxindex 34282a1d..e0c6023f 100644--- a/src/components/challenge/comments/index.tsx+++ b/src/components/challenge/comments/index.tsx@@ -8,7 +8,7 @@ import Comment from '~/components/challenge/comments/comment';import { Button } from '~/components/ui/button';import { toast } from '~/components/ui/use-toast';import NoComments from './nocomments';-import { addChallengeComment } from './comment.action';+import { addComment } from './comment.action';import { Textarea } from '~/components/ui/textarea';import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';import { useInView } from 'react-intersection-observer';@@ -33,8 +33,8 @@ const Comments = ({ challengeId, commentCount }: Props) => {const { data, status, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery({queryFn: ({ pageParam = '' }) =>- getInfiniteComments({ challengeId, take: 10, lastCursor: pageParam }),- queryKey: ['comments'],+ getInfiniteComments({ challengeId, take: 10, lastCursor: +pageParam }),+ queryKey: ['comments', challengeId],getNextPageParam: (lastPage) => lastPage.metaData.lastCursor,});@@ -51,8 +51,11 @@ const Comments = ({ challengeId, commentCount }: Props) => {async function createChallengeComment() {try {setIsCommenting(true);- const res = await addChallengeComment(challengeId, text);-+ const res = await addComment({+ text,+ rootChallengeId: challengeId,+ rootType: 'CHALLENGE',+ });if (res === 'text_is_empty') {toast({title: 'Empty Comment',@@ -66,7 +69,7 @@ const Comments = ({ challengeId, commentCount }: Props) => {}setIsCommenting(false);setText('');- await queryClient.invalidateQueries(['comments']);+ await queryClient.invalidateQueries(['comments', challengeId]);} catch (e) {toast({title: 'Unauthorized',diff --git a/src/components/challenge/description/index.tsx b/src/components/challenge/description/index.tsxindex cba309d3..94fef268 100644--- a/src/components/challenge/description/index.tsx+++ b/src/components/challenge/description/index.tsx@@ -3,7 +3,6 @@import { clsx } from 'clsx';import { debounce } from 'lodash';-import * as DialogPrimitive from '@radix-ui/react-dialog';import { useSession } from 'next-auth/react';import { useRouter } from 'next/navigation';import { useRef, useState } from 'react';@@ -15,28 +14,21 @@ import { Button } from '~/components/ui/button';import { UserBadge } from '~/components/ui/user-badge';import {Dialog,- DialogContent,- DialogFooter,- DialogHeader,+ DialogContent, DialogHeader,DialogTitle,- DialogTrigger,+ DialogTrigger} from '~/components/ui/dialog';import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '~/components/ui/tooltip';import { TypographyH3 } from '~/components/ui/typography/h3';import { DifficultyBadge } from '~/components/ui/difficulty-badge';import { ActionMenu } from '~/components/ui/action-menu';-import { Checkbox } from '~/components/ui/checkbox';-import { Form, FormField, FormItem } from '~/components/ui/form';import { Markdown } from '~/components/ui/markdown';-import { Textarea } from '~/components/ui/textarea';-import { TypographyLarge } from '~/components/ui/typography/large';import { ShareForm } from '../share-form';import { type ChallengeRouteData } from '~/app/challenge/[id]/getChallengeRouteData';-import { toast } from '~/components/ui/use-toast';import { addOrRemoveBookmark } from '../bookmark.action';import { incrementOrDecrementUpvote } from '../increment.action';-import { addChallengeReport } from '../report.action';+import ReportDialog from '~/components/report';import { getRelativeTime } from '~/utils/relativeTime';interface Props {@@ -90,48 +82,6 @@ export function Description({ challenge }: Props) {},});- async function onSubmit(data: FormValues) {- try {- const response = await addChallengeReport(- 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>,- });- }- } catch (e) {- toast({- title: 'Something went wrong.',- variant: 'destructive',- description: <p>An error was encountered while trying to make a report.</p>,- });- }- }return (<div className="custom-scrollable-element overflow-y-auto h-full px-4 pt-3 pb-36">{/* NOTE: collapse this element */}@@ -251,98 +201,21 @@ export function Description({ challenge }: Props) {<p>Login to Upvote</p></TooltipContent></Tooltip>- <Dialog>- <DialogTrigger>- <ActionMenu- items={[- {- key: 'feedback',- label: 'Feedback',- icon: 'Flag',- },- ]}- onChange={() => {- // do nothing- }}- />- </DialogTrigger>-- <DialogContent>- <Form {...form}>- <form onSubmit={form.handleSubmit(onSubmit)}>- <DialogHeader>- <DialogTitle>Feedback: {challenge.name}</DialogTitle>- </DialogHeader>-- <div className="my-4 flex flex-col gap-4">- <TypographyLarge>Issues Encountered</TypographyLarge>- <FormField- name="examples"- render={({ field }) => (- <FormItem>- <div className="flex items-center gap-4">- <Checkbox- id="examples"- checked={field.value as boolean}- onChange={field.onChange}- onCheckedChange={field.onChange}- />- <label htmlFor="examples">- Description or examples are unclear or incorrect- </label>- </div>- </FormItem>- )}- />- <FormField- name="derogatory"- render={({ field }) => (- <FormItem>- <div className="flex items-center gap-4">- <Checkbox- id="derogatory"- checked={field.value as boolean}- onCheckedChange={field.onChange}- />- <label htmlFor="derogatory">Racist or other derogatory statement</label>- </div>- </FormItem>- )}- />- <FormField- name="other"- render={({ field }) => (- <FormItem>- <div className="flex items-center gap-4">- <Checkbox- id="other"- checked={field.value as boolean}- onCheckedChange={field.onChange}- />- <label htmlFor="other">Other</label>- </div>- </FormItem>- )}- />- <FormField- name="comments"- render={({ field }) => (- <FormItem>- <TypographyLarge>Comments</TypographyLarge>- <Textarea value={field.value as string} onChange={field.onChange} />- </FormItem>- )}- />- </div>- <DialogFooter>- <DialogPrimitive.Close asChild>- <Button type="submit">Report</Button>- </DialogPrimitive.Close>- </DialogFooter>- </form>- </Form>- </DialogContent>- </Dialog>+ <ReportDialog reportType="CHALLENGE" challengeId={challenge.id}>+ <ActionMenu+ items={[+ {+ key: 'feedback',+ label: 'Feedback',+ icon: 'Flag',+ },+ ]}+ onChange={() => {+ // do nothing+ }}+ />+ </ReportDialog>+</div><div className="mb-6 flex items-center gap-4">diff --git a/src/components/challenge/report.action.ts b/src/components/challenge/report.action.tsdeleted file mode 100644index deb8878e..00000000--- a/src/components/challenge/report.action.ts+++ /dev/null@@ -1,31 +0,0 @@-'use server';--import { prisma } from '~/server/db';-import type { FormValues } from './description';--export async function addChallengeReport(challengeId: number, userId: string, data: FormValues) {- if (userId === undefined) return 'not_logged_in';-- const report = await prisma.challengeReport.findMany({- where: {- challengeId,- authorId: userId,- },- });- if (report.length > 0) {- console.info(report);- return 'report_already_made';- }-- await prisma.challengeReport.create({- data: {- challengeId,- authorId: userId,- text: data.comments,- unclear: data.examples,- derogatory: data.derogatory,- },- });-- return 'created';-}diff --git a/src/components/challenge/solutions/getSolutionData.ts b/src/components/challenge/solutions/getSolutionData.tsnew file mode 100644index 00000000..cc3e1ac3--- /dev/null+++ b/src/components/challenge/solutions/getSolutionData.ts@@ -0,0 +1,56 @@+'use server';+import { prisma } from "~/server/db";++export interface SolutionCommentQueryParams {+ solutionId: number;+ take?: number;+ lastCursor?: number;+}++export async function getInfiniteComments(+ { solutionId, take = 10, lastCursor }: SolutionCommentQueryParams,+) {+ const results = await prisma.comment.findMany({+ where: {+ rootType: "SOLUTION",+ rootSolutionId: solutionId,+ },+ take,+ ...(+ lastCursor && {+ skip: 1,+ cursor: {+ id: lastCursor,+ },+ }+ ),+ orderBy: {+ createdAt: "desc",+ },+ include: {+ user: true,+ },+ });++ const last = results.at(-1);+ const hasNextPage = last && last.id+ ? await prisma.comment.findMany({+ where: {+ rootSolutionId: solutionId,+ },+ skip: 1,+ take: 1,+ cursor: {+ id: last.id,+ },+ }).then((f) => f.length > 0)+ : false;++ return {+ data: results,+ metaData: {+ lastCursor: last? last.id : null,+ hasNextPage,+ }+ };+}diff --git a/src/components/challenge/solutions/solution-comments.tsx b/src/components/challenge/solutions/solution-comments.tsxnew file mode 100644index 00000000..e714ff45--- /dev/null+++ b/src/components/challenge/solutions/solution-comments.tsx@@ -0,0 +1,147 @@+'use client';++import clsx from 'clsx';+import { ChevronDown, MessageCircle } from 'lucide-react';+import { useRouter } from 'next/navigation';+import { useEffect, useState } from 'react';+import Comment from '~/components/challenge/comments/comment';+import { Button } from '~/components/ui/button';+import { toast } from '~/components/ui/use-toast';+import NoComments from '../comments/nocomments';+import { addComment } from '../comments/comment.action';+import { Textarea } from '~/components/ui/textarea';+import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';+import { useInView } from 'react-intersection-observer';+import { getInfiniteComments } from './getSolutionData';+import { CommentSkeleton } from '../comments/comment-skeleton';++interface Props {+ solutionId: number;+ commentCount: number;+}++const Comments = ({ solutionId, commentCount }: Props) => {+ const [showComments, setShowComments] = useState(false);+ const [text, setText] = useState('');+ const [isCommenting, setIsCommenting] = useState(false);+ const router = useRouter();+ const { ref, inView } = useInView();+ const queryClient = useQueryClient();++ const { data, status, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery({+ queryFn: ({ pageParam = '' }) =>+ getInfiniteComments({ solutionId, take: 10, lastCursor: pageParam }),+ queryKey: ['comments', solutionId],+ getNextPageParam: (lastPage) => lastPage.metaData.lastCursor,+ });++ const handleClick = () => {+ setShowComments(!showComments);+ };++ const handleEnterKey = async (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (!e.shiftKey && e.key === 'Enter' && !isCommenting) {+ await createChallengeComment();+ }+ };++ async function createChallengeComment() {+ try {+ setIsCommenting(true);+ const res = await addComment({+ text,+ rootSolutionId: solutionId,+ rootType: 'SOLUTION',+ });+ if (res === 'text_is_empty') {+ toast({+ title: 'Empty Comment',+ description: <p>You cannot post an empty comment.</p>,+ });+ } else if (res === 'unauthorized') {+ toast({+ title: 'Unauthorized',+ description: <p>You need to be signed in to post a comment.</p>,+ });+ }+ setIsCommenting(false);+ setText('');+ queryClient.invalidateQueries(['comments', solutionId]);+ } catch (e) {+ toast({+ title: 'Unauthorized',+ variant: 'destructive',+ description: <p>You need to be signed in to post a comment.</p>,+ });+ } finally {+ router.refresh();+ }+ }++ useEffect(() => {+ if (inView && hasNextPage) fetchNextPage();+ }, [hasNextPage, inView, fetchNextPage]);++ return (+ <div className="relative">+ <button+ className="flex w-full items-center justify-between gap-2 p-3 font-medium text-neutral-500 duration-300 hover:text-neutral-700 dark:hover:text-zinc-300"+ onClick={() => handleClick()}+ >+ <div className="flex items-center">+ <MessageCircle className="h-5 w-5"></MessageCircle>+ Comments ({commentCount})+ </div>+ <ChevronDown+ className={clsx('h-4 w-4 duration-300', {+ '-rotate-180': !showComments,+ })}+ ></ChevronDown>+ </button>+ <div+ className={clsx('flex flex-col-reverse overscroll-contain duration-300', {+ 'h-64 overflow-y-auto': showComments,+ 'h-0 overflow-y-hidden': !showComments,+ })}+ >+ {(status === 'loading' || isFetchingNextPage) && <CommentSkeleton />}+ {status === 'success' &&+ (data?.pages[0]?.data.length === 0 ? (+ <NoComments></NoComments>+ ) : (+ data?.pages.map((page) =>+ page.data.map((comment, index) =>+ page.data.length === index + 1 ? (+ <div ref={ref} key={`comment-${comment.id}`}>+ <Comment key={comment.id} comment={comment} />+ </div>+ ) : (+ <Comment key={comment.id} comment={comment} />+ ),+ ),+ )+ ))}+ </div>+ <div className="m-2 mt-0 flex items-end justify-between gap-2 rounded-xl bg-background/90 bg-neutral-100 p-1 pr-2 backdrop-blur-sm dark:border-zinc-700 dark:bg-zinc-700/90">+ <Textarea+ value={text}+ onChange={(e) => {+ setText(e.target.value);+ }}+ onKeyDown={handleEnterKey}+ rows={2}+ className="min-h-0 resize-none border-0 focus-visible:ring-0 focus-visible:ring-offset-0"+ placeholder="Enter your comment here."+ />+ <Button+ onClick={createChallengeComment}+ className="h-8 rounded-lg bg-emerald-600 px-3 py-2 hover:bg-emerald-500 dark:bg-emerald-400 dark:hover:bg-emerald-300"+ >+ Comment+ </Button>+ </div>+ </div>+ );+};++export default Comments;diff --git a/src/components/challenge/solutions/solution-detail.tsx b/src/components/challenge/solutions/solution-detail.tsxindex a057b9e1..c245ac29 100644--- a/src/components/challenge/solutions/solution-detail.tsx+++ b/src/components/challenge/solutions/solution-detail.tsx@@ -1,6 +1,6 @@'use client';-import { Calendar, MessageCircle, Share, X } from 'lucide-react';+import { Calendar, Share, X } from 'lucide-react';import Link from 'next/link';import type { ChallengeSolution } from '~/app/challenge/[id]/solutions/[solutionId]/page';import { Avatar, AvatarFallback, AvatarImage } from '~/components/ui/avatar';@@ -9,6 +9,9 @@ import { Markdown } from '~/components/ui/markdown';import { TypographyLarge } from '~/components/ui/typography/large';import { toast } from '~/components/ui/use-toast';import { UserBadge } from '~/components/ui/user-badge';+import Comment from './solution-comments';+import ReportDialog from '~/components/report';+import { ActionMenu } from '~/components/ui/action-menu';interface Props {solution: ChallengeSolution;@@ -25,10 +28,6 @@ export function SolutionDetails({ solution }: Props) {}};- const handleCommentClick = () => {- console.log('something');- };-return (<div className="relative flex h-full flex-col"><div className="sticky right-0 top-0 w-full flex border-b border-zinc-300 bg-background/90 p-2 backdrop-blur-sm dark:border-zinc-700 dark:bg-muted/90">@@ -44,27 +43,36 @@ export function SolutionDetails({ solution }: Props) {<AvatarFallback>{solution.user?.name}</AvatarFallback></Avatar><TypographyLarge>{solution.title}</TypographyLarge>+ <div className="ml-auto">+ <ReportDialog reportType="SOLUTION" solutionId={solution.id as number}>+ <ActionMenu+ items={[+ {+ key: 'report',+ label: 'Report',+ icon: 'Flag',+ }+ ]}+ onChange={() => {+ // do nothing+ }}+ />+ </ReportDialog>+ </div></div><div className="flex items-center gap-4"><UserBadge username={solution.user?.name ?? ''} /><div className="flex items-center"><Calendar className="mr-2 h-4 w-4 stroke-gray-400" />- <span className="text-xs text-gray-400">{solution.createdAt.toLocaleString()}</span>+ <span className="text-xs text-gray-400">{solution?.createdAt?.toLocaleString()}</span></div></div></div>- <Markdown>{solution.description}</Markdown>+ <Markdown>{solution.description || ''}</Markdown></div><div className="sticky bottom-0 -mx-[1px] overflow-hidden rounded-xl border border-zinc-300 border-b-background bg-background/90 shadow-[0_0_3rem_-0.25rem_#0004] backdrop-blur-sm duration-300 dark:border-zinc-700 dark:border-b-muted dark:bg-muted/90 dark:shadow-[0_0_3rem_-0.25rem_#0008]"></div>+ <Comment solutionId={solution.id as number} commentCount={solution.jimComments.length} /><div className="flex gap-2">- <Button- variant="ghost"- onClick={handleCommentClick}- className="group text-gray-500 group-hover:text-gray-400"- >- <MessageCircle className="mr-2 h-4 w-4 stroke-gray-500 group-hover:stroke-gray-400" />{' '}- Comments- </Button><Buttonvariant="ghost"onClick={handleShareClick}diff --git a/src/components/report/index.tsx b/src/components/report/index.tsxnew file mode 100644index 00000000..8f35881d--- /dev/null+++ b/src/components/report/index.tsx@@ -0,0 +1,284 @@+import { type IssueType, ReportIssue, ReportType } from '@prisma/client';+import React from 'react';+import { type ChallengeReport, type UserReport, type CommentReport, addReport, type SolutionReport } from '~/components/report/report.action';+import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, DialogTrigger } from '~/components/ui/dialog';+import { Button } from '~/components/ui/button';+import { useForm } from 'react-hook-form';+import { FormField, FormItem } from '~/components/ui/form';+import { Checkbox } from '~/components/ui/checkbox';+import { Textarea } from '~/components/ui/textarea';+import Text from '~/components/ui/typography/typography';+import { toast } from '~/components/ui/use-toast';++export interface ReportDialogPropsBase {+ triggerAsChild?: boolean;+ // reportType?: ReportType;+}++export interface ReportUserDialogProps extends ReportDialogPropsBase {+ reportType: 'USER'+ userId: string;+}++export interface ReportChallengeDialogProps extends ReportDialogPropsBase {+ reportType: 'CHALLENGE';+ challengeId: number;+}++export interface ReportCommentDialogProps extends ReportDialogPropsBase {+ reportType: 'COMMENT';+ commentId: number;+}++export interface ReportSolutionDialogProps extends ReportDialogPropsBase {+ reportType: 'SOLUTION';+ solutionId: number;+}++export default function ReportDialog({ children, triggerAsChild = false, reportType = 'COMMENT', ...props }: React.PropsWithChildren<ReportUserDialogProps | ReportChallengeDialogProps | ReportCommentDialogProps | ReportSolutionDialogProps>) {+ const { handleSubmit, formState: { errors }, register, control, setValue } = useForm({+ defaultValues: {+ derogatory: false,+ unclear: false,+ bullying: false,+ spam: false,+ hateSpeech: false,+ threat: false,+ comments: '',+ }+ });++ const [show, setShow] = React.useState(false);++ let desc = '';+ switch (reportType) {+ case 'CHALLENGE':+ desc = 'Report Challenge';+ break;+ case 'COMMENT':+ desc = 'Report Comment';+ break;+ case 'USER':+ desc = 'Report User';+ break;+ case 'SOLUTION':+ desc = 'Report Solution';+ break;+ }++ return (+ <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 }[]);++ 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={({ field }) => (+ <FormItem>+ <div className="flex gap-2 items-center">+ <Checkbox+ {...register('derogatory')}+ onCheckedChange={(e) => setValue('derogatory', e as boolean)}+ />+ <div>Derogatory</div>+ </div>+ </FormItem>+ )}+ control={control}+ />+ <FormField+ name='derogatory'+ render={({ field }) => (+ <FormItem>+ <div className="flex gap-2 items-center">+ <Checkbox+ {...register('bullying')}+ onCheckedChange={(e) => setValue('bullying', e as boolean)}+ />+ <div>Bullying</div>+ </div>+ </FormItem>+ )}+ control={control}+ />+ <FormField+ name='hateSpeech'+ render={({ field }) => (+ <FormItem>+ <div className="flex gap-2 items-center">+ <Checkbox+ {...register('hateSpeech')}+ onCheckedChange={(e) => setValue('hateSpeech', e as boolean)}+ />+ <div>Hate speech</div>+ </div>++ </FormItem>+ )}+ control={control}+ />+ <FormField+ name='spam'+ render={({ field }) => (+ <FormItem>+ <div className="flex gap-2 items-center">+ <Checkbox+ {...register('spam')}+ onCheckedChange={(e) => setValue('spam', e as boolean)}+ />+ <div>Spam</div>+ </div>+ </FormItem>+ )}+ control={control}+ />+ <FormField+ name='threat'+ render={({ field }) => (+ <FormItem>+ <div className="flex gap-2 items-center">+ <Checkbox+ {...register('threat')}+ onCheckedChange={(e) => setValue('threat', e as boolean)}+ />+ <div>Threat of violence</div>+ </div>+ </FormItem>+ )}+ control={control}+ />+ {+ reportType === 'CHALLENGE' && (+ <FormField+ name='unclear'+ render={({ field }) => (+ <FormItem>+ <div className="flex gap-2 items-center">+ <Checkbox+ {...register('unclear')}+ onCheckedChange={(e) => setValue('unclear', e as boolean)}+ />+ <div>Unclear</div>+ </div>+ </FormItem>+ )}+ control={control}+ />+ )+ }++ <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>+ )+}\ No newline at end of filediff --git a/src/components/report/report.action.ts b/src/components/report/report.action.tsnew file mode 100644index 00000000..667047b4--- /dev/null+++ b/src/components/report/report.action.ts@@ -0,0 +1,136 @@+"use server";++import { prisma } from "~/server/db";+import type { FormValues } from "../challenge/description";+import { type Report, type Prisma } from "@prisma/client";+import { getServerAuthSession } from "~/server/auth";++export type ReportBase = {+ issues: Prisma.ReportIssueCreateWithoutReportInput[]+}++export type ChallengeReport =+ & Omit<+ Report,+ "id" | "type" | "userId" | "commentId" | "reporterId" | "status" | "solutionId"+ >+ & { type: "CHALLENGE" }+ & ReportBase;++export type UserReport =+ & Omit<+ Report,+ "id" | "type" | "challengeId" | "commentId" | "reporterId" | "status" | "solutionId"+ >+ & { type: "USER" }+ & ReportBase;++export type CommentReport =+ & Omit<+ Report,+ "id" | "type" | "challengeId" | "userId" | "reporterId" | "status" | "solutionId"+ >+ & { type: "COMMENT" }+ & ReportBase;++export type SolutionReport =+ & Omit<+ Report,+ "id" | "type" | "challengeId" | "userId" | "reporterId" | "status" | "commentId"+ >+ & { type: "SOLUTION" }+ & ReportBase;+++/**+ * @param report a report object specific to a user, challenge, or comment report type+ * @returns 'created' if successful, 'not_logged_in' if the user is not logged in, and 'already_exists' if there's a pending report of the same type by the same user.+ */+export async function addReport(+ report: ChallengeReport | UserReport | CommentReport | SolutionReport,+) {+ const reporter = await getServerAuthSession();+ if (!reporter?.user.id) return "not_logged_in";++ let filterData;+ switch (report.type) {+ case "CHALLENGE":+ filterData = {+ challengeId: report.challengeId,+ };+ break;+ case 'COMMENT':+ filterData = {+ commentId: report.commentId,+ };+ break;+ case 'USER':+ filterData = {+ userId: report.userId+ };+ break;+ case 'SOLUTION':+ filterData = {+ solutionId: report.solutionId+ };+ break;+ }+ console.info('HAAAAAAAA', report.type, reporter.user.id, filterData);+ const alreadyReported = await prisma.report.findFirst({+ where: {+ type: report.type,+ status: "PENDING",+ reporterId: reporter.user.id,+ ...filterData,+ },+ });++ if (alreadyReported) return "already_exists";++ await prisma.report.create({+ data: {+ reporterId: reporter.user.id,+ ...report,+ issues: {+ createMany: {+ data: report.issues,+ }+ },+ status: "PENDING",++ },+ });++ return "created";+}++export async function addChallengeReport(+ challengeId: number,+ userId: string,+ data: FormValues,+) {+ if (userId === undefined) return "not_logged_in";++ const report = await prisma.challengeReport.findMany({+ where: {+ challengeId,+ authorId: userId,+ },+ });+ if (report.length > 0) {+ console.info(report);+ return "report_already_made";+ }++ await prisma.challengeReport.create({+ data: {+ challengeId,+ authorId: userId,+ text: data.comments,+ unclear: data.examples,+ derogatory: data.derogatory,+ },+ });++ return "created";+}diff --git a/src/components/user/dashboard/index.tsx b/src/components/user/dashboard/index.tsxindex 4d9f60ee..f9bcfa6a 100644--- a/src/components/user/dashboard/index.tsx+++ b/src/components/user/dashboard/index.tsx@@ -7,6 +7,9 @@ import { SolutionsTab } from '../dashboard/solutions-tab';import type { User } from '@prisma/client';import { getRelativeTime } from '~/utils/relativeTime';import { prisma } from '~/server/db';+import ReportDialog from '~/components/report';+import { ActionMenu } from '~/components/ui/action-menu';+import UserHeader from './user-header';import { Button } from '~/components/ui/button';import Link from 'next/link';import { getServerSession } from 'next-auth';@@ -68,7 +71,7 @@ export default async function Dashboard({ user }: Props) {/></div><div>- <p className="text-3xl font-bold tracking-tight">{user.name}</p>+ <UserHeader user={user} /><pclassName="text-sm italic tracking-tight"title={`Joined ${user.createdAt.toString()}`}diff --git a/src/components/user/dashboard/user-header.tsx b/src/components/user/dashboard/user-header.tsxnew file mode 100644index 00000000..aea82590--- /dev/null+++ b/src/components/user/dashboard/user-header.tsx@@ -0,0 +1,35 @@+'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";++export interface UserHeaderProps {+ user: User;+}++export default function UserHeader({+ user,+}: UserHeaderProps) {+ return (+ <div className="flex gap-4">+ <Text intent="h1">{user.name}</Text>+ <ReportDialog reportType="USER" userId={user.id}>+ <ActionMenu+ items={[+ {+ key: 'report',+ label: 'Report',+ icon: 'Flag',+ }+ ]}+ onChange={() => {+ // do nothing+ }}+ />+ </ReportDialog>+ </div>+ )+}\ No newline at end of file