-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservices.py
More file actions
184 lines (148 loc) · 5.04 KB
/
services.py
File metadata and controls
184 lines (148 loc) · 5.04 KB
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
"""
Service layer for user and history operations.
Contains business logic for user management and history tracking.
"""
from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy import desc
from sqlalchemy.orm.query import Query
from database import User, HistoryEntry
from auth import hash_password, get_user_by_email, get_user_by_username
from schemas import UserRegistration, SaveHistoryRequest
import logging
logger: logging.Logger = logging.getLogger(__name__)
class UserService:
"""Service class for user-related operations."""
@staticmethod
def create_user(db: Session, user_data: UserRegistration) -> User:
"""
Create a new user account.
Args:
db: Database session
user_data: User registration data
Returns:
Created user object
Raises:
ValueError: If email or username already exists
"""
# Check if email already exists
existing_user: User | None = get_user_by_email(db, user_data.email)
if existing_user:
raise ValueError("Email already registered")
# Check if username already exists
existing_username: User | None = get_user_by_username(db, user_data.username)
if existing_username:
raise ValueError("Username already taken")
# Create new user
hashed_password: str = hash_password(user_data.password)
db_user = User(
email=user_data.email,
username=user_data.username,
hashed_password=hashed_password,
)
db.add(db_user)
db.commit()
db.refresh(db_user)
logger.info(f"New user created: {user_data.email}")
return db_user
@staticmethod
def get_user_by_id(db: Session, user_id: int) -> Optional[User]:
"""
Get user by ID.
Args:
db: Database session
user_id: User ID
Returns:
User object if found, None otherwise
"""
return db.query(User).filter(User.id == user_id).first()
class HistoryService:
"""Service class for history-related operations."""
@staticmethod
def save_history_entry(
db: Session, user_id: int, history_data: SaveHistoryRequest
) -> HistoryEntry:
"""
Save a new history entry for the user.
Args:
db: Database session
user_id: User ID
history_data: History entry data
Returns:
Created history entry
"""
db_entry = HistoryEntry(
user_id=user_id,
concept=history_data.concept,
explanation=history_data.explanation,
)
db.add(db_entry)
db.commit()
db.refresh(db_entry)
logger.info(f"History entry saved for user {user_id}: {history_data.concept}")
return db_entry
@staticmethod
def get_user_history(
db: Session, user_id: int, limit: int = 50, offset: int = 0
) -> tuple[List[HistoryEntry], int]:
"""
Get user's history entries with pagination.
Args:
db: Database session
user_id: User ID
limit: Maximum number of entries to return
offset: Number of entries to skip
Returns:
Tuple of (history entries list, total count)
"""
query: Query[HistoryEntry] = db.query(HistoryEntry).filter(
HistoryEntry.user_id == user_id
)
# Get total count
total: int = query.count()
# Get paginated results, ordered by creation date (newest first)
entries: List[HistoryEntry] = (
query.order_by(desc(HistoryEntry.created_at))
.offset(offset)
.limit(limit)
.all()
)
return entries, total
@staticmethod
def get_history_entry_by_id(
db: Session, entry_id: int, user_id: int
) -> Optional[HistoryEntry]:
"""
Get a specific history entry for the user.
Args:
db: Database session
entry_id: History entry ID
user_id: User ID (for security check)
Returns:
History entry if found and belongs to user, None otherwise
"""
return (
db.query(HistoryEntry)
.filter(HistoryEntry.id == entry_id, HistoryEntry.user_id == user_id)
.first()
)
@staticmethod
def delete_history_entry(db: Session, entry_id: int, user_id: int) -> bool:
"""
Delete a history entry for the user.
Args:
db: Database session
entry_id: History entry ID
user_id: User ID (for security check)
Returns:
True if deleted successfully, False if not found
"""
entry: HistoryEntry | None = HistoryService.get_history_entry_by_id(
db, entry_id, user_id
)
if not entry:
return False
db.delete(entry)
db.commit()
logger.info(f"History entry deleted: {entry_id} for user {user_id}")
return True