Spaces:
Runtime error

cipher-attack copilot-swe-agent[bot] commited on
Commit
367a22d
·
unverified ·
1 Parent(s): 708cda4

feat: add Telegram Mini App quiz admin

Browse files

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

.env.example CHANGED
@@ -5,6 +5,8 @@ GATE_CHANNEL=@DBUCentral
5
  ADMIN_IDS=111111,222222
6
  DEFAULT_LANG=am
7
  LOG_LEVEL=INFO
 
 
8
 
9
  # Watermark stamped on every uploaded PDF (defaults shown)
10
  WATERMARK_ENABLED=true
 
5
  ADMIN_IDS=111111,222222
6
  DEFAULT_LANG=am
7
  LOG_LEVEL=INFO
8
+ # Optional. Hugging Face Spaces uses SPACE_HOST automatically when this is blank.
9
+ # MINI_APP_URL=https://your-space.hf.space
10
 
11
  # Watermark stamped on every uploaded PDF (defaults shown)
12
  WATERMARK_ENABLED=true
app.py CHANGED
@@ -1,12 +1,12 @@
1
- """Hugging Face Space entrypoint (Gradio SDK).
2
-
3
- Gradio only serves a tiny status page (also used for uptime pings).
4
- The Telegram bot runs in a background thread.
5
- """
6
  import asyncio
 
7
  import threading
 
8
 
9
- import gradio as gr
 
 
10
 
11
  try: # ZeroGPU Spaces expect at least one @spaces.GPU function
12
  import spaces
@@ -18,6 +18,21 @@ except ImportError: # running locally
18
  pass
19
 
20
  from app.main import run_bot_forever
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
 
23
  def _runner() -> None:
@@ -26,8 +41,5 @@ def _runner() -> None:
26
 
27
  threading.Thread(target=_runner, daemon=True, name="telegram-bot").start()
28
 
29
- with gr.Blocks(title="DBU Central Bot") as demo:
30
- gr.Markdown("### DBU Central Bot is running ✅")
31
-
32
  if __name__ == "__main__":
33
- demo.launch()
 
1
+ """Telegram Mini App and background bot entrypoint."""
 
 
 
 
2
  import asyncio
3
+ import os
4
  import threading
5
+ from pathlib import Path
6
 
7
+ from fastapi import FastAPI
8
+ from fastapi.responses import FileResponse
9
+ import uvicorn
10
 
11
  try: # ZeroGPU Spaces expect at least one @spaces.GPU function
12
  import spaces
 
18
  pass
19
 
20
  from app.main import run_bot_forever
21
+ from app.webapp.api import router as webapp_router
22
+
23
+ app = FastAPI(title="DBU Central Bot Mini App")
24
+ app.include_router(webapp_router, prefix="/api")
25
+ _WEBAPP_PAGE = Path(__file__).parent / "app" / "webapp" / "index.html"
26
+
27
+
28
+ @app.get("/", include_in_schema=False)
29
+ async def webapp_home() -> FileResponse:
30
+ return FileResponse(_WEBAPP_PAGE, media_type="text/html")
31
+
32
+
33
+ @app.get("/healthz", include_in_schema=False)
34
+ async def health() -> dict[str, str]:
35
+ return {"status": "ok"}
36
 
37
 
38
  def _runner() -> None:
 
41
 
42
  threading.Thread(target=_runner, daemon=True, name="telegram-bot").start()
43
 
 
 
 
44
  if __name__ == "__main__":
45
+ uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))
app/bot/handlers/__init__.py CHANGED
@@ -1,6 +1,6 @@
1
  from aiogram import Router
2
 
3
- from app.bot.handlers import admin, admin_queue, analytics, channel_posts, contribute, gate, groups, inline, library, menu, search, start
4
 
5
 
6
  def build_router() -> Router:
@@ -8,6 +8,7 @@ def build_router() -> Router:
8
  # order matters: specific handlers first, plain-text search fallback LAST
9
  router.include_router(gate.router)
10
  router.include_router(admin.router)
 
11
  router.include_router(admin_queue.router)
12
  router.include_router(analytics.router)
13
  router.include_router(channel_posts.router)
 
1
  from aiogram import Router
2
 
3
+ from app.bot.handlers import admin, admin_queue, analytics, channel_posts, contribute, gate, groups, inline, library, menu, quiz, search, start
4
 
5
 
6
  def build_router() -> Router:
 
8
  # order matters: specific handlers first, plain-text search fallback LAST
9
  router.include_router(gate.router)
10
  router.include_router(admin.router)
11
+ router.include_router(quiz.router)
12
  router.include_router(admin_queue.router)
13
  router.include_router(analytics.router)
14
  router.include_router(channel_posts.router)
app/bot/handlers/quiz.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import html
2
+ from datetime import datetime, timezone
3
+
4
+ from aiogram import F, Router
5
+ from aiogram.filters import Command
6
+ from aiogram.types import (
7
+ CallbackQuery,
8
+ InlineKeyboardButton,
9
+ InlineKeyboardMarkup,
10
+ Message,
11
+ WebAppInfo,
12
+ )
13
+ from sqlalchemy import func, select
14
+ from sqlalchemy.ext.asyncio import AsyncSession
15
+
16
+ from app.config import get_settings
17
+ from app.core.i18n import all_translations
18
+ from app.db.models import Quiz, QuizAttempt, QuizQuestion, QuizResponse
19
+
20
+ router = Router()
21
+ router.message.filter(F.chat.type == "private")
22
+ router.callback_query.filter(F.message.chat.type == "private")
23
+ _OPTIONS = ("a", "b", "c", "d")
24
+
25
+
26
+ def _button(text: str, data: str) -> InlineKeyboardButton:
27
+ return InlineKeyboardButton(text=text, callback_data=data)
28
+
29
+
30
+ async def _question_count(session: AsyncSession, quiz_id: int) -> int:
31
+ result = await session.execute(
32
+ select(func.count()).select_from(QuizQuestion).where(QuizQuestion.quiz_id == quiz_id)
33
+ )
34
+ return int(result.scalar_one())
35
+
36
+
37
+ @router.message(Command("quiz"))
38
+ @router.message(F.text.in_(all_translations("btn_quiz")))
39
+ async def show_quizzes(message: Message, session: AsyncSession) -> None:
40
+ webapp_url = get_settings().telegram_webapp_url
41
+ if webapp_url:
42
+ button = InlineKeyboardButton(
43
+ text="የመማሪያ መተግበሪያን ክፈት",
44
+ web_app=WebAppInfo(url=webapp_url),
45
+ )
46
+ await message.answer(
47
+ "ፈተናዎችንና ውጤቶችን በመማሪያ መተግበሪያው ውስጥ ያግኙ።",
48
+ reply_markup=InlineKeyboardMarkup(inline_keyboard=[[button]]),
49
+ )
50
+ return
51
+
52
+ result = await session.execute(
53
+ select(Quiz).where(Quiz.is_active.is_(True)).order_by(Quiz.id.desc())
54
+ )
55
+ quizzes = list(result.scalars().all())
56
+ if not quizzes:
57
+ await message.answer("እስካሁን የተዘጋጀ ፈተና የለም።")
58
+ return
59
+ rows = []
60
+ for quiz in quizzes:
61
+ count = await _question_count(session, quiz.id)
62
+ rows.append([_button(f"{quiz.title[:50]} · {count}", f"qz:start:{quiz.id}")])
63
+ await message.answer("ፈተና ይምረጡ፦", reply_markup=InlineKeyboardMarkup(inline_keyboard=rows))
64
+
65
+
66
+ def _question_markup(attempt_id: int, question: QuizQuestion) -> InlineKeyboardMarkup:
67
+ return InlineKeyboardMarkup(
68
+ inline_keyboard=[
69
+ [_button(letter.upper(), f"qz:a:{attempt_id}:{question.id}:{letter}")]
70
+ for letter in _OPTIONS
71
+ ]
72
+ )
73
+
74
+
75
+ def _question_text(question: QuizQuestion, number: int, total: int) -> str:
76
+ options = "\n".join(
77
+ f"<b>{letter.upper()}.</b> {html.escape(getattr(question, f'option_{letter}'))}"
78
+ for letter in _OPTIONS
79
+ )
80
+ return f"<b>ጥያቄ {number}/{total}</b>\n{html.escape(question.prompt)}\n\n{options}"
81
+
82
+
83
+ @router.callback_query(F.data.startswith("qz:start:"))
84
+ async def start_quiz(call: CallbackQuery, session: AsyncSession) -> None:
85
+ parts = call.data.split(":")
86
+ if len(parts) != 3 or not parts[2].isdigit():
87
+ await call.answer("የፈተና መለያው ትክክል አይደለም።", show_alert=True)
88
+ return
89
+ quiz = await session.get(Quiz, int(parts[2]))
90
+ if not quiz or not quiz.is_active:
91
+ await call.answer("ይህ ፈተና አሁን አይገኝም።", show_alert=True)
92
+ return
93
+ questions_result = await session.execute(
94
+ select(QuizQuestion).where(QuizQuestion.quiz_id == quiz.id).order_by(QuizQuestion.position)
95
+ )
96
+ questions = list(questions_result.scalars().all())
97
+ if not questions:
98
+ await call.answer("ይህ ፈተና ጥያቄ የለውም።", show_alert=True)
99
+ return
100
+ attempt = QuizAttempt(quiz_id=quiz.id, user_id=call.from_user.id, question_count=len(questions))
101
+ session.add(attempt)
102
+ await session.flush()
103
+ await call.answer()
104
+ await call.message.edit_text(
105
+ f"📘 <b>{html.escape(quiz.title)}</b>\n\n{_question_text(questions[0], 1, len(questions))}",
106
+ reply_markup=_question_markup(attempt.id, questions[0]),
107
+ )
108
+
109
+
110
+ @router.callback_query(F.data.startswith("qz:a:"))
111
+ async def answer_question(call: CallbackQuery, session: AsyncSession) -> None:
112
+ parts = call.data.split(":")
113
+ if (
114
+ len(parts) != 5
115
+ or not parts[2].isdigit()
116
+ or not parts[3].isdigit()
117
+ or parts[4] not in _OPTIONS
118
+ ):
119
+ await call.answer("የመልስ ምርጫው ትክክል አይደለም።", show_alert=True)
120
+ return
121
+ _, _, attempt_value, question_value, choice = parts
122
+ attempt = await session.get(QuizAttempt, int(attempt_value))
123
+ if (
124
+ attempt is None
125
+ or attempt.user_id != call.from_user.id
126
+ or attempt.status != "in_progress"
127
+ ):
128
+ await call.answer("ይህ የፈተና ሙከራ አልተገኘም ወይም ተጠናቋል።", show_alert=True)
129
+ return
130
+
131
+ answered = await session.execute(
132
+ select(func.count())
133
+ .select_from(QuizResponse)
134
+ .where(QuizResponse.attempt_id == attempt.id)
135
+ )
136
+ index = int(answered.scalar_one())
137
+ result = await session.execute(
138
+ select(QuizQuestion)
139
+ .where(QuizQuestion.quiz_id == attempt.quiz_id)
140
+ .order_by(QuizQuestion.position)
141
+ .offset(index)
142
+ .limit(1)
143
+ )
144
+ question = result.scalar_one_or_none()
145
+ if question is None or question.id != int(question_value):
146
+ await call.answer("ይህ ጥያቄ አስቀድሞ ተመልሷል።", show_alert=True)
147
+ return
148
+
149
+ correct = choice == question.correct_option
150
+ session.add(
151
+ QuizResponse(
152
+ attempt_id=attempt.id,
153
+ question_id=question.id,
154
+ selected_option=choice,
155
+ is_correct=correct,
156
+ )
157
+ )
158
+ if correct:
159
+ attempt.correct_count += 1
160
+ await session.flush()
161
+ await call.answer("ትክክል ነው!" if correct else "ትክክል አይደለም።")
162
+
163
+ next_result = await session.execute(
164
+ select(QuizQuestion)
165
+ .where(QuizQuestion.quiz_id == attempt.quiz_id)
166
+ .order_by(QuizQuestion.position)
167
+ .offset(index + 1)
168
+ .limit(1)
169
+ )
170
+ next_question = next_result.scalar_one_or_none()
171
+ if next_question:
172
+ feedback = (
173
+ "✅ ትክክል ነው።\n\n" if correct else
174
+ f"❌ ትክክለኛው መልስ፦ {question.correct_option.upper()}. "
175
+ f"{html.escape(getattr(question, f'option_{question.correct_option}'))}\n\n"
176
+ )
177
+ await call.message.edit_text(
178
+ feedback + _question_text(next_question, index + 2, attempt.question_count),
179
+ reply_markup=_question_markup(attempt.id, next_question),
180
+ )
181
+ return
182
+
183
+ attempt.status = "completed"
184
+ attempt.completed_at = datetime.now(timezone.utc)
185
+ feedback = (
186
+ "✅ ትክክል ነው።\n" if correct else
187
+ f"❌ ትክክለኛው መልስ፦ {question.correct_option.upper()}. "
188
+ f"{html.escape(getattr(question, f'option_{question.correct_option}'))}\n"
189
+ )
190
+ await call.message.edit_text(
191
+ f"{feedback}\n🎉 <b>ፈተናው ተጠናቋል!</b>\n"
192
+ f"ውጤት፦ <b>{attempt.correct_count}/{attempt.question_count}</b>\n"
193
+ "የቅርብ ውጤቶችዎን ለማየት፦ /quizscore"
194
+ )
195
+
196
+
197
+ @router.message(Command("quizscore"))
198
+ async def show_scores(message: Message, session: AsyncSession) -> None:
199
+ result = await session.execute(
200
+ select(QuizAttempt, Quiz.title)
201
+ .join(Quiz, Quiz.id == QuizAttempt.quiz_id)
202
+ .where(QuizAttempt.user_id == message.from_user.id, QuizAttempt.status == "completed")
203
+ .order_by(QuizAttempt.completed_at.desc())
204
+ .limit(10)
205
+ )
206
+ rows = result.all()
207
+ if not rows:
208
+ await message.answer("እስካሁን የጨረሱት ፈተና የለም። /quiz በመጫን ይጀምሩ።")
209
+ return
210
+ lines = [
211
+ f"• {html.escape(title)} — {attempt.correct_count}/{attempt.question_count}"
212
+ for attempt, title in rows
213
+ ]
214
+ await message.answer("<b>የቅርብ 10 ውጤቶች</b>\n" + "\n".join(lines))
app/bot/keyboards/common.py CHANGED
@@ -3,8 +3,10 @@ from aiogram.types import (
3
  InlineKeyboardMarkup,
4
  KeyboardButton,
5
  ReplyKeyboardMarkup,
 
6
  )
