Spaces:
Sleeping
Sleeping
taboola commited on
Commit ·
7d40f39
1
Parent(s): 38a90da
Revert "add teacher retention, feedback-loop, and issue-report analytics to admin backend"
Browse filesThis reverts commit c5b36039af43f2a5fead8efe0ba08ca4b3b49db3.
Files changed (9)
- chatkit/backend/alembic/versions/0015_issue_reports.pyDeleted-54
- chatkit/backend/app/admin.py-32
- chatkit/backend/app/auth.py+2-2
- chatkit/backend/app/config.py-15
- chatkit/backend/app/database.py-232
- chatkit/backend/app/main.py-52
- chatkit/backend/app/models.py-23
- chatkit/backend/app/notifications.pyDeleted-68
- chatkit/backend/tests/test_database.py-122
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""add issue_reports table
Revision ID: 0015_issue_reportsRevises: 0014_teacher_vocabularyCreate Date: 2026-07-22
Backs the "report an issue" form: submissions are emailed to admins andalso persisted here so they show up as a dismissible alert in the admindashboard until dismissed."""from alembic import opimport sqlalchemy as sa
from app.db import active_schema
revision = "0015_issue_reports"down_revision = "0014_teacher_vocabulary"branch_labels = Nonedepends_on = None
def upgrade() -> None: schema = active_schema() inspector = sa.inspect(op.get_bind()) tables = inspector.get_table_names(schema=schema)
if "issue_reports" not in tables: op.create_table( "issue_reports", sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True), sa.Column("reporter_email", sa.String(255), nullable=False), sa.Column("category", sa.String(32), nullable=False, server_default="bug"), sa.Column("subject", sa.String(255), nullable=False), sa.Column("description", sa.Text(), nullable=False), sa.Column("page_context", sa.String(255), server_default=""), sa.Column("status", sa.String(16), nullable=False, server_default="open"), sa.Column( "created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False, ), sa.Column("dismissed_at", sa.DateTime(timezone=True), nullable=True), schema=schema, ) op.create_index( "ix_issue_reports_created_at", "issue_reports", ["created_at"], schema=schema )
def downgrade() -> None: schema = active_schema() op.drop_index("ix_issue_reports_created_at", table_name="issue_reports", schema=schema) op.drop_table("issue_reports", schema=schema)22 unmodified lines23242526272829303132334 unmodified lines3839404142434445464757 unmodified lines10510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713822 unmodified linesadmin_list_students,delete_session,delete_user,dismiss_issue_report,get_active_users,get_answer_grid,get_assessments_processed,get_feedback_loop_funnel,get_parsed_data,get_practice_quiz_funnel,get_quiz_results,4 unmodified linesget_student,get_student_improvement_summary,get_student_timeline,get_teacher_retention,get_teacher_vocabulary,list_all_users,list_open_issue_reports,set_teacher_vocabulary,set_user_admin,wipe_quiz_data,57 unmodified linesreturn await get_student_improvement_summary()@router.get("/analytics/teacher-retention")async def dashboard_teacher_retention(_admin=Depends(get_current_admin)):return await get_teacher_retention()@router.get("/analytics/feedback-loop")async def dashboard_feedback_loop(_admin=Depends(get_current_admin)):return await get_feedback_loop_funnel()# ---- Issue reports (admin only) ----@router.get("/issues")async def dashboard_list_issues(_admin=Depends(get_current_admin)):return {"issues": await list_open_issue_reports()}@router.post("/issues/{issue_id}/dismiss")async def dashboard_dismiss_issue(issue_id: int, _admin=Depends(get_current_admin)):ok = await dismiss_issue_report(issue_id)if not ok:raise HTTPException(status_code=404, detail="Issue not found or already dismissed")return {"status": "dismissed"}# ---- User management (admin only) ----22 unmodified lines2324252627282930314 unmodified lines363738394041424357 unmodified lines10110210310410510622 unmodified linesadmin_list_students,delete_session,delete_user,get_active_users,get_answer_grid,get_assessments_processed,get_parsed_data,get_practice_quiz_funnel,get_quiz_results,4 unmodified linesget_student,get_student_improvement_summary,get_student_timeline,get_teacher_vocabulary,list_all_users,set_teacher_vocabulary,set_user_admin,wipe_quiz_data,57 unmodified linesreturn await get_student_improvement_summary()# ---- User management (admin only) ----
27 unmodified lines282930313233343536373827 unmodified lines# Grants admin access to this account regardless of the `is_admin` flag in# Supabase — so it doesn't need a manual DB update to stay an admin.EXTRA_ADMIN_EMAIL = "astraealiu44@gmail.com"def _apply_admin_override(user: dict) -> dict:if user.get("email") == EXTRA_ADMIN_EMAIL and not user.get("is_admin"):return {**user, "is_admin": True}return user27 unmodified lines282930313233343536373827 unmodified lines# Grants admin access to this account regardless of the `is_admin` flag in# Supabase — so it doesn't need a manual DB update to stay an admin._EXTRA_ADMIN_EMAIL = "astraealiu44@gmail.com"def _apply_admin_override(user: dict) -> dict:if user.get("email") == _EXTRA_ADMIN_EMAIL and not user.get("is_admin"):return {**user, "is_admin": True}return user
50 unmodified lines5152535455565758596061626364656619 unmodified lines86878889909192939450 unmodified lines# Frontend URL for redirectsfrontend_url: str = "http://localhost:3000"# SMTP — used only to email admins when a "report an issue" form is# submitted (see app/notifications.py). Left blank, sending is skipped# (logged, not raised) so the report still saves and shows up in the# admin dashboard even with no mail server configured.smtp_host: str = ""smtp_port: int = 587smtp_user: str = ""smtp_password: str = ""smtp_from: str = ""@lru_cachedef get_settings() -> Settings:19 unmodified linesupload_dir=os.getenv("UPLOAD_DIR", ""),max_file_size_mb=int(os.getenv("MAX_FILE_SIZE_MB", "20")),frontend_url=os.getenv("FRONTEND_URL", "http://localhost:3000"),smtp_host=os.getenv("SMTP_HOST", ""),smtp_port=int(os.getenv("SMTP_PORT", "587")),smtp_user=os.getenv("SMTP_USER", ""),smtp_password=os.getenv("SMTP_PASSWORD", ""),smtp_from=os.getenv("SMTP_FROM", ""),)50 unmodified lines51525354555619 unmodified lines7677787950 unmodified lines# Frontend URL for redirectsfrontend_url: str = "http://localhost:3000"@lru_cachedef get_settings() -> Settings:19 unmodified linesupload_dir=os.getenv("UPLOAD_DIR", ""),max_file_size_mb=int(os.getenv("MAX_FILE_SIZE_MB", "20")),frontend_url=os.getenv("FRONTEND_URL", "http://localhost:3000"),)
26 unmodified lines2728293031323312 unmodified lines46474849505152535455565758596061112 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331071 unmodified lines1305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135473 unmodified lines14281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155626 unmodified linesfrom .models import (AnswerGrid as AnswerGridRecord,Base,IssueReport,LoginEvent,ParsedData,PracticeQuiz,12 unmodified linesreturn datetime.now(timezone.utc)def _aware(dt: datetime) -> datetime:"""Postgres (DateTime(timezone=True)) round-trips tz-aware datetimes;SQLite always hands back naive ones regardless of column type. Anythingcomparing a DB-fetched datetime against another in plain Python (not aSQL WHERE clause, which each dialect handles consistently on its own)needs both sides on the same footing — assume naive values are UTC,since every datetime this app writes is generated via _now()."""return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)def _row(obj) -> dict:"""Serialize an ORM object to a plain dict of its columns."""return {c.key: getattr(obj, c.key) for c in obj.__table__.columns}112 unmodified linesawait db.commit()async def get_admin_emails() -> list[str]:"""Every teacher with is_admin=True in the DB — used as the recipientlist for issue-report notifications. Doesn't include email-based adminoverrides granted only in code (see auth._apply_admin_override); callersthat need those too should merge them in separately."""async with get_sessionmaker()() as db:res = await db.execute(select(Teacher.email).where(Teacher.is_admin.is_(True)))return [e for (e,) in res.all()]async def create_issue_report(reporter_email: str,category: str,subject: str,description: str,page_context: str = "",) -> dict:async with get_sessionmaker()() as db:report = IssueReport(reporter_email=reporter_email,category=category,subject=subject,description=description,page_context=page_context,)db.add(report)await db.flush()await db.refresh(report)row = _row(report)await db.commit()return rowasync def list_open_issue_reports() -> list[dict]:async with get_sessionmaker()() as db:res = await db.execute(select(IssueReport).where(IssueReport.status == "open").order_by(IssueReport.created_at.desc()))return [_row(r) for r in res.scalars().all()]async def dismiss_issue_report(report_id: int) -> bool:async with get_sessionmaker()() as db:res = await db.execute(update(IssueReport).where(IssueReport.id == report_id, IssueReport.status == "open").values(status="dismissed", dismissed_at=_now()))await db.commit()return res.rowcount > 0 # type: ignore[attr-defined]async def list_all_users() -> list[dict]:"""Admin: all teachers (without password hashes), with per-teacher counts."""async with get_sessionmaker()() as db:1071 unmodified lines}async def get_teacher_retention() -> dict:"""Of teachers whose account is old enough to judge, what share came backand logged in again *after* their first week / first month — not justduring initial signup/onboarding. Shows sustained use rather thanone-time testing.A teacher only counts toward a window's denominator once their accounthas existed at least that long (a 3-day-old account can't yet prove ordisprove week-1 retention), and toward the numerator if any login_eventfor them lands strictly after `created_at + window`."""now = _now()async with get_sessionmaker()() as db:teachers_res = await db.execute(select(Teacher.id, Teacher.created_at))teachers = [(tid, _aware(created_at)) for tid, created_at in teachers_res.all()]logins_res = await db.execute(select(LoginEvent.user_id, LoginEvent.created_at).where(LoginEvent.role == "teacher"))logins_by_teacher: dict[int, list[datetime]] = {}for user_id, created_at in logins_res.all():logins_by_teacher.setdefault(user_id, []).append(_aware(created_at))def window_stats(days: int) -> dict:eligible = 0retained = 0for teacher_id, created_at in teachers:cutoff = created_at + timedelta(days=days)if cutoff > now:continue # account not old enough to judge this window yeteligible += 1if any(t > cutoff for t in logins_by_teacher.get(teacher_id, [])):retained += 1pct = round(100 * retained / eligible, 1) if eligible else 0.0return {"eligible": eligible, "retained": retained, "pct": pct}return {"week": window_stats(7),"month": window_stats(30),}async def get_assessments_processed(months: int = 6) -> dict:"""Monthly counts of exams uploaded (saved quizzes) and student reportsgenerated, for the admin analytics bar chart."""73 unmodified lines}async def get_feedback_loop_funnel(teacher_id: Optional[int] = None) -> dict:"""Exam result → weakness identified → practice generated → practicecompleted → later reassessment, for the admin funnel chart.The unit here is one student's result on one real exam (aStudentResult row on a Quiz with status="saved" and nosource_practice_quiz_id — i.e. not the synthetic quiz row a completedpractice quiz feeds into the dashboard as). PracticeQuiz has no FK backto the exam that triggered it, so each stage is correlated by student +timestamp ordering instead: the practice quiz counted for a given examresult is the earliest one generated for that student after the exam,and a "reassessment" is any later real exam for that same student afterthat practice was completed."""async with get_sessionmaker()() as db:quiz_stmt = select(Quiz.id, Quiz.created_at).where(Quiz.status == "saved", Quiz.source_practice_quiz_id.is_(None))if teacher_id is not None:quiz_stmt = quiz_stmt.where(Quiz.teacher_id == teacher_id)quiz_res = await db.execute(quiz_stmt)quiz_created_at: dict[int, datetime] = {qid: _aware(dt) for qid, dt in quiz_res.all()}empty = {"uploaded": 0,"weakness_identified": 0,"practice_generated": 0,"practice_completed": 0,"reassessed": 0,}if not quiz_created_at:return emptyresult_res = await db.execute(select(StudentResult.quiz_id,StudentResult.student_id,StudentResult.weaknesses,).where(StudentResult.quiz_id.in_(quiz_created_at.keys())))results = result_res.all()if not results:return emptystudent_ids = {sid for _, sid, _ in results}pq_stmt = select(PracticeQuiz.student_id,PracticeQuiz.created_at,PracticeQuiz.completed_at,PracticeQuiz.status,).where(PracticeQuiz.student_id.in_(student_ids))if teacher_id is not None:pq_stmt = pq_stmt.where(PracticeQuiz.teacher_id == teacher_id)pq_res = await db.execute(pq_stmt)practice_by_student: dict[int, list[tuple]] = {}for sid, created_at, completed_at, status in pq_res.all():practice_by_student.setdefault(sid, []).append((_aware(created_at),_aware(completed_at) if completed_at else None,status,))# Every real exam per student (quiz_id kept so a student's own# triggering exam is never counted as its own "later" reassessment).exam_stmt = (select(StudentResult.student_id, Quiz.id, Quiz.created_at).join(Quiz, StudentResult.quiz_id == Quiz.id).where(Quiz.status == "saved", Quiz.source_practice_quiz_id.is_(None)))if teacher_id is not None:exam_stmt = exam_stmt.where(Quiz.teacher_id == teacher_id)exam_res = await db.execute(exam_stmt)exams_by_student: dict[int, list[tuple]] = {}for sid, qid, created_at in exam_res.all():exams_by_student.setdefault(sid, []).append((qid, _aware(created_at)))uploaded = len(results)weakness_identified = 0practice_generated = 0practice_completed = 0reassessed = 0for quiz_id, student_id, weaknesses in results:if not (weaknesses or "").strip():continueweakness_identified += 1quiz_time = quiz_created_at[quiz_id]practices_after = sorted((p for p in practice_by_student.get(student_id, []) if p[0] > quiz_time),key=lambda p: p[0],)if not practices_after:continuepractice_generated += 1_, completed_at, status = practices_after[0]if status != "completed" or completed_at is None:continuepractice_completed += 1later_exams = [tfor other_qid, t in exams_by_student.get(student_id, [])if other_qid != quiz_id and t > completed_at]if later_exams:reassessed += 1return {"uploaded": uploaded,"weakness_identified": weakness_identified,"practice_generated": practice_generated,"practice_completed": practice_completed,"reassessed": reassessed,}async def get_all_students_category_history(teacher_id: Optional[int] = None,) -> dict[int, dict[str, list[dict]]]:26 unmodified lines27282930313212 unmodified lines454647484950112 unmodified lines1631641651661671681071 unmodified lines12401241124212431244124573 unmodified lines13191320132113221323132426 unmodified linesfrom .models import (AnswerGrid as AnswerGridRecord,Base,LoginEvent,ParsedData,PracticeQuiz,12 unmodified linesreturn datetime.now(timezone.utc)def _row(obj) -> dict:"""Serialize an ORM object to a plain dict of its columns."""return {c.key: getattr(obj, c.key) for c in obj.__table__.columns}112 unmodified linesawait db.commit()async def list_all_users() -> list[dict]:"""Admin: all teachers (without password hashes), with per-teacher counts."""async with get_sessionmaker()() as db:1071 unmodified lines}async def get_assessments_processed(months: int = 6) -> dict:"""Monthly counts of exams uploaded (saved quizzes) and student reportsgenerated, for the admin analytics bar chart."""73 unmodified lines}async def get_all_students_category_history(teacher_id: Optional[int] = None,) -> dict[int, dict[str, list[dict]]]:
57 unmodified lines58596061626364655 unmodified lines71727374757677787980811012 unmodified lines10941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114757 unmodified lineslist_practice_quizzes,mark_practice_quiz_opened,submit_practice_quiz,create_issue_report,get_admin_emails,)from .auth import (get_current_user,5 unmodified linesget_student_from_raw_token,login_student,public_student,EXTRA_ADMIN_EMAIL,)from .config import get_settingsfrom .crypto import encryptfrom .notifications import send_issue_report_emailfrom .student_credentials import (ensure_student_login,generate_unique_username,1012 unmodified linesraise HTTPException(status_code=500, detail=f"Rewrite failed: {str(e)}")# =============================================================================# Issue Reports ("report an issue" form — any logged-in teacher)# =============================================================================_ISSUE_CATEGORIES = {"bug", "feature", "other"}class IssueReportRequest(BaseModel):category: str = "bug"subject: strdescription: strpage_context: str = ""@app.post("/api/issues")async def api_submit_issue_report(body: IssueReportRequest, user=Depends(get_current_user)):if body.category not in _ISSUE_CATEGORIES:raise HTTPException(status_code=400, detail="Invalid category.")if not body.subject.strip() or not body.description.strip():raise HTTPException(status_code=400, detail="Subject and description are required.")report = await create_issue_report(user["email"],body.category,body.subject.strip(),body.description.strip(),body.page_context,)# DB-flagged admins plus the code-level admin override (see# auth._apply_admin_override) — that account is an admin in the app but# was never flipped in the DB, so get_admin_emails() alone would miss it.admin_emails = {*await get_admin_emails(), EXTRA_ADMIN_EMAIL}await send_issue_report_email(sorted(admin_emails),user["email"],body.category,body.subject.strip(),body.description.strip(),body.page_context,)return {"status": "submitted", "id": report["id"]}# =============================================================================# Practice Quizzes (individualized, student-facing, single-attempt, no login)# =============================================================================57 unmodified lines5859606162635 unmodified lines6970717273747576771012 unmodified lines10901091109210931094109557 unmodified lineslist_practice_quizzes,mark_practice_quiz_opened,submit_practice_quiz,)from .auth import (get_current_user,5 unmodified linesget_student_from_raw_token,login_student,public_student,)from .config import get_settingsfrom .crypto import encryptfrom .student_credentials import (ensure_student_login,generate_unique_username,1012 unmodified linesraise HTTPException(status_code=500, detail=f"Rewrite failed: {str(e)}")# =============================================================================# Practice Quizzes (individualized, student-facing, single-attempt, no login)# =============================================================================
338 unmodified lines339340341342343344345346347348349350351352353354355356357358359360361362363364338 unmodified linescreated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), index=True)class IssueReport(Base):"""A "report an issue" submission — emailed to admins on creation andsurfaced as a dismissible alert in the admin dashboard until an admindismisses it. No FK to teachers: intentionally keeps working even if thereporting account is later deleted."""__tablename__ = "issue_reports"id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)reporter_email: Mapped[str] = mapped_column(String(255), nullable=False)category: Mapped[str] = mapped_column(String(32), nullable=False, default="bug")subject: Mapped[str] = mapped_column(String(255), nullable=False)description: Mapped[str] = mapped_column(Text, nullable=False)page_context: Mapped[str] = mapped_column(String(255), default="")status: Mapped[str] = mapped_column(String(16), nullable=False, default="open")created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), index=True)dismissed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)338 unmodified lines339340341338 unmodified linescreated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), index=True)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Email notifications. Currently just one: notify admins when a "report anissue" form is submitted. Kept separate from app/auth.py's password-relatedcrypto and app/database.py's persistence — this module only ever sends mail,never touches the DB or auth."""
from __future__ import annotations
import asyncioimport loggingimport smtplibfrom email.message import EmailMessage
from .config import get_settings
logger = logging.getLogger(__name__)
def _send_sync(to_addrs: list[str], subject: str, body: str) -> None: settings = get_settings() msg = EmailMessage() msg["Subject"] = subject msg["From"] = settings.smtp_from or settings.smtp_user msg["To"] = ", ".join(to_addrs) msg.set_content(body)
with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=10) as smtp: smtp.starttls() if settings.smtp_user: smtp.login(settings.smtp_user, settings.smtp_password) smtp.send_message(msg)
async def send_issue_report_email( to_addrs: list[str], reporter_email: str, category: str, subject: str, description: str, page_context: str,) -> None: """Best-effort notification — never raises. A submitted report is already saved to the DB and visible in the admin dashboard before this runs, so a mail-server hiccup shouldn't turn into a 500 for the person reporting the issue.""" settings = get_settings() if not settings.smtp_host or not to_addrs: logger.info( "Skipping issue-report email (SMTP not configured or no admin recipients): %s", subject, ) return
body = ( f"New issue report from {reporter_email}\n" f"Category: {category}\n" f"Page: {page_context or '(not provided)'}\n\n" f"{description}" ) try: # smtplib is blocking network I/O — keep it off the event loop the # same way bcrypt hashing is (see app/auth.py), so one slow/hung # mail-server connection can't stall every other in-flight request. await asyncio.to_thread( _send_sync, to_addrs, f"[ClassLens] New issue report: {subject}", body ) except Exception as exc: logger.warning("Failed to send issue-report email: %s", exc)134 unmodified lines135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262134 unmodified linesassert len(await database.admin_list_sessions()) == 2 # admin sees both@pytest.mark.unitasync def test_teacher_retention_windows(fresh_db):from datetime import datetime, timedelta, timezonefrom app.db import get_sessionmakerfrom app.models import LoginEvent, Teachernow = datetime.now(timezone.utc)async with get_sessionmaker()() as db:old_returning = Teacher(email="returning@example.com",password_hash="h",created_at=now - timedelta(days=40),)old_one_time = Teacher(email="onetime@example.com",password_hash="h",created_at=now - timedelta(days=40),)too_new = Teacher(email="new@example.com", password_hash="h", created_at=now - timedelta(days=3))db.add_all([old_returning, old_one_time, too_new])await db.flush()# Returning teacher logged in again well after both the week and# month cutoffs from their signup.db.add(LoginEvent(role="teacher", user_id=old_returning.id, created_at=now - timedelta(days=2)))await db.commit()retention = await database.get_teacher_retention()# Only the two 40-day-old accounts are eligible for either window — the# 3-day-old one hasn't existed long enough to judge yet.assert retention["week"]["eligible"] == 2assert retention["week"]["retained"] == 1assert retention["week"]["pct"] == 50.0assert retention["month"]["eligible"] == 2assert retention["month"]["retained"] == 1@pytest.mark.unitasync def test_feedback_loop_funnel_stages(fresh_db):from datetime import datetime, timedelta, timezonefrom app.db import get_sessionmakerfrom app.models import PracticeQuiz, Quiz, StudentResultuid = await database.create_user("t@example.com", "h")s1 = await database.match_or_create_student(uid, "Alice")s2 = await database.match_or_create_student(uid, "Bob")now = datetime.now(timezone.utc)t0 = now - timedelta(days=10)async with get_sessionmaker()() as db:quiz1 = Quiz(teacher_id=uid, title="Exam 1", status="saved", created_at=t0)db.add(quiz1)await db.flush()db.add_all([# Alice: weakness identified, practice generated + completed,# then reassessed with a later real exam — completes all 5 stages.StudentResult(quiz_id=quiz1.id, student_id=s1, score=60.0, weaknesses="verb tense"),# Bob: no weakness identified — stops at stage 1.StudentResult(quiz_id=quiz1.id, student_id=s2, score=95.0, weaknesses=""),])db.add(PracticeQuiz(teacher_id=uid,student_id=s1,share_token="tok1",status="completed",created_at=t0 + timedelta(days=1),completed_at=t0 + timedelta(days=2),))await db.flush()quiz2 = Quiz(teacher_id=uid, title="Exam 2", status="saved", created_at=t0 + timedelta(days=3))db.add(quiz2)await db.flush()db.add(StudentResult(quiz_id=quiz2.id, student_id=s1, score=80.0))await db.commit()funnel = await database.get_feedback_loop_funnel()# Alice+Bob's results on quiz1, plus Alice's reassessment result on quiz2.assert funnel["uploaded"] == 3assert funnel["weakness_identified"] == 1 # Alice onlyassert funnel["practice_generated"] == 1assert funnel["practice_completed"] == 1assert funnel["reassessed"] == 1 # Alice's quiz2 came after her practice completed@pytest.mark.unitasync def test_issue_report_lifecycle(fresh_db):admin_id = await database.create_user("admin@example.com", "h")await database.set_user_admin(admin_id, True)await database.create_user("teacher@example.com", "h")assert await database.get_admin_emails() == ["admin@example.com"]created = await database.create_issue_report("teacher@example.com", "bug", "Upload fails", "Steps to reproduce...", "/dashboard")assert created["status"] == "open"open_issues = await database.list_open_issue_reports()assert len(open_issues) == 1assert open_issues[0]["subject"] == "Upload fails"assert await database.dismiss_issue_report(created["id"]) is Trueassert await database.list_open_issue_reports() == []# Already dismissed — dismissing again finds nothing to update.assert await database.dismiss_issue_report(created["id"]) is False@pytest.mark.unitdef test_score_student_grades_only_concrete_keys():grid = grid_from_dict(134 unmodified lines135136137138139140134 unmodified linesassert len(await database.admin_list_sessions()) == 2 # admin sees both@pytest.mark.unitdef test_score_student_grades_only_concrete_keys():grid = grid_from_dict(
chatkit/backend/alembic/versions/0015_issue_reports.pyDeleted-54
chatkit/backend/app/admin.py-32
chatkit/backend/app/auth.py+2-2
chatkit/backend/app/config.py-15
chatkit/backend/app/database.py-232
chatkit/backend/app/main.py-52
chatkit/backend/app/models.py-23
chatkit/backend/app/notifications.pyDeleted-68
chatkit/backend/tests/test_database.py-122