58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
import { db } from "@/db";
|
|
import { forms } from "@/db/schema";
|
|
import { FormFillerClient } from "./client";
|
|
import { getServerSession } from "next-auth";
|
|
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export default async function FormsSubmitPage() {
|
|
const session = await getServerSession(authOptions);
|
|
const discordId = (session?.user as { discordId?: string })?.discordId;
|
|
|
|
// Automatically retrieve the first form, or create a default one
|
|
let form = await db.query.forms.findFirst();
|
|
if (!form) {
|
|
const [newForm] = await db
|
|
.insert(forms)
|
|
.values({
|
|
title: "Erika Custom Form",
|
|
description: "Welcome! Please fill out the form below.",
|
|
})
|
|
.returning();
|
|
form = newForm;
|
|
}
|
|
|
|
const questionsList = await db.query.questions.findMany({
|
|
where: (q, { eq }) => eq(q.formId, form.id),
|
|
orderBy: (q, { asc }) => [asc(q.displayOrder)],
|
|
});
|
|
|
|
let initialAnswers: Record<string, string> = {};
|
|
if (discordId) {
|
|
const existingSubmission = await db.query.submissions.findFirst({
|
|
where: (s, { eq, and }) =>
|
|
and(eq(s.formId, form.id), eq(s.userDiscordId, discordId)),
|
|
});
|
|
|
|
if (existingSubmission) {
|
|
const answersList = await db.query.answers.findMany({
|
|
where: (a, { eq }) => eq(a.submissionId, existingSubmission.id),
|
|
});
|
|
for (const a of answersList) {
|
|
initialAnswers[a.questionId] = a.value;
|
|
}
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="max-w-2xl mx-auto p-4 md:p-6 space-y-6">
|
|
<FormFillerClient
|
|
form={form}
|
|
questions={questionsList}
|
|
initialAnswers={initialAnswers}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|