File size: 8,871 Bytes
2985cd5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | from typing import List, Optional
from datetime import datetime
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.exc import IntegrityError
from ..models.task import Task, TaskCreate, TaskUpdate, TaskRead
from ..utils.error_handlers import NotFoundError, ValidationError, UnauthorizedError
class TaskService:
"""Service class for handling task-related business logic."""
@staticmethod
async def create_task(session: AsyncSession, task_create: TaskCreate, user_id: int) -> TaskRead:
"""
Create a new task for a user.
Args:
session: Database session
task_create: Task creation data
user_id: ID of the user creating the task
Returns:
Created task as TaskRead object
"""
# Create task object with the authenticated user ID
# We need to create the Task object directly since TaskCreate doesn't include user_id
task_data = task_create.model_dump()
task_data['user_id'] = user_id # Add the user_id to the data
db_task = Task.model_validate(task_data)
session.add(db_task)
await session.commit()
await session.refresh(db_task)
# Return as TaskRead object
return TaskRead.model_validate(db_task)
@staticmethod
async def get_task_by_id(session: AsyncSession, task_id: int, user_id: int) -> TaskRead:
"""
Get a specific task by ID for a user.
Args:
session: Database session
task_id: ID of the task to retrieve
user_id: ID of the requesting user
Returns:
Task as TaskRead object
Raises:
NotFoundError: If task doesn't exist
UnauthorizedError: If task exists but doesn't belong to the user
"""
# First, check if the task exists regardless of ownership
statement_exists = select(Task).where(Task.id == task_id)
result_exists = await session.execute(statement_exists)
task_exists = result_exists.scalar_one_or_none()
if not task_exists:
raise NotFoundError(message=f"Task with id {task_id} not found")
# Now check if the user owns the task
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
result = await session.execute(statement)
task = result.scalar_one_or_none()
if not task:
# Task exists but doesn't belong to the user - return 401 Unauthorized
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
return TaskRead.model_validate(task)
@staticmethod
async def get_tasks_for_user(session: AsyncSession, user_id: int, limit: int = 20, offset: int = 0) -> List[TaskRead]:
"""
Get all tasks for a specific user.
Args:
session: Database session
user_id: ID of the user whose tasks to retrieve
limit: Maximum number of tasks to return
offset: Number of tasks to skip
Returns:
List of tasks as TaskRead objects
"""
statement = select(Task).where(Task.user_id == user_id).offset(offset).limit(limit)
result = await session.execute(statement)
tasks = result.scalars().all()
return [TaskRead.model_validate(task) for task in tasks]
@staticmethod
async def update_task(session: AsyncSession, task_id: int, task_update: TaskUpdate, user_id: int) -> TaskRead:
"""
Update a specific task for a user.
Args:
session: Database session
task_id: ID of the task to update
task_update: Task update data
user_id: ID of the requesting user
Returns:
Updated task as TaskRead object
Raises:
NotFoundError: If task doesn't exist
UnauthorizedError: If task exists but doesn't belong to the user
"""
# First, check if the task exists regardless of ownership
statement_exists = select(Task).where(Task.id == task_id)
result_exists = await session.execute(statement_exists)
task_exists = result_exists.scalar_one_or_none()
if not task_exists:
raise NotFoundError(message=f"Task with id {task_id} not found")
# Now check if the user owns the task
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
result = await session.execute(statement)
task = result.scalar_one_or_none()
if not task:
# Task exists but doesn't belong to the user - return 401 Unauthorized
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
# Update task fields with provided values
update_data = task_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(task, field, value)
task.updated_at = datetime.utcnow()
session.add(task)
await session.commit()
await session.refresh(task)
return TaskRead.model_validate(task)
@staticmethod
async def delete_task(session: AsyncSession, task_id: int, user_id: int) -> bool:
"""
Delete a specific task for a user.
Args:
session: Database session
task_id: ID of the task to delete
user_id: ID of the requesting user
Returns:
True if task was deleted, False otherwise
Raises:
NotFoundError: If task doesn't exist
UnauthorizedError: If task exists but doesn't belong to the user
"""
# First, check if the task exists regardless of ownership
statement_exists = select(Task).where(Task.id == task_id)
result_exists = await session.execute(statement_exists)
task_exists = result_exists.scalar_one_or_none()
if not task_exists:
raise NotFoundError(message=f"Task with id {task_id} not found")
# Now check if the user owns the task
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
result = await session.execute(statement)
task = result.scalar_one_or_none()
if not task:
# Task exists but doesn't belong to the user - return 401 Unauthorized
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
await session.delete(task)
await session.commit()
return True
@staticmethod
async def toggle_task_completion(session: AsyncSession, task_id: int, user_id: int) -> TaskRead:
"""
Toggle the completion status of a specific task.
Args:
session: Database session
task_id: ID of the task to toggle
user_id: ID of the requesting user
Returns:
Updated task as TaskRead object
Raises:
NotFoundError: If task doesn't exist
UnauthorizedError: If task exists but doesn't belong to the user
"""
# First, check if the task exists regardless of ownership
statement_exists = select(Task).where(Task.id == task_id)
result_exists = await session.execute(statement_exists)
task_exists = result_exists.scalar_one_or_none()
if not task_exists:
raise NotFoundError(message=f"Task with id {task_id} not found")
# Now check if the user owns the task
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
result = await session.execute(statement)
task = result.scalar_one_or_none()
if not task:
# Task exists but doesn't belong to the user - return 401 Unauthorized
raise UnauthorizedError(message=f"Access denied: Task with id {task_id} does not belong to you")
# Toggle the completion status
task.completed = not task.completed
task.updated_at = datetime.utcnow()
session.add(task)
await session.commit()
await session.refresh(task)
return TaskRead.model_validate(task)
@staticmethod
async def verify_task_ownership(session: AsyncSession, task_id: int, user_id: int) -> bool:
"""
Verify if a user owns a specific task.
Args:
session: Database session
task_id: ID of the task to check
user_id: ID of the user to check ownership for
Returns:
True if the user owns the task, False otherwise
"""
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
result = await session.execute(statement)
task = result.scalar_one_or_none()
return task is not None |