Skip to content

Add form submission #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/src/exceptions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
class FormwiseError(Exception):
"""Base exception for all formwise exceptions."""

def __init__(self, message: str = ""):
def __init__(self, message: str | dict = ""):
self.message = message
super().__init__(self.message)

Expand Down
4 changes: 2 additions & 2 deletions backend/src/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from src.config import settings

from .form import Form
from .form import Form, FormResponse
from .user import User


Expand All @@ -14,7 +14,7 @@ class Config(BaseModel):
max_responses: int = settings.MAX_RESPONSES


DOCUMENT_MODELS = [User, Form]
DOCUMENT_MODELS = [User, Form, FormResponse]

__all__ = [
"Config",
Expand Down
7 changes: 6 additions & 1 deletion backend/src/models/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,12 @@ class URLField(BaseField):
type: Literal[FieldType.URL] = FieldType.URL

def validate_answer(self, answer: str) -> str:
return AnyHttpUrl(answer).unicode_string()
try:
return AnyHttpUrl(answer).unicode_string()
except ValueError as err:
raise ValueError(
"Answer must be a valid URL. Example: https://example.com"
) from err


# Type alias
Expand Down
27 changes: 23 additions & 4 deletions backend/src/models/form.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Annotated
from typing import TYPE_CHECKING, Annotated, Any
from uuid import uuid4

from beanie import Document, Link
from pydantic import BaseModel, Field, field_validator
Expand Down Expand Up @@ -67,6 +68,23 @@ class FormRead(BaseModel):
created_at: datetime


class FormSubmission(BaseModel):
"""Request model for submitting a form."""

answers: dict[str, Any]


class FormResponse(Document, FormSubmission):
"""Database model for a form submission"""

class Settings:
name = "responses"

id: Annotated[str, Field(default_factory=lambda: uuid4().hex)]
form: Link[Form]
created_at: Annotated[datetime, Field(default_factory=lambda: datetime.now(tz=UTC))]


class FormOverview(BaseModel):
"""Response model for a form (overview)."""

Expand All @@ -77,7 +95,7 @@ class FormOverview(BaseModel):
created_at: datetime

@staticmethod
def from_forms(form_list: list[Form]) -> list["FormOverview"]:
async def from_forms(form_list: list[Form]) -> list["FormOverview"]:
"""Creates a list of FormOverview instances from a list of Form instances,
sorted by creation date in descending order.

Expand All @@ -91,8 +109,9 @@ def from_forms(form_list: list[Form]) -> list["FormOverview"]:
return [
FormOverview(
**form.model_dump(),
# TODO: Add response count
response_count=0,
response_count=await FormResponse.find(
FormResponse.form.id == form.id
).count(),
)
for form in form_list
]
Expand Down
67 changes: 61 additions & 6 deletions backend/src/routers/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
FormGenerate,
FormOverview,
FormRead,
FormResponse,
FormSubmission,
)
from src.models.user import User
from src.utils.form_generation import FormGenerator
Expand Down Expand Up @@ -52,7 +54,7 @@
new_form = Form(**form.model_dump(), creator=user)
await new_form.create()

logger.info('Created Form: "%s" for User: %s', new_form.title, user)
logger.info('Created Form: "%s" for User: %s', new_form.id, user)
return new_form


Expand Down Expand Up @@ -100,7 +102,7 @@
"""Retrieves a form."""
form = await Form.get(form_id, fetch_links=True)
if not form:
raise EntityNotFoundError("Form not found")
raise EntityNotFoundError("Form not found.")

return FormRead(**form.model_dump())

Expand All @@ -113,14 +115,17 @@
"""Deletes a form and its submissions (if owned by the user)."""
form = await Form.get(form_id, fetch_links=True)
if not form:
raise EntityNotFoundError("Form not found")
raise EntityNotFoundError("Form not found.")

if form.creator.id != user.id:
raise ForbiddenError("Not authorized to delete this form.")

# Delete form responses
await FormResponse.find(FormResponse.form.id == form.id).delete()
# Delete form
await form.delete()
# TODO: Implement deletion of form submissions
logger.info('Deleted Form: "%s" for User: %s', form.title, user)

logger.info('Deleted Form: "%s" for User: %s', form.id, user)


@router.get(
Expand All @@ -130,4 +135,54 @@
)
async def get_forms(user: CurrentUserWithLinks):
"""Retrieves a list of user's forms."""
return FormOverview.from_forms(user.forms)
return await FormOverview.from_forms(user.forms)


@router.post(
"/{form_id}/submit",
status_code=status.HTTP_200_OK,
)
async def submit_response(form_id: str, submission: FormSubmission):
"""Submits a form response."""
form = await Form.get(form_id)
if not form:
raise EntityNotFoundError("Form not found.")

Check warning on line 149 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L147-L149

Added lines #L147 - L149 were not covered by tests

if not form.is_active:
raise ForbiddenError("Form is not active.")

Check warning on line 152 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L151-L152

Added lines #L151 - L152 were not covered by tests

# Validate submission
invalid_fields = {}
validated_answers = {}

Check warning on line 156 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L155-L156

Added lines #L155 - L156 were not covered by tests

for field in form.fields:
answer = submission.answers.get(field.tag)

Check warning on line 159 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L158-L159

Added lines #L158 - L159 were not covered by tests

if not answer:
if field.required:
invalid_fields[field.tag] = "Field is required."

Check warning on line 163 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L161-L163

Added lines #L161 - L163 were not covered by tests
else:
validated_answers[field.tag] = None
continue

Check warning on line 166 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L165-L166

Added lines #L165 - L166 were not covered by tests

try:
validated_answers[field.tag] = field.validate_answer(answer)
except ValueError as err:
invalid_fields[field.tag] = str(err)

Check warning on line 171 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L168-L171

Added lines #L168 - L171 were not covered by tests

if invalid_fields:
raise BadRequestError(invalid_fields)

Check warning on line 174 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L173-L174

Added lines #L173 - L174 were not covered by tests

# Save form response
new_response = FormResponse(form=form, answers=validated_answers)
await new_response.create()
logger.info("Submitted response for form: %s", form.id)

Check warning on line 179 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L177-L179

Added lines #L177 - L179 were not covered by tests

# Check if form response limit has been reached
response_count = await FormResponse.find(FormResponse.form.id == form.id).count()
if response_count >= settings.MAX_RESPONSES:
form.is_active = False
await form.save()
logger.info("Form response limit reached, disabling form: %s", form.id)

Check warning on line 186 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L182-L186

Added lines #L182 - L186 were not covered by tests

return {"detail": "Form response submitted successfully."}

Check warning on line 188 in backend/src/routers/form.py

View check run for this annotation

Codecov / codecov/patch

backend/src/routers/form.py#L188

Added line #L188 was not covered by tests
38 changes: 22 additions & 16 deletions frontend/app/(console)/forms/[formId]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"use client";

import FormResponses from "@/components/form/form-responses";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import FormWise from "@/components/form/formwise";
import { useForm } from "@/hooks/use-forms";
import { useRouter } from "next/navigation";
import FormWise from "@/components/form/formwise";
import FormResponses from "@/components/form/form-responses";

interface FormPageProps {
params: {
Expand All @@ -25,20 +25,26 @@ export default function FormPage({ params }: FormPageProps) {

return (
<div className="container mx-auto p-4">
<Tabs defaultValue="preview">
<div className="flex justify-start md:justify-center">
<TabsList>
<TabsTrigger value="preview">Preview</TabsTrigger>
<TabsTrigger value="responses">Responses</TabsTrigger>
</TabsList>
</div>
<TabsContent value="preview">
<FormWise form={form!} preview />
</TabsContent>
<TabsContent value="responses">
<FormResponses formId={params.formId} />
</TabsContent>
</Tabs>
<section className="flex justify-start md:justify-center mb-4">
<h1 className="text-2xl font-bold">{form?.title}</h1>
</section>

<main>
<Tabs defaultValue="preview">
<div className="flex justify-start md:justify-center">
<TabsList>
<TabsTrigger value="preview">Preview</TabsTrigger>
<TabsTrigger value="responses">Responses</TabsTrigger>
</TabsList>
</div>
<TabsContent value="preview">
<FormWise form={form!} preview />
</TabsContent>
<TabsContent value="responses">
<FormResponses formId={params.formId} />
</TabsContent>
</Tabs>
</main>
</div>
);
}
Expand Down
37 changes: 37 additions & 0 deletions frontend/app/(submission)/f/[formId]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"use client";

import { useForm } from "@/hooks/use-forms";
import { useRouter } from "next/navigation";

import FormWise from "@/components/form/formwise";
import Logo from "@/components/logo";
import Loader from "@/components/layout/loader";

interface FormSubmissionPageProps {
params: {
formId: string;
};
}

export default function FormSubmissionPage({
params,
}: FormSubmissionPageProps) {
const { data: form, isLoading, error } = useForm(params.formId);
const router = useRouter();

if (isLoading) {
return <Loader />;
} else if (error) {
router.push("/404");
return null;
}

return (
<div className="container mx-auto px-4">
<FormWise form={form!} />
<div className="flex justify-center mt-8 mb-4">
<Logo target_blank />
</div>
</div>
);
}
45 changes: 45 additions & 0 deletions frontend/app/(submission)/success/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"use client";

import { useRouter } from "next/navigation";
import { CheckIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";

export default function SuccessPage() {
const router = useRouter();

const handleSubmitAnother = () => {
router.back();
};

return (
<div className="min-h-[calc(100vh-7rem)] flex items-center justify-center container mx-auto p-4">
<Card className="w-full max-w-md text-center">
<CardHeader className="flex flex-col items-center space-y-4">
<CheckIcon className="text-primary" size={48} strokeWidth={2} />
<CardTitle>Success</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-muted-foreground">
Your response has been recorded.
</p>
</CardContent>
<CardFooter>
<Button
variant="link"
className="w-full"
onClick={handleSubmitAnother}
>
Submit Another Response
</Button>
</CardFooter>
</Card>
</div>
);
}
4 changes: 0 additions & 4 deletions frontend/components/dashboard/form-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
import { Button } from "@/components/ui/button";
import {
MoreVerticalIcon,
TypeIcon,
Share2Icon,
Trash2Icon,
ClockIcon,
Expand Down Expand Up @@ -82,9 +81,6 @@ export default function FormCard({ form, maxResponses }: FormCardProps) {
<DropdownMenuItem onClick={handleShare}>
<Share2Icon className="mr-2 h-4 w-4" /> Share
</DropdownMenuItem>
<DropdownMenuItem>
<TypeIcon className="mr-2 h-4 w-4" /> Rename
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="focus:text-destructive"
Expand Down
Loading
Loading