93 lines
2.7 KiB
Python
93 lines
2.7 KiB
Python
from typing import Dict, Any
|
|
from sqlalchemy.orm import Session
|
|
from fastapi import HTTPException
|
|
from email_validator import validate_email, EmailNotValidError
|
|
from models.contact import Contact
|
|
from schemas.contact import ContactCreate
|
|
|
|
def validate_contact_data(contact_data: Dict[str, Any]) -> Dict[str, str]:
|
|
"""
|
|
Validates contact form data, checking for required fields and email format.
|
|
|
|
Args:
|
|
contact_data (Dict[str, Any]): The contact form data to validate
|
|
|
|
Returns:
|
|
Dict[str, str]: Dictionary of validation errors, empty if validation passes
|
|
"""
|
|
errors = {}
|
|
|
|
# Check required fields
|
|
if not contact_data.get("name"):
|
|
errors["name"] = "Name is required"
|
|
|
|
if not contact_data.get("email"):
|
|
errors["email"] = "Email is required"
|
|
else:
|
|
# Validate email format
|
|
try:
|
|
validate_email(contact_data["email"])
|
|
except EmailNotValidError:
|
|
errors["email"] = "Invalid email format"
|
|
|
|
if not contact_data.get("message"):
|
|
errors["message"] = "Message is required"
|
|
|
|
return errors
|
|
|
|
def create_contact(db: Session, contact_data: ContactCreate) -> Contact:
|
|
"""
|
|
Creates a new contact submission in the database.
|
|
|
|
Args:
|
|
db (Session): The database session
|
|
contact_data (ContactCreate): The validated contact data
|
|
|
|
Returns:
|
|
Contact: The newly created contact object
|
|
"""
|
|
db_contact = Contact(
|
|
name=contact_data.name,
|
|
email=contact_data.email,
|
|
message=contact_data.message
|
|
)
|
|
|
|
db.add(db_contact)
|
|
db.commit()
|
|
db.refresh(db_contact)
|
|
|
|
return db_contact
|
|
|
|
def handle_contact_submission(db: Session, contact_data: Dict[str, Any]) -> Contact:
|
|
"""
|
|
Handles the complete contact form submission process including validation
|
|
and database creation.
|
|
|
|
Args:
|
|
db (Session): The database session
|
|
contact_data (Dict[str, Any]): The raw contact form data
|
|
|
|
Returns:
|
|
Contact: The created contact object
|
|
|
|
Raises:
|
|
HTTPException: If validation fails with a 400 status code and detailed error messages
|
|
"""
|
|
# Validate the contact data
|
|
validation_errors = validate_contact_data(contact_data)
|
|
|
|
if validation_errors:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail={"message": "Validation error", "errors": validation_errors}
|
|
)
|
|
|
|
# Create a ContactCreate instance from the validated data
|
|
contact_create = ContactCreate(
|
|
name=contact_data["name"],
|
|
email=contact_data["email"],
|
|
message=contact_data["message"]
|
|
)
|
|
|
|
# Create the contact in the database
|
|
return create_contact(db, contact_create) |