7
 
 
8
  from app.core.catalog import STREAMS, YEARS
9
  from app.core.i18n import t
10
 
@@ -48,10 +50,18 @@ def main_menu(lang: str) -> ReplyKeyboardMarkup:
48
  def b(key: str) -> KeyboardButton:
49
  return KeyboardButton(text=t(lang, key))
50
 
 
 
 
 
 
 
 
51
  return ReplyKeyboardMarkup(
52
  keyboard=[
53
  [b("btn_library"), b("btn_contribute")],
54
- [b("btn_profile"), b("btn_top")],
 
55
  [b("btn_gpa"), b("btn_invite")],
56
  ],
57
  resize_keyboard=True,
 
3
  InlineKeyboardMarkup,
4
  KeyboardButton,
5
  ReplyKeyboardMarkup,
6
+ WebAppInfo,
7
  )
8
 
9
+ from app.config import get_settings
10
  from app.core.catalog import STREAMS, YEARS
11
  from app.core.i18n import t
12
 
 
50
  def b(key: str) -> KeyboardButton:
51
  return KeyboardButton(text=t(lang, key))
52
 
53
+ mini_app_url = get_settings().telegram_webapp_url
54
+ quiz_button = (
55
+ KeyboardButton(text=t(lang, "btn_quiz"), web_app=WebAppInfo(url=mini_app_url))
56
+ if mini_app_url
57
+ else b("btn_quiz")
58
+ )
59
+
60
  return ReplyKeyboardMarkup(
61
  keyboard=[
62
  [b("btn_library"), b("btn_contribute")],
63
+ [quiz_button, b("btn_profile")],
64
+ [b("btn_top")],
65
  [b("btn_gpa"), b("btn_invite")],
66
  ],
67
  resize_keyboard=True,
app/bot/manual.py CHANGED
@@ -130,7 +130,14 @@ def sections(f: dict) -> list[tuple[str, str, list[Cmd]]]:
130
  "and a badge at 1, 5 and 15 approved files. Rejecting tells them why; 3 rejections in 14 days "
131
  "pause their uploads for 7 days.", "Review student files"),
132
  ]),
133
- ("5) XP, weekly season and prizes",
 
 
 
 
 
 
 
134
  f"XP: daily check-in 3-7, download +1, invite +{f['ref_join']} when a friend joins and "
135
  f"+{f['ref_qualified']} when they become active (max {f['ref_weekly']} a week), contributions above. "
136
  f"Automatic XP is capped at {f['daily_cap']} a day. Every XP is written to an unchangeable ledger.", [
@@ -156,7 +163,7 @@ def sections(f: dict) -> list[tuple[str, str, list[Cmd]]]:
156
  "Your tool against cheating: act when /season shows a flag.",
157
  "Every change is logged.", "Change a student's trust score"),
158
  ]),
159
- ("6) Growth and the channel", "", [
160
  Cmd("growth", "/growth",
161
  "New students per day (7 days) and, for each source (poster, inline, referral, group, tags), how "
162
  "many joined, passed the join check, finished onboarding and were still active after 3 days. Also "
@@ -184,7 +191,7 @@ def sections(f: dict) -> list[tuple[str, str, list[Cmd]]]:
184
  "Your announcement always matches what the bot really does.",
185
  "Prizes are only mentioned when they are switched on.", "Write/post the channel announcement"),
186
  ]),
187
- ("7) System", "", [
188
  Cmd("stats", "/stats", "Totals: users, how many passed the join check, onboarded, active today, "
189
  "referrals, courses, files, downloads and files waiting for review.",
190
  "A quick health check of the whole project.", "", "Key numbers"),
@@ -203,6 +210,9 @@ def settings_text(f: dict) -> str:
203
  "<b>8) Settings (Hugging Face Space → Settings → Secrets)</b>\n"
204
  "BOT_TOKEN, DATABASE_URL: required.\n"
205
  "ADMIN_IDS: your Telegram id(s), comma separated.\n"
 
 
 
206
  "GATE_CHANNELS: places students must join (default: the channel and the forum).\n"
207
  "LIBRARY_CHANNEL_ID: private channel that stores the stamped PDFs (backup).\n"
208
  "PRIZES_ENABLED (default true), PRIZE_TOP (default 50,30,20), PRIZE_RAFFLE (10), MIN_WEEK_XP (40), "
 
130
  "and a badge at 1, 5 and 15 approved files. Rejecting tells them why; 3 rejections in 14 days "
131
  "pause their uploads for 7 days.", "Review student files"),
132
  ]),
133
+ ("5) Practice quizzes", "Quiz creation and management are available in the Telegram Mini App admin panel. "
134
+ "Only Telegram IDs in ADMIN_IDS can open that panel.", [
135
+ Cmd("quiz", "/quiz", "Shows available practice quizzes to students.",
136
+ "Opens the Mini App when configured, or the bot quiz list otherwise.", "", "Practice quizzes"),
137
+ Cmd("quizscore", "/quizscore", "Shows a student's 10 most recent quiz scores.",
138
+ "Scores are separate from XP and do not affect the weekly contest.", "", "Recent quiz scores"),
139
+ ]),
140
+ ("6) XP, weekly season and prizes",
141
  f"XP: daily check-in 3-7, download +1, invite +{f['ref_join']} when a friend joins and "
142
  f"+{f['ref_qualified']} when they become active (max {f['ref_weekly']} a week), contributions above. "
143
  f"Automatic XP is capped at {f['daily_cap']} a day. Every XP is written to an unchangeable ledger.", [
 
163
  "Your tool against cheating: act when /season shows a flag.",
164
  "Every change is logged.", "Change a student's trust score"),
165
  ]),
