From 3181207a4fd5d7601b6bd40df77ea4c8b6a5fc4f Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Mon, 28 Apr 2025 19:58:48 +0000 Subject: [PATCH] feat: add contact form submission endpoint with validation --- ...428_195813_92cb49ef_update_contact_form.py | 32 +++++ endpoints/contact.post.py | 19 +++ helpers/contact_form_helpers.py | 128 ++++++++++++++++++ models/contact_form.py | 20 +++ requirements.txt | 4 + schemas/contact_form.py | 35 +++++ 6 files changed, 238 insertions(+) create mode 100644 alembic/versions/20250428_195813_92cb49ef_update_contact_form.py create mode 100644 helpers/contact_form_helpers.py create mode 100644 models/contact_form.py create mode 100644 schemas/contact_form.py diff --git a/alembic/versions/20250428_195813_92cb49ef_update_contact_form.py b/alembic/versions/20250428_195813_92cb49ef_update_contact_form.py new file mode 100644 index 0000000..f6dac8b --- /dev/null +++ b/alembic/versions/20250428_195813_92cb49ef_update_contact_form.py @@ -0,0 +1,32 @@ +"""Initial creation of ContactForm +Revision ID: 0002 +Revises: 0001 +Create Date: 2023-11-02 10:00:00.000000 +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0002' +down_revision = '0001' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'contact_forms', + sa.Column('id', sa.String(36), primary_key=True), + sa.Column('name', sa.String(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('message', sa.Text(), nullable=False), + sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()), + sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now()) + ) + op.create_index(op.f('ix_contact_forms_email'), 'contact_forms', ['email'], unique=False) + + +def downgrade(): + op.drop_index(op.f('ix_contact_forms_email'), table_name='contact_forms') + op.drop_table('contact_forms') \ No newline at end of file diff --git a/endpoints/contact.post.py b/endpoints/contact.post.py index e69de29..f896e18 100644 --- a/endpoints/contact.post.py +++ b/endpoints/contact.post.py @@ -0,0 +1,19 @@ +from fastapi import APIRouter, Depends, status +from sqlalchemy.orm import Session +from typing import Dict, Any +from core.database import get_db +from helpers.contact_form_helpers import handle_contact_form_submission + +router = APIRouter() + +@router.post("/contact", status_code=status.HTTP_201_CREATED) +async def submit_contact_form( + form_data: Dict[str, Any], + db: Session = Depends(get_db) +): + """ + Submit a contact form with name, email, and message. + All fields are required and email must be in valid format. + """ + response = handle_contact_form_submission(db=db, form_data=form_data) + return response \ No newline at end of file diff --git a/helpers/contact_form_helpers.py b/helpers/contact_form_helpers.py new file mode 100644 index 0000000..6279c1f --- /dev/null +++ b/helpers/contact_form_helpers.py @@ -0,0 +1,128 @@ +from typing import Optional, Dict, Any +from sqlalchemy.orm import Session +from fastapi import HTTPException +from email_validator import validate_email, EmailNotValidError +from uuid import UUID + +from models.contact_form import ContactForm +from schemas.contact_form import ContactFormCreate + +def validate_contact_form_data(form_data: Dict[str, Any]) -> Dict[str, str]: + """ + Validates contact form data and returns error messages for invalid fields. + + Args: + form_data (Dict[str, Any]): The contact form data to validate + + Returns: + Dict[str, str]: Dictionary of field errors, empty if validation passes + """ + errors = {} + + # Check for required fields + if not form_data.get("name"): + errors["name"] = "Name is required" + + # Validate email + if not form_data.get("email"): + errors["email"] = "Email is required" + else: + try: + validate_email(form_data["email"]) + except EmailNotValidError: + errors["email"] = "Invalid email format" + + # Check message + if not form_data.get("message"): + errors["message"] = "Message is required" + + return errors + +def create_contact_form(db: Session, form_data: ContactFormCreate) -> ContactForm: + """ + Creates a new contact form submission in the database. + + Args: + db (Session): The database session + form_data (ContactFormCreate): The validated form data + + Returns: + ContactForm: The newly created contact form object + """ + db_contact_form = ContactForm( + name=form_data.name, + email=form_data.email, + message=form_data.message + ) + + db.add(db_contact_form) + db.commit() + db.refresh(db_contact_form) + + return db_contact_form + +def get_contact_form_by_id(db: Session, form_id: UUID) -> Optional[ContactForm]: + """ + Retrieves a contact form submission by its ID. + + Args: + db (Session): The database session + form_id (UUID): The ID of the contact form to retrieve + + Returns: + Optional[ContactForm]: The contact form if found, otherwise None + """ + return db.query(ContactForm).filter(ContactForm.id == form_id).first() + +def format_validation_errors(errors: Dict[str, str]) -> Dict[str, Any]: + """ + Formats validation errors for the API response. + + Args: + errors (Dict[str, str]): Dictionary of field errors + + Returns: + Dict[str, Any]: Formatted error response + """ + return { + "status": "error", + "message": "Validation failed", + "errors": errors + } + +def handle_contact_form_submission(db: Session, form_data: Dict[str, Any]) -> Dict[str, Any]: + """ + Validates and processes a contact form submission. + + Args: + db (Session): The database session + form_data (Dict[str, Any]): The raw form data + + Returns: + Dict[str, Any]: Response data + + Raises: + HTTPException: If validation fails + """ + # Validate form data + validation_errors = validate_contact_form_data(form_data) + + if validation_errors: + error_response = format_validation_errors(validation_errors) + raise HTTPException(status_code=400, detail=error_response) + + # Create validated form data object + form_create = ContactFormCreate( + name=form_data["name"], + email=form_data["email"], + message=form_data["message"] + ) + + # Save to database + contact_form = create_contact_form(db, form_create) + + return { + "status": "success", + "message": "Contact form submitted successfully", + "id": str(contact_form.id) + } \ No newline at end of file diff --git a/models/contact_form.py b/models/contact_form.py new file mode 100644 index 0000000..e5f7a48 --- /dev/null +++ b/models/contact_form.py @@ -0,0 +1,20 @@ +from sqlalchemy import Column, String, Text, DateTime +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.sql import func +from core.database import Base +import uuid + +class ContactForm(Base): + __tablename__ = "contact_forms" + + # Primary key using UUID + id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + + # Form fields + name = Column(String, nullable=False) + email = Column(String, nullable=False, index=True) + message = Column(Text, nullable=False) + + # Timestamps + created_at = Column(DateTime, default=func.now()) + updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 596e6f3..ec13e88 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,3 +7,7 @@ sqlalchemy>=1.4.0 python-dotenv>=0.19.0 bcrypt>=3.2.0 alembic>=1.13.1 +email_validator +jose +passlib +pydantic diff --git a/schemas/contact_form.py b/schemas/contact_form.py new file mode 100644 index 0000000..3f94414 --- /dev/null +++ b/schemas/contact_form.py @@ -0,0 +1,35 @@ +from pydantic import BaseModel, Field, EmailStr +from typing import Optional +from datetime import datetime +from uuid import UUID + +class ContactFormBase(BaseModel): + name: str = Field(..., description="Name of the person submitting the form") + email: EmailStr = Field(..., description="Email address of the person submitting the form") + message: str = Field(..., description="Message content from the contact form") + +class ContactFormCreate(ContactFormBase): + pass + +class ContactFormUpdate(BaseModel): + name: Optional[str] = Field(None, description="Name of the person submitting the form") + email: Optional[EmailStr] = Field(None, description="Email address of the person submitting the form") + message: Optional[str] = Field(None, description="Message content from the contact form") + +class ContactFormSchema(ContactFormBase): + id: UUID + created_at: datetime + updated_at: datetime + + class Config: + orm_mode = True + schema_extra = { + "example": { + "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", + "name": "John Doe", + "email": "john.doe@example.com", + "message": "I would like to inquire about your services.", + "created_at": "2023-01-01T12:00:00", + "updated_at": "2023-01-01T12:00:00" + } + } \ No newline at end of file