""" Todo service layer - Business logic for todo operations Implements CRUD operations for todos using PostgreSQL database. This module provides the business logic layer, keeping route handlers thin. Storage: - PostgreSQL database with SQLAlchemy async ORM - Database sessions provided via dependency injection - Transactions managed with commit/rollback - User-scoped todos (filtered by user_id) """ from typing import List, Dict, Optional, Union from datetime import datetime from fastapi import HTTPException from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from models.database_todo import Todo, PriorityEnum, RecurrenceEnum async def create_todo( description: str, user_id: int, priority: Optional[PriorityEnum] = None, tags: Optional[List[str]] = None, due_date: Optional[Union[str, datetime]] = None, recurrence_type: Optional[RecurrenceEnum] = None, reminder_time: Optional[Union[int, str]] = None, db: AsyncSession = None ) -> Dict: """ Create a new todo in the database for authenticated user Args: description: Task description (1-500 characters) user_id: ID of the authenticated user (owner) priority: Task priority level (HIGH, MEDIUM, LOW) tags: Array of tags for categorization due_date: Deadline for the task (ISO 8601 format string) recurrence_type: Recurrence pattern (NONE, DAILY, WEEKLY, MONTHLY) reminder_time: Minutes before due time for notification db: Async database session Returns: Dict containing the created todo with all fields Business Rules: - ID auto-generated by database - completed defaults to False - user_id set to authenticated user's ID - created_at and updated_at set by database defaults - Transaction committed on success, rolled back on error Raises: HTTPException: 500 if database error occurs """ try: # Prepare the todo with all fields todo_data = { "description": description, "user_id": user_id, "completed": False } if priority is not None: todo_data["priority"] = priority if tags is not None: todo_data["tags"] = tags if due_date is not None: # Handle both string and datetime types for due_date if isinstance(due_date, str): # Parse the ISO 8601 date string with proper timezone handling try: # Handle different ISO 8601 formats that may come from the frontend date_str = due_date.strip() # If the date string is empty, set to None if not date_str: todo_data["due_date"] = None else: # Handle 'Z' suffix (UTC timezone) by replacing with '+00:00' if date_str.endswith('Z'): date_str = date_str[:-1] + '+00:00' # Handle the 'T' separator for datetime format if 'T' in date_str: # Replace 'T' with ' ' for fromisoformat compatibility date_str = date_str.replace('T', ' ') # Parse the datetime string parsed_date = datetime.fromisoformat(date_str) todo_data["due_date"] = parsed_date except ValueError as e: raise HTTPException(status_code=400, detail=f"Invalid due_date format. Use ISO 8601 format (e.g., 2023-12-31T18:00:00 or 2023-12-31 18:00:00). Error: {str(e)}") elif isinstance(due_date, datetime): # If it's already a datetime object (from Pydantic model), use it directly todo_data["due_date"] = due_date else: # If it's neither a string nor datetime, set to None todo_data["due_date"] = None if recurrence_type is not None: todo_data["recurrence_type"] = recurrence_type if reminder_time is not None: # Ensure reminder_time is converted to integer if isinstance(reminder_time, str): if reminder_time == "": todo_data["reminder_time"] = 10 # Default value else: try: todo_data["reminder_time"] = int(reminder_time) except ValueError: raise HTTPException(status_code=400, detail="Invalid reminder_time format. Must be a number.") else: # It's already an int todo_data["reminder_time"] = int(reminder_time) todo = Todo(**todo_data) db.add(todo) await db.commit() await db.refresh(todo) return { "id": todo.id, "description": todo.description, "completed": todo.completed, "priority": todo.priority, "tags": todo.tags, "due_date": todo.due_date, "recurrence_type": todo.recurrence_type, "reminder_time": todo.reminder_time, "user_id": todo.user_id, "created_at": todo.created_at, "updated_at": todo.updated_at } except HTTPException: # Re-raise HTTP exceptions (like the invalid date format error) raise except Exception as e: await db.rollback() raise HTTPException(status_code=500, detail=f"Failed to create todo: {str(e)}") async def list_todos( user_id: int, db: AsyncSession, search: Optional[str] = None, status: Optional[str] = None, priority: Optional[str] = None, tags: Optional[str] = None, recurrence: Optional[str] = None, sort_by: Optional[str] = None, order: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None ) -> List[Dict]: """ Return all todos for authenticated user from the database with optional filtering and sorting Args: user_id: ID of the authenticated user db: Async database session search: Keyword to search in description status: Filter by completion status ('completed' or 'incomplete') priority: Filter by priority level ('HIGH', 'MEDIUM', 'LOW') tags: Comma-separated list of tags to filter by recurrence: Filter by recurrence type ('NONE', 'DAILY', 'WEEKLY', 'MONTHLY') sort_by: Sort by field ('priority', 'due_date', 'created_at', 'description', 'id') order: Sort order ('asc' or 'desc') limit: Number of results to return offset: Number of results to skip Returns: List of todo dictionaries with all fields (filtered by user_id) Business Rules: - Returns only todos belonging to authenticated user - Supports optional filtering by search term, status, priority, tags, and recurrence - Supports optional sorting by various fields - Supports optional pagination with limit and offset - Other users' todos are not visible """ try: # Build query with user filter query = select(Todo).where(Todo.user_id == user_id) # Apply search filter (description contains keyword) # For better performance with large datasets, use PostgreSQL full-text search if search: # Using PostgreSQL's full-text search for better performance with large datasets # This approach is more efficient than ilike for large collections from sqlalchemy import text # Use parameterized query to prevent SQL injection query = query.where(text("to_tsvector('english', description) @@ plainto_tsquery('english', :search)")).params(search=search) # Apply status filter if status: if status.lower() == 'completed': query = query.where(Todo.completed == True) elif status.lower() == 'incomplete': query = query.where(Todo.completed == False) # Apply priority filter if priority: try: priority_enum = PriorityEnum[priority.upper()] query = query.where(Todo.priority == priority_enum) except KeyError: raise HTTPException(status_code=400, detail=f"Invalid priority: {priority}") # Apply tags filter if tags: tag_list = tags.split(',') for tag in tag_list: tag = tag.strip() # For JSON array, use contains to check if the tag exists in the tags array query = query.where(Todo.tags.contains([tag])) # Apply recurrence filter if recurrence: try: recurrence_enum = RecurrenceEnum[recurrence.upper()] query = query.where(Todo.recurrence_type == recurrence_enum) except KeyError: raise HTTPException(status_code=400, detail=f"Invalid recurrence type: {recurrence}") # Apply sorting if sort_by: if sort_by == 'priority': order_field = Todo.priority elif sort_by == 'due_date': order_field = Todo.due_date elif sort_by == 'created_at': order_field = Todo.created_at elif sort_by == 'description': order_field = Todo.description elif sort_by == 'id': order_field = Todo.id else: # Default to id if sort_by is invalid order_field = Todo.id # Apply sort order if order and order.lower() == 'desc': query = query.order_by(order_field.desc()) else: query = query.order_by(order_field.asc()) else: # Default sorting query = query.order_by(Todo.id) # Apply limit and offset for pagination if limit is not None: query = query.limit(limit) if offset is not None: query = query.offset(offset) result = await db.execute(query) todos = result.scalars().all() return [ { "id": todo.id, "description": todo.description, "completed": todo.completed, "priority": todo.priority, "tags": todo.tags, "due_date": todo.due_date, "recurrence_type": todo.recurrence_type, "reminder_time": todo.reminder_time, "user_id": todo.user_id, "created_at": todo.created_at, "updated_at": todo.updated_at } for todo in todos ] except HTTPException: # Re-raise HTTP exceptions raise except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to list todos: {str(e)}") async def get_todo(todo_id: int, user_id: int, db: AsyncSession) -> Dict: """ Get a specific todo by ID from the database with ownership verification Args: todo_id: The ID of the todo to retrieve user_id: ID of the authenticated user db: Async database session Returns: Dict containing the todo data Raises: HTTPException: 404 if todo not found HTTPException: 403 if todo belongs to different user HTTPException: 500 if database error occurs Business Rules: - Returns single todo if found and owned by user - Raises 404 if todo does not exist - Raises 403 if user doesn't own the todo """ try: result = await db.execute(select(Todo).where(Todo.id == todo_id)) todo = result.scalar_one_or_none() if todo is None: raise HTTPException(status_code=404, detail=f"Todo {todo_id} not found") # Verify ownership if todo.user_id != user_id: raise HTTPException(status_code=403, detail="Access denied") return { "id": todo.id, "description": todo.description, "completed": todo.completed, "priority": todo.priority, "tags": todo.tags, "due_date": todo.due_date, "recurrence_type": todo.recurrence_type, "reminder_time": todo.reminder_time, "user_id": todo.user_id, "created_at": todo.created_at, "updated_at": todo.updated_at } except HTTPException: raise # Re-raise 404/403 except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to get todo: {str(e)}") async def delete_todo(todo_id: int, user_id: int, db: AsyncSession) -> None: """ Delete a todo permanently with ownership verification Args: todo_id: The ID of the todo to delete user_id: ID of the authenticated user db: Async database session Raises: HTTPException: 404 if todo not found HTTPException: 403 if todo belongs to different user HTTPException: 500 if database error occurs Business Rules: - User must own the todo to delete it - Todo is permanently removed (no soft delete) - Subsequent operations on deleted ID return 404 - Transaction committed on success, rolled back on error """ try: result = await db.execute(select(Todo).where(Todo.id == todo_id)) todo = result.scalar_one_or_none() if todo is None: raise HTTPException(status_code=404, detail=f"Todo {todo_id} not found") # Verify ownership if todo.user_id != user_id: raise HTTPException(status_code=403, detail="Access denied") await db.delete(todo) await db.commit() return None except HTTPException: raise # Re-raise 404/403 except Exception as e: await db.rollback() raise HTTPException(status_code=500, detail=f"Failed to delete todo: {str(e)}") async def update_todo( todo_id: int, user_id: int, db: AsyncSession, description: Optional[str] = None, completed: Optional[bool] = None, priority: Optional[PriorityEnum] = None, tags: Optional[List[str]] = None, due_date: Optional[Union[str, datetime]] = None, recurrence_type: Optional[RecurrenceEnum] = None, reminder_time: Optional[Union[int, str]] = None ) -> Dict: """ Update a todo's fields with ownership verification Args: todo_id: The ID of the todo to update user_id: ID of the authenticated user db: Async database session description: New description (optional) completed: New completion status (optional) priority: New priority level (optional) tags: New tags array (optional) due_date: New due date (optional, ISO 8601 format string) recurrence_type: New recurrence type (optional) reminder_time: New reminder time (optional) Returns: Dict containing the updated todo with all fields Raises: HTTPException: 404 if todo not found HTTPException: 403 if todo belongs to different user HTTPException: 500 if database error occurs Business Rules: - User must own the todo to update it - updated_at timestamp is refreshed by database automatically - At least one field should be provided for update - Partial updates are supported - If completing a recurring task, creates the next instance with updated due date - Transaction committed on success, rolled back on error """ try: result = await db.execute(select(Todo).where(Todo.id == todo_id)) todo = result.scalar_one_or_none() if todo is None: raise HTTPException(status_code=404, detail=f"Todo {todo_id} not found") # Verify ownership if todo.user_id != user_id: raise HTTPException(status_code=403, detail="Access denied") # Check if we're marking this as completed and it's a recurring task was_completed = todo.completed will_be_completed = completed if completed is not None else todo.completed # Update fields if provided if description is not None: todo.description = description if completed is not None: todo.completed = completed if priority is not None: todo.priority = priority if tags is not None: todo.tags = tags if due_date is not None: if isinstance(due_date, str): if due_date: # Only update if not empty string # Parse the ISO 8601 date string with proper timezone handling try: # Handle different ISO 8601 formats that may come from the frontend date_str = due_date.strip() # Handle 'Z' suffix (UTC timezone) by replacing with '+00:00' if date_str.endswith('Z'): date_str = date_str[:-1] + '+00:00' # Handle the 'T' separator for datetime format if 'T' in date_str: # Replace 'T' with ' ' for fromisoformat compatibility date_str = date_str.replace('T', ' ') # Parse the datetime string parsed_date = datetime.fromisoformat(date_str) todo.due_date = parsed_date except ValueError as e: raise HTTPException(status_code=400, detail=f"Invalid due_date format. Use ISO 8601 format (e.g., 2023-12-31T18:00:00 or 2023-12-31 18:00:00). Error: {str(e)}") else: # Set to None if empty string is passed todo.due_date = None elif isinstance(due_date, datetime): # If it's already a datetime object (from Pydantic model), use it directly todo.due_date = due_date else: # If it's neither a string nor datetime, set to None todo.due_date = None if recurrence_type is not None: todo.recurrence_type = recurrence_type if reminder_time is not None: if isinstance(reminder_time, str): if reminder_time == "": # Set to default if empty string is passed todo.reminder_time = 10 else: try: todo.reminder_time = int(reminder_time) except ValueError: raise HTTPException(status_code=400, detail="Invalid reminder_time format. Must be a number.") else: # It's already an int todo.reminder_time = int(reminder_time) await db.commit() await db.refresh(todo) # If the task was marked as completed and it's a recurring task, create the next instance if not was_completed and will_be_completed and todo.recurrence_type != RecurrenceEnum.NONE: # Calculate next due date based on recurrence pattern for the new instance from datetime import datetime, timedelta next_due_date = None if todo.due_date: current_due_date = todo.due_date if todo.recurrence_type == RecurrenceEnum.DAILY: next_due_date = current_due_date + timedelta(days=1) elif todo.recurrence_type == RecurrenceEnum.WEEKLY: next_due_date = current_due_date + timedelta(weeks=1) elif todo.recurrence_type == RecurrenceEnum.MONTHLY: # Calculate next month (handle month overflow) year = current_due_date.year month = current_due_date.month + 1 if month > 12: year += 1 month = 1 # Handle day overflow (e.g., Jan 31 + 1 month should be Feb 28/29, not Mar 3) day = min(current_due_date.day, 28) # Use 28 to avoid month overflow issues next_due_date = current_due_date.replace(year=year, month=month, day=day) # Create a new todo with the same properties but reset completion status new_todo_data = { "description": todo.description, "user_id": todo.user_id, "completed": False, # New recurring task starts as incomplete "priority": todo.priority, "tags": todo.tags, "due_date": next_due_date, "recurrence_type": todo.recurrence_type, "reminder_time": int(todo.reminder_time) if todo.reminder_time is not None else 10, } new_todo = Todo(**new_todo_data) db.add(new_todo) await db.commit() return { "id": todo.id, "description": todo.description, "completed": todo.completed, "priority": todo.priority, "tags": todo.tags, "due_date": todo.due_date, "recurrence_type": todo.recurrence_type, "reminder_time": todo.reminder_time, "user_id": todo.user_id, "created_at": todo.created_at, "updated_at": todo.updated_at } except HTTPException: raise # Re-raise 404/403 except Exception as e: await db.rollback() raise HTTPException(status_code=500, detail=f"Failed to update todo: {str(e)}")