mira tengo esto: """ Service layer for Task operations. This module contains the…
- User
mira tengo esto:
""" Service layer for Task operations.
This module contains the business logic for managing tasks. It interacts with the
TaskModelfrom the database and uses theTaskPydantic model for data validation. """from datetime import datetime, date from typing import Optional, List from peewee import DoesNotExist from fastapi import HTTPException, status
from config.database import ( # pylint: disable=import-error TaskModel, # pylint: disable=import-error StatusModel, # pylint: disable=import-error UserModel, # pylint: disable=import-error ) # pylint: disable=import-error from models.task import TaskCreate, TaskRead, TaskUpdate # pylint: disable=import-error from models.change import Change # pylint: disable=import-error from models.user import UserRead # pylint: disable=import-error
class TaskService: """Service layer for Task operations"""
@staticmethod def create_task(task: TaskCreate, current_user: UserRead) -> TaskRead: """ Create a new task. Args: task (TaskCreate): The task data for creation. current_user (UserRead): The current authenticated user. Returns: TaskRead: The created task instance. Raises: ValueError: If the status or user does not exist. HTTPException: If the user does not have permission to assign tasks. """ try: status_instance = StatusModel.get_by_id(task.status_id) except DoesNotExist as exc: raise ValueError(f"Status with id {task.status_id} not found") from exc # Asignar al usuario actual si no se especifica otro user_id = task.user_id if task.user_id else current_user.id if ( task.user_id and task.user_id != current_user.id and current_user.role.name != "Administrator" ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You do not have permission to assign tasks to other users.", ) try: user_instance = UserModel.get_by_id(user_id) except DoesNotExist as exc: raise ValueError(f"User with id {user_id} not found") from exc task_instance = TaskModel.create( title=task.title, description=task.description, date_of_creation=datetime.utcnow().date(), expiration_date=task.expiration_date, status=status_instance, user=user_instance, is_favorite=task.is_favorite or False, ) return TaskRead.from_orm(task_instance) @staticmethod def get_task_by_id(task_id: int, current_user: UserRead) -> Optional[TaskRead]: """ Retrieve a task by ID. Args: task_id (int): The ID of the task to retrieve. current_user (UserRead): The current authenticated user. Returns: Optional[TaskRead]: The task instance if found, else None. Raises: HTTPException: If the user does not have permission to view the task. """ try: task_instance = TaskModel.get_by_id(task_id) if ( task_instance.user.id != current_user.id and current_user.role.name != "Administrator" ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You do not have permission to view this task", ) return TaskRead.from_orm(task_instance) except DoesNotExist: return None @staticmethod def update_task( task_id: int, task: TaskUpdate, current_user: UserRead ) -> Optional[TaskRead]: """ Update an existing task by ID. Args: task_id (int): The ID of the task to update. task (TaskUpdate): The new task data. current_user (UserRead): The current authenticated user. Returns: Optional[TaskRead]: The updated task instance if successful, else None. Raises: HTTPException: If the user does not have permission to update the task. ValueError: If the status or user does not exist. """ try: task_instance = TaskModel.get_by_id(task_id) if ( task_instance.user.id != current_user.id and current_user.role.name != "Administrator" ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You do not have permission to update this task", ) if task.status_id: try: status_instance = StatusModel.get_by_id(task.status_id) task_instance.status = status_instance except DoesNotExist as exc: raise ValueError( f"Status with id {task.status_id} not found" ) from exc if task.user_id: if ( task.user_id != current_user.id and current_user.role.name != "Administrator" ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You do not have permission to assign tasks to other users", ) try: user_instance = UserModel.get_by_id(task.user_id) task_instance.user = user_instance except DoesNotExist as exc: raise ValueError(f"User with id {task.user_id} not found") from exc updated = False changes = [] if task.title and task.title != task_instance.title: changes.append(("title", task_instance.title, task.title)) task_instance.title = task.title updated = True if task.description and task.description != task_instance.description: changes.append( ("description", task_instance.description, task.description) ) task_instance.description = task.description updated = True if ( task.expiration_date and task.expiration_date != task_instance.expiration_date ): changes.append( ( "expiration_date", str(task_instance.expiration_date), str(task.expiration_date), ) ) task_instance.expiration_date = task.expiration_date updated = True if ( task.is_favorite is not None and task.is_favorite != task_instance.is_favorite ): changes.append( ( "is_favorite", str(task_instance.is_favorite), str(task.is_favorite), ) ) task_instance.is_favorite = task.is_favorite updated = True if updated: task_instance.save() for field, old, new in changes: Change.create( task=task_instance, timestamp=datetime.utcnow(), field_changed=field, old_value=old, new_value=new, ) return TaskRead.from_orm(task_instance) except DoesNotExist: return None @staticmethod def delete_task(task_id: int, current_user: UserRead) -> bool: """ Delete a task by ID. Args: task_id (int): The ID of the task to delete. current_user (UserRead): The current authenticated user. Returns: bool: True if the task was deleted, else False. Raises: HTTPException: If the user does not have permission to delete the task. """ try: task_instance = TaskModel.get_by_id(task_id) if ( task_instance.user.id != current_user.id and current_user.role.name != "Administrator" ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You do not have permission to delete this task", ) task_instance.delete_instance() return True except DoesNotExist: return False @staticmethod def get_all_tasks( current_user: UserRead, status_id: Optional[int] = None, expiration_date: Optional[date] = None, ) -> List[TaskRead]: """ Retrieve all tasks with optional filtering by status and expiration date. Args: current_user (UserRead): The current authenticated user. status_id (Optional[int], optional): Filter by status ID. expiration_date (Optional[date], optional): Filter by expiration date. Returns: List[TaskRead]: A list of task instances. """ query = TaskModel.select() if current_user.role.name != "Administrator": query = query.where(TaskModel.user.id == current_user.id) if status_id: query = query.where(TaskModel.status.id == status_id) if expiration_date: query = query.where(TaskModel.expiration_date == expiration_date) tasks = query.execute() return [TaskRead.from_orm(task) for task in tasks] @staticmethod def mark_as_favorite(task_id: int, current_user: UserRead) -> Optional[TaskRead]: """ Mark a task as favorite. Args: task_id (int): The ID of the task to mark. current_user (UserRead): The current authenticated user. Returns: Optional[TaskRead]: The updated task instance if successful, else None. Raises: HTTPException: If the user does not have permission to mark the task. """ try: task_instance = TaskModel.get_by_id(task_id) if ( task_instance.user.id != current_user.id and current_user.role.name != "Administrator" ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You do not have permission to mark this task as a favorite", ) task_instance.is_favorite = True task_instance.save() return TaskRead.from_orm(task_instance) except DoesNotExist: return None @staticmethod def unmark_as_favorite(task_id: int, current_user: UserRead) -> Optional[TaskRead]: """ Unmark a task as favorite. Args: task_id (int): The ID of the task to unmark. current_user (UserRead): The current authenticated user. Returns: Optional[TaskRead]: The updated task instance if successful, else None. Raises: HTTPException: If the user does not have permission to unmark the task. """ try: task_instance = TaskModel.get_by_id(task_id) if ( task_instance.user.id != current_user.id and current_user.role.name != "Administrator" ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You do not have permission to uncheck this task as a favorite.", ) task_instance.is_favorite = False task_instance.save() return TaskRead.from_orm(task_instance) except DoesNotExist: return None - Assistant