166
+ ("7) Growth and the channel", "", [
167
  Cmd("growth", "/growth",
168
  "New students per day (7 days) and, for each source (poster, inline, referral, group, tags), how "
169
  "many joined, passed the join check, finished onboarding and were still active after 3 days. Also "
 
191
  "Your announcement always matches what the bot really does.",
192
  "Prizes are only mentioned when they are switched on.", "Write/post the channel announcement"),
193
  ]),
194
+ ("8) System", "", [
195
  Cmd("stats", "/stats", "Totals: users, how many passed the join check, onboarded, active today, "
196
  "referrals, courses, files, downloads and files waiting for review.",
197
  "A quick health check of the whole project.", "", "Key numbers"),
 
210
  "<b>8) Settings (Hugging Face Space → Settings → Secrets)</b>\n"
211
  "BOT_TOKEN, DATABASE_URL: required.\n"
212
  "ADMIN_IDS: your Telegram id(s), comma separated.\n"
213
+ "MINI_APP_URL: optional HTTPS URL for the Mini App (Hugging Face SPACE_HOST is used when blank). "
214
+ "Set the bot's domain with /setdomain in BotFather. The admin panel uses ADMIN_IDS and Telegram's "
215
+ "signed Mini App profile.\n"
216
  "GATE_CHANNELS: places students must join (default: the channel and the forum).\n"
217
  "LIBRARY_CHANNEL_ID: private channel that stores the stamped PDFs (backup).\n"
218
  "PRIZES_ENABLED (default true), PRIZE_TOP (default 50,30,20), PRIZE_RAFFLE (10), MIN_WEEK_XP (40), "
app/config.py CHANGED
@@ -1,4 +1,5 @@
1
 
 
2
  from functools import lru_cache
3
 
4
  from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -27,6 +28,7 @@ class Settings(BaseSettings):
27
  admin_ids: str = ""
28
  default_lang: str = "en"
29
  library_channel_id: int = 0
 
30
 
31
  log_level: str = "INFO"
32
 
@@ -124,6 +126,17 @@ class Settings(BaseSettings):
124
  if value.isdigit()
125
  }
126
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  @lru_cache
129
  def get_settings() -> Settings:
 
1
 
2
+ import os
3
  from functools import lru_cache
4
 
5
  from pydantic_settings import BaseSettings, SettingsConfigDict
 
28
  admin_ids: str = ""
29
  default_lang: str = "en"
30
  library_channel_id: int = 0
31
+ mini_app_url: str = ""
32
 
33
  log_level: str = "INFO"
34
 
 
126
  if value.isdigit()
127
  }
128
 
129
+ @property
130
+ def telegram_webapp_url(self) -> str:
131
+ """Return the configured HTTPS URL, or the Hugging Face Space URL."""
132
+ url = self.mini_app_url.strip()
133
+ if not url:
134
+ host = os.getenv("SPACE_HOST", "").strip().strip("/")
135
+ url = f"https://{host}" if host else ""
136
+ if not url.startswith("https://"):
137
+ return ""
138
+ return url.rstrip("/")
139
+
140
 
141
  @lru_cache
142
  def get_settings() -> Settings:
app/db/models/__init__.py CHANGED
@@ -3,9 +3,14 @@ from app.db.models.course import Course
3
  from app.db.models.group import BotGroup
4
  from app.db.models.material import Material
5
  from app.db.models.pending import PendingMaterial
 
6
  from app.db.models.referral import Referral
7
  from app.db.models.submission import Submission
8
  from app.db.models.user import User
9
  from app.db.models.xp import SeasonResult, XpEvent
10
 
11
- __all__ = ["User", "Course", "Material", "Referral", "PendingMaterial", "XpEvent", "SeasonResult", "BotGroup", "Submission", "ActivityEvent", "ChannelPost"]
 
 
 
 
 
3
  from app.db.models.group import BotGroup
4
  from app.db.models.material import Material
5
  from app.db.models.pending import PendingMaterial
6
+ from app.db.models.quiz import Quiz, QuizAttempt, QuizQuestion, QuizResponse
7
  from app.db.models.referral import Referral
8
  from app.db.models.submission import Submission
9
  from app.db.models.user import User
10
  from app.db.models.xp import SeasonResult, XpEvent
11
 
12
+ __all__ = [
13
+ "User", "Course", "Material", "Referral", "PendingMaterial", "XpEvent", "SeasonResult",
14
+ "BotGroup", "Submission", "ActivityEvent", "ChannelPost", "Quiz", "QuizQuestion",
15
+ "QuizAttempt", "QuizResponse",
16
+ ]
app/db/models/quiz.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Optional
3
+
4
+ from sqlalchemy import (
5
+ BigInteger,
6
+ Boolean,
7
+ DateTime,
8
+ ForeignKey,
9
+ Integer,
10
+ String,
11
+ Text,
12
+ UniqueConstraint,
13
+ func,
14
+ )
15
+ from sqlalchemy.orm import Mapped, mapped_column
16
+
17
+ from app.db.base import Base
18
+
19
+
20
+ class Quiz(Base):
21
+ __tablename__ = "quizzes"
22
+
23
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
24
+ title: Mapped[str] = mapped_column(String(120))
25
+ created_by: Mapped[int] = mapped_column(BigInteger)
26
+ is_active: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
27
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
28
+
29
+
30
+ class QuizQuestion(Base):
31
+ __tablename__ = "quiz_questions"
32
+ __table_args__ = (UniqueConstraint("quiz_id", "position", name="uq_quiz_question_position"),)
33
+
34
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
35
+ quiz_id: Mapped[int] = mapped_column(ForeignKey("quizzes.id", ondelete="CASCADE"), index=True)
36
+ position: Mapped[int] = mapped_column(Integer)
37
+ prompt: Mapped[str] = mapped_column(Text)
38
+ option_a: Mapped[str] = mapped_column(String(300))
39
+ option_b: Mapped[str] = mapped_column(String(300))
40
+ option_c: Mapped[str] = mapped_column(String(300))
41
+ option_d: Mapped[str] = mapped_column(String(300))
42
+ correct_option: Mapped[str] = mapped_column(String(1))
43
+
44
+
45
+ class QuizAttempt(Base):
46
+ __tablename__ = "quiz_attempts"
47
+
48
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
49
+ quiz_id: Mapped[int] = mapped_column(ForeignKey("quizzes.id"), index=True)
50
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
51
+ correct_count: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
52
+ question_count: Mapped[int] = mapped_column(Integer)
53
+ status: Mapped[str] = mapped_column(String(12), default="in_progress", server_default="in_progress")
54
+ started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
55
+ completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
56
+
57
+
58
+ class QuizResponse(Base):
59
+ __tablename__ = "quiz_responses"
60
+ __table_args__ = (UniqueConstraint("attempt_id", "question_id", name="uq_quiz_response_attempt_question"),)
61
+
62
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
63
+ attempt_id: Mapped[int] = mapped_column(ForeignKey("quiz_attempts.id", ondelete="CASCADE"), index=True)
64
+ question_id: Mapped[int] = mapped_column(ForeignKey("quiz_questions.id"), index=True)
65
+ selected_option: Mapped[str] = mapped_column(String(1))
66
+ is_correct: Mapped[bool] = mapped_column(Boolean)
67
+ answered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
app/services/quiz_rules.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def normalize_choice(value: str) -> str | None:
2
+ """Normalize an admin's correct-answer entry to the stored option key."""
3
+ normalized = value.strip().lower()
4
+ return {
5
+ "a": "a",
6
+ "1": "a",
7
+ "b": "b",
8
+ "2": "b",
9
+ "c": "c",
10
+ "3": "c",
11
+ "d": "d",
12
+ "4": "d",
13
+ }.get(normalized)
app/webapp/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Telegram Mini App HTTP interface."""
app/webapp/api.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timezone
2
+ from typing import Literal
3
+
4
+ from fastapi import APIRouter, Depends, Header, HTTPException
5
+ from pydantic import BaseModel, Field, field_validator
6
+ from sqlalchemy import delete, func, select
7
+ from sqlalchemy.ext.asyncio import AsyncSession
8
+
9
+ from app.config import get_settings
10
+ from app.db.models import Quiz, QuizAttempt, QuizQuestion, QuizResponse, User
11
+ from app.db.session import SessionFactory
12
+ from app.webapp.auth import TelegramIdentity, validate_init_data
13
+
14
+ router = APIRouter()
15
+
16
+
17
+ class QuizInput(BaseModel):
18
+ title: str = Field(min_length=1, max_length=120)
19
+
20
+ @field_validator("title")
21
+ @classmethod
22
+ def clean_title(cls, value: str) -> str:
23
+ value = value.strip()
24
+ if not value:
25
+ raise ValueError("የፈተና ርዕስ ባዶ መሆን የለበትም።")
26
+ return value
27
+
28
+
29
+ class QuizUpdate(BaseModel):
30
+ title: str | None = Field(default=None, min_length=1, max_length=120)
31
+ is_active: bool | None = None
32
+
33
+ @field_validator("title")
34
+ @classmethod
35
+ def clean_title(cls, value: str | None) -> str | None:
36
+ if value is None:
37
+ return None
38
+ value = value.strip()
39
+ if not value:
40
+ raise ValueError("የፈተና ርዕስ ባዶ መሆን የለበትም።")
41
+ return value
42
+
43
+
44
+ class QuestionInput(BaseModel):
45
+ prompt: str = Field(min_length=1, max_length=1000)
46
+ options: list[str] = Field(min_length=4, max_length=4)
47
+ correct_option: Literal["a", "b", "c", "d"]
48
+
49
+ @field_validator("prompt")
50
+ @classmethod
51
+ def clean_prompt(cls, value: str) -> str:
52
+ value = value.strip()
53
+ if not value:
54
+ raise ValueError("ጥያቄው ባዶ መሆን የለበትም።")
55
+ return value
56
+
57
+ @field_validator("options")
58
+ @classmethod
59
+ def clean_options(cls, values: list[str]) -> list[str]:
60
+ cleaned = [value.strip() for value in values]
61
+ if any(not value or len(value) > 300 for value in cleaned):
62
+ raise ValueError("እያንዳንዱ ምርጫ ከ1 እስከ 300 ፊደላት ይሁን።")
63
+ return cleaned
64
+
65
+
66
+ class AnswerInput(BaseModel):
67
+ question_id: int = Field(gt=0)
68
+ choice: Literal["a", "b", "c", "d"]
69
+
70
+
71
+ async def telegram_identity(
72
+ x_telegram_init_data: str | None = Header(default=None, alias="X-Telegram-Init-Data"),
73
+ ) -> TelegramIdentity:
74
+ try:
75
+ return validate_init_data(x_telegram_init_data or "", get_settings().bot_token)
76
+ except ValueError as exc:
77
+ raise HTTPException(status_code=401, detail="ይህን ገጽ ከቴሌግራም ቦቱ ይክፈቱ።") from exc
78
+
79
+
80
+ def _require_admin(identity: TelegramIdentity) -> None:
81
+ if identity.user_id not in get_settings().admin_id_set:
82
+ raise HTTPException(status_code=403, detail="የአስተዳዳሪ ፈቃድ ያስፈልጋል።")
83
+
84
+
85
+ async def _require_student_or_admin(identity: TelegramIdentity, session: AsyncSession) -> None:
86
+ if identity.user_id in get_settings().admin_id_set:
87
+ return
88
+ user = await session.get(User, identity.user_id)
89
+ if user is None:
90
+ raise HTTPException(status_code=403, detail="መጀመሪያ ቦቱን ከፍተው ምዝገባዎን ያጠናቅቁ።")
91
+ if user.is_banned or not user.gate_passed:
92
+ raise HTTPException(status_code=403, detail="ፈተናዎችን ለመጠቀም የቦቱን ምዝገባ ያጠናቅቁ።")
93
+
94
+
95
+ async def _counts(session: AsyncSession, quiz_id: int) -> tuple[int, int]:
96
+ questions = await session.scalar(
97
+ select(func.count()).select_from(QuizQuestion).where(QuizQuestion.quiz_id == quiz_id)
98
+ )
99
+ attempts = await session.scalar(
100
+ select(func.count()).select_from(QuizAttempt).where(QuizAttempt.quiz_id == quiz_id)
101
+ )
102
+ return int(questions or 0), int(attempts or 0)
103
+
104
+
105
+ def _question_data(question: QuizQuestion, *, position: int | None = None) -> dict:
106
+ return {
107
+ "id": question.id,
108
+ "position": position if position is not None else question.position,
109
+ "prompt": question.prompt,
110
+ "options": [
111
+ question.option_a,
112
+ question.option_b,
113
+ question.option_c,
114
+ question.option_d,
115
+ ],
116
+ }
117
+
118
+
119
+ def _admin_question_data(question: QuizQuestion) -> dict:
120
+ return {
121
+ **_question_data(question),
122
+ "correct_option": question.correct_option,
123
+ }
124
+
125
+
126
+ async def _has_attempts(session: AsyncSession, quiz_id: int) -> bool:
127
+ return bool(await session.scalar(
128
+ select(func.count()).select_from(QuizAttempt).where(QuizAttempt.quiz_id == quiz_id)
129
+ ))
130
+
131
+
132
+ @router.get("/session")
133
+ async def get_session(identity: TelegramIdentity = Depends(telegram_identity)) -> dict:
134
+ is_admin = identity.user_id in get_settings().admin_id_set
135
+ async with SessionFactory() as session:
136
+ if not is_admin:
137
+ user = await session.get(User, identity.user_id)
138
+ if user is None or user.is_banned or not user.gate_passed:
139
+ raise HTTPException(status_code=403, detail="ፈተናዎችን ለመጠቀም የቦቱን ምዝገባ ያጠናቅቁ።")
140
+ profile = identity.profile
141
+ return {
142
+ "id": identity.user_id,
143
+ "first_name": profile.get("first_name", ""),
144
+ "last_name": profile.get("last_name", ""),
145
+ "username": profile.get("username", ""),
146
+ "photo_url": profile.get("photo_url", ""),
147
+ "is_admin": is_admin,
148
+ }
149
+
150
+
151
+ @router.get("/quizzes")
152
+ async def list_student_quizzes(identity: TelegramIdentity = Depends(telegram_identity)) -> list[dict]:
153
+ async with SessionFactory() as session:
154
+ await _require_student_or_admin(identity, session)
155
+ quizzes_result = await session.execute(
156
+ select(Quiz).where(Quiz.is_active.is_(True)).order_by(Quiz.id.desc())
157
+ )
158
+ quizzes = list(quizzes_result.scalars().all())
159
+ output = []
160
+ for quiz in quizzes:
161
+ count, _ = await _counts(session, quiz.id)
162
+ output.append({"id": quiz.id, "title": quiz.title, "question_count": count})
163
+ return output
164
+
165
+
166
+ @router.get("/scores")
167
+ async def list_student_scores(identity: TelegramIdentity = Depends(telegram_identity)) -> list[dict]:
168
+ async with SessionFactory() as session:
169
+ await _require_student_or_admin(identity, session)
170
+ result = await session.execute(
171
+ select(QuizAttempt, Quiz.title)
172
+ .join(Quiz, Quiz.id == QuizAttempt.quiz_id)
173
+ .where(QuizAttempt.user_id == identity.user_id, QuizAttempt.status == "completed")
174
+ .order_by(QuizAttempt.completed_at.desc())
175
+ .limit(20)
176
+ )
177
+ return [
178
+ {
179
+ "quiz": title,
180
+ "correct": attempt.correct_count,
181
+ "total": attempt.question_count,
182
+ "completed_at": attempt.completed_at.isoformat() if attempt.completed_at else None,
183
+ }
184
+ for attempt, title in result.all()
185
+ ]
186
+
187
+
188
+ @router.post("/quizzes/{quiz_id}/start")
189
+ async def start_quiz(
190
+ quiz_id: int,
191
+ identity: TelegramIdentity = Depends(telegram_identity),
192
+ ) -> dict:
193
+ async with SessionFactory() as session:
194
+ await _require_student_or_admin(identity, session)
195
+ quiz = await session.get(Quiz, quiz_id)
196
+ if quiz is None or not quiz.is_active:
197
+ raise HTTPException(status_code=404, detail="ፈተናው አልተገኘም።")
198
+ result = await session.execute(
199
+ select(QuizQuestion).where(QuizQuestion.quiz_id == quiz.id).order_by(QuizQuestion.position)
200
+ )
201
+ questions = list(result.scalars().all())
202
+ if not questions:
203
+ raise HTTPException(status_code=409, detail="ይህ ፈተና ጥያቄዎች የሉትም።")
204
+ attempt = QuizAttempt(
205
+ quiz_id=quiz.id,
206
+ user_id=identity.user_id,
207
+ question_count=len(questions),
208
+ )
209
+ session.add(attempt)
210
+ await session.flush()
211
+ response = {
212
+ "attempt_id": attempt.id,
213
+ "quiz_title": quiz.title,
214
+ "question": _question_data(questions[0], position=1),
215
+ "total": len(questions),
216
+ }
217
+ await session.commit()
218
+ return response
219
+
220
+
221
+ @router.post("/attempts/{attempt_id}/answer")
222
+ async def answer_question(
223
+ attempt_id: int,
224
+ answer: AnswerInput,
225
+ identity: TelegramIdentity = Depends(telegram_identity),
226
+ ) -> dict:
227
+ question_id, choice = answer.question_id, answer.choice
228
+ async with SessionFactory() as session:
229
+ await _require_student_or_admin(identity, session)
230
+ attempt_result = await session.execute(
231
+ select(QuizAttempt)
232
+ .where(QuizAttempt.id == attempt_id)
233
+ .with_for_update()
234
+ )
235
+ attempt = attempt_result.scalar_one_or_none()
236
+ if (
237
+ attempt is None
238
+ or attempt.user_id != identity.user_id
239
+ or attempt.status != "in_progress"
240
+ ):
241
+ raise HTTPException(status_code=404, detail="የፈተና ሙከራው አልተገኘም።")
242
+
243
+ answered_count = await session.scalar(
244
+ select(func.count())
245
+ .select_from(QuizResponse)
246
+ .where(QuizResponse.attempt_id == attempt.id)
247
+ )
248
+ index = int(answered_count or 0)
249
+ result = await session.execute(
250
+ select(QuizQuestion)
251
+ .where(QuizQuestion.quiz_id == attempt.quiz_id)
252
+ .order_by(QuizQuestion.position)
253
+ .offset(index)
254
+ .limit(1)
255
+ )
256
+ question = result.scalar_one_or_none()
257
+ if question is None or question.id != question_id:
258
+ raise HTTPException(status_code=409, detail="ይህ ጥያቄ አስቀድሞ ተመልሷል።")
259
+
260
+ correct = choice == question.correct_option
261
+ session.add(
262
+ QuizResponse(
263
+ attempt_id=attempt.id,
264
+ question_id=question.id,
265
+ selected_option=choice,
266
+ is_correct=correct,
267
+ )
268
+ )
269
+ if correct:
270
+ attempt.correct_count += 1
271
+
272
+ next_result = await session.execute(
273
+ select(QuizQuestion)
274
+ .where(QuizQuestion.quiz_id == attempt.quiz_id)
275
+ .order_by(QuizQuestion.position)
276
+ .offset(index + 1)
277
+ .limit(1)
278
+ )
279
+ next_question = next_result.scalar_one_or_none()
280
+ response = {
281
+ "correct": correct,
282
+ "correct_option": question.correct_option,
283
+ "correct_text": getattr(question, f"option_{question.correct_option}"),
284
+ "next_question": (
285
+ _question_data(next_question, position=index + 2) if next_question else None
286
+ ),
287
+ "score": attempt.correct_count,
288
+ "total": attempt.question_count,
289
+ "complete": next_question is None,
290
+ }
291
+ if next_question is None:
292
+ attempt.status = "completed"
293
+ attempt.completed_at = datetime.now(timezone.utc)
294
+ await session.commit()
295
+ return response
296
+
297
+
298
+ @router.get("/admin/quizzes")
299
+ async def list_admin_quizzes(identity: TelegramIdentity = Depends(telegram_identity)) -> list[dict]:
300
+ _require_admin(identity)
301
+ async with SessionFactory() as session:
302
+ result = await session.execute(select(Quiz).order_by(Quiz.id.desc()))
303
+ quizzes = list(result.scalars().all())
304
+ output = []
305
+ for quiz in quizzes:
306
+ question_count, attempt_count = await _counts(session, quiz.id)
307
+ output.append({
308
+ "id": quiz.id,
309
+ "title": quiz.title,
310
+ "is_active": quiz.is_active,
311
+ "question_count": question_count,
312
+ "attempt_count": attempt_count,
313
+ })
314
+ return output
315
+
316
+
317
+ @router.post("/admin/quizzes", status_code=201)
318
+ async def create_admin_quiz(
319
+ body: QuizInput,
320
+ identity: TelegramIdentity = Depends(telegram_identity),
321
+ ) -> dict:
322
+ _require_admin(identity)
323
+ async with SessionFactory() as session:
324
+ quiz = Quiz(title=body.title, created_by=identity.user_id)
325
+ session.add(quiz)
326
+ await session.flush()
327
+ response = {"id": quiz.id, "title": quiz.title, "is_active": False, "question_count": 0}
328
+ await session.commit()
329
+ return response
330
+
331
+
332
+ @router.patch("/admin/quizzes/{quiz_id}")
333
+ async def update_admin_quiz(
334
+ quiz_id: int,
335
+ body: QuizUpdate,
336
+ identity: TelegramIdentity = Depends(telegram_identity),
337
+ ) -> dict:
338
+ _require_admin(identity)
339
+ if body.title is None and body.is_active is None:
340
+ raise HTTPException(status_code=422, detail="ለማስተካከል ርዕስ ወይም የህትመት ሁኔታ ይምረጡ።")
341
+ async with SessionFactory() as session:
342
+ quiz = await session.get(Quiz, quiz_id)
343
+ if quiz is None:
344
+ raise HTTPException(status_code=404, detail="ፈተናው አልተገኘም።")
345
+ if body.title is not None:
346
+ quiz.title = body.title
347
+ if body.is_active is not None:
348
+ question_count, _ = await _counts(session, quiz.id)
349
+ if body.is_active and question_count == 0:
350
+ raise HTTPException(status_code=409, detail="ከማተምዎ በፊት ቢያንስ አንድ ጥያቄ ያስገቡ።")
351
+ quiz.is_active = body.is_active
352
+ question_count, attempt_count = await _counts(session, quiz.id)
353
+ await session.commit()
354
+ return {
355
+ "id": quiz.id,
356
+ "title": quiz.title,
357
+ "is_active": quiz.is_active,
358
+ "question_count": question_count,
359
+ "attempt_count": attempt_count,
360
+ }
361
+
362
+
363
+ @router.delete("/admin/quizzes/{quiz_id}", status_code=204)
364
+ async def delete_admin_quiz(
365
+ quiz_id: int,
366
+ identity: TelegramIdentity = Depends(telegram_identity),
367
+ ) -> None:
368
+ _require_admin(identity)
369
+ async with SessionFactory() as session:
370
+ quiz = await session.get(Quiz, quiz_id)
371
+ if quiz is None:
372
+ raise HTTPException(status_code=404, detail="ፈተናው አልተገኘም።")
373
+ if await _has_attempts(session, quiz.id):
374
+ raise HTTPException(status_code=409, detail="ሙከራ የተመዘገበበትን ፈተና ማጥፋት አይቻልም።")
375
+ await session.execute(delete(QuizQuestion).where(QuizQuestion.quiz_id == quiz.id))
376
+ await session.delete(quiz)
377
+ await session.commit()
378
+
379
+
380
+ @router.get("/admin/quizzes/{quiz_id}/questions")
381
+ async def list_admin_questions(
382
+ quiz_id: int,
383
+ identity: TelegramIdentity = Depends(telegram_identity),
384
+ ) -> list[dict]:
385
+ _require_admin(identity)
386
+ async with SessionFactory() as session:
387
+ quiz = await session.get(Quiz, quiz_id)
388
+ if quiz is None:
389
+ raise HTTPException(status_code=404, detail="ፈተናው አልተገኘም።")
390
+ result = await session.execute(
391
+ select(QuizQuestion).where(QuizQuestion.quiz_id == quiz.id).order_by(QuizQuestion.position)
392
+ )
393
+ return [
394
+ {**_admin_question_data(question), "position": position}
395
+ for position, question in enumerate(result.scalars().all(), start=1)
396
+ ]
397
+
398
+
399
+ @router.post("/admin/quizzes/{quiz_id}/questions", status_code=201)
400
+ async def add_admin_question(
401
+ quiz_id: int,
402
+ body: QuestionInput,
403
+ identity: TelegramIdentity = Depends(telegram_identity),
404
+ ) -> dict:
405
+ _require_admin(identity)
406
+ async with SessionFactory() as session:
407
+ quiz = await session.get(Quiz, quiz_id)
408
+ if quiz is None:
409
+ raise HTTPException(status_code=404, detail="ፈተናው አልተገኘም።")
410
+ if quiz.is_active or await _has_attempts(session, quiz.id):
411
+ raise HTTPException(
412
+ status_code=409,
413
+ detail="ያልታተመና የተማሪ ሙከራ የሌለውን ፈተና ብቻ ማስተካከል ይቻላል።",
414
+ )
415
+ last_position = await session.scalar(
416
+ select(func.max(QuizQuestion.position)).where(QuizQuestion.quiz_id == quiz.id)
417
+ )
418
+ position = int(last_position or 0) + 1
419
+ question = QuizQuestion(
420
+ quiz_id=quiz.id,
421
+ position=position,
422
+ prompt=body.prompt,
423
+ option_a=body.options[0],
424
+ option_b=body.options[1],
425
+ option_c=body.options[2],
426
+ option_d=body.options[3],
427
+ correct_option=body.correct_option,
428
+ )
429
+ session.add(question)
430
+ await session.flush()
431
+ response = _admin_question_data(question)
432
+ await session.commit()
433
+ return response
434
+
435
+
436
+ @router.put("/admin/questions/{question_id}")
437
+ async def update_admin_question(
438
+ question_id: int,
439
+ body: QuestionInput,
440
+ identity: TelegramIdentity = Depends(telegram_identity),
441
+ ) -> dict:
442
+ _require_admin(identity)
443
+ async with SessionFactory() as session:
444
+ question = await session.get(QuizQuestion, question_id)
445
+ if question is None:
446
+ raise HTTPException(status_code=404, detail="ጥያቄው አልተገኘም።")
447
+ quiz = await session.get(Quiz, question.quiz_id)
448
+ if quiz is None or quiz.is_active or await _has_attempts(session, question.quiz_id):
449
+ raise HTTPException(
450
+ status_code=409,
451
+ detail="ያልታተመና የተማሪ ሙከራ የሌለውን ፈተና ብቻ ማስተካከል ይቻላል።",
452
+ )
453
+ question.prompt = body.prompt
454
+ question.option_a, question.option_b, question.option_c, question.option_d = body.options
455
+ question.correct_option = body.correct_option
456
+ response = _admin_question_data(question)
457
+ await session.commit()
458
+ return response
459
+
460
+
461
+ @router.delete("/admin/questions/{question_id}", status_code=204)
462
+ async def delete_admin_question(
463
+ question_id: int,
464
+ identity: TelegramIdentity = Depends(telegram_identity),
465
+ ) -> None:
466
+ _require_admin(identity)
467
+ async with SessionFactory() as session:
468
+ question = await session.get(QuizQuestion, question_id)
469
+ if question is None:
470
+ raise HTTPException(status_code=404, detail="ጥያቄው አልተገኘም።")
471
+ quiz = await session.get(Quiz, question.quiz_id)
472
+ if quiz is None or quiz.is_active or await _has_attempts(session, quiz.id):
473
+ raise HTTPException(
474
+ status_code=409,
475
+ detail="ያልታተመና የተማሪ ሙከራ የሌለውን ፈተና ብቻ ማስተካከል ይቻላል።",
476
+ )
477
+ await session.delete(question)
478
+ await session.commit()
479
+
480
+
481
+ @router.get("/admin/quizzes/{quiz_id}/results")
482
+ async def get_admin_results(
483
+ quiz_id: int,
484
+ identity: TelegramIdentity = Depends(telegram_identity),
485
+ ) -> list[dict]:
486
+ _require_admin(identity)
487
+ async with SessionFactory() as session:
488
+ if await session.get(Quiz, quiz_id) is None:
489
+ raise HTTPException(status_code=404, detail="ፈተናው አልተገኘም።")
490
+ result = await session.execute(
491
+ select(QuizAttempt, User.full_name, User.username)
492
+ .join(User, User.id == QuizAttempt.user_id)
493
+ .where(QuizAttempt.quiz_id == quiz_id, QuizAttempt.status == "completed")
494
+ .order_by(QuizAttempt.completed_at.desc())
495
+ .limit(100)
496
+ )
497
+ return [
498
+ {
499
+ "user_id": attempt.user_id,
500
+ "name": name,
501
+ "username": username,
502
+ "correct": attempt.correct_count,
503
+ "total": attempt.question_count,
504
+ "completed_at": attempt.completed_at.isoformat() if attempt.completed_at else None,
505
+ }
506
+ for attempt, name, username in result.all()
507
+ ]
app/webapp/auth.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import time
5
+ from dataclasses import dataclass
6
+ from urllib.parse import parse_qsl
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class TelegramIdentity:
11
+ user_id: int
12
+ profile: dict
13
+
14
+
15
+ def validate_init_data(
16
+ init_data: str,
17
+ bot_token: str,
18
+ *,
19
+ now: int | None = None,
20
+ max_age: int = 86_400,
21
+ ) -> TelegramIdentity:
22
+ """Validate Telegram's signed Mini App data before trusting its profile."""
23
+ if not init_data or len(init_data) > 8192:
24
+ raise ValueError("Missing or oversized Telegram initialization data.")
25
+
26
+ pairs = parse_qsl(init_data, keep_blank_values=True)
27
+ if len({key for key, _ in pairs}) != len(pairs):
28
+ raise ValueError("Duplicate Telegram initialization fields.")
29
+ fields = dict(pairs)
30
+ received_hash = fields.pop("hash", "")
31
+ if len(received_hash) != 64:
32
+ raise ValueError("Missing Telegram signature.")
33
+
34
+ check_string = "\n".join(f"{key}={value}" for key, value in sorted(fields.items()))
35
+ secret_key = hmac.new(b"WebAppData", bot_token.encode(), hashlib.sha256).digest()
36
+ expected_hash = hmac.new(secret_key, check_string.encode(), hashlib.sha256).hexdigest()
37
+ if not hmac.compare_digest(expected_hash, received_hash):
38
+ raise ValueError("Invalid Telegram signature.")
39
+
40
+ try:
41
+ auth_date = int(fields["auth_date"])
42
+ profile = json.loads(fields["user"])
43
+ user_id = int(profile["id"])
44
+ except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
45
+ raise ValueError("Invalid Telegram profile data.") from exc
46
+
47
+ current_time = int(time.time()) if now is None else now
48
+ age = current_time - auth_date
49
+ if age < -60 or age > max_age:
50
+ raise ValueError("Telegram authorization has expired.")
51
+ if user_id <= 0 or not isinstance(profile, dict):
52
+ raise ValueError("Invalid Telegram user.")
53
+ return TelegramIdentity(user_id=user_id, profile=profile)
app/webapp/index.html ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="am">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
6
+ <meta name="theme-color" content="#146c5a">
7
+ <title>DBU የመማሪያ ማዕከል</title>
8
+ <script src="https://telegram.org/js/telegram-web-app.js"></script>
9
+ <style>
10
+ :root {
11
+ color-scheme: light dark;
12
+ --bg: var(--tg-theme-bg-color, #f3f6f5);
13
+ --card: var(--tg-theme-secondary-bg-color, #fff);
14
+ --text: var(--tg-theme-text-color, #172b26);
15
+ --muted: var(--tg-theme-hint-color, #64746f);
16
+ --accent: var(--tg-theme-button-color, #146c5a);
17
+ --accent-text: var(--tg-theme-button-text-color, #fff);
18
+ --line: color-mix(in srgb, var(--text) 12%, transparent);
19
+ --danger: #b3261e;
20
+ font-family: system-ui, -apple-system, "Noto Sans Ethiopic", sans-serif;
21
+ }
22
+ * { box-sizing: border-box; }
23
+ body { margin: 0; background: var(--bg); color: var(--text); }
24
+ header { padding: 18px 16px 12px; background: var(--accent); color: var(--accent-text); }
25
+ header h1 { margin: 0; font-size: 19px; }
26
+ #profile { margin-top: 5px; font-size: 13px; opacity: .88; }
27
+ nav { display: flex; gap: 8px; padding: 12px 12px 0; overflow-x: auto; }
28
+ nav button, .secondary {
29
+ color: var(--text); background: var(--card); border: 1px solid var(--line);
30
+ }
31
+ button {
32
+ min-height: 42px; border: 0; border-radius: 12px; padding: 10px 14px;
33
+ color: var(--accent-text); background: var(--accent); font: inherit; font-weight: 650;
34
+ cursor: pointer;
35
+ }
36
+ button:disabled { opacity: .55; cursor: default; }
37
+ nav button.active { color: var(--accent-text); background: var(--accent); border-color: var(--accent); }
38
+ main { padding: 14px 12px 28px; max-width: 720px; margin: auto; }
39
+ h2 { font-size: 18px; margin: 8px 2px 12px; }
40
+ h3 { font-size: 15px; margin: 0 0 8px; }
41
+ p { line-height: 1.5; }
42
+ .muted { color: var(--muted); font-size: 13px; }
43
+ .card { padding: 14px; margin: 10px 0; border-radius: 15px; background: var(--card); }
44
+ .row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
45
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
46
+ .actions button { flex: 1 1 auto; }
47
+ .secondary { color: var(--text); }
48
+ .danger { color: var(--danger); background: transparent; border: 1px solid var(--danger); }
49
+ .field { display: grid; gap: 6px; margin: 10px 0; }
50
+ label { font-size: 13px; font-weight: 600; }
51
+ input, textarea, select {
52
+ width: 100%; padding: 11px 12px; border: 1px solid var(--line); border-radius: 10px;
53
+ background: var(--bg); color: var(--text); font: inherit;
54
+ }
55
+ textarea { min-height: 84px; resize: vertical; }
56
+ .choice { width: 100%; text-align: left; margin: 5px 0; color: var(--text); background: var(--card); border: 1px solid var(--line); }
57
+ .feedback { border-left: 4px solid var(--accent); padding: 10px 12px; background: var(--card); border-radius: 8px; }
58
+ #notice { display: none; margin: 12px; padding: 11px; border-radius: 10px; background: #fee; color: #842018; }
59
+ .hidden { display: none !important; }
60
+ .question { white-space: pre-wrap; line-height: 1.6; }
61
+ .score { font-size: 24px; font-weight: 750; }
62
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
63
+ th, td { padding: 9px 5px; border-bottom: 1px solid var(--line); text-align: left; }
64
+ @media (prefers-color-scheme: dark) {
65
+ :root { --danger: #ff8a80; }
66
+ #notice { background: #3a201e; color: #ffd9d5; }
67
+ }
68
+ </style>
69
+ </head>
70
+ <body>
71
+ <header>
72
+ <h1>🎓 የመማሪያ ማዕከል</h1>
73
+ <div id="profile">እየተገናኘ ነው…</div>
74
+ </header>
75
+ <nav id="navigation" class="hidden">
76
+ <button type="button" data-view="learn" class="active">መማር</button>
77
+ <button type="button" data-view="scores">ውጤቶቼ</button>
78
+ <button type="button" data-view="admin" id="admin-tab" class="hidden">አስተዳደር</button>
79
+ </nav>
80
+ <div id="notice" role="alert"></div>
81
+ <main>
82
+ <section id="learn-view">
83
+ <div id="quiz-list"></div>
84
+ <div id="quiz-run" class="hidden"></div>
85
+ </section>
86
+ <section id="scores-view" class="hidden"></section>
87
+ <section id="admin-view" class="hidden">
88
+ <h2>ፈተናዎችን ማስተዳደር</h2>
89
+ <form id="create-quiz" class="card">
90
+ <h3>አዲስ ፈተና</h3>
91
+ <div class="field">
92
+ <label for="quiz-title">የፈተናው ርዕስ</label>
93
+ <input id="quiz-title" maxlength="120" required>
94
+ </div>
95
+ <button type="submit">ፈተና ፍጠር</button>
96
+ </form>
97
+ <div id="admin-quizzes"></div>
98
+ <div id="question-manager" class="hidden"></div>
99
+ <div id="results-panel" class="hidden"></div>
100
+ </section>
101
+ </main>
102
+ <script>
103
+ (() => {
104
+ const tg = window.Telegram?.WebApp;
105
+ const state = { initData: tg?.initData || "", profile: null, attempt: null, quiz: null };
106
+ const $ = (id) => document.getElementById(id);
107
+ const showNotice = (message) => {
108
+ const notice = $("notice");
109
+ notice.textContent = message;
110
+ notice.style.display = "block";
111
+ };
112
+ const clearNotice = () => { $("notice").style.display = "none"; };
113
+ const node = (tag, text, className = "") => {
114
+ const item = document.createElement(tag);
115
+ if (text !== undefined) item.textContent = text;
116
+ if (className) item.className = className;
117
+ return item;
118
+ };
119
+ const button = (text, action, className = "") => {
120
+ const item = node("button", text, className);
121
+ item.type = "button";
122
+ item.addEventListener("click", action);
123
+ return item;
124
+ };
125
+ async function api(path, options = {}) {
126
+ const response = await fetch(`/api${path}`, {
127
+ ...options,
128
+ headers: {
129
+ "Content-Type": "application/json",
130
+ "X-Telegram-Init-Data": state.initData,
131
+ ...(options.headers || {})
132
+ }
133
+ });
134
+ const payload = response.status === 204 ? null : await response.json();
135
+ if (!response.ok) {
136
+ const message = typeof payload?.detail === "string" ? payload.detail : "ያስገቡትን መረጃ ያረጋግጡ።";
137
+ throw new Error(message || "ጥያቄውን ማስኬድ አልተቻለም።");
138
+ }
139
+ return payload;
140
+ }
141
+ function switchView(name) {
142
+ for (const view of ["learn", "scores", "admin"]) {
143
+ $(`${view}-view`).classList.toggle("hidden", view !== name);
144
+ document.querySelector(`[data-view="${view}"]`)?.classList.toggle("active", view === name);
145
+ }
146
+ if (name === "learn") loadQuizzes();
147
+ if (name === "scores") loadScores();
148
+ if (name === "admin") loadAdminQuizzes();
149
+ }
150
+ async function loadQuizzes() {
151
+ const list = $("quiz-list");
152
+ list.classList.remove("hidden");
153
+ list.replaceChildren(node("p", "ፈተናዎች በመጫን ላይ…", "muted"));
154
+ $("quiz-run").classList.add("hidden");
155
+ try {
156
+ const quizzes = await api("/quizzes");
157
+ list.replaceChildren(node("h2", "የልምምድ ፈተናዎች"));
158
+ if (!quizzes.length) list.append(node("p", "እስካሁን የተዘጋጀ ፈተና የለም።", "muted"));
159
+ for (const quiz of quizzes) {
160
+ const card = node("article", undefined, "card");
161
+ const title = node("h3", quiz.title);
162
+ const count = node("p", `${quiz.question_count} ጥያቄዎች`, "muted");
163
+ card.append(title, count, button("ጀምር", () => startQuiz(quiz)));
164
+ list.append(card);
165
+ }
166
+ } catch (error) { showNotice(error.message); }
167
+ }
168
+ async function startQuiz(quiz) {
169
+ clearNotice();
170
+ try {
171
+ const started = await api(`/quizzes/${quiz.id}/start`, { method: "POST" });
172
+ state.attempt = started.attempt_id;
173
+ state.quiz = { title: started.quiz_title, total: started.total };
174
+ $("quiz-list").classList.add("hidden");
175
+ renderQuestion(started.question);
176
+ } catch (error) { showNotice(error.message); }
177
+ }
178
+ function renderQuestion(question) {
179
+ const run = $("quiz-run");
180
+ run.replaceChildren();
181
+ run.classList.remove("hidden");
182
+ const card = node("article", undefined, "card");
183
+ card.append(node("p", state.quiz.title, "muted"));
184
+ card.append(node("h2", `ጥያቄ ${question.position}/${state.quiz.total}`));
185
+ card.append(node("p", question.prompt, "question"));
186
+ const letters = ["a", "b", "c", "d"];
187
+ question.options.forEach((choice, index) => {
188
+ card.append(button(`${letters[index].toUpperCase()}. ${choice}`, () => submitAnswer(question, letters[index]), "choice"));
189
+ });
190
+ run.append(card, button("ወደ ፈተናዎች ዝርዝር ተመለስ", loadQuizzes, "secondary"));
191
+ }
192
+ async function submitAnswer(question, choice) {
193
+ clearNotice();
194
+ try {
195
+ const result = await api(`/attempts/${state.attempt}/answer`, {
196
+ method: "POST",
197
+ body: JSON.stringify({ question_id: question.id, choice })
198
+ });
199
+ const run = $("quiz-run");
200
+ const card = node("article", undefined, "card");
201
+ card.append(node("p", result.correct ? "✅ ትክክል ነው!" :
202
+ `❌ ትክክለኛው መልስ፦ ${result.correct_option.toUpperCase()}. ${result.correct_text}`, "feedback"));
203
+ if (result.complete) {
204
+ card.append(node("p", "ፈተናው ተጠናቋል።"));
205
+ card.append(node("p", `${result.score} / ${result.total}`, "score"));
206
+ card.append(button("ውጤቶቼን እይ", () => switchView("scores")));
207
+ card.append(button("ሌላ ፈተና ምረጥ", loadQuizzes, "secondary"));
208
+ } else {
209
+ card.append(button("ቀጣይ ጥያቄ", () => renderQuestion(result.next_question)));
210
+ }
211
+ run.replaceChildren(card);
212
+ } catch (error) { showNotice(error.message); }
213
+ }
214
+ async function loadScores() {
215
+ const section = $("scores-view");
216
+ section.replaceChildren(node("h2", "የቅርብ ውጤቶቼ"));
217
+ try {
218
+ const scores = await api("/scores");
219
+ if (!scores.length) section.append(node("p", "እስካሁን የጨረሱት ፈተና የለም።", "muted"));
220
+ for (const score of scores) {
221
+ const card = node("article", undefined, "card");
222
+ card.append(node("h3", score.quiz), node("p", `${score.correct} / ${score.total}`, "score"));
223
+ section.append(card);
224
+ }
225
+ } catch (error) { showNotice(error.message); }
226
+ }
227
+ async function loadAdminQuizzes() {
228
+ const list = $("admin-quizzes");
229
+ list.replaceChildren(node("p", "የአስተዳደር መረጃ በመጫን ላይ…", "muted"));
230
+ $("question-manager").classList.add("hidden");
231
+ $("results-panel").classList.add("hidden");
232
+ try {
233
+ const quizzes = await api("/admin/quizzes");
234
+ list.replaceChildren();
235
+ if (!quizzes.length) list.append(node("p", "እስካሁን ፈተና አልፈጠሩም።", "muted"));
236
+ for (const quiz of quizzes) list.append(renderAdminQuiz(quiz));
237
+ } catch (error) { showNotice(error.message); }
238
+ }
239
+ function renderAdminQuiz(quiz) {
240
+ const card = node("article", undefined, "card");
241
+ const heading = node("h3", quiz.title);
242
+ const status = node("p",
243
+ `${quiz.is_active ? "ታትሟል" : "ረቂቅ"} · ${quiz.question_count} ጥያቄ · ${quiz.attempt_count} ሙከራ`,
244
+ "muted");
245
+ card.append(heading, status);
246
+ const actions = node("div", undefined, "actions");
247
+ actions.append(button("ጥያቄዎችን አስተዳድር", () => manageQuestions(quiz), "secondary"));
248
+ actions.append(button("ርዕስ ቀይር", async () => {
249
+ const title = window.prompt("አዲሱን ርዕስ ያስገቡ", quiz.title);
250
+ if (!title?.trim()) return;
251
+ try {
252
+ await api(`/admin/quizzes/${quiz.id}`, {
253
+ method: "PATCH",
254
+ body: JSON.stringify({ title: title.trim() })
255
+ });
256
+ await loadAdminQuizzes();
257
+ } catch (error) { showNotice(error.message); }
258
+ }, "secondary"));
259
+ actions.append(button(quiz.is_active ? "ዝጋ" : "አትም", () => toggleQuiz(quiz), "secondary"));
260
+ actions.append(button("ውጤት", () => showResults(quiz), "secondary"));
261
+ if (quiz.attempt_count === 0) {
262
+ actions.append(button("ሰርዝ", () => deleteQuiz(quiz), "danger"));
263
+ }
264
+ card.append(actions);
265
+ return card;
266
+ }
267
+ async function toggleQuiz(quiz) {
268
+ clearNotice();
269
+ try {
270
+ await api(`/admin/quizzes/${quiz.id}`, {
271
+ method: "PATCH",
272
+ body: JSON.stringify({ is_active: !quiz.is_active })
273
+ });
274
+ await loadAdminQuizzes();
275
+ } catch (error) { showNotice(error.message); }
276
+ }
277
+ async function deleteQuiz(quiz) {
278
+ if (!confirm(`“${quiz.title}” ፈተናን ማጥፋት ይፈልጋሉ?`)) return;
279
+ try {
280
+ await api(`/admin/quizzes/${quiz.id}`, { method: "DELETE" });
281
+ await loadAdminQuizzes();
282
+ } catch (error) { showNotice(error.message); }
283
+ }
284
+ async function manageQuestions(quiz) {
285
+ clearNotice();
286
+ const panel = $("question-manager");
287
+ state.adminQuiz = quiz;
288
+ $("results-panel").classList.add("hidden");
289
+ panel.classList.remove("hidden");
290
+ panel.replaceChildren(node("h2", `${quiz.title} · ጥያቄዎች`));
291
+ if (quiz.is_active || quiz.attempt_count) {
292
+ panel.append(node("p", "ፈተናው ከታተመ ወይም ተማሪ ከሞከረ በኋላ ጥያቄዎቹን መቀየር አይቻልም።", "muted"));
293
+ } else {
294
+ panel.append(questionForm(quiz.id));
295
+ }
296
+ try {
297
+ const questions = await api(`/admin/quizzes/${quiz.id}/questions`);
298
+ for (const question of questions) panel.append(renderAdminQuestion(quiz, question));
299
+ } catch (error) { showNotice(error.message); }
300
+ }
301
+ function questionForm(quizId, question = null) {
302
+ const form = node("form", undefined, "card");
303
+ form.append(node("h3", question ? "ጥያቄ ማስተካከል" : "አዲስ ጥያቄ"));
304
+ const promptLabel = node("label", "ጥያቄ");
305
+ const prompt = node("textarea");
306
+ prompt.required = true;
307
+ prompt.maxLength = 1000;
308
+ prompt.value = question?.prompt || "";
309
+ form.append(promptLabel, prompt);
310
+ const options = [];
311
+ for (let i = 0; i < 4; i++) {
312
+ const label = node("label", `${String.fromCharCode(65 + i)} ምርጫ`);
313
+ const input = node("input");
314
+ input.required = true;
315
+ input.maxLength = 300;
316
+ input.value = question?.options[i] || "";
317
+ form.append(label, input);
318
+ options.push(input);
319
+ }
320
+ const correctLabel = node("label", "ትክክለኛ መልስ");
321
+ const correct = document.createElement("select");
322
+ ["a", "b", "c", "d"].forEach((letter) => {
323
+ const option = node("option", letter.toUpperCase());
324
+ option.value = letter;
325
+ correct.append(option);
326
+ });
327
+ correct.value = question?.correct_option || "a";
328
+ form.append(correctLabel, correct);
329
+ const submit = node("button", question ? "አስቀምጥ" : "ጥያቄ ጨምር");
330
+ submit.type = "submit";
331
+ form.append(submit);
332
+ if (question) form.append(button("ይቅር", () => manageQuestions(state.adminQuiz), "secondary"));
333
+ form.addEventListener("submit", async (event) => {
334
+ event.preventDefault();
335
+ const payload = {
336
+ prompt: prompt.value,
337
+ options: options.map((input) => input.value),
338
+ correct_option: correct.value
339
+ };
340
+ try {
341
+ await api(question ? `/admin/questions/${question.id}` : `/admin/quizzes/${quizId}/questions`, {
342
+ method: question ? "PUT" : "POST",
343
+ body: JSON.stringify(payload)
344
+ });
345
+ await loadAdminQuizzes();
346
+ const currentQuiz = (await api("/admin/quizzes")).find((item) => item.id === quizId);
347
+ if (currentQuiz) await manageQuestions(currentQuiz);
348
+ } catch (error) { showNotice(error.message); }
349
+ });
350
+ return form;
351
+ }
352
+ function renderAdminQuestion(quiz, question) {
353
+ const card = node("article", undefined, "card");
354
+ card.append(node("h3", `ጥያቄ ${question.position}`), node("p", question.prompt, "question"));
355
+ question.options.forEach((choice, index) => {
356
+ card.append(node("p", `${String.fromCharCode(65 + index)}. ${choice}${question.correct_option === "abcd"[index] ? " ✓" : ""}`));
357
+ });
358
+ if (!quiz.is_active && quiz.attempt_count === 0) {
359
+ const actions = node("div", undefined, "actions");
360
+ actions.append(button("አስተካክል", () => {
361
+ const panel = $("question-manager");
362
+ const existing = panel.querySelector("form");
363
+ if (existing) existing.remove();
364
+ panel.insertBefore(questionForm(quiz.id, question), panel.children[1] || null);
365
+ }, "secondary"));
366
+ actions.append(button("ሰርዝ", async () => {
367
+ if (!confirm("ይህን ጥያቄ ማጥፋት ይፈልጋሉ?")) return;
368
+ try {
369
+ await api(`/admin/questions/${question.id}`, { method: "DELETE" });
370
+ const currentQuiz = (await api("/admin/quizzes")).find((item) => item.id === quiz.id);
371
+ await manageQuestions(currentQuiz);
372
+ } catch (error) { showNotice(error.message); }
373
+ }, "danger"));
374
+ card.append(actions);
375
+ }
376
+ return card;
377
+ }
378
+ async function showResults(quiz) {
379
+ clearNotice();
380
+ const panel = $("results-panel");
381
+ panel.classList.remove("hidden");
382
+ $("question-manager").classList.add("hidden");
383
+ panel.replaceChildren(node("h2", `${quiz.title} · የተማሪዎች ውጤት`));
384
+ try {
385
+ const rows = await api(`/admin/quizzes/${quiz.id}/results`);
386
+ if (!rows.length) panel.append(node("p", "እስካሁን የተጠናቀቀ ሙከራ የለም።", "muted"));
387
+ const table = document.createElement("table");
388
+ const head = document.createElement("tr");
389
+ ["ተማሪ", "ውጤት", "ያጠናቀቀበት"].forEach((text) => head.append(node("th", text)));
390
+ table.append(head);
391
+ rows.forEach((row) => {
392
+ const tr = document.createElement("tr");
393
+ const name = row.username ? `${row.name} (@${row.username})` : row.name;
394
+ tr.append(node("td", `${name} · ${row.user_id}`));
395
+ tr.append(node("td", `${row.correct}/${row.total}`));
396
+ tr.append(node("td", row.completed_at ? new Date(row.completed_at).toLocaleDateString("am-ET") : "—"));
397
+ table.append(tr);
398
+ });
399
+ panel.append(table);
400
+ } catch (error) { showNotice(error.message); }
401
+ }
402
+ $("create-quiz").addEventListener("submit", async (event) => {
403
+ event.preventDefault();
404
+ try {
405
+ const created = await api("/admin/quizzes", {
406
+ method: "POST",
407
+ body: JSON.stringify({ title: $("quiz-title").value })
408
+ });
409
+ $("quiz-title").value = "";
410
+ await loadAdminQuizzes();
411
+ await manageQuestions(created);
412
+ } catch (error) { showNotice(error.message); }
413
+ });
414
+ document.querySelectorAll("[data-view]").forEach((item) =>
415
+ item.addEventListener("click", () => switchView(item.dataset.view)));
416
+ async function boot() {
417
+ if (!tg || !state.initData) {
418
+ showNotice("ይህን ገጽ ከቴሌግራም ቦቱ ይክፈቱ።");
419
+ $("profile").textContent = "የቴሌግራም መለያ አልተገናኘም";
420
+ return;
421
+ }
422
+ tg.ready();
423
+ tg.expand();
424
+ try {
425
+ state.profile = await api("/session");
426
+ $("profile").textContent = [state.profile.first_name, state.profile.last_name].filter(Boolean).join(" ");
427
+ $("navigation").classList.remove("hidden");
428
+ if (state.profile.is_admin) $("admin-tab").classList.remove("hidden");
429
+ await loadQuizzes();
430
+ } catch (error) {
431
+ $("profile").textContent = "ማረጋገጥ አልተሳካም";
432
+ showNotice(error.message);
433
+ }
434
+ }
435
+ boot();
436
+ })();
437
+ </script>
438
+ </body>
439
+ </html>
locales/en.json CHANGED
@@ -12,6 +12,7 @@
12
  "onboarded": "✅ You're registered! Pick from the menu below.",
13
  "menu_title": "Main menu 👇",
14
  "btn_library": "📚 Library",
 
15
  "btn_gpa": "🧮 GPA calculator",
16
  "btn_invite": "👥 Invite friends",
17
  "soon": "🚧 This section is coming soon.",
 
12
  "onboarded": "✅ You're registered! Pick from the menu below.",
13
  "menu_title": "Main menu 👇",
14
  "btn_library": "📚 Library",
15
+ "btn_quiz": "🎓 የመማሪያ ፈተና",
16
  "btn_gpa": "🧮 GPA calculator",
17
  "btn_invite": "👥 Invite friends",
18
  "soon": "🚧 This section is coming soon.",
requirements.txt CHANGED
@@ -5,3 +5,5 @@ aiosqlite>=0.20
5
  pydantic-settings>=2.2
6
  pypdf>=4.0
7
  reportlab>=4.0
 
 
 
5
  pydantic-settings>=2.2
6
  pypdf>=4.0
7
  reportlab>=4.0
8
+ fastapi>=0.110,<1
9
+ uvicorn[standard]>=0.29
tests/test_quiz.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+
3
+ from sqlalchemy.ext.asyncio import create_async_engine
4
+
5
+ from app.db.base import Base
6
+ import app.db.models # noqa: F401
7
+ from app.services.quiz_rules import normalize_choice
8
+
9
+
10
+ def test_correct_option_accepts_letters_and_numbers():
11
+ assert [normalize_choice(value) for value in ("A", "2", "c", "D", "4")] == [
12
+ "a", "b", "c", "d", "d",
13
+ ]
14
+ assert normalize_choice("E") is None
15
+ assert normalize_choice("") is None
16
+
17
+
18
+ def test_quiz_tables_create_on_sqlite():
19
+ async def create_schema():
20
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
21
+ async with engine.begin() as connection:
22
+ await connection.run_sync(Base.metadata.create_all)
23
+ await engine.dispose()
24
+
25
+ asyncio.run(create_schema())
tests/test_webapp_api.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from types import SimpleNamespace
3
+ from unittest.mock import AsyncMock
4
+
5
+ import pytest
6
+ from fastapi import HTTPException
7
+
8
+ from app.webapp.auth import TelegramIdentity
9
+
10
+
11
+ def _webapp_api(monkeypatch):
12
+ monkeypatch.setenv("BOT_TOKEN", "123456:test-token")
13
+ monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
14
+ from app.webapp import api
15
+
16
+ return api
17
+
18
+
19
+ def test_admin_actions_reject_non_admins(monkeypatch):
20
+ webapp_api = _webapp_api(monkeypatch)
21
+ monkeypatch.setattr(
22
+ webapp_api,
23
+ "get_settings",
24
+ lambda: SimpleNamespace(admin_id_set={42}),
25
+ )
26
+
27
+ with pytest.raises(HTTPException) as error:
28
+ webapp_api._require_admin(TelegramIdentity(user_id=7, profile={}))
29
+
30
+ assert error.value.status_code == 403
31
+
32
+
33
+ def test_admin_can_use_quizzes_without_student_record(monkeypatch):
34
+ webapp_api = _webapp_api(monkeypatch)
35
+ monkeypatch.setattr(
36
+ webapp_api,
37
+ "get_settings",
38
+ lambda: SimpleNamespace(admin_id_set={42}),
39
+ )
40
+ session = AsyncMock()
41
+
42
+ asyncio.run(
43
+ webapp_api._require_student_or_admin(
44
+ TelegramIdentity(user_id=42, profile={}),
45
+ session,
46
+ )
47
+ )
48
+
49
+ session.get.assert_not_awaited()
tests/test_webapp_auth.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import hmac
3
+ import time
4
+ from urllib.parse import urlencode
5
+
6
+ import pytest
7
+
8
+ from app.webapp.auth import validate_init_data
9
+
10
+
11
+ def _signed_data(token: str, fields: dict[str, str]) -> str:
12
+ check_string = "\n".join(f"{key}={value}" for key, value in sorted(fields.items()))
13
+ secret = hmac.new(b"WebAppData", token.encode(), hashlib.sha256).digest()
14
+ fields = {
15
+ **fields,
16
+ "hash": hmac.new(secret, check_string.encode(), hashlib.sha256).hexdigest(),
17
+ }
18
+ return urlencode(fields)
19
+
20
+
21
+ def test_telegram_init_data_authenticates_profile():
22
+ token = "123456:example-token"
23
+ fields = {
24
+ "auth_date": str(int(time.time())),
25
+ "user": '{"id":42,"first_name":"Student"}',
26
+ }
27
+
28
+ identity = validate_init_data(_signed_data(token, fields), token)
29
+
30
+ assert identity.user_id == 42
31
+ assert identity.profile["first_name"] == "Student"
32
+
33
+
34
+ def test_telegram_init_data_rejects_tampering_and_expiration():
35
+ token = "123456:example-token"
36
+ fields = {
37
+ "auth_date": "1000",
38
+ "user": '{"id":42,"first_name":"Student"}',
39
+ }
40
+ signed = _signed_data(token, fields)
41
+
42
+ with pytest.raises(ValueError, match="expired"):
43
+ validate_init_data(signed, token, now=1000 + 86_401)
44
+ with pytest.raises(ValueError, match="signature"):
45
+ validate_init_data(signed.replace("Student", "Admin"), token, now=1000)