File size: 12,650 Bytes
bc45e54
054d73a
 
 
 
 
 
 
 
 
bc45e54
054d73a
e5c2788
054d73a
 
bc45e54
 
 
 
 
054d73a
 
bc45e54
 
 
 
 
 
 
 
 
 
 
 
 
 
054d73a
bc45e54
 
 
 
 
 
 
 
 
 
 
054d73a
bc45e54
 
 
 
 
 
 
 
 
 
 
 
054d73a
 
bc45e54
 
 
 
 
 
054d73a
bc45e54
 
054d73a
 
bc45e54
054d73a
bc45e54
054d73a
bc45e54
 
 
 
 
 
054d73a
 
bc45e54
054d73a
 
 
bc45e54
 
 
 
054d73a
bc45e54
 
 
 
 
054d73a
bc45e54
054d73a
 
bc45e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
054d73a
bc45e54
054d73a
bc45e54
 
 
 
 
 
 
 
 
054d73a
bc45e54
054d73a
 
bc45e54
 
 
 
054d73a
bc45e54
 
054d73a
 
 
 
bc45e54
 
 
 
 
 
054d73a
bc45e54
 
 
 
 
054d73a
bc45e54
054d73a
 
bc45e54
 
 
054d73a
bc45e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad5d4b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc45e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
054d73a
 
bc45e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SQLite database for ClassLens - users, sessions, parsed data, prompts, reports."""

from __future__ import annotations

import aiosqlite
import json
from pathlib import Path
from datetime import datetime
from typing import Optional

from .config import get_settings

DATABASE_PATH = Path(__file__).parent.parent / "classlens.db"


def _get_db_path() -> Path:
    settings = get_settings()
    if settings.database_path:
        return Path(settings.database_path)
    return DATABASE_PATH


async def init_database():
    """Initialize the database with required tables."""
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        await db.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                email TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                display_name TEXT,
                created_at TEXT NOT NULL,
                last_login TEXT
            )
        """)

        await db.execute("""
            CREATE TABLE IF NOT EXISTS exam_sessions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                title TEXT DEFAULT 'Untitled Session',
                status TEXT DEFAULT 'draft',
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users(id)
            )
        """)

        await db.execute("""
            CREATE TABLE IF NOT EXISTS parsed_data (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id INTEGER NOT NULL,
                data_type TEXT NOT NULL,
                file_name TEXT,
                raw_text TEXT,
                structured_data TEXT NOT NULL,
                created_at TEXT NOT NULL,
                FOREIGN KEY (session_id) REFERENCES exam_sessions(id) ON DELETE CASCADE
            )
        """)

        await db.execute("""
            CREATE TABLE IF NOT EXISTS prompts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                name TEXT NOT NULL,
                content TEXT NOT NULL,
                is_default BOOLEAN DEFAULT 0,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users(id)
            )
        """)

        await db.execute("""
            CREATE TABLE IF NOT EXISTS reports (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                session_id INTEGER NOT NULL,
                prompt_id INTEGER,
                html_content TEXT NOT NULL,
                created_at TEXT NOT NULL,
                FOREIGN KEY (session_id) REFERENCES exam_sessions(id) ON DELETE CASCADE,
                FOREIGN KEY (prompt_id) REFERENCES prompts(id)
            )
        """)

        await db.commit()


# ---- User CRUD ----

async def create_user(email: str, password_hash: str, display_name: str = "") -> int:
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        cursor = await db.execute(
            "INSERT INTO users (email, password_hash, display_name, created_at) VALUES (?, ?, ?, ?)",
            (email, password_hash, display_name or email.split("@")[0], now),
        )
        await db.commit()
        return cursor.lastrowid


