File size: 8,019 Bytes
697c967
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aab8fae
 
 
697c967
6a3de9e
697c967
6a3de9e
697c967
 
 
b403b1b
 
697c967
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a3de9e
697c967
6a3de9e
697c967
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a3de9e
697c967
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a3de9e
697c967
6a3de9e
697c967
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import List, Optional
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from models.task import Task, TaskCreate, TaskUpdate, TaskComplete
from models.user import User
from models.task import TaskRead
from utils.logging import get_logger
from fastapi import HTTPException, status
from datetime import datetime
import asyncio

logger = get_logger(__name__)

class TaskService:
    """
    Service class for handling task-related business logic with authorization.
    """

    @staticmethod
    async def get_tasks_by_user_id(session: AsyncSession, user_id: int) -> List[TaskRead]:
        """
        Get all tasks for a specific user.
        """
        try:
            # Query tasks for the specific user
            statement = select(Task).where(Task.user_id == user_id)
            result = await session.exec(statement)
            tasks = result.all()

            # Convert to response schema
            task_list = [TaskRead.model_validate(task) for task in tasks]

            logger.info(f"Retrieved {len(task_list)} tasks for user {user_id}")

            return task_list
        except Exception as e:
            logger.error(f"Error retrieving tasks for user {user_id}: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Error retrieving tasks"
            )

    @staticmethod
    async def get_task_by_id(session: AsyncSession, user_id: int, task_id: int) -> TaskRead:
        """
        Get a specific task by ID for a specific user.
        """
        try:
            # Query for the specific task that belongs to the user
            statement = select(Task).where(Task.user_id == user_id, Task.id == task_id)
            result = await session.exec(statement)
            task = result.first()

            if not task:
                logger.warning(f"Task {task_id} not found for user {user_id}")
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="Task not found"
                )

            logger.info(f"Retrieved task {task_id} for user {user_id}")

            return TaskRead.model_validate(task)
        except HTTPException:
            raise
        except Exception as e:
            logger.error(f"Error retrieving task {task_id} for user {user_id}: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Error retrieving task"
            )

    @staticmethod
    async def create_task(session: AsyncSession, user_id: int, task_data: TaskCreate) -> TaskRead:
        """
        Create a new task for a specific user.
        """
        try:
            task_data_dict = task_data.model_dump()
            task_data_dict['user_id'] = user_id
            db_task = Task.model_validate(task_data_dict)

            # Add to session
            session.add(db_task)
            await session.flush()
            await session.refresh(db_task)

            logger.info(f"Created task {db_task.id} for user {user_id}")

            return TaskRead.model_validate(db_task)
        except Exception as e:
            await session.rollback()
            logger.error(f"Error creating task for user {user_id}: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Error creating task"
            )

    @staticmethod
    async def update_task(session: AsyncSession, user_id: int, task_id: int, task_data: TaskUpdate) -> TaskRead:
        """
        Update a specific task for a specific user.
        """
        try:
            # Query for the specific task that belongs to the user
            statement = select(Task).where(Task.user_id == user_id, Task.id == task_id)
            result = await session.exec(statement)
            task = result.first()

            if not task:
                logger.warning(f"Task {task_id} not found for user {user_id}")
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="Task not found"
                )

            # Update task fields if provided
            update_data = task_data.model_dump(exclude_unset=True)
            for field, value in update_data.items():
                setattr(task, field, value)

            # Update the updated_at timestamp
            task.updated_at = datetime.utcnow()

            # Add changes to the session
            session.add(task)
            await session.flush()
            await session.refresh(task)

            logger.info(f"Updated task {task_id} for user {user_id}")

            return TaskRead.model_validate(task)
        except HTTPException:
            raise
        except Exception as e:
            await session.rollback()
            logger.error(f"Error updating task {task_id} for user {user_id}: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Error updating task"
            )

    @staticmethod
    async def delete_task(session: AsyncSession, user_id: int, task_id: int) -> bool:
        """
        Delete a specific task for a specific user.
        """
        try:
            # Query for the specific task that belongs to the user
            statement = select(Task).where(Task.user_id == user_id, Task.id == task_id)
            result = await session.exec(statement)
            task = result.first()

            if not task:
                logger.warning(f"Task {task_id} not found for user {user_id}")
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="Task not found"
                )

            # Delete the task
            await session.delete(task)
            await session.flush()

            logger.info(f"Deleted task {task_id} for user {user_id}")

            return True
        except HTTPException:
            raise
        except Exception as e:
            await session.rollback()
            logger.error(f"Error deleting task {task_id} for user {user_id}: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Error deleting task"
            )

    @staticmethod
    async def update_task_completion(session: AsyncSession, user_id: int, task_id: int, completion_data: TaskComplete) -> TaskRead:
        """
        Update the completion status of a specific task for a specific user.
        """
        try:
            # Query for the specific task that belongs to the user
            statement = select(Task).where(Task.user_id == user_id, Task.id == task_id)
            result = await session.exec(statement)
            task = result.first()

            if not task:
                logger.warning(f"Task {task_id} not found for user {user_id}")
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="Task not found"
                )

            # Update completion status
            task.completed = completion_data.completed
            task.updated_at = datetime.utcnow()

            # Add changes to the session
            session.add(task)
            await session.flush()
            await session.refresh(task)

            logger.info(f"Updated completion status for task {task_id} for user {user_id}")

            return TaskRead.model_validate(task)
        except HTTPException:
            raise
        except Exception as e:
            await session.rollback()
            logger.error(f"Error updating completion status for task {task_id} for user {user_id}: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Error updating task completion status"
            )