diff --git a/alembic/versions/20250428_141952_c116fc2a_update_contact_form.py b/alembic/versions/20250428_141952_c116fc2a_update_contact_form.py new file mode 100644 index 0000000..260cbc5 --- /dev/null +++ b/alembic/versions/20250428_141952_c116fc2a_update_contact_form.py @@ -0,0 +1,32 @@ +"""create contact_forms table +Revision ID: 0002 +Revises: 0001 +Create Date: 2023-07-15 12: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..25f0361 100644 --- a/endpoints/contact.post.py +++ b/endpoints/contact.post.py @@ -0,0 +1,25 @@ +from fastapi import APIRouter, Depends, status +from sqlalchemy.orm import Session +from core.database import get_db +from schemas.contact_form import ContactFormCreate +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( + contact_form: ContactFormCreate, + 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. + """ + # Convert Pydantic model to dict for processing + form_data = contact_form.dict() + + # Process the form submission using the helper function + # This will validate fields and handle database operations + result = handle_contact_form_submission(db, form_data) + + return result \ 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..0060ed8 --- /dev/null +++ b/helpers/contact_form_helpers.py @@ -0,0 +1,145 @@ +from typing import Dict, Optional, Any, List, Union +from sqlalchemy.orm import Session +from fastapi import HTTPException +from email_validator import validate_email, EmailNotValidError +from models.contact_form import ContactForm +from schemas.contact_form import ContactFormCreate +from uuid import UUID + +def create_contact_form(db: Session, contact_data: ContactFormCreate) -> ContactForm: + """ + Creates a new contact form submission in the database. + + Args: + db (Session): The database session. + contact_data (ContactFormCreate): The data for the contact form submission. + + Returns: + ContactForm: The newly created contact form object. + """ + db_contact_form = ContactForm(**contact_data.dict()) + db.add(db_contact_form) + db.commit() + db.refresh(db_contact_form) + return db_contact_form + +def validate_contact_form_data(form_data: Dict[str, Any]) -> Dict[str, Union[bool, str]]: + """ + Validates contact form data, checking for required fields and email format. + + Args: + form_data (Dict[str, Any]): The form data to validate. + + Returns: + Dict[str, Union[bool, str]]: A dictionary with validation results: + - 'valid': Boolean indicating if the data is valid + - 'error': Error message if validation fails, None otherwise + """ + # Check for required fields + if not form_data.get('name'): + return {'valid': False, 'error': 'Name is required'} + + if not form_data.get('email'): + return {'valid': False, 'error': 'Email is required'} + + if not form_data.get('message'): + return {'valid': False, 'error': 'Message is required'} + + # Validate email format + try: + validate_email(form_data['email']) + except EmailNotValidError: + return {'valid': False, 'error': 'Invalid email format'} + + return {'valid': True, 'error': None} + +def get_contact_form_by_id(db: Session, contact_form_id: UUID) -> Optional[ContactForm]: + """ + Retrieves a single contact form submission by its ID. + + Args: + db (Session): The database session. + contact_form_id (UUID): The ID of the contact form to retrieve. + + Returns: + Optional[ContactForm]: The contact form object if found, otherwise None. + """ + return db.query(ContactForm).filter(ContactForm.id == contact_form_id).first() + +def get_contact_forms( + db: Session, + skip: int = 0, + limit: int = 100, + email: Optional[str] = None +) -> List[ContactForm]: + """ + Retrieves contact form submissions with optional filtering by email. + + Args: + db (Session): The database session. + skip (int, optional): Number of records to skip. Defaults to 0. + limit (int, optional): Maximum number of records to return. Defaults to 100. + email (Optional[str], optional): Filter by email address. Defaults to None. + + Returns: + List[ContactForm]: A list of contact form objects. + """ + query = db.query(ContactForm) + + if email: + query = query.filter(ContactForm.email == email) + + return query.offset(skip).limit(limit).all() + +def format_contact_form_error(error_message: str) -> Dict[str, str]: + """ + Formats a contact form validation error message for API response. + + Args: + error_message (str): The error message to format. + + Returns: + Dict[str, str]: A dictionary with the formatted error message. + """ + return {"detail": error_message} + +def handle_contact_form_submission( + db: Session, + form_data: Dict[str, Any] +) -> Dict[str, Any]: + """ + Processes a contact form submission with validation. + + Args: + db (Session): The database session. + form_data (Dict[str, Any]): The form data to process. + + Returns: + Dict[str, Any]: Response data with status and message. + + Raises: + HTTPException: If validation fails with a 400 status code. + """ + # Validate form data + validation_result = validate_contact_form_data(form_data) + + if not validation_result['valid']: + raise HTTPException( + status_code=400, + detail=validation_result['error'] + ) + + # Create contact form submission + contact_form_data = ContactFormCreate( + name=form_data['name'], + email=form_data['email'], + message=form_data['message'] + ) + + new_contact_form = create_contact_form(db, contact_form_data) + + return { + "success": True, + "message": "Contact form submitted successfully", + "id": str(new_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..b77d517 --- /dev/null +++ b/models/contact_form.py @@ -0,0 +1,20 @@ +from sqlalchemy import Column, String, DateTime, Text +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) + + # Required 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..67be75f --- /dev/null +++ b/schemas/contact_form.py @@ -0,0 +1,39 @@ +from pydantic import BaseModel, EmailStr, Field +from typing import Optional +from datetime import datetime +from uuid import UUID + +# Base schema for ContactForm, used for inheritance +class ContactFormBase(BaseModel): + name: str = Field(..., description="Contact's name") + email: EmailStr = Field(..., description="Contact's email address") + message: str = Field(..., description="Contact message") + +# Schema for creating a new ContactForm +class ContactFormCreate(ContactFormBase): + pass + +# Schema for updating an existing ContactForm (all fields optional) +class ContactFormUpdate(BaseModel): + name: Optional[str] = Field(None, description="Contact's name") + email: Optional[EmailStr] = Field(None, description="Contact's email address") + message: Optional[str] = Field(None, description="Contact message") + +# Schema for representing a ContactForm in responses +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 more information about your services.", + "created_at": "2023-01-01T12:00:00", + "updated_at": "2023-01-01T12:00:00" + } + } \ No newline at end of file