async def get_user_by_email(email: str) -> Optional[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute("SELECT * FROM users WHERE email = ?", (email,)) as cursor:
            row = await cursor.fetchone()
            return dict(row) if row else None


async def get_user_by_id(user_id: int) -> Optional[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute("SELECT * FROM users WHERE id = ?", (user_id,)) as cursor:
            row = await cursor.fetchone()
            return dict(row) if row else None


async def update_last_login(user_id: int):
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        await db.execute("UPDATE users SET last_login = ? WHERE id = ?", (now, user_id))
        await db.commit()


# ---- Session CRUD ----

async def create_session(user_id: int, title: str = "Untitled Session") -> int:
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        cursor = await db.execute(
            "INSERT INTO exam_sessions (user_id, title, status, created_at, updated_at) VALUES (?, ?, 'draft', ?, ?)",
            (user_id, title, now, now),
        )
        await db.commit()
        return cursor.lastrowid


async def get_sessions(user_id: int) -> list[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute(
            "SELECT * FROM exam_sessions WHERE user_id = ? ORDER BY created_at DESC", (user_id,)
        ) as cursor:
            rows = await cursor.fetchall()
            return [dict(row) for row in rows]


async def get_session(session_id: int) -> Optional[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute("SELECT * FROM exam_sessions WHERE id = ?", (session_id,)) as cursor:
            row = await cursor.fetchone()
            return dict(row) if row else None


async def update_session_status(session_id: int, status: str):
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        await db.execute(
            "UPDATE exam_sessions SET status = ?, updated_at = ? WHERE id = ?",
            (status, now, session_id),
        )
        await db.commit()


# ---- Parsed Data CRUD ----

async def save_parsed_data(
    session_id: int, data_type: str, file_name: str, raw_text: str, structured_data: dict
) -> int:
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        cursor = await db.execute(
            "INSERT INTO parsed_data (session_id, data_type, file_name, raw_text, structured_data, created_at) VALUES (?, ?, ?, ?, ?, ?)",
            (session_id, data_type, file_name, raw_text, json.dumps(structured_data, ensure_ascii=False), now),
        )
        await db.commit()
        return cursor.lastrowid


async def get_parsed_data(session_id: int) -> list[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute(
            "SELECT * FROM parsed_data WHERE session_id = ? ORDER BY data_type, created_at",
            (session_id,),
        ) as cursor:
            rows = await cursor.fetchall()
            result = []
            for row in rows:
                d = dict(row)
                d["structured_data"] = json.loads(d["structured_data"])
                result.append(d)
            return result


async def delete_parsed_data(session_id: int, data_type: Optional[str] = None):
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        if data_type:
            await db.execute(
                "DELETE FROM parsed_data WHERE session_id = ? AND data_type = ?",
                (session_id, data_type),
            )
        else:
            await db.execute("DELETE FROM parsed_data WHERE session_id = ?", (session_id,))
        await db.commit()


# ---- Answer Grid CRUD ----

ANSWER_GRID_DATA_TYPE = "answer_grid"


async def save_answer_grid(session_id: int, grid_dict: dict) -> int:
    """Save confirmed answer grid, replacing any previous one for the session."""
    await delete_parsed_data(session_id, ANSWER_GRID_DATA_TYPE)
    return await save_parsed_data(
        session_id=session_id,
        data_type=ANSWER_GRID_DATA_TYPE,
        file_name="",
        raw_text="",
        structured_data=grid_dict,
    )


async def get_answer_grid(session_id: int) -> Optional[dict]:
    """Return the saved answer grid dict or None if not confirmed."""
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute(
            "SELECT structured_data FROM parsed_data WHERE session_id = ? AND data_type = ? ORDER BY created_at DESC LIMIT 1",
            (session_id, ANSWER_GRID_DATA_TYPE),
        ) as cursor:
            row = await cursor.fetchone()
            if not row:
                return None
            return json.loads(row["structured_data"])


# ---- Prompt CRUD ----

async def save_prompt(user_id: int, name: str, content: str, is_default: bool = False) -> int:
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        cursor = await db.execute(
            "INSERT INTO prompts (user_id, name, content, is_default, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
            (user_id, name, content, is_default, now, now),
        )
        await db.commit()
        return cursor.lastrowid


async def get_prompts(user_id: int) -> list[dict]:
    """Get user's own prompts plus all default prompts."""
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute(
            "SELECT * FROM prompts WHERE user_id = ? OR is_default = 1 ORDER BY is_default DESC, updated_at DESC",
            (user_id,),
        ) as cursor:
            rows = await cursor.fetchall()
            return [dict(row) for row in rows]


async def get_all_prompts() -> list[dict]:
    """Get all prompts from all users (for the 'read others' dropdown)."""
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute(
            "SELECT p.*, u.email as author_email FROM prompts p JOIN users u ON p.user_id = u.id ORDER BY p.updated_at DESC"
        ) as cursor:
            rows = await cursor.fetchall()
            return [dict(row) for row in rows]


async def get_prompt(prompt_id: int) -> Optional[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute("SELECT * FROM prompts WHERE id = ?", (prompt_id,)) as cursor:
            row = await cursor.fetchone()
            return dict(row) if row else None


async def update_prompt(prompt_id: int, name: str, content: str):
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        await db.execute(
            "UPDATE prompts SET name = ?, content = ?, updated_at = ? WHERE id = ?",
            (name, content, now, prompt_id),
        )
        await db.commit()


async def delete_prompt(prompt_id: int):
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        await db.execute("DELETE FROM prompts WHERE id = ?", (prompt_id,))
        await db.commit()


# ---- Report CRUD ----

async def save_report(session_id: int, prompt_id: Optional[int], html_content: str) -> int:
    db_path = _get_db_path()
    now = datetime.utcnow().isoformat()
    async with aiosqlite.connect(db_path) as db:
        cursor = await db.execute(
            "INSERT INTO reports (session_id, prompt_id, html_content, created_at) VALUES (?, ?, ?, ?)",
            (session_id, prompt_id, html_content, now),
        )
        await db.commit()
        return cursor.lastrowid


async def get_reports(session_id: int) -> list[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute(
            "SELECT * FROM reports WHERE session_id = ? ORDER BY created_at DESC",
            (session_id,),
        ) as cursor:
            rows = await cursor.fetchall()
            return [dict(row) for row in rows]


async def get_report(report_id: int) -> Optional[dict]:
    db_path = _get_db_path()
    async with aiosqlite.connect(db_path) as db:
        db.row_factory = aiosqlite.Row
        async with db.execute("SELECT * FROM reports WHERE id = ?", (report_id,)) as cursor:
            row = await cursor.fetchone()
            return dict(row) if row else None