Skip to content

Commit

Permalink
Merge branch 'main' into 16-subscription-animations
Browse files Browse the repository at this point in the history
  • Loading branch information
PauMatas committed Mar 15, 2024
2 parents d11e475 + dd3e1b0 commit c5905fd
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 15 deletions.
2 changes: 2 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ model User {
username String? @unique
generacio Int @default(2020)
image String?
isAdmin Boolean @default(false)
accounts Account[]
sessions Session[]
posts Post[]
Expand Down Expand Up @@ -105,6 +106,7 @@ model Post {
authorId String
tipus TipusType
year Int
NonUploaderAuthorEmail String?
isAnonymous Boolean @default(false)
subject Subject @relation(fields: [subjectId], references: [id])
author User @relation(fields: [authorId], references: [id])
Expand Down
7 changes: 6 additions & 1 deletion src/app/[slug]/submit/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ProfileForm } from "@/components/Form"
import { db } from "@/lib/db"
import { getAuthSession } from "@/lib/auth"
import { notFound } from "next/navigation"

interface PageProps {
Expand All @@ -20,13 +21,17 @@ const page = async ({ params }: PageProps) => {
const startsWithVowel = /^[aeiouàáâãäåæçèéêëìíîïðòóôõöøùúûüýÿ]/i
const subjectNameArticle = subject.name.match(startsWithVowel) ? "d'" : "de "

const session = await getAuthSession()
const isAdmin = session?.user?.isAdmin
if (isAdmin === undefined) return notFound()

return (
<>
<h1 className="text-3xl md:text-4xl h-14">
Penja apunts {subjectNameArticle}
{subject.name}
</h1>
<ProfileForm PreselectedSubject={slug} />
<ProfileForm PreselectedSubject={slug} isAdmin={isAdmin} />
</>
)
}
Expand Down
30 changes: 28 additions & 2 deletions src/app/api/subject/post/create/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export async function POST(req: Request) {

const body = await req.json()

const { pdf, title, assignatura, tipus, anonim } =
const { pdf, title, assignatura, tipus, anonim, authorEmail } =
ApuntsPostValidator.parse(body)

const subject = await db.subject.findFirst({
Expand Down Expand Up @@ -42,14 +42,40 @@ export async function POST(req: Request) {
) {
return new Response("Invalid tipus", { status: 422 })
}
var authorId = session.user.id
var NonUploaderAuthorEmail = null
if (authorEmail !== "Uploader") {
NonUploaderAuthorEmail = session.user.email
const author = await db.user.findFirst({
where: {
email: authorEmail,
},
})
if (author) {
authorId = author.id
} else {
return new Response("Author not found", { status: 404 })
}
}
const existingPost = await db.post.findFirst({
where: {
title: title,
subjectId: subject.id,
authorId: authorId,
},
})
if (existingPost) {
return new Response("Post already exists", { status: 406 })
}
await db.post.create({
data: {
title: title,
content: pdf,
subjectId: subject.id,
authorId: session.user.id,
authorId: authorId,
tipus: tipus as TipusType,
year: year,
NonUploaderAuthorEmail: NonUploaderAuthorEmail,
isAnonymous: anonim,
},
})
Expand Down
12 changes: 7 additions & 5 deletions src/app/submit/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { FC } from "react"
import { getAuthSession } from "@/lib/auth"
import { ProfileForm } from "@/components/Form"
import { notFound } from "next/navigation"

interface pageProps {}

const page: FC<pageProps> = ({}) => {
return <ProfileForm PreselectedSubject={"AllSubjects"} />
const page = async ({}) => {
const session = await getAuthSession()
const isAdmin = session?.user?.isAdmin
if (isAdmin === undefined) return notFound()
return <ProfileForm PreselectedSubject={"AllSubjects"} isAdmin={isAdmin} />
}

export default page
57 changes: 50 additions & 7 deletions src/components/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,17 @@ const formSchema = z.object({
required_error: "Selecciona un tipus.",
}),
anonim: z.boolean().default(false),
authorEmail: z.string({
required_error: "Selecciona un email",
}),
})

export function ProfileForm({
PreselectedSubject,
isAdmin,
}: {
PreselectedSubject: string
isAdmin: boolean
}) {
const router = useRouter()

Expand All @@ -51,23 +56,37 @@ export function ProfileForm({
assignatura,
tipus,
anonim,
authorEmail,
}: ApuntsPostCreationRequest) => {
const payload: ApuntsPostCreationRequest = {
pdf,
title,
assignatura,
tipus,
anonim,
authorEmail,
}
const { data } = await axios.post("/api/subject/post/create", payload)
return data
},
onError: () => {
toast({
title: "Alguna cosa no ha anat bé",
description: "No s'ha pogut crear el post. Torna-ho a provar més tard.",
variant: "destructive",
})
onError: (error) => {
if ((error as any).response && (error as any).response.status === 406) {
return toast({
title: "Ja tens un post amb aquest títol per aquesta assignatura",
description:
"Si creus que això és un error, contacta amb nosaltres a [email protected]",
})
} else {
const Errmessage = (error as Error).message
? (error as Error).message
: "No s'ha pogut crear el post."
toast({
title: Errmessage,
description:
"Alguna cosa ha anat malament, si creus que no hauria d'haver-hi cap problema, contacta amb nosaltres a [email protected]",
variant: "destructive",
})
}
},
onSuccess: (subjectAcronym) => {
router.push(`/${subjectAcronym}`)
Expand All @@ -85,7 +104,12 @@ export function ProfileForm({
if (PreselectedSubject !== "AllSubjects") {
form.setValue("assignatura", PreselectedSubject)
}
}, [PreselectedSubject])
}, [PreselectedSubject, form])
useEffect(() => {
if (!isAdmin) {
form.setValue("authorEmail", "Uploader")
}
}, [form, isAdmin])
async function onSubmit(data: ApuntsPostCreationRequest) {
const [res] = await uploadFiles([data.pdf], "fileUploader")
const payload: ApuntsPostCreationRequest = {
Expand All @@ -94,6 +118,7 @@ export function ProfileForm({
assignatura: data.assignatura,
tipus: data.tipus,
anonim: data.anonim,
authorEmail: data.authorEmail,
}

createApuntsPost(payload)
Expand Down Expand Up @@ -345,6 +370,24 @@ export function ProfileForm({
</FormItem>
)}
/>
{isAdmin && (
<FormField
control={form.control}
name="authorEmail"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="Gràcies per ajudar" {...field} />
</FormControl>
<FormDescription>
Email de l&apos;autor/a dels apunts
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
<Button type="submit" isLoading={form.formState.isSubmitting}>
Submit
</Button>
Expand Down
2 changes: 2 additions & 0 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const authOptions: NextAuthOptions = {
session.user.image = token.picture
session.user.username = token.username
session.user.generacio = token.generacio as string
session.user.isAdmin = token.isAdmin as boolean
}

return session
Expand Down Expand Up @@ -75,6 +76,7 @@ export const authOptions: NextAuthOptions = {
picture: dbUser.image,
username: dbUser.username,
generacio: dbUser.generacio,
isAdmin: dbUser.isAdmin,
}
},
redirect() {
Expand Down
1 change: 1 addition & 0 deletions src/lib/validators/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const ApuntsPostValidator = z.object({
assignatura: z.string().min(2).max(5),
tipus: z.string(),
anonim: z.boolean(),
authorEmail: z.string(), // this is not an email field because it can be set as "Uploader"
})

export type PostCreationRequest = z.infer<typeof PostValidator>
Expand Down
1 change: 1 addition & 0 deletions src/types/next-auth.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ declare module "next-auth" {
id: UserId
username?: string | null
generacio?: string | null
isAdmin?: boolean
}
}
}

0 comments on commit c5905fd

Please sign in to comment.