79 lines
2.2 KiB
TypeScript
79 lines
2.2 KiB
TypeScript
import { db } from "@/db";
|
|
import { FormFillerClient } from "../client";
|
|
import { getServerSession } from "next-auth";
|
|
import { authOptions } from "@/lib/auth-options";
|
|
import { notFound } from "next/navigation";
|
|
import LoginDialog from "@/components/login-dialog";
|
|
import { canAccessForm, getSessionDiscordId } from "@/lib/auth";
|
|
import { RealtimeRefresh } from "@/components/realtime-refresh";
|
|
import {
|
|
decodeCheckboxAnswer,
|
|
type FormAnswerValue,
|
|
} from "@/lib/form-answer-values";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export default async function FormsSubmitPage(
|
|
props: {
|
|
params: Promise<{ id: string }>;
|
|
}
|
|
) {
|
|
const params = await props.params;
|
|
const session = await getServerSession(authOptions);
|
|
const discordId = getSessionDiscordId(session);
|
|
|
|
const form = await db.query.forms.findFirst({
|
|
where: (f, { eq }) => eq(f.id, params.id),
|
|
});
|
|
|
|
if (!form) {
|
|
return notFound();
|
|
}
|
|
|
|
if (!discordId) {
|
|
return <LoginDialog />;
|
|
}
|
|
|
|
if (!(await canAccessForm(form, discordId))) {
|
|
return notFound();
|
|
}
|
|
|
|
const questionsList = await db.query.questions.findMany({
|
|
where: (q, { eq }) => eq(q.formId, form.id),
|
|
orderBy: (q, { asc }) => [asc(q.displayOrder)],
|
|
});
|
|
|
|
const existingSubmission = await db.query.submissions.findFirst({
|
|
where: (s, { eq, and }) =>
|
|
and(eq(s.formId, form.id), eq(s.userDiscordId, discordId)),
|
|
});
|
|
|
|
const initialAnswers: Record<string, FormAnswerValue> = {};
|
|
if (existingSubmission) {
|
|
const answersList = await db.query.answers.findMany({
|
|
where: (a, { eq }) => eq(a.submissionId, existingSubmission.id),
|
|
});
|
|
const questionTypes = new Map(questionsList.map((question) => [question.id, question.type]));
|
|
for (const answer of answersList) {
|
|
initialAnswers[answer.questionId] =
|
|
questionTypes.get(answer.questionId) === "checkbox"
|
|
? decodeCheckboxAnswer(answer.value)
|
|
: answer.value;
|
|
}
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<RealtimeRefresh topic="forms" formId={form.id} />
|
|
<div className="mx-auto max-w-2xl">
|
|
<FormFillerClient
|
|
form={form}
|
|
questions={questionsList}
|
|
initialAnswers={initialAnswers}
|
|
hasSubmission={Boolean(existingSubmission)}
|
|
/>
|
|
</div>
|
|
</>
|
|
);
|
|
}
|