-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
417 lines (383 loc) · 19.2 KB
/
database.py
File metadata and controls
417 lines (383 loc) · 19.2 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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import os
import aiosqlite
from datetime import datetime, timedelta
from typing import List, Optional
from config import DATABASE_PATH
class Database:
def __init__(self):
self.db_path = DATABASE_PATH
async def init_db(self):
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
create table if not exists users (
id integer primary key,
user_id integer unique not null,
username text,
first_name text,
last_name text,
is_active boolean default true,
user_type text default 'student',
created_at timestamp default current_timestamp
)
''')
await db.execute('''
create table if not exists reports (
id integer primary key autoincrement,
user_id integer not null,
current_stage text not null,
plans text not null,
plans_completed boolean,
plans_failure_reason text,
problems text not null,
is_read_by_curator boolean default false,
created_at timestamp default current_timestamp,
foreign key (user_id) references users (user_id)
)
''')
await db.execute('''
create table if not exists curator_student_relations (
id integer primary key autoincrement,
curator_id integer not null,
student_id integer not null,
created_at timestamp default current_timestamp,
foreign key (curator_id) references users (user_id),
foreign key (student_id) references users (user_id),
unique(curator_id, student_id)
)
''')
await db.commit()
async def add_user(self, user_id: int, username: str = None, first_name: str = None, last_name: str = None, user_type: str = 'student'):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
insert or replace into users (user_id, username, first_name, last_name, user_type)
values (?, ?, ?, ?, ?)
''', (user_id, username, first_name, last_name, user_type))
await db.commit()
async def get_user_profile(self, user_id: int) -> Optional[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select user_id, username, first_name, last_name
from users
where user_id = ?
''', (user_id,))
row = await cursor.fetchone()
if row:
return {'user_id': row[0], 'username': row[1], 'first_name': row[2], 'last_name': row[3]}
return None
async def get_all_active_users(self) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select user_id, username, first_name, last_name
from users
where is_active = true and user_type = 'student'
''')
rows = await cursor.fetchall()
return [{'user_id': row[0], 'username': row[1], 'first_name': row[2], 'last_name': row[3]} for row in rows]
async def save_report(self, user_id: int, current_stage: str, plans: str, problems: str, plans_completed: bool = None, plans_failure_reason: str = None):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
insert into reports (user_id, current_stage, plans, problems, plans_completed, plans_failure_reason)
values (?, ?, ?, ?, ?, ?)
''', (user_id, current_stage, plans, problems, plans_completed, plans_failure_reason))
await db.commit()
async def get_user_reports(self, user_id: int) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select current_stage, plans, problems, plans_completed, plans_failure_reason, created_at
from reports
where user_id = ?
order by created_at desc
''', (user_id,))
rows = await cursor.fetchall()
return [{
'current_stage': row[0], 'plans': row[1], 'problems': row[2],
'plans_completed': row[3], 'plans_failure_reason': row[4], 'created_at': row[5]
} for row in rows]
async def get_last_report_date(self, user_id: int) -> Optional[datetime]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select created_at
from reports
where user_id = ?
order by created_at desc
limit 1
''', (user_id,))
row = await cursor.fetchone()
if row:
return datetime.fromisoformat(row[0])
return None
async def get_reports_for_current_week(self, user_id: int) -> List[dict]:
"""Получает отчеты пользователя за текущую календарную неделю"""
# Находим начало текущей недели (понедельник)
today = datetime.now().date()
days_since_monday = today.weekday() # 0 = понедельник, 6 = воскресенье
week_start = today - timedelta(days=days_since_monday)
week_start_datetime = datetime.combine(week_start, datetime.min.time())
week_start_str = week_start_datetime.strftime('%Y-%m-%d %H:%M:%S')
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select current_stage, plans, problems, created_at
from reports
where user_id = ? and created_at >= ?
order by created_at desc
''', (user_id, week_start_str))
rows = await cursor.fetchall()
return [{'current_stage': row[0], 'plans': row[1], 'problems': row[2], 'created_at': row[3]} for row in rows]
async def get_students_missing_weekly_reports(self) -> List[dict]:
today = datetime.now().date()
days_since_monday = today.weekday()
week_start = today - timedelta(days=days_since_monday)
week_start_datetime = datetime.combine(week_start, datetime.min.time())
week_start_str = week_start_datetime.strftime('%Y-%m-%d %H:%M:%S')
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select
csr.curator_id,
c.username,
c.first_name,
c.last_name,
s.user_id,
s.username,
s.first_name,
s.last_name
from curator_student_relations csr
join users c on csr.curator_id = c.user_id and c.is_active = true
join users s on csr.student_id = s.user_id and s.is_active = true
left join reports r on r.user_id = s.user_id and r.created_at >= ?
group by csr.curator_id, c.username, c.first_name, c.last_name, s.user_id, s.username, s.first_name, s.last_name
having max(r.created_at) is null
order by csr.curator_id, s.first_name, s.last_name
''', (week_start_str,))
rows = await cursor.fetchall()
return [
{
'curator_id': row[0],
'curator_username': row[1],
'curator_first_name': row[2],
'curator_last_name': row[3],
'student_id': row[4],
'student_username': row[5],
'student_first_name': row[6],
'student_last_name': row[7]
}
for row in rows
]
async def get_last_stage_choice(self, user_id: int) -> Optional[str]:
"""Получает последний выбранный этап пользователя"""
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select current_stage
from reports
where user_id = ?
order by created_at desc
limit 1
''', (user_id,))
row = await cursor.fetchone()
if row:
return row[0]
return None
async def has_previous_reports(self, user_id: int) -> bool:
"""Проверяет, есть ли у пользователя предыдущие отчеты"""
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select count(*)
from reports
where user_id = ?
''', (user_id,))
row = await cursor.fetchone()
return row[0] > 0
async def add_curator_student_relation(self, curator_id: int, student_id: int):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
insert or ignore into curator_student_relations (curator_id, student_id)
values (?, ?)
''', (curator_id, student_id))
await db.commit()
async def get_curator_students(self, curator_id: int) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select u.user_id, u.username, u.first_name, u.last_name
from users u
join curator_student_relations csr on u.user_id = csr.student_id
where csr.curator_id = ? and u.is_active = true
''', (curator_id,))
rows = await cursor.fetchall()
return [{'user_id': row[0], 'username': row[1], 'first_name': row[2], 'last_name': row[3]} for row in rows]
async def get_student_curator(self, student_id: int) -> Optional[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select u.user_id, u.username, u.first_name, u.last_name
from users u
join curator_student_relations csr on u.user_id = csr.curator_id
where csr.student_id = ? and u.is_active = true
''', (student_id,))
row = await cursor.fetchone()
if row:
return {'user_id': row[0], 'username': row[1], 'first_name': row[2], 'last_name': row[3]}
return None
async def get_unread_reports_for_curator(self, curator_id: int) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select r.id, r.user_id, r.current_stage, r.plans, r.problems, r.created_at,
u.first_name, u.last_name, u.username
from reports r
join users u on r.user_id = u.user_id
join curator_student_relations csr on u.user_id = csr.student_id
where csr.curator_id = ? and r.is_read_by_curator = false
order by r.created_at desc
''', (curator_id,))
rows = await cursor.fetchall()
return [{
'id': row[0], 'user_id': row[1], 'current_stage': row[2],
'plans': row[3], 'problems': row[4], 'created_at': row[5],
'student_name': f"{row[6]} {row[7]}" if row[6] and row[7] else row[8] or f"ID: {row[1]}"
} for row in rows]
async def mark_report_as_read(self, report_id: int, curator_id: int):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
update reports
set is_read_by_curator = true
where id = ? and user_id in (
select student_id from curator_student_relations
where curator_id = ?
)
''', (report_id, curator_id))
await db.commit()
async def get_report_by_id(self, report_id: int) -> Optional[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select user_id, current_stage, plans, problems, created_at
from reports
where id = ?
''', (report_id,))
row = await cursor.fetchone()
if row:
return {
'user_id': row[0], 'current_stage': row[1],
'plans': row[2], 'problems': row[3], 'created_at': row[4]
}
return None
async def get_all_student_reports_for_curator(self, curator_id: int, student_id: int) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select r.id, r.user_id, r.current_stage, r.plans, r.problems, r.plans_completed,
r.plans_failure_reason, r.is_read_by_curator, r.created_at,
u.first_name, u.last_name, u.username
from reports r
join users u on r.user_id = u.user_id
join curator_student_relations csr on u.user_id = csr.student_id
where csr.curator_id = ? and r.user_id = ?
order by r.created_at desc
''', (curator_id, student_id))
rows = await cursor.fetchall()
return [{
'id': row[0], 'user_id': row[1], 'current_stage': row[2], 'plans': row[3],
'problems': row[4], 'plans_completed': bool(row[5]) if row[5] is not None else None,
'plans_failure_reason': row[6], 'is_read_by_curator': bool(row[7]),
'created_at': row[8], 'student_name': f"{row[9]} {row[10]}" if row[9] and row[10] else row[11] or f"ID: {student_id}"
} for row in rows]
async def get_all_students_with_curators(self) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select
u.user_id, u.username, u.first_name, u.last_name,
c.user_id as curator_id, c.username as curator_username,
c.first_name as curator_first_name, c.last_name as curator_last_name
from users u
left join curator_student_relations csr on u.user_id = csr.student_id
left join users c on csr.curator_id = c.user_id
where u.user_type = 'student' and u.is_active = true
order by u.first_name, u.last_name
''')
rows = await cursor.fetchall()
return [{
'user_id': row[0], 'username': row[1], 'first_name': row[2], 'last_name': row[3],
'curator_id': row[4], 'curator_username': row[5],
'curator_first_name': row[6], 'curator_last_name': row[7]
} for row in rows]
async def get_user_type(self, user_id: int) -> str:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute(
'select user_type from users where user_id = ?', (user_id,)
)
row = await cursor.fetchone()
return row[0] if row else 'student'
async def get_all_curators(self) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select user_id, username, first_name, last_name, created_at
from users
where user_type = 'curator' and is_active = true
order by first_name, last_name
''')
rows = await cursor.fetchall()
return [{
'user_id': row[0], 'username': row[1], 'first_name': row[2],
'last_name': row[3], 'created_at': row[4]
} for row in rows]
async def get_curator_stats(self, curator_id: int) -> dict:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select count(distinct csr.student_id) as student_count,
count(r.id) as total_reports,
count(case when r.is_read_by_curator = false then 1 end) as unread_reports
from curator_student_relations csr
left join reports r on csr.student_id = r.user_id
where csr.curator_id = ?
''', (curator_id,))
row = await cursor.fetchone()
return {
'student_count': row[0] or 0,
'total_reports': row[1] or 0,
'unread_reports': row[2] or 0
}
async def remove_curator_student_relation(self, curator_id: int, student_id: int):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
delete from curator_student_relations
where curator_id = ? and student_id = ?
''', (curator_id, student_id))
await db.commit()
async def deactivate_curator(self, curator_id: int):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
update users
set is_active = false
where user_id = ? and user_type = 'curator'
''', (curator_id,))
await db.commit()
async def activate_curator(self, curator_id: int):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
update users
set is_active = true
where user_id = ? and user_type = 'curator'
''', (curator_id,))
await db.commit()
async def get_students_without_curators(self) -> List[dict]:
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute('''
select u.user_id, u.username, u.first_name, u.last_name
from users u
left join curator_student_relations csr on u.user_id = csr.student_id
where u.user_type = 'student' and u.is_active = true and csr.student_id is null
order by u.first_name, u.last_name
''')
rows = await cursor.fetchall()
return [{'user_id': row[0], 'username': row[1], 'first_name': row[2], 'last_name': row[3]} for row in rows]
async def assign_student_to_curator(self, student_id: int, curator_id: int):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
insert or replace into curator_student_relations (curator_id, student_id)
values (?, ?)
''', (curator_id, student_id))
await db.commit()
async def is_admin(self, user_id: int) -> bool:
admin_id_value = os.getenv('ADMIN_ID')
if not admin_id_value:
return False
try:
return user_id == int(admin_id_value)
except ValueError:
return False