wzender commited on
Commit
aeda545
·
1 Parent(s): 94f899a

feat(board-work): implement board work feature for student answers

Browse files

- Save a picture of the student's board with every answer in practice, quizzes, tests, and simulations.
- Require board work for quizzes and tests before a choice can be submitted.
- Allow teachers to grade the board work, providing points for the process.
- Create API endpoints for uploading board work and retrieving it for teacher review.
- Add frontend functionality to handle board work submission and display in the teacher's grading interface.
- Implement database migrations to support new board work data structure and relationships.
- Add comprehensive tests for the new functionality, ensuring correct behavior in various scenarios.

docs/tasks/prd-mathly.md CHANGED
@@ -404,6 +404,7 @@ A tab bar at the bottom of the screen leads between them: home, path (named "ה
404
 
405
  - **STU-1 Home** is one screen (it fits 360×800 with every lesson), like a game's level select: the stars collected (three per lesson), the lessons perfected, the streak and the daily goal; one big **play** button for the next lesson (the one with a round in progress, else the earliest behind the curriculum, else the first with fewer than three stars); the nearest test in one strip (the days left and the readiness number, which open the test's card with the readiness bar, the plan and the practice tests, and today's task, TST-3, as a button); small buttons for a required simulation, the new assignments (their number, opening "הגשות") and photo help with the latest request's state (AI-1); and every lesson as a small tile: its number (a crown when perfect), its stars (★ a lesson round finished, ★★ a round with 8 of 10 or more, ★★★ every skill of the lesson mastered), "⏰" when behind the curriculum (PTH-11) and "◐" when a round is open. Tapping a tile opens the lesson's round (STU-9). The path is reached from its tab ("העמקה").
406
  - **STU-9 Lesson round (סבב שיעור).** At most 10 questions from the lesson's skills that are not mastered, at most 3 from each (a lesson with one skill left is a round of 3); a lesson with every skill mastered draws 10 from all of them. Instant feedback as on the exercise screen (EX); every answer is a practice answer of its skill (mastery, daily goal, review list). The result shows the score, the lesson's stars, the skills mastered in the round and those one good day away, and each mistake's name and tip; never the right answers.
 
407
  - **STU-2 Path:** see 4.4.
408
  - **STU-3 Grades:** all quiz (best grade), exercise test, simulation and assignment grades.
409
  - **STU-4 Collection:** see MST-7.
 
404
 
405
  - **STU-1 Home** is one screen (it fits 360×800 with every lesson), like a game's level select: the stars collected (three per lesson), the lessons perfected, the streak and the daily goal; one big **play** button for the next lesson (the one with a round in progress, else the earliest behind the curriculum, else the first with fewer than three stars); the nearest test in one strip (the days left and the readiness number, which open the test's card with the readiness bar, the plan and the practice tests, and today's task, TST-3, as a button); small buttons for a required simulation, the new assignments (their number, opening "הגשות") and photo help with the latest request's state (AI-1); and every lesson as a small tile: its number (a crown when perfect), its stars (★ a lesson round finished, ★★ a round with 8 of 10 or more, ★★★ every skill of the lesson mastered), "⏰" when behind the curriculum (PTH-11) and "◐" when a round is open. Tapping a tile opens the lesson's round (STU-9). The path is reached from its tab ("העמקה").
406
  - **STU-9 Lesson round (סבב שיעור).** At most 10 questions from the lesson's skills that are not mastered, at most 3 from each (a lesson with one skill left is a round of 3); a lesson with every skill mastered draws 10 from all of them. Instant feedback as on the exercise screen (EX); every answer is a practice answer of its skill (mastery, daily goal, review list). The result shows the score, the lesson's stars, the skills mastered in the round and those one good day away, and each mistake's name and tip; never the right answers.
407
+ - **STU-10 The way on the board (הדרך).** Every answer (practice, lesson rounds, lesson quizzes, exercise tests, the simulation) keeps a picture of the question's board when something is written on it; in quizzes and tests a choice needs the way on the board first. The teacher's "בדיקת דרך" tab lists the handed-in quizzes and tests of their students; each question shows the choices (the right one marked), the student's choice and board, and points for the way (automatic, 0, ½, full) that recompute the grade. Work pictures are private to the student and their teachers and follow the answer pictures' retention.
408
  - **STU-2 Path:** see 4.4.
409
  - **STU-3 Grades:** all quiz (best grade), exercise test, simulation and assignment grades.
410
  - **STU-4 Collection:** see MST-7.
mathly2/assignments.py CHANGED
@@ -428,4 +428,9 @@ def teaching_counts(request: Request, user: dict = Depends(need("class.teach")))
428
  students = len({m["email"] for i in ids for m in here.members(i)})
429
  ai_waiting = len(store.ai_requests(class_ids=ids, kinds=["photo", "check"], states=["waiting"])) if ids else 0
430
  again = len(store.ai_requests(class_ids=ids, kinds=["again"], states=["waiting"])) if ids else 0 # students asking to look again are in the inbox
431
- return {"classes": len(classes), "tests": len(tests), "assignments": len(assignments), "inbox": waiting + again, "progress": students, "ai": ai_waiting}
 
 
 
 
 
 
428
  students = len({m["email"] for i in ids for m in here.members(i)})
429
  ai_waiting = len(store.ai_requests(class_ids=ids, kinds=["photo", "check"], states=["waiting"])) if ids else 0
430
  again = len(store.ai_requests(class_ids=ids, kinds=["again"], states=["waiting"])) if ids else 0 # students asking to look again are in the inbox
431
+ from .boardwork import GRADED
432
+ ids_of_students = list({m["user_id"] for i in ids for m in here.members(i) if m["user_id"]})
433
+ to_check = sum(1 for kind in GRADED for rows in (store.attempts_of_users(ids_of_students, kind) if ids_of_students else {}).values()
434
+ for r in rows if r["submitted_at"] and not r.get("checked_at")) # handed-in quizzes and tests whose way is not checked yet
435
+ return {"classes": len(classes), "tests": len(tests), "assignments": len(assignments), "inbox": waiting + again, "progress": students, "ai": ai_waiting,
436
+ "work": to_check}
mathly2/attempts.py CHANGED
@@ -33,10 +33,21 @@ def _right(bank, question: dict, answers: dict) -> bool:
33
  return bool(graded and graded["correct"])
34
 
35
 
36
- def grade(bank, questions: list[dict], answers: dict) -> tuple[int, int]:
37
- """(grade, number right). A question without an answer, or with an answer the bank does not know, is wrong."""
 
 
 
 
 
 
 
 
 
 
38
  right = sum(1 for q in questions if _right(bank, q, answers))
39
- return percent(right, len(questions)), right
 
40
 
41
 
42
  def add_wrong_to_review(store, bank, row: dict, at: datetime) -> None:
 
33
  return bool(graded and graded["correct"])
34
 
35
 
36
+ CREDITS = (0, 0.5, 1) # what a teacher can give a question for its work: nothing, half, all
37
+
38
+
39
+ def points(bank, question: dict, answers: dict, credit: dict | None = None) -> float:
40
+ """A question's points: the teacher's credit for the work when they gave one, else 1 for a right answer and 0 for a wrong one."""
41
+ given = (credit or {}).get(question["key"])
42
+ return float(given) if given in CREDITS else (1.0 if _right(bank, question, answers) else 0.0)
43
+
44
+
45
+ def grade(bank, questions: list[dict], answers: dict, credit: dict | None = None) -> tuple[int, int]:
46
+ """(grade, number right). A question without an answer, or with an answer the bank does not know, is wrong. The teacher's credit for the
47
+ work (in halves) replaces a question's points."""
48
  right = sum(1 for q in questions if _right(bank, q, answers))
49
+ halves = sum(round(2 * points(bank, q, answers, credit)) for q in questions)
50
+ return percent(halves, 2 * len(questions)), right
51
 
52
 
53
  def add_wrong_to_review(store, bank, row: dict, at: datetime) -> None:
mathly2/boardreview.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An AI review of the way (הדרך) in a practice test (מבחן תרגול) or the simulation, sent back to the student after handing in.
2
+
3
+ After a test is handed in, the boards of its questions go to Gemini in ONE request (the free tier allows few requests a minute), with each
4
+ question, its choices, the right choice (for the model only) and the student's choice. The model judges the way per question (correct, partial,
5
+ wrong, unclear) and writes a short feedback line and a tip in Hebrew, without ever saying the right answer: results never show it. The review is
6
+ stored on the attempt (`review`): {"state": "pending" | "done" | "failed", ...} and shown on the result; the teacher sees it as a suggestion.
7
+
8
+ Nothing here knows a student: a request carries pictures and questions, never a name or an email. Without GEMINI_API_KEY there is no review.
9
+ The review runs in a background thread; a review left pending by a restart is started again when the result is next read."""
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import io
14
+ import json
15
+ import logging
16
+ import threading
17
+ import time
18
+ import urllib.error
19
+ import urllib.request
20
+ from datetime import datetime, timedelta
21
+
22
+ from . import clock
23
+
24
+ log = logging.getLogger("mathly2.boardreview")
25
+
26
+ REVIEWED = ("exercise_test", "simulation")
27
+ DEFAULT_MODEL = "gemini-2.5-flash" # a model with a free tier; GEMINI_MODEL overrides it
28
+ ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"
29
+ STALE = timedelta(minutes=10) # a pending review older than this was lost (a restart) and is started again
30
+ RETRIES = 3 # tries after "too many requests", waiting as the API asks (or 20, 40 s)
31
+ SIDE = 1280 # a board is shrunk to this longest side before it is sent
32
+ VERDICTS = ("correct", "partial", "wrong", "unclear")
33
+
34
+ INSTRUCTIONS = """אתם מורים למתמטיקה בכיתה ט בישראל. תלמיד פתר מבחן אמריקאי, ולכל שאלה כתב את הדרך על לוח. קיבלתם את השאלות, התשובות האפשריות, \
35
+ התשובה הנכונה (רק בשבילכם), התשובה שהתלמיד בחר, ותמונה של הלוח שלו לכל שאלה.
36
+ לכל שאלה עם לוח, הַעריכו את הדרך (לא רק את התשובה הסופית):
37
+ - verdict: "correct" אם הדרך נכונה ומובילה לתשובה; "partial" אם יש התחלה נכונה או רעיון נכון אבל טעות או חוסר; "wrong" אם השיטה שגויה; "unclear" אם אי אפשר לקרוא או שאין בלוח דרך של ממש.
38
+ - feedback: משפט או שניים לתלמיד, בעברית, בפנייה ברבים (אתם), חם וענייני: מה טוב בדרך, ואם יש טעות, איפה היא הטעות הראשונה ומה סוגה.
39
+ - tip: טיפ אחד קצר ומעשי לפעם הבאה.
40
+ אסור לכתוב את התשובה הסופית הנכונה, את המספר שלה או איזו אפשרות נכונה. אם התלמיד טעה, כוונו אותו לשלב, אל תפתרו בשבילו.
41
+ summary: משפט או שניים על הדרך במבחן כולו: חוזקה אחת ודבר אחד לשפר.
42
+ נוסחאות כתבו בתוך $...$."""
43
+
44
+ SCHEMA = {
45
+ "type": "OBJECT",
46
+ "properties": {
47
+ "summary": {"type": "STRING"},
48
+ "questions": {"type": "ARRAY", "items": {"type": "OBJECT", "properties": {
49
+ "n": {"type": "INTEGER"}, "verdict": {"type": "STRING", "enum": list(VERDICTS)},
50
+ "feedback": {"type": "STRING"}, "tip": {"type": "STRING"}}, "required": ["n", "verdict", "feedback", "tip"]}},
51
+ },
52
+ "required": ["summary", "questions"],
53
+ }
54
+
55
+
56
+ class ReviewFailure(Exception):
57
+ def __init__(self, reason: str, detail: str = ""):
58
+ super().__init__(reason)
59
+ self.reason, self.detail = reason, detail
60
+
61
+
62
+ def _small(jpeg: bytes) -> bytes:
63
+ from PIL import Image
64
+ image = Image.open(io.BytesIO(jpeg)).convert("RGB")
65
+ image.thumbnail((SIDE, SIDE))
66
+ out = io.BytesIO()
67
+ image.save(out, "JPEG", quality=85)
68
+ return out.getvalue()
69
+
70
+
71
+ def _letter(i: int) -> str:
72
+ return "אבגדהוזחטי"[i] if i < 10 else str(i + 1)
73
+
74
+
75
+ class GeminiReviewer:
76
+ """Gemini over its REST API (no SDK). `review(items)` -> {"summary", "questions": [{n, verdict, feedback, tip}]}."""
77
+
78
+ def __init__(self, key: str, model: str = "", sleep=time.sleep) -> None:
79
+ self.key, self.model, self.sleep = key, model or DEFAULT_MODEL, sleep
80
+ self._lock = threading.Lock() # one request at a time: the free tier counts requests a minute
81
+
82
+ def _parts(self, items: list[dict]) -> list[dict]:
83
+ parts = [{"text": INSTRUCTIONS}]
84
+ for it in items:
85
+ choices = "\n".join(f" {_letter(i)}. {c}" for i, c in enumerate(it["choices"]))
86
+ picked = _letter(it["picked"]) if it["picked"] is not None else "לא ענה"
87
+ parts.append({"text": f"\n\nשאלה {it['n']}:\n{it['question']}\nאפשרויות:\n{choices}\nהתשובה הנכונה (לא לגלות): {_letter(it['correct'])}\n"
88
+ f"התלמיד בחר: {picked}\nהלוח של התלמיד לשאלה {it['n']}:"})
89
+ parts.append({"inline_data": {"mime_type": "image/jpeg", "data": base64.b64encode(_small(it["image"])).decode()}})
90
+ return parts
91
+
92
+ def _call(self, body: bytes) -> dict:
93
+ request = urllib.request.Request(ENDPOINT.format(model=self.model), data=body, method="POST",
94
+ headers={"Content-Type": "application/json", "x-goog-api-key": self.key})
95
+ with urllib.request.urlopen(request, timeout=180) as response:
96
+ return json.loads(response.read())
97
+
98
+ def review(self, items: list[dict]) -> dict:
99
+ body = json.dumps({"contents": [{"role": "user", "parts": self._parts(items)}],
100
+ "generationConfig": {"temperature": 0.2, "responseMimeType": "application/json", "responseSchema": SCHEMA}}).encode()
101
+ with self._lock:
102
+ for attempt in range(RETRIES + 1):
103
+ try:
104
+ data = self._call(body)
105
+ break
106
+ except urllib.error.HTTPError as exc:
107
+ detail = exc.read().decode("utf-8", "replace")[:500]
108
+ if exc.code == 429 and attempt < RETRIES:
109
+ self.sleep(_retry_after(detail, 20 * (attempt + 1)))
110
+ continue
111
+ raise ReviewFailure({400: "bad_request", 401: "api_key_invalid", 403: "permission", 404: "model_not_found",
112
+ 429: "rate_limited"}.get(exc.code, "provider_error"), f"HTTP {exc.code}: {detail}") from None
113
+ except (urllib.error.URLError, TimeoutError) as exc:
114
+ raise ReviewFailure("no_connection", str(exc)[:300]) from None
115
+ try:
116
+ candidate = data["candidates"][0]
117
+ if candidate.get("finishReason") not in (None, "STOP"):
118
+ raise ReviewFailure("incomplete", str(candidate.get("finishReason")))
119
+ text = "".join(p.get("text", "") for p in candidate["content"]["parts"] if not p.get("thought"))
120
+ out = json.loads(text)
121
+ except ReviewFailure:
122
+ raise
123
+ except (KeyError, IndexError, ValueError, TypeError) as exc:
124
+ raise ReviewFailure("bad_output", f"{type(exc).__name__}: {str(data)[:300]}") from None
125
+ return out
126
+
127
+
128
+ def _retry_after(detail: str, default: float) -> float:
129
+ """The wait the API asks for in a 429 ("retryDelay": "17s"), else `default` seconds."""
130
+ try:
131
+ for d in json.loads(detail).get("error", {}).get("details", []):
132
+ if str(d.get("retryDelay", "")).endswith("s"):
133
+ return min(90.0, float(d["retryDelay"][:-1]) + 1)
134
+ except (ValueError, AttributeError, TypeError):
135
+ pass
136
+ return default
137
+
138
+
139
+ def make_reviewer(settings):
140
+ return GeminiReviewer(settings.gemini_key, settings.gemini_model) if settings.gemini_key else None
141
+
142
+
143
+ # ---- running a review for an attempt ----
144
+
145
+ _running: set[str] = set()
146
+ _running_lock = threading.Lock()
147
+
148
+
149
+ def _items(app, row: dict) -> tuple[list[dict], dict]:
150
+ """The questions that have a board, as the reviewer takes them, and n -> question key."""
151
+ bank, store = app.state.bank, app.state.store
152
+ work = store.work_of(row["user_id"], row["id"])
153
+ items, keys = [], {}
154
+ for n, q in enumerate(row["questions"], start=1):
155
+ pid = work.get(q["key"])
156
+ served = bank.practice_question(q["skill_id"], q["key"])
157
+ picture = store.get_picture(pid) if pid else None
158
+ if not served or not picture or picture["deleted_at"]:
159
+ continue
160
+ correct = next((c["index"] for c in served["choices"] if (bank.grade(q["skill_id"], q["key"], c["index"]) or {}).get("correct")), 0)
161
+ picked = row["answers"].get(q["key"])
162
+ items.append({"n": n, "question": served["question"], "choices": [c["text"] for c in served["choices"]], "correct": correct,
163
+ "picked": picked if isinstance(picked, int) else None, "image": app.state.pictures.get(picture["path"])})
164
+ keys[n] = q["key"]
165
+ return items, keys
166
+
167
+
168
+ def run(app, attempt_id: str) -> None:
169
+ """Review one handed-in attempt and store the result on it. Never raises: a failure is stored as {"state": "failed"}."""
170
+ store = app.state.store
171
+ try:
172
+ row = store.get_attempt(attempt_id)
173
+ items, keys = _items(app, row)
174
+ if not items:
175
+ result = {"state": "done", "summary": None, "questions": {}}
176
+ else:
177
+ got = app.state.reviewer.review(items)
178
+ questions = {}
179
+ for q in got.get("questions", []):
180
+ key = keys.get(q.get("n"))
181
+ if key and q.get("verdict") in VERDICTS:
182
+ questions[key] = {"verdict": q["verdict"], "feedback": str(q.get("feedback", ""))[:600], "tip": str(q.get("tip", ""))[:300]}
183
+ result = {"state": "done", "summary": str(got.get("summary") or "")[:800] or None, "questions": questions}
184
+ result["at"] = clock.now().isoformat()
185
+ except ReviewFailure as exc:
186
+ log.warning("board review failed: %s %s", exc.reason, exc.detail)
187
+ result = {"state": "failed", "reason": exc.reason, "at": clock.now().isoformat()}
188
+ except Exception:
189
+ log.exception("board review failed")
190
+ result = {"state": "failed", "reason": "provider_error", "at": clock.now().isoformat()}
191
+ try:
192
+ store.save_attempt(attempt_id, review=result)
193
+ finally:
194
+ with _running_lock:
195
+ _running.discard(attempt_id)
196
+
197
+
198
+ def start_in_thread(app, attempt_id: str) -> None:
199
+ threading.Thread(target=run, args=(app, attempt_id), name="board-review", daemon=True).start()
200
+
201
+
202
+ def ensure(app, row: dict) -> dict:
203
+ """For a handed-in practice test or simulation: start its review if it has none yet (or a lost one). Returns the row as it is now."""
204
+ if row["kind"] not in REVIEWED or row["submitted_at"] is None or getattr(app.state, "reviewer", None) is None:
205
+ return row
206
+ review = row.get("review")
207
+ if review and not (review.get("state") == "pending" and clock.now() - datetime.fromisoformat(review["at"]) > STALE):
208
+ return row
209
+ with _running_lock:
210
+ if row["id"] in _running:
211
+ return row
212
+ _running.add(row["id"])
213
+ row = app.state.store.save_attempt(row["id"], review={"state": "pending", "at": clock.now().isoformat()})
214
+ app.state.run_review(app, row["id"])
215
+ return app.state.store.get_attempt(row["id"]) or row
216
+
217
+
218
+ def student_view(row: dict) -> dict | None:
219
+ """What the student sees: pending, failed, or per question its verdict, feedback and tip (by question key), and the summary."""
220
+ review = row.get("review")
221
+ if not review:
222
+ return None
223
+ if review["state"] != "done":
224
+ return {"state": review["state"]}
225
+ return {"state": "done", "summary": review.get("summary"), "questions": review.get("questions", {})}
mathly2/boardwork.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The work on the board (הדרך): every answer keeps a picture of the student's board for its question, so a teacher can grade the way and not
2
+ only the final answer.
3
+
4
+ The browser sends the picture when the student answers (practice, a lesson round) or chooses (a quiz, an exercise test, the simulation), and
5
+ again before handing in when the board changed. One picture is kept per student, attempt (or "practice") and question; the one it replaces is
6
+ left with nothing referring to it, and the hourly cleanup removes it. In a graded attempt (a lesson quiz, an exercise test, the simulation) the
7
+ teacher of the student's class sees each question with the student's choice and board, and can give it 0, half or full points for the work;
8
+ the attempt's grade is recomputed."""
9
+ from __future__ import annotations
10
+
11
+ from datetime import timedelta
12
+
13
+ from fastapi import APIRouter, Depends, HTTPException, Query, Request
14
+ from fastapi.concurrency import run_in_threadpool
15
+ from pydantic import BaseModel
16
+
17
+ from . import attempts, clock, pictures
18
+ from .access import allowed, learner, need
19
+ from .written import picture_error
20
+
21
+ router = APIRouter(prefix="/api")
22
+
23
+ PRACTICE = "practice"
24
+ GRADED = ("quiz", "exercise_test", "simulation") # the attempts whose work a teacher grades
25
+ LATE_UPLOAD = timedelta(minutes=10) # a hand-in waits for the last pictures; after this an attempt's work is closed
26
+ WORK_REQUIRED = GRADED # the browser asks for work on the board before a choice in these
27
+
28
+
29
+ def _skill_of_key(bank, key: str) -> str | None:
30
+ """The skill a bank question key belongs to (a key starts with its skill's id)."""
31
+ for skill in bank.skills:
32
+ if key.startswith(skill["id"]) and key in bank.question_keys(skill["id"]):
33
+ return skill["id"]
34
+ return None
35
+
36
+
37
+ @router.post("/work", status_code=201)
38
+ async def upload_work(request: Request, ref: str = Query(..., max_length=64), key: str = Query(..., max_length=200),
39
+ user: dict = Depends(learner)) -> dict:
40
+ """The student's board for one answer, as a picture (raw image bytes). `ref`: the attempt's id, or "practice"."""
41
+ store, bank = request.app.state.store, request.app.state.bank
42
+ if ref == PRACTICE:
43
+ skill_id = _skill_of_key(bank, key)
44
+ else:
45
+ row = store.get_attempt(ref)
46
+ if row is None or row["user_id"] != user["id"]:
47
+ raise HTTPException(404, "הבוחן לא נמצא")
48
+ if not attempts.is_open(row) and clock.now() - row["submitted_at"] > LATE_UPLOAD:
49
+ raise HTTPException(409, "הבוחן כבר הוגש")
50
+ skill_id = next((q["skill_id"] for q in row["questions"] if q["key"] == key), None)
51
+ if skill_id is None:
52
+ raise HTTPException(404, "השאלה לא נמצאה")
53
+ declared = request.headers.get("content-length")
54
+ if declared and declared.isdigit() and int(declared) > pictures.MAX_IMAGE + 1024:
55
+ raise picture_error(pictures.PictureError(413, "image_too_large"))
56
+ data, kind = await request.body(), request.headers.get("content-type", "")
57
+
58
+ def work() -> dict:
59
+ jpeg = pictures.clean_image(data, kind)
60
+ saved = pictures.store_picture(store, request.app.state.pictures, user["id"], "work", jpeg)
61
+ store.save_work(user["id"], ref, key, skill_id, saved["id"], clock.now())
62
+ return saved
63
+ try:
64
+ row = await run_in_threadpool(work)
65
+ except pictures.PictureError as exc:
66
+ raise picture_error(exc) from exc
67
+ return {"id": row["id"]}
68
+
69
+
70
+ # ---- the teacher: graded attempts with their work, and points for the way ----
71
+
72
+ def _taught(request: Request, user: dict) -> list[dict]:
73
+ store = request.app.state.store
74
+ return store.classes() if allowed(user["roles"], "*") else store.classes_taught(user["email"])
75
+
76
+
77
+ def teaches_student(request: Request, user: dict, student_id: str) -> bool:
78
+ """Is the caller a teacher of a class this student is in (or a developer)?"""
79
+ if allowed(user["roles"], "*"):
80
+ return True
81
+ store = request.app.state.store
82
+ return any(m["user_id"] == student_id for c in store.classes_taught(user["email"]) for m in store.members(c["id"]))
83
+
84
+
85
+ def _title(request: Request, row: dict) -> str:
86
+ bank, store = request.app.state.bank, request.app.state.store
87
+ if row["kind"] == "quiz":
88
+ return "בוחן: " + next((l["name"] for l in bank.lessons if l["id"] == row["scope"]), row["scope"])
89
+ test_id, _, number = row["scope"].partition(":")
90
+ test = store.get_test(int(test_id)) if test_id.isdigit() else None
91
+ when = f" ({test['date'].day}.{test['date'].month})" if test else ""
92
+ return (f"מבחן תרגול {number}" if row["kind"] == "exercise_test" else "מבחן סימולציה") + when
93
+
94
+
95
+ def _iso(value):
96
+ return value.isoformat() if value else None
97
+
98
+
99
+ @router.get("/teaching/work")
100
+ def work_list(request: Request, user: dict = Depends(need("class.teach"))) -> list[dict]:
101
+ """The handed-in quizzes and tests of the teacher's students, the ones not checked yet first, then the newest."""
102
+ store, items, seen = request.app.state.store, [], set()
103
+ for klass in _taught(request, user):
104
+ emails = {m["user_id"]: m["email"] for m in store.members(klass["id"]) if m["user_id"]}
105
+ for kind in GRADED:
106
+ for uid, rows in store.attempts_of_users(list(emails), kind).items():
107
+ for row in rows:
108
+ if attempts.is_open(row) or row["id"] in seen:
109
+ continue
110
+ seen.add(row["id"])
111
+ items.append({"id": row["id"], "kind": kind, "title": _title(request, row), "student": emails[uid],
112
+ "class": {"id": klass["id"], "name": klass["name"]}, "grade": row["grade"],
113
+ "submitted_at": _iso(row["submitted_at"]), "checked": bool(row.get("checked_at"))})
114
+ items.sort(key=lambda i: i["submitted_at"] or "", reverse=True)
115
+ return sorted(items, key=lambda i: i["checked"])
116
+
117
+
118
+ def _graded_attempt(request: Request, user: dict, attempt_id: str) -> dict:
119
+ row = request.app.state.store.get_attempt(attempt_id)
120
+ if row is None or row["kind"] not in GRADED or attempts.is_open(row) or not teaches_student(request, user, row["user_id"]):
121
+ raise HTTPException(404, "הבוחן לא נמצא")
122
+ return row
123
+
124
+
125
+ def teacher_view(request: Request, row: dict) -> dict:
126
+ """Every question with its choices (the right one marked: this is the teacher), the student's choice, the automatic points, the
127
+ teacher's credit and the board's picture."""
128
+ bank, store = request.app.state.bank, request.app.state.store
129
+ work = store.work_of(row["user_id"], row["id"])
130
+ questions = []
131
+ for q in row["questions"]:
132
+ served = bank.practice_question(q["skill_id"], q["key"])
133
+ if served is None:
134
+ continue
135
+ choices = [{**c, "correct": bool((bank.grade(q["skill_id"], q["key"], c["index"]) or {}).get("correct"))} for c in served["choices"]]
136
+ picked = row["answers"].get(q["key"])
137
+ questions.append({"key": q["key"], "skill_name": (bank.skill(q["skill_id"]) or {}).get("name", ""),
138
+ "question": served["question"], **{k: served[k] for k in ("figure", "graph") if k in served},
139
+ "choices": choices, "picked": picked if isinstance(picked, int) else None,
140
+ "auto": 1 if any(c["correct"] and c["index"] == picked for c in choices) else 0,
141
+ "credit": row["credit"].get(q["key"]), "work": work.get(q["key"]),
142
+ "ai": ((row.get("review") or {}).get("questions") or {}).get(q["key"])}) # the AI's review of the way: a suggestion
143
+ student = next((m["email"] for c in store.classes() for m in store.members(c["id"]) if m["user_id"] == row["user_id"]), "")
144
+ return {"id": row["id"], "kind": row["kind"], "title": _title(request, row), "student": student, "grade": row["grade"],
145
+ "submitted_at": _iso(row["submitted_at"]), "checked_at": _iso(row.get("checked_at")), "checked_by": row.get("checked_by"),
146
+ "questions": questions, "ai_summary": (row.get("review") or {}).get("summary")}
147
+
148
+
149
+ @router.get("/teaching/work/{attempt_id}")
150
+ def work_open(attempt_id: str, request: Request, user: dict = Depends(need("class.teach"))) -> dict:
151
+ return teacher_view(request, _graded_attempt(request, user, attempt_id))
152
+
153
+
154
+ class Credit(BaseModel):
155
+ credit: dict[str, float | None]
156
+
157
+
158
+ @router.post("/teaching/work/{attempt_id}")
159
+ def work_check(attempt_id: str, body: Credit, request: Request, user: dict = Depends(need("class.teach"))) -> dict:
160
+ """Points for the way: per question 0, 0.5 or 1 (None: back to the automatic points). The grade is recomputed from all of them."""
161
+ store, bank = request.app.state.store, request.app.state.bank
162
+ row = _graded_attempt(request, user, attempt_id)
163
+ keys = {q["key"] for q in row["questions"]}
164
+ credit = dict(row["credit"])
165
+ for key, value in body.credit.items():
166
+ if key not in keys or (value is not None and value not in attempts.CREDITS):
167
+ raise HTTPException(422, "ניקוד לא תקין")
168
+ if value is None:
169
+ credit.pop(key, None)
170
+ else:
171
+ credit[key] = value
172
+ value, _ = attempts.grade(bank, row["questions"], row["answers"], credit)
173
+ saved = store.save_attempt(row["id"], credit=credit, grade=value, checked_at=clock.now(), checked_by=user["email"])
174
+ return teacher_view(request, saved)
mathly2/cleanup.py CHANGED
@@ -20,7 +20,7 @@ def run(store, backend, now: datetime | None = None) -> dict:
20
  for pic in store.pictures():
21
  refs = store.picture_refs(pic["id"])
22
  referenced = any(refs.values())
23
- if pic["kind"] == "answer" and retention.is_expired(clock.school_day(pic["created_at"]), today):
24
  reason = "expired"
25
  elif not referenced and now - pic["created_at"] > retention.ORPHAN_AGE:
26
  reason = "orphans"
 
20
  for pic in store.pictures():
21
  refs = store.picture_refs(pic["id"])
22
  referenced = any(refs.values())
23
+ if pic["kind"] in ("answer", "work") and retention.is_expired(clock.school_day(pic["created_at"]), today):
24
  reason = "expired"
25
  elif not referenced and now - pic["created_at"] > retention.ORPHAN_AGE:
26
  reason = "orphans"
mathly2/config.py CHANGED
@@ -27,6 +27,8 @@ class Settings:
27
  answer_bucket: str = "m2-answers" # the private bucket for answer pictures (not mathly1's)
28
  anthropic_key: str = "" # the AI is unavailable without it (a send fails with "missing key")
29
  math_model: str = "" # empty: the default model in ai.py
 
 
30
  cache_seconds: float = 30 # how long slow-changing reads are remembered; 0 is off
31
  vapid_private_key: str = "" # the server's push key; push notifications are off without it
32
  vapid_subject: str = "" # a contact the push services may write to ("mailto:...")
@@ -60,6 +62,8 @@ def load_settings(env_file: Path | None = None) -> Settings:
60
  answer_bucket=env("MATHLY_M2_ANSWER_BUCKET") or "m2-answers",
61
  anthropic_key=env("ANTHROPIC_API_KEY"),
62
  math_model=env("MATH_MODEL"),
 
 
63
  cache_seconds=float(env("MATHLY_CACHE_SECONDS") or 30),
64
  vapid_private_key=env("VAPID_PRIVATE_KEY"),
65
  vapid_subject=env("VAPID_SUBJECT"),
 
27
  answer_bucket: str = "m2-answers" # the private bucket for answer pictures (not mathly1's)
28
  anthropic_key: str = "" # the AI is unavailable without it (a send fails with "missing key")
29
  math_model: str = "" # empty: the default model in ai.py
30
+ gemini_key: str = "" # the AI review of the way in tests (boardreview.py); none without it
31
+ gemini_model: str = "" # empty: the default (free tier) model in boardreview.py
32
  cache_seconds: float = 30 # how long slow-changing reads are remembered; 0 is off
33
  vapid_private_key: str = "" # the server's push key; push notifications are off without it
34
  vapid_subject: str = "" # a contact the push services may write to ("mailto:...")
 
62
  answer_bucket=env("MATHLY_M2_ANSWER_BUCKET") or "m2-answers",
63
  anthropic_key=env("ANTHROPIC_API_KEY"),
64
  math_model=env("MATH_MODEL"),
65
+ gemini_key=env("GEMINI_API_KEY"),
66
+ gemini_model=env("GEMINI_MODEL"),
67
  cache_seconds=float(env("MATHLY_CACHE_SECONDS") or 30),
68
  vapid_private_key=env("VAPID_PRIVATE_KEY"),
69
  vapid_subject=env("VAPID_SUBJECT"),
mathly2/main.py CHANGED
@@ -15,7 +15,7 @@ from .access import RoleResolver, learner, permissions_of
15
  from .auth import DevAuthenticator, SupabaseAuthenticator, current_user
16
  from .bank import Bank, load_bank
17
 
18
- from . import accounts, ai, ai_help, assignments, classes, cleanup, content, progress, prompter, quizzes, reads, realtests, review, rounds, skills, status, subjects, worksheets, written
19
  from .config import Settings, load_settings
20
  from .cached import CachedStore
21
  from .store import InMemoryStore, StoreUnavailable, SupabaseStore
@@ -36,7 +36,7 @@ class FreshStaticFiles(StaticFiles):
36
  log = logging.getLogger("mathly2")
37
 
38
 
39
- def create_app(settings: Settings | None = None, bank: Bank | None = None, store=None, authenticator=None, picture_store=None, pusher=None, ai_client=None) -> FastAPI:
40
  @asynccontextmanager
41
  async def lifespan(application: FastAPI):
42
  # Against the real database the pictures are tidied every hour (nothing runs without Supabase, so local runs and tests are quiet).
@@ -63,6 +63,8 @@ def create_app(settings: Settings | None = None, bank: Bank | None = None, store
63
  app.state.pusher = pusher or Pusher(app.state.store, settings.vapid_private_key, default_subject(settings))
64
  app.state.notify_request = written.notify_new_request
65
  app.state.ai = ai_client or ai.make_ai(settings)
 
 
66
  app.state.worksheet_files = (SupabasePictures(settings.supabase_url, settings.supabase_secret, "m2-worksheets")
67
  if settings.supabase_on else MemoryPictures())
68
  app.state.run_worksheet = worksheets.submit # drafting in the background (tests may run it inline)
@@ -84,6 +86,7 @@ def create_app(settings: Settings | None = None, bank: Bank | None = None, store
84
  app.include_router(accounts.router)
85
  app.include_router(skills.router)
86
  app.include_router(rounds.router)
 
87
  app.include_router(quizzes.router)
88
  app.include_router(realtests.router)
89
  app.include_router(progress.router)
 
15
  from .auth import DevAuthenticator, SupabaseAuthenticator, current_user
16
  from .bank import Bank, load_bank
17
 
18
+ from . import accounts, ai, ai_help, assignments, boardreview, boardwork, classes, cleanup, content, progress, prompter, quizzes, reads, realtests, review, rounds, skills, status, subjects, worksheets, written
19
  from .config import Settings, load_settings
20
  from .cached import CachedStore
21
  from .store import InMemoryStore, StoreUnavailable, SupabaseStore
 
36
  log = logging.getLogger("mathly2")
37
 
38
 
39
+ def create_app(settings: Settings | None = None, bank: Bank | None = None, store=None, authenticator=None, picture_store=None, pusher=None, ai_client=None, reviewer=None) -> FastAPI:
40
  @asynccontextmanager
41
  async def lifespan(application: FastAPI):
42
  # Against the real database the pictures are tidied every hour (nothing runs without Supabase, so local runs and tests are quiet).
 
63
  app.state.pusher = pusher or Pusher(app.state.store, settings.vapid_private_key, default_subject(settings))
64
  app.state.notify_request = written.notify_new_request
65
  app.state.ai = ai_client or ai.make_ai(settings)
66
+ app.state.reviewer = reviewer or boardreview.make_reviewer(settings) # the AI review of the way in tests; None without GEMINI_API_KEY
67
+ app.state.run_review = boardreview.start_in_thread # in the background (tests may run it inline)
68
  app.state.worksheet_files = (SupabasePictures(settings.supabase_url, settings.supabase_secret, "m2-worksheets")
69
  if settings.supabase_on else MemoryPictures())
70
  app.state.run_worksheet = worksheets.submit # drafting in the background (tests may run it inline)
 
86
  app.include_router(accounts.router)
87
  app.include_router(skills.router)
88
  app.include_router(rounds.router)
89
+ app.include_router(boardwork.router)
90
  app.include_router(quizzes.router)
91
  app.include_router(realtests.router)
92
  app.include_router(progress.router)
mathly2/quizzes.py CHANGED
@@ -56,10 +56,15 @@ def view(request: Request, row: dict) -> dict:
56
  base["test"] = _test_info(request, row)
57
  if attempts.is_open(row):
58
  questions = [q for q in (bank.practice_question(r["skill_id"], r["key"]) for r in row["questions"]) if q]
59
- return {**base, "state": "open", "due_at": _iso(row["due_at"]) if attempts.is_timed(row) else None, "now": _iso(clock.now()), "answers": row["answers"], "questions": questions}
 
 
 
 
60
  result = attempts.result(bank, row)
61
  result.pop("lesson", None)
62
- return {**base, "state": "submitted", **result, "submitted_at": _iso(row["submitted_at"])}
 
63
 
64
 
65
  _view = view
 
56
  base["test"] = _test_info(request, row)
57
  if attempts.is_open(row):
58
  questions = [q for q in (bank.practice_question(r["skill_id"], r["key"]) for r in row["questions"]) if q]
59
+ from .boardwork import WORK_REQUIRED
60
+ return {**base, "state": "open", "due_at": _iso(row["due_at"]) if attempts.is_timed(row) else None, "now": _iso(clock.now()), "answers": row["answers"], "questions": questions,
61
+ "work_required": row["kind"] in WORK_REQUIRED, "work": sorted(request.app.state.store.work_of(row["user_id"], row["id"]))} # questions whose board is saved
62
+ from . import boardreview
63
+ row = boardreview.ensure(request.app, row) # a practice test or the simulation: the AI reviews the way
64
  result = attempts.result(bank, row)
65
  result.pop("lesson", None)
66
+ return {**base, "state": "submitted", **result, "submitted_at": _iso(row["submitted_at"]), "review": boardreview.student_view(row),
67
+ "keys": [q["key"] for q in row["questions"]]}
68
 
69
 
70
  _view = view
mathly2/static/app.css CHANGED
@@ -662,3 +662,23 @@ body:has(#lesson-map) p:has(> #to-subjects) { margin-block: 0 4px; }
662
  .pr-form textarea { min-height: 180px; }
663
  .pr-actions { flex-wrap: wrap; }
664
  .pr-help pre { background: color-mix(in srgb, currentColor 8%, transparent); padding: 8px; border-radius: 6px; overflow-x: auto; white-space: pre-wrap; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
  .pr-form textarea { min-height: 180px; }
663
  .pr-actions { flex-wrap: wrap; }
664
  .pr-help pre { background: color-mix(in srgb, currentColor 8%, transparent); padding: 8px; border-radius: 6px; overflow-x: auto; white-space: pre-wrap; }
665
+
666
+ /* ---------- the work on the board: the student's prompt and the teacher's check (board-work) ---------- */
667
+ .qz-need-work { border-color: var(--sky-gold); }
668
+ .work-list li { flex-wrap: wrap; }
669
+ .work-q .work-choices li { padding: 6px 8px; border-radius: 8px; }
670
+ .work-q .work-choices li.right { background: color-mix(in srgb, var(--ok, #15803d) 18%, transparent); }
671
+ .work-q .work-choices li.picked:not(.right) { background: color-mix(in srgb, var(--danger) 16%, transparent); }
672
+ .work-q .work-pic { display: block; max-width: 100%; border-radius: 8px; border: 1px solid var(--line); background: #fff; }
673
+ .work-points { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 10px; }
674
+ .work-points button[aria-pressed="true"] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
675
+ .work-points .work-now { margin-inline-start: auto; font-size: 18px; }
676
+ .qz-review { margin-block: 12px; padding: 12px; border-radius: 12px; border: 1px solid var(--line); background: color-mix(in srgb, var(--sky-accent) 6%, var(--surface)); }
677
+ .qz-review h4 { margin: 0 0 6px; }
678
+ .qz-review-list li { display: block; padding: 8px 0; }
679
+ .qz-review-list li p { margin: 4px 0; }
680
+ .qz-review-list li.v-correct .tag { border-color: var(--ok, #15803d); }
681
+ .qz-review-list li.v-wrong .tag { border-color: var(--danger); }
682
+ .qz-review .spin { display: inline-block; width: 12px; height: 12px; border-radius: 50%; border: 2px solid var(--line); border-top-color: var(--accent); animation: spin 1s linear infinite; vertical-align: middle; }
683
+ @keyframes spin { to { transform: rotate(360deg); } }
684
+ .work-ai { margin: 4px 0 8px; }
mathly2/static/boardwork.js ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The work on the board (הדרך): after an answer, a picture of the question's board goes to the server, so the teacher can grade the way and
2
+ // not only the final answer. A picture is sent again only when the board changed; an empty board sends nothing.
3
+ import { sendPicture } from "./media.js";
4
+
5
+ const sent = new Map(); // board key -> the sketch's signature when it was last sent
6
+
7
+ /** Is there anything but the question's copy on this board? */
8
+ export const hasWork = boardKey => !!window.MathlyBoard?.hasWork?.(boardKey);
9
+
10
+ /** Send the board's picture as the work for one answer: `ref` is the attempt's id or "practice". Resolves to true when the server has it. */
11
+ export async function sendWork(boardKey, ref, questionKey) {
12
+ const board = window.MathlyBoard;
13
+ if (!board?.hasWork?.(boardKey)) return false;
14
+ const sig = board.workSig(boardKey);
15
+ if (sent.get(boardKey) === sig) return true;
16
+ const blob = await board.pictureOf(boardKey);
17
+ if (!blob) return false;
18
+ await sendPicture(`/api/work?ref=${encodeURIComponent(ref)}&key=${encodeURIComponent(questionKey)}`, blob);
19
+ sent.set(boardKey, sig);
20
+ return true;
21
+ }
22
+
23
+ /** The same, never failing the caller (practice and rounds go on whatever happens to the picture). */
24
+ export const sendWorkQuietly = (...args) => sendWork(...args).catch(() => false);
mathly2/static/exercise.js CHANGED
@@ -6,6 +6,7 @@ import { clear as clearComet, cross as crossComet } from "./comets.js";
6
  import { esc, fmt } from "./math.js";
7
  import * as aiSheet from "./ai_sheet.js";
8
  import { pathHref, shuffled } from "./ui.js";
 
9
 
10
 
11
  const COUNTDOWN = 3; // seconds before the next question after a right answer
@@ -213,6 +214,7 @@ async function answer(button) {
213
  }
214
  buttons.forEach(b => b.classList.remove("pending", "dim"));
215
  button.removeAttribute("aria-busy");
 
216
  Object.assign(skill, { round: result.round, state: result.state, correct_in_row: result.correct_in_row, today: result.today });
217
  updateProgress();
218
  const feedback = q("#ex-fb");
 
6
  import { esc, fmt } from "./math.js";
7
  import * as aiSheet from "./ai_sheet.js";
8
  import { pathHref, shuffled } from "./ui.js";
9
+ import { sendWorkQuietly } from "./boardwork.js";
10
 
11
 
12
  const COUNTDOWN = 3; // seconds before the next question after a right answer
 
214
  }
215
  buttons.forEach(b => b.classList.remove("pending", "dim"));
216
  button.removeAttribute("aria-busy");
217
+ sendWorkQuietly(`${skill.id}:${question.key}`, "practice", question.key); // the board of this answer, for the teacher
218
  Object.assign(skill, { round: result.round, state: result.state, correct_in_row: result.correct_in_row, today: result.today });
219
  updateProgress();
220
  const feedback = q("#ex-fb");
mathly2/static/math-board.js CHANGED
@@ -859,12 +859,19 @@ if(window.MathlyBoardMath) window.MathlyBoardMath.onFonts=()=>el&&paint();
859
 
860
  /* ---------- handing in ---------- */
861
  // the whole sketch as a picture on white paper: as wide as the board (wider when it was written further right), as tall as what is drawn
862
- function snapshot(){
863
- const all=marks(); if(!all.some(m=>m.kind!=="card")) return null;
864
- const [,y0,x1,y1]=edges(all), top=Math.max(0,y0-24), W=Math.min(Math.max(canvas.clientWidth,x1+24),8000), H=Math.min(y1+24-top,8000), k=2;
865
- const out=document.createElement("canvas"); out.width=W*k; out.height=Math.round(H*k);
 
 
 
 
 
 
 
866
  const keep=ctx; ctx=out.getContext("2d"); paper="#fff";
867
- try{ ctx.fillStyle="#fff"; ctx.fillRect(0,0,out.width,out.height); ctx.setTransform(k,0,0,k,0,-top*k); all.forEach(draw); }
868
  finally{ ctx=keep; paper=PAPER; }
869
  return new Promise(ok=>out.toBlob(ok,"image/png"));
870
  }
@@ -939,5 +946,5 @@ function closeFull(){
939
  // the header's switch: beside the exercise on a desktop screen, full screen on a phone
940
  const button=()=>`<button class="mx-board-btn" data-board-toggle aria-pressed="${isOn()&&desk()}" title="לוח טיוטה">${ic("pen")}<span>לוח</span></button>`;
941
 
942
- window.MathlyBoard={button,mount,toggle,show,openFull,closeFull,isOn,desk};
943
  })();
 
859
 
860
  /* ---------- handing in ---------- */
861
  // the whole sketch as a picture on white paper: as wide as the board (wider when it was written further right), as tall as what is drawn
862
+ function snapshot(){ return pictureOf(key); }
863
+ /* the work on the board (הדרך): has this question's sketch anything but the question's copy; its picture, even while the board is closed;
864
+ and a signature that changes when the sketch does (so a picture is sent again only after a change) */
865
+ const hasWork=k=>(sketches.get(k)?.marks||[]).some(m=>m.kind!=="card");
866
+ const workSig=k=>JSON.stringify(sketches.get(k)?.marks||[]);
867
+ function pictureOf(k){
868
+ const all=sketches.get(k)?.marks||[]; if(!all.some(m=>m.kind!=="card")) return null;
869
+ if(!el) build();
870
+ const wide=canvas.clientWidth||720;
871
+ const [,y0,x1,y1]=edges(all), top=Math.max(0,y0-24), W=Math.min(Math.max(wide,x1+24),8000), H=Math.min(y1+24-top,8000), k2=2;
872
+ const out=document.createElement("canvas"); out.width=W*k2; out.height=Math.round(H*k2);
873
  const keep=ctx; ctx=out.getContext("2d"); paper="#fff";
874
+ try{ ctx.fillStyle="#fff"; ctx.fillRect(0,0,out.width,out.height); ctx.setTransform(k2,0,0,k2,0,-top*k2); all.forEach(draw); }
875
  finally{ ctx=keep; paper=PAPER; }
876
  return new Promise(ok=>out.toBlob(ok,"image/png"));
877
  }
 
946
  // the header's switch: beside the exercise on a desktop screen, full screen on a phone
947
  const button=()=>`<button class="mx-board-btn" data-board-toggle aria-pressed="${isOn()&&desk()}" title="לוח טיוטה">${ic("pen")}<span>לוח</span></button>`;
948
 
949
+ window.MathlyBoard={button,mount,toggle,show,openFull,closeFull,isOn,desk,hasWork,workSig,pictureOf};
950
  })();
mathly2/static/quiz.js CHANGED
@@ -6,6 +6,7 @@ import { loadBoard } from "./exercise.js";
6
  import { figures } from "./figures.js";
7
  import { esc, fmt } from "./math.js";
8
  import { pathHref, shuffled } from "./ui.js";
 
9
 
10
  const LIVE_AT = new Set([300, 60, 10, 0]); // seconds left at which the timer is announced to a screen reader
11
 
@@ -103,7 +104,7 @@ async function tick() {
103
  async function finish(submit) {
104
  const id = attempt.id;
105
  try {
106
- if (submit) await saving;
107
  const data = submit ? await api(`/api/attempts/${id}/submit`, { method: "POST" }) : await api(`/api/attempts/${id}`);
108
  if (data.state === "open") { setTimeout(() => layer && finish(false), 1000); return; } // a hair early on the device: ask again
109
  show(data);
@@ -144,8 +145,27 @@ function renderQuestion() {
144
 
145
  let saving = Promise.resolve(); // the answer saves still on their way to the server
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  async function choose(button) {
148
  const question = attempt.questions[at], index = Number(button.dataset.i), before = attempt.answers[question.key];
 
149
  attempt.answers[question.key] = index;
150
  layer.querySelectorAll(".qz-choice").forEach(b => { const on = Number(b.dataset.i) === index; b.classList.toggle("picked", on); b.setAttribute("aria-pressed", String(on)); });
151
  q(`.qz-dot[data-go="${at}"]`)?.classList.add("done");
@@ -153,6 +173,7 @@ async function choose(button) {
153
  saving = save.catch(() => {}); // one save at a time, and a submit waits for the last one (else it is graded without it)
154
  try {
155
  await save;
 
156
  } catch (error) {
157
  if (error instanceof ApiError && error.status === 409) return finish(false); // time ran out: the server already submitted
158
  if (before === undefined) delete attempt.answers[question.key]; else attempt.answers[question.key] = before;
@@ -173,6 +194,39 @@ function submit() {
173
  finish(true);
174
  }
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  function renderResult() {
177
  const r = attempt;
178
  stopTimer();
@@ -186,7 +240,9 @@ function renderResult() {
186
  ${r.missed.length ? `<h4>הטעויות</h4><ol class="qz-missed" id="qz-missed">${r.missed.map(m => `<li><p class="ex-text" dir="auto">${fmt(m.question)}</p>
187
  ${m.picked ? `<p class="muted">בחרתם: <span dir="auto">${fmt(m.picked)}</span></p>` : `<p class="muted">לא ענו על השאלה.</p>`}
188
  ${m.mistake ? `<p><b>${esc(m.mistake.name)}</b>${m.mistake.tip ? `<br>${fmt(m.mistake.tip)}` : ""}</p>` : ""}</li>`).join("")}</ol>` : ""}
 
189
  <p class="qz-actions">${names(r).again ? `<button type="button" class="primary" id="qz-retake">${names(r).again}</button> ` : ""}<button type="button" data-close>${r.kind === "quiz" ? "חזרה למסלול" : "חזרה למבחן"}</button></p>`;
 
190
  const best = r.kind === "quiz" ? api(`/api/lessons/${encodeURIComponent(r.lesson.id)}/quiz`).then(f => f.best === null ? "" : `הציון של השיעור: ${f.best}`)
191
  : r.kind === "exercise_test" ? api(`/api/tests/${encodeURIComponent(r.test.id)}`).then(t => `הציון הטוב במבחן התרגול: ${t.exercise_tests[r.test.number - 1].best ?? ""}`) : Promise.resolve("");
192
  best.then(text => { if (text && q("#qz-best")) q("#qz-best").textContent = text; }).catch(() => {});
@@ -202,6 +258,7 @@ function onClick(event) {
202
  const choice = target.closest(".qz-choice");
203
  if (choice) { choose(choice); return; }
204
  if (target.closest("#qz-submit")) { submit(); return; }
 
205
  if (target.closest("#qz-yes")) { finish(true); return; }
206
  if (target.closest("#qz-back")) { q("#qz-warn").innerHTML = ""; warned = false; return; }
207
  } else if (target.closest("#qz-retake")) {
 
6
  import { figures } from "./figures.js";
7
  import { esc, fmt } from "./math.js";
8
  import { pathHref, shuffled } from "./ui.js";
9
+ import { hasWork, sendWork } from "./boardwork.js";
10
 
11
  const LIVE_AT = new Set([300, 60, 10, 0]); // seconds left at which the timer is announced to a screen reader
12
 
 
104
  async function finish(submit) {
105
  const id = attempt.id;
106
  try {
107
+ if (submit) { await saving; await sendAllWork(); } // the boards go with the hand-in
108
  const data = submit ? await api(`/api/attempts/${id}/submit`, { method: "POST" }) : await api(`/api/attempts/${id}`);
109
  if (data.state === "open") { setTimeout(() => layer && finish(false), 1000); return; } // a hair early on the device: ask again
110
  show(data);
 
145
 
146
  let saving = Promise.resolve(); // the answer saves still on their way to the server
147
 
148
+ const boardKey = key => `quiz:${attempt.id}:${key}`;
149
+
150
+ /** In a quiz or a test the way counts: a choice needs something written on the board for this question (or a board already saved). */
151
+ function needsWork(question) {
152
+ if (!attempt.work_required || hasWork(boardKey(question.key)) || (attempt.work || []).includes(question.key)) return false;
153
+ q("#qz-fb").innerHTML = `<div class="ex-note qz-need-work" id="qz-need-work" role="alert"><p><b>✏️ קודם כותבים את הדרך בלוח</b></p>
154
+ <p>המורה בודק גם את הדרך, לא רק את התשובה. פתרו בלוח ואז בחרו תשובה.</p>
155
+ <p><button type="button" class="primary" id="qz-open-board">פתיחת הלוח</button></p></div>`;
156
+ return true;
157
+ }
158
+
159
+ /** Send the board of every answered question that changed since it was last sent (before handing in). */
160
+ function sendAllWork() {
161
+ const id = attempt.id;
162
+ return Promise.allSettled(attempt.questions.filter(x => attempt.answers[x.key] !== undefined)
163
+ .map(x => sendWork(`quiz:${id}:${x.key}`, id, x.key).then(ok => { if (ok && attempt?.id === id) (attempt.work ||= []).push(x.key); })));
164
+ }
165
+
166
  async function choose(button) {
167
  const question = attempt.questions[at], index = Number(button.dataset.i), before = attempt.answers[question.key];
168
+ if (needsWork(question)) return;
169
  attempt.answers[question.key] = index;
170
  layer.querySelectorAll(".qz-choice").forEach(b => { const on = Number(b.dataset.i) === index; b.classList.toggle("picked", on); b.setAttribute("aria-pressed", String(on)); });
171
  q(`.qz-dot[data-go="${at}"]`)?.classList.add("done");
 
173
  saving = save.catch(() => {}); // one save at a time, and a submit waits for the last one (else it is graded without it)
174
  try {
175
  await save;
176
+ sendWork(boardKey(question.key), id, question.key).then(ok => { if (ok && attempt?.id === id) (attempt.work ||= []).push(question.key); }).catch(() => {});
177
  } catch (error) {
178
  if (error instanceof ApiError && error.status === 409) return finish(false); // time ran out: the server already submitted
179
  if (before === undefined) delete attempt.answers[question.key]; else attempt.answers[question.key] = before;
 
194
  finish(true);
195
  }
196
 
197
+ const VERDICT = { correct: ["✓", "דרך נכונה"], partial: ["◐", "חלק מהדרך נכון"], wrong: ["✗", "הדרך לא נכונה"], unclear: ["?", "לא הצלחנו לקרוא"] };
198
+
199
+ /** The AI's review of the way (a practice test, the simulation): waiting, failed, or per question with a board its verdict, feedback and tip. */
200
+ function reviewHtml(r) {
201
+ const review = r.review;
202
+ if (!review) return "";
203
+ if (review.state === "pending") return `<section class="qz-review" id="qz-review" data-state="pending"><h4>משוב על הדרך</h4>
204
+ <p class="muted"><span class="spin" aria-hidden="true"></span> בודקים את הדרך שכתבתם בלוח… זה לוקח כדקה.</p></section>`;
205
+ if (review.state === "failed") return `<section class="qz-review" id="qz-review" data-state="failed"><h4>משוב על הדרך</h4><p class="muted">לא הצלחנו לבדוק את הדרך הפעם. המורה יראו את הלוחות.</p></section>`;
206
+ const rows = (r.keys || []).map((key, i) => [i + 1, review.questions[key]]).filter(([, q]) => q);
207
+ return `<section class="qz-review" id="qz-review" data-state="done"><h4>משוב על הדרך</h4>
208
+ ${review.summary ? `<p class="qz-review-sum">${fmt(review.summary)}</p>` : ""}
209
+ ${rows.length ? `<ol class="plain qz-review-list">${rows.map(([n, q]) => `<li class="v-${esc(q.verdict)}" data-n="${n}"><p><b>שאלה ${n}</b>
210
+ <span class="tag"><span aria-hidden="true">${VERDICT[q.verdict][0]}</span> ${VERDICT[q.verdict][1]}</span></p>
211
+ <p>${fmt(q.feedback)}</p>${q.tip ? `<p class="muted">💡 ${fmt(q.tip)}</p>` : ""}</li>`).join("")}</ol>`
212
+ : `<p class="muted">לא נשמרה דרך בלוח באף שא��ה.</p>`}
213
+ <p class="muted qz-review-note">משוב אוטומטי. המורה בודקים את הדרך ונותנים את הנקודות.</p></section>`;
214
+ }
215
+
216
+ /** While the review is being written, ask again every few seconds and redraw only its section. */
217
+ function waitForReview(id) {
218
+ setTimeout(async () => {
219
+ if (!layer || attempt?.id !== id || attempt.review?.state !== "pending") return;
220
+ try {
221
+ const fresh = await api(`/api/attempts/${encodeURIComponent(id)}`);
222
+ if (!layer || attempt?.id !== id) return;
223
+ attempt.review = fresh.review;
224
+ q("#qz-review")?.replaceWith(Object.assign(document.createElement("div"), { innerHTML: reviewHtml(fresh) }).firstElementChild || "");
225
+ } catch { /* try again */ }
226
+ waitForReview(id);
227
+ }, 4000);
228
+ }
229
+
230
  function renderResult() {
231
  const r = attempt;
232
  stopTimer();
 
240
  ${r.missed.length ? `<h4>הטעויות</h4><ol class="qz-missed" id="qz-missed">${r.missed.map(m => `<li><p class="ex-text" dir="auto">${fmt(m.question)}</p>
241
  ${m.picked ? `<p class="muted">בחרתם: <span dir="auto">${fmt(m.picked)}</span></p>` : `<p class="muted">לא ענו על השאלה.</p>`}
242
  ${m.mistake ? `<p><b>${esc(m.mistake.name)}</b>${m.mistake.tip ? `<br>${fmt(m.mistake.tip)}` : ""}</p>` : ""}</li>`).join("")}</ol>` : ""}
243
+ ${reviewHtml(r)}
244
  <p class="qz-actions">${names(r).again ? `<button type="button" class="primary" id="qz-retake">${names(r).again}</button> ` : ""}<button type="button" data-close>${r.kind === "quiz" ? "חזרה למסלול" : "חזרה למבחן"}</button></p>`;
245
+ if (r.review?.state === "pending") waitForReview(r.id);
246
  const best = r.kind === "quiz" ? api(`/api/lessons/${encodeURIComponent(r.lesson.id)}/quiz`).then(f => f.best === null ? "" : `הציון של השיעור: ${f.best}`)
247
  : r.kind === "exercise_test" ? api(`/api/tests/${encodeURIComponent(r.test.id)}`).then(t => `הציון הטוב במבחן התרגול: ${t.exercise_tests[r.test.number - 1].best ?? ""}`) : Promise.resolve("");
248
  best.then(text => { if (text && q("#qz-best")) q("#qz-best").textContent = text; }).catch(() => {});
 
258
  const choice = target.closest(".qz-choice");
259
  if (choice) { choose(choice); return; }
260
  if (target.closest("#qz-submit")) { submit(); return; }
261
+ if (target.closest("#qz-open-board")) { window.MathlyBoard?.show?.(0); return; }
262
  if (target.closest("#qz-yes")) { finish(true); return; }
263
  if (target.closest("#qz-back")) { q("#qz-warn").innerHTML = ""; warned = false; return; }
264
  } else if (target.closest("#qz-retake")) {
mathly2/static/round.js CHANGED
@@ -5,6 +5,7 @@ import { figures } from "./figures.js";
5
  import { esc, fmt } from "./math.js";
6
  import { loadBoard } from "./exercise.js";
7
  import { homeHref, shuffled } from "./ui.js";
 
8
 
9
  const COUNTDOWN = 2; // seconds before the next question after a right answer
10
  let layer = null, round = null, timer = null, streak = 0;
@@ -132,6 +133,7 @@ async function answer(button) {
132
  }
133
  buttons.forEach(b => b.classList.remove("pending", "dim"));
134
  button.removeAttribute("aria-busy");
 
135
  const following = result.round;
136
  round = { ...round, results: following.results, state: following.state };
137
  updateProgress();
 
5
  import { esc, fmt } from "./math.js";
6
  import { loadBoard } from "./exercise.js";
7
  import { homeHref, shuffled } from "./ui.js";
8
+ import { sendWorkQuietly } from "./boardwork.js";
9
 
10
  const COUNTDOWN = 2; // seconds before the next question after a right answer
11
  let layer = null, round = null, timer = null, streak = 0;
 
133
  }
134
  buttons.forEach(b => b.classList.remove("pending", "dim"));
135
  button.removeAttribute("aria-busy");
136
+ sendWorkQuietly(`round:${round.id}:${round.question.key}`, round.id, round.question.key); // the board of this answer, for the teacher
137
  const following = result.round;
138
  round = { ...round, results: following.results, state: following.state };
139
  updateProgress();
mathly2/static/teacher.js CHANGED
@@ -10,6 +10,7 @@ const tabs = active => `<div class="subtabs" id="teacher-tabs" role="group" aria
10
  <button type="button" data-tab="tests" aria-pressed="${active === "tests"}">מבחנים <span class="tab-count" data-count="tests"></span></button>
11
  <button type="button" data-tab="assignments" aria-pressed="${active === "assignments"}">משימות <span class="tab-count" data-count="assignments"></span></button>
12
  <button type="button" data-tab="inbox" aria-pressed="${active === "inbox"}">תיבת בדיקה <span class="tab-count" data-count="inbox"></span></button>
 
13
  <button type="button" data-tab="progress" aria-pressed="${active === "progress"}">התקדמות <span class="tab-count" data-count="progress"></span></button>
14
  <button type="button" data-tab="ai" aria-pressed="${active === "ai"}">AI <span class="tab-count" data-count="ai"></span></button></div>`;
15
 
@@ -26,7 +27,7 @@ async function fillCounts() {
26
 
27
  function wireTabs() {
28
  fillCounts();
29
- const screens = { classes: showClasses, tests: showTests, assignments: () => work().then(m => m.showAssignments(context)), inbox: () => work().then(m => m.showInbox(context)), progress: () => import("./teacher_progress.js").then(m => m.show(context)), ai: () => import("./teacher_ai.js").then(m => m.show(context)) };
30
  document.querySelectorAll("#teacher-tabs [data-tab]").forEach(b => b.addEventListener("click", () => screens[b.dataset.tab]()));
31
  }
32
 
 
10
  <button type="button" data-tab="tests" aria-pressed="${active === "tests"}">מבחנים <span class="tab-count" data-count="tests"></span></button>
11
  <button type="button" data-tab="assignments" aria-pressed="${active === "assignments"}">משימות <span class="tab-count" data-count="assignments"></span></button>
12
  <button type="button" data-tab="inbox" aria-pressed="${active === "inbox"}">תיבת בדיקה <span class="tab-count" data-count="inbox"></span></button>
13
+ <button type="button" data-tab="work" aria-pressed="${active === "work"}">בדיקת דרך <span class="tab-count" data-count="work"></span></button>
14
  <button type="button" data-tab="progress" aria-pressed="${active === "progress"}">התקדמות <span class="tab-count" data-count="progress"></span></button>
15
  <button type="button" data-tab="ai" aria-pressed="${active === "ai"}">AI <span class="tab-count" data-count="ai"></span></button></div>`;
16
 
 
27
 
28
  function wireTabs() {
29
  fillCounts();
30
+ const screens = { classes: showClasses, tests: showTests, assignments: () => work().then(m => m.showAssignments(context)), inbox: () => work().then(m => m.showInbox(context)), work: () => import("./teacher_boardwork.js").then(m => m.show(context)), progress: () => import("./teacher_progress.js").then(m => m.show(context)), ai: () => import("./teacher_ai.js").then(m => m.show(context)) };
31
  document.querySelectorAll("#teacher-tabs [data-tab]").forEach(b => b.addEventListener("click", () => screens[b.dataset.tab]()));
32
  }
33
 
mathly2/static/teacher_boardwork.js ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The teacher's "בדיקת דרך" tab: the handed-in quizzes and tests of my students, each question with the student's choice and the board they
2
+ // wrote the way on. The teacher can give a question 0, half or full points for the way; the grade is recomputed on the server.
3
+ import { api } from "./api.js";
4
+ import { figures } from "./figures.js";
5
+ import { esc, fmt } from "./math.js";
6
+ import { pictureUrl } from "./media.js";
7
+
8
+ const KINDS = { quiz: "בוחן", exercise_test: "מבחן תרגול", simulation: "סימולציה" };
9
+ const POINTS = [[null, "אוטומטי"], [0, "0"], [0.5, "½"], [1, "מלא"]];
10
+ let ctx;
11
+
12
+ /** The list: the ones not checked yet first. */
13
+ export async function show(context) {
14
+ ctx = context;
15
+ const items = await api("/api/teaching/work");
16
+ ctx.draw(`${ctx.tabs("work")}<section id="boardwork"><h2>בדיקת הדרך</h2>
17
+ <p class="muted">בכל שאלה בבוחן ובמבחן נשמר הלוח של התלמיד. אפשר לתת נקודות על הדרך: חצי או מלא גם לתשובה שגויה, או 0 לתשובה נכונה בלי דרך.</p>
18
+ ${items.length ? `<ul class="plain work-list">${items.map(i => `<li data-attempt="${esc(i.id)}"><span class="grow"><b>${fmt(i.title)}</b><br>
19
+ <span class="muted" dir="ltr">${esc(i.student)}</span> <span class="muted">· ${esc(i.class.name)}</span></span>
20
+ <span class="tag">${i.grade ?? "-"}</span><span class="tag${i.checked ? " st-graded" : ""}">${i.checked ? "✓ נבדק" : "○ לבדיקה"}</span>
21
+ <button type="button" data-open="${esc(i.id)}">פתיחה</button></li>`).join("")}</ul>`
22
+ : `<p class="card muted" id="no-work">עוד אין בחנים או מבחנים שהוגשו.</p>`}</section>`);
23
+ ctx.wire();
24
+ document.querySelectorAll("[data-open]").forEach(b => b.addEventListener("click", () => open(b.dataset.open)));
25
+ }
26
+
27
+ const pointsOf = q => q.credit ?? q.auto;
28
+
29
+ function questionCard(q, i) {
30
+ const picked = q.choices.find(c => c.index === q.picked);
31
+ return `<article class="card work-q" data-key="${esc(q.key)}">
32
+ <p class="muted">${i + 1}. ${fmt(q.skill_name)}</p>
33
+ <p class="ex-text" dir="auto">${fmt(q.question)}</p>${figures(q)}
34
+ <ul class="plain work-choices">${q.choices.map(c => `<li class="${c.correct ? "right" : ""}${c.index === q.picked ? " picked" : ""}"><span dir="auto">${fmt(c.text)}</span>
35
+ <span>${c.correct ? "✓ נכונה" : ""}${c.index === q.picked ? " ← בחר/ה" : ""}</span></li>`).join("")}</ul>
36
+ ${picked ? "" : `<p class="muted">לא ענה/תה על השאלה.</p>`}
37
+ <h4>הדרך</h4>${q.ai ? `<p class="work-ai"><span class="tag">AI: ${({ correct: "✓ נכונה", partial: "◐ חלקית", wrong: "✗ שגויה", unclear: "? לא ברורה" })[q.ai.verdict] || ""}</span> ${fmt(q.ai.feedback)}</p>` : ""}${q.work ? `<img class="work-pic" data-picture="${esc(q.work)}" alt="הלוח של התלמיד בשאלה ${i + 1}" hidden>` : `<p class="muted no-work">אין לוח לשאלה הזו.</p>`}
38
+ <div class="work-points" role="group" aria-label="נקודות לשאלה ${i + 1}"><span class="muted">נקודות:</span>${POINTS.map(([v, label]) =>
39
+ `<button type="button" data-points="${v === null ? "auto" : v}" aria-pressed="${(q.credit ?? null) === v}">${label}${v === null ? ` (${q.auto})` : ""}</button>`).join("")}
40
+ <b class="work-now">${pointsOf(q)}</b></div></article>`;
41
+ }
42
+
43
+ /** One attempt: every question with the choice and the board; the points buttons; save. */
44
+ async function open(id, note = "") {
45
+ const data = await api(`/api/teaching/work/${encodeURIComponent(id)}`);
46
+ const chosen = Object.fromEntries(data.questions.map(q => [q.key, q.credit ?? null]));
47
+ ctx.draw(`${ctx.tabs("work")}<section id="work-check" data-attempt="${esc(data.id)}"><p><button type="button" id="work-back">‹ לרשימה</button></p>
48
+ <h2>${fmt(data.title)}</h2><p class="muted" dir="ltr">${esc(data.student)}</p>
49
+ <p>ציון: <b id="work-grade">${data.grade}</b>${data.checked_at ? ` <span class="muted">· נבדק</span>` : ""}</p>
50
+ ${note ? `<p class="ex-note" role="status">${esc(note)}</p>` : ""}
51
+ ${data.questions.map(questionCard).join("")}
52
+ <p class="work-save"><button type="button" class="primary" id="work-save">שמירת הנקודות</button></p></section>`);
53
+ ctx.wire();
54
+ document.querySelectorAll("#work-check img[data-picture]").forEach(async img => { try { img.src = await pictureUrl(img.dataset.picture); img.hidden = false; } catch { img.replaceWith(Object.assign(document.createElement("p"), { className: "muted", textContent: "התמונה לא זמינה" })); } });
55
+ document.getElementById("work-back").addEventListener("click", () => show(ctx));
56
+ document.querySelectorAll(".work-q").forEach(card => card.addEventListener("click", event => {
57
+ const b = event.target.closest("[data-points]");
58
+ if (!b) return;
59
+ const q = data.questions.find(x => x.key === card.dataset.key), v = b.dataset.points === "auto" ? null : Number(b.dataset.points);
60
+ chosen[q.key] = v;
61
+ card.querySelectorAll("[data-points]").forEach(x => x.setAttribute("aria-pressed", String(x === b)));
62
+ card.querySelector(".work-now").textContent = v ?? q.auto;
63
+ }));
64
+ document.getElementById("work-save").addEventListener("click", async event => {
65
+ event.target.disabled = true;
66
+ try {
67
+ const saved = await api(`/api/teaching/work/${encodeURIComponent(id)}`, { method: "POST", body: { credit: chosen } });
68
+ await open(id, `נשמר. הציון עכשיו ${saved.grade}.`);
69
+ } catch (error) {
70
+ event.target.disabled = false;
71
+ event.target.insertAdjacentHTML("afterend", `<p class="error" role="alert">${esc(error.message || "משהו השתבש")}</p>`);
72
+ }
73
+ });
74
+ }
75
+
76
+ export const kindName = kind => KINDS[kind] || kind;
mathly2/store.py CHANGED
@@ -46,11 +46,12 @@ PROGRESS_FIELDS = ("current_key", "current_helped", "started_at", "mastered_at",
46
  PROGRESS_DEFAULTS = {"current_key": None, "current_helped": False, "started_at": None, "mastered_at": None, "round_start": None}
47
 
48
 
49
- ATTEMPT_FIELDS = {"answers", "submitted_at", "timed_out", "grade"}
50
 
51
 
52
  def _copy_attempt(row: dict) -> dict:
53
- return {**row, "questions": [dict(q) for q in row["questions"]], "answers": dict(row["answers"])}
 
54
 
55
 
56
  def _when(value):
@@ -64,7 +65,8 @@ def _when(value):
64
  def _attempt_row(row: dict) -> dict:
65
  """A database row as the in-memory store gives it: real datetimes, plain lists and dicts."""
66
  return {**row, "started_at": _when(row["started_at"]), "due_at": _when(row["due_at"]), "submitted_at": _when(row.get("submitted_at")),
67
- "questions": list(row.get("questions") or []), "answers": dict(row.get("answers") or {})}
 
68
 
69
 
70
  TEST_FIELDS = {"date", "lessons", "note", "questions", "minutes", "subject_id"}
@@ -100,7 +102,7 @@ def _test_row(row: dict) -> dict:
100
  "created_at": _when(row["created_at"]), "removed_at": _when(row.get("removed_at"))}
101
 
102
 
103
- PICTURE_KINDS = ("page", "answer", "help")
104
  SUBMISSION_FIELDS = {"pictures", "state", "late", "handed_at", "grade", "teacher_note", "checked_at", "checked_by"}
105
  REQUEST_FIELDS = {"state", "picture_id"}
106
  AI_FIELDS = {"state", "picture_id", "skill_id", "snapshot", "result", "teacher_note", "failure", "budget", "sent_by", "sent_at", "done_at"}
@@ -137,6 +139,7 @@ class InMemoryStore:
137
  self._answers: list[dict] = []
138
  self._comets: dict[str, dict[str, str]] = {} # user_id -> {comet_id: caught_at}
139
  self._attempts: dict[str, dict] = {} # attempt id -> row
 
140
  self._reward: dict[str, dict] = {} # user_id -> {last_comet_day, last_catch_day}
141
  self._tests: dict[int, dict] = {} # test id -> row
142
  self._pictures: dict[str, dict] = {}
@@ -461,7 +464,23 @@ class InMemoryStore:
461
  return {"assignments": sorted(a["id"] for a in self._assignments.values() if pid in a["pages"]),
462
  "submissions": sorted(s["id"] for s in self._submissions.values() if pid in s["pictures"]),
463
  "requests": sorted(r["id"] for r in self._requests.values() if r["picture_id"] == pid),
464
- "ai_requests": sorted(r["id"] for r in self._ai.values() if r["picture_id"] == pid)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
 
466
  def create_assignment(self, class_id: int, title: str, due_date: date, created_by: str, kind: str, *, note: str = "", pages=(),
467
  quiz_lesson: str | None = None, test_id: int | None = None, exercise_number: int | None = None,
@@ -712,7 +731,8 @@ class InMemoryStore:
712
 
713
  def create_attempt(self, user_id: str, kind: str, scope: str, started_at: datetime, due_at: datetime, questions: list[dict]) -> dict:
714
  row = {"id": str(uuid.uuid4()), "user_id": user_id, "kind": kind, "scope": scope, "started_at": started_at, "due_at": due_at,
715
- "submitted_at": None, "timed_out": False, "grade": None, "questions": [dict(q) for q in questions], "answers": {}}
 
716
  with self._lock:
717
  self._attempts[row["id"]] = row
718
  return _copy_attempt(row)
@@ -731,7 +751,7 @@ class InMemoryStore:
731
  row = self._attempts.get(str(attempt_id))
732
  if row is None:
733
  raise KeyError(attempt_id)
734
- row.update({k: (dict(v) if k == "answers" else v) for k, v in fields.items()})
735
  return _copy_attempt(row)
736
 
737
  def save_open_answers(self, attempt_id: str, answers: dict) -> dict | None:
@@ -1267,7 +1287,21 @@ class SupabaseStore:
1267
  return {"assignments": sorted(r["id"] for r in self._request("GET", "m2_assignments", {"pages": f"cs.{{{pid}}}", "select": "id"})),
1268
  "submissions": sorted(r["id"] for r in self._request("GET", "m2_submissions", {"pictures": f"cs.{{{pid}}}", "select": "id"})),
1269
  "requests": sorted(r["id"] for r in self._request("GET", "m2_photo_requests", {"picture_id": self._eq(pid), "select": "id"})),
1270
- "ai_requests": sorted(r["id"] for r in self._request("GET", "m2_ai_requests", {"picture_id": self._eq(pid), "select": "id"}))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1271
 
1272
  def create_assignment(self, class_id: int, title: str, due_date: date, created_by: str, kind: str, *, note: str = "", pages=(),
1273
  quiz_lesson: str | None = None, test_id: int | None = None, exercise_number: int | None = None,
 
46
  PROGRESS_DEFAULTS = {"current_key": None, "current_helped": False, "started_at": None, "mastered_at": None, "round_start": None}
47
 
48
 
49
+ ATTEMPT_FIELDS = {"answers", "submitted_at", "timed_out", "grade", "credit", "checked_at", "checked_by", "review"}
50
 
51
 
52
  def _copy_attempt(row: dict) -> dict:
53
+ return {**row, "questions": [dict(q) for q in row["questions"]], "answers": dict(row["answers"]), "credit": dict(row.get("credit") or {}),
54
+ "review": copy.deepcopy(row.get("review"))}
55
 
56
 
57
  def _when(value):
 
65
  def _attempt_row(row: dict) -> dict:
66
  """A database row as the in-memory store gives it: real datetimes, plain lists and dicts."""
67
  return {**row, "started_at": _when(row["started_at"]), "due_at": _when(row["due_at"]), "submitted_at": _when(row.get("submitted_at")),
68
+ "questions": list(row.get("questions") or []), "answers": dict(row.get("answers") or {}), "credit": dict(row.get("credit") or {}),
69
+ "checked_at": _when(row.get("checked_at")), "checked_by": row.get("checked_by"), "review": row.get("review")}
70
 
71
 
72
  TEST_FIELDS = {"date", "lessons", "note", "questions", "minutes", "subject_id"}
 
102
  "created_at": _when(row["created_at"]), "removed_at": _when(row.get("removed_at"))}
103
 
104
 
105
+ PICTURE_KINDS = ("page", "answer", "help", "work")
106
  SUBMISSION_FIELDS = {"pictures", "state", "late", "handed_at", "grade", "teacher_note", "checked_at", "checked_by"}
107
  REQUEST_FIELDS = {"state", "picture_id"}
108
  AI_FIELDS = {"state", "picture_id", "skill_id", "snapshot", "result", "teacher_note", "failure", "budget", "sent_by", "sent_at", "done_at"}
 
139
  self._answers: list[dict] = []
140
  self._comets: dict[str, dict[str, str]] = {} # user_id -> {comet_id: caught_at}
141
  self._attempts: dict[str, dict] = {} # attempt id -> row
142
+ self._work: dict[tuple, dict] = {} # (user id, ref, question key) -> the board's picture for that answer
143
  self._reward: dict[str, dict] = {} # user_id -> {last_comet_day, last_catch_day}
144
  self._tests: dict[int, dict] = {} # test id -> row
145
  self._pictures: dict[str, dict] = {}
 
464
  return {"assignments": sorted(a["id"] for a in self._assignments.values() if pid in a["pages"]),
465
  "submissions": sorted(s["id"] for s in self._submissions.values() if pid in s["pictures"]),
466
  "requests": sorted(r["id"] for r in self._requests.values() if r["picture_id"] == pid),
467
+ "ai_requests": sorted(r["id"] for r in self._ai.values() if r["picture_id"] == pid),
468
+ "work": sorted(f"{w['ref']}:{w['question_key']}" for w in self._work.values() if w["picture_id"] == pid)}
469
+
470
+ # --- the work on the board: one picture per student, attempt (or "practice") and question ---
471
+
472
+ def save_work(self, user_id: str, ref: str, question_key: str, skill_id: str, picture_id: str, at: datetime | None = None) -> str | None:
473
+ """Keep this picture as the work for the answer. Returns the picture it replaced (nothing refers to it any more), or None."""
474
+ with self._lock:
475
+ old = self._work.get((user_id, ref, question_key))
476
+ self._work[(user_id, ref, question_key)] = {"user_id": user_id, "ref": ref, "question_key": question_key, "skill_id": skill_id,
477
+ "picture_id": str(picture_id), "saved_at": at or datetime.now(timezone.utc)}
478
+ return old["picture_id"] if old and old["picture_id"] != str(picture_id) else None
479
+
480
+ def work_of(self, user_id: str, ref: str) -> dict[str, str]:
481
+ """The question keys of an attempt (or "practice") that have work, each with its picture id."""
482
+ with self._lock:
483
+ return {w["question_key"]: w["picture_id"] for (u, r, _), w in self._work.items() if u == user_id and r == ref}
484
 
485
  def create_assignment(self, class_id: int, title: str, due_date: date, created_by: str, kind: str, *, note: str = "", pages=(),
486
  quiz_lesson: str | None = None, test_id: int | None = None, exercise_number: int | None = None,
 
731
 
732
  def create_attempt(self, user_id: str, kind: str, scope: str, started_at: datetime, due_at: datetime, questions: list[dict]) -> dict:
733
  row = {"id": str(uuid.uuid4()), "user_id": user_id, "kind": kind, "scope": scope, "started_at": started_at, "due_at": due_at,
734
+ "submitted_at": None, "timed_out": False, "grade": None, "questions": [dict(q) for q in questions], "answers": {},
735
+ "credit": {}, "checked_at": None, "checked_by": None, "review": None}
736
  with self._lock:
737
  self._attempts[row["id"]] = row
738
  return _copy_attempt(row)
 
751
  row = self._attempts.get(str(attempt_id))
752
  if row is None:
753
  raise KeyError(attempt_id)
754
+ row.update({k: (dict(v) if k in ("answers", "credit") else v) for k, v in fields.items()})
755
  return _copy_attempt(row)
756
 
757
  def save_open_answers(self, attempt_id: str, answers: dict) -> dict | None:
 
1287
  return {"assignments": sorted(r["id"] for r in self._request("GET", "m2_assignments", {"pages": f"cs.{{{pid}}}", "select": "id"})),
1288
  "submissions": sorted(r["id"] for r in self._request("GET", "m2_submissions", {"pictures": f"cs.{{{pid}}}", "select": "id"})),
1289
  "requests": sorted(r["id"] for r in self._request("GET", "m2_photo_requests", {"picture_id": self._eq(pid), "select": "id"})),
1290
+ "ai_requests": sorted(r["id"] for r in self._request("GET", "m2_ai_requests", {"picture_id": self._eq(pid), "select": "id"})),
1291
+ "work": sorted(f"{r['ref']}:{r['question_key']}" for r in self._request("GET", "m2_work", {"picture_id": self._eq(pid), "select": "ref,question_key"}))}
1292
+
1293
+ def save_work(self, user_id: str, ref: str, question_key: str, skill_id: str, picture_id: str, at: datetime | None = None) -> str | None:
1294
+ where = {"user_id": self._eq(user_id), "ref": self._eq(ref), "question_key": self._eq(question_key), "select": "picture_id"}
1295
+ old = self._request("GET", "m2_work", where)
1296
+ body = {"user_id": user_id, "ref": ref, "question_key": question_key, "skill_id": skill_id, "picture_id": str(picture_id),
1297
+ "saved_at": (at or datetime.now(timezone.utc)).isoformat()}
1298
+ self._request("POST", "m2_work", {"on_conflict": "user_id,ref,question_key"}, body, returning=False, upsert=True)
1299
+ before = str(old[0]["picture_id"]) if old else None
1300
+ return before if before and before != str(picture_id) else None
1301
+
1302
+ def work_of(self, user_id: str, ref: str) -> dict[str, str]:
1303
+ rows = self._request("GET", "m2_work", {"user_id": self._eq(user_id), "ref": self._eq(ref), "select": "question_key,picture_id"})
1304
+ return {r["question_key"]: str(r["picture_id"]) for r in rows}
1305
 
1306
  def create_assignment(self, class_id: int, title: str, due_date: date, created_by: str, kind: str, *, note: str = "", pages=(),
1307
  quiz_lesson: str | None = None, test_id: int | None = None, exercise_number: int | None = None,
mathly2/supabase/migrations/20261120090000_m2_board_work.sql ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Mathly 2: the work on the board (הדרך). Every answer keeps a picture of the student's board for that question (kind 'work' in m2_pictures),
2
+ -- one per student, attempt (or 'practice') and question in m2_work. A teacher can give a graded attempt's question partial or full credit for the
3
+ -- work: m2_attempts.credit maps a question key to 0, 0.5 or 1, and the grade is recomputed. Additive, plus one widened check.
4
+ -- No policies and no browser grants, as in the other m2_ tables.
5
+ -- Rollback: drop table public.m2_work; alter table public.m2_attempts drop column credit, drop column checked_at, drop column checked_by;
6
+ -- delete from public.m2_pictures where kind = 'work';
7
+ -- alter table public.m2_pictures drop constraint m2_pictures_kind_check;
8
+ -- alter table public.m2_pictures add constraint m2_pictures_kind_check check (kind in ('page', 'answer', 'help'));
9
+ begin;
10
+ alter table public.m2_pictures drop constraint m2_pictures_kind_check;
11
+ alter table public.m2_pictures add constraint m2_pictures_kind_check check (kind in ('page', 'answer', 'help', 'work'));
12
+
13
+ alter table public.m2_attempts add column credit jsonb not null default '{}'::jsonb;
14
+ alter table public.m2_attempts add column checked_at timestamptz;
15
+ alter table public.m2_attempts add column checked_by text;
16
+
17
+ -- `ref`: the attempt's id (a quiz, an exercise test, the simulation, a lesson round), or 'practice' for the exercise screen. The latest board wins.
18
+ create table public.m2_work (
19
+ user_id uuid not null,
20
+ ref text not null,
21
+ question_key text not null,
22
+ skill_id text not null,
23
+ picture_id uuid not null references public.m2_pictures(id) on delete cascade,
24
+ saved_at timestamptz not null default now(),
25
+ primary key (user_id, ref, question_key)
26
+ );
27
+ create index m2_work_picture on public.m2_work (picture_id);
28
+
29
+ alter table public.m2_work enable row level security;
30
+ revoke all on public.m2_work from public, anon, authenticated;
31
+ grant all on public.m2_work to service_role;
32
+ commit;
mathly2/supabase/migrations/20261121090000_m2_board_review.sql ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ -- Mathly 2: the AI review of the way (הדרך) in a practice test or the simulation, sent back to the student after handing in (boardreview.py).
2
+ -- {"state": "pending" | "done" | "failed", "summary", "questions": {question key: {verdict, feedback, tip}}, "at"}. Additive.
3
+ -- Rollback: alter table public.m2_attempts drop column review;
4
+ alter table public.m2_attempts add column review jsonb;
mathly2/tests/conftest.py CHANGED
@@ -2,5 +2,5 @@
2
  import os
3
 
4
  for name in ("SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SECRET_KEY", "TEACHER_EMAILS", "DEVELOPER_EMAILS",
5
- "ADMIN_EMAILS", "ANTHROPIC_API_KEY", "MATH_MODEL"):
6
  os.environ[name] = ""
 
2
  import os
3
 
4
  for name in ("SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SECRET_KEY", "TEACHER_EMAILS", "DEVELOPER_EMAILS",
5
+ "ADMIN_EMAILS", "ANTHROPIC_API_KEY", "MATH_MODEL", "GEMINI_API_KEY", "GEMINI_MODEL"):
6
  os.environ[name] = ""
mathly2/tests/test_boardwork_api.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The work on the board: saved with every answer, seen and given points by the student's teacher (board-work 1.1-1.4)."""
2
+ import io
3
+ import uuid
4
+
5
+ import pytest
6
+ from fastapi.testclient import TestClient
7
+ from PIL import Image
8
+
9
+ from mathly2 import cleanup, clock
10
+ from mathly2.bank import load_bank
11
+ from mathly2.config import Settings
12
+ from mathly2.main import create_app
13
+ from mathly2.store import InMemoryStore
14
+ from mathly2.tests.test_quizzes_api import right_index, skill_of
15
+
16
+ TEACHER, KID, OTHER_TEACHER, STRANGER = "t@school.test", "kid@school.test", "t2@school.test", "other@school.test"
17
+
18
+
19
+ def auth(email):
20
+ return {"Authorization": f"Bearer dev:{email}"}
21
+
22
+
23
+ def uid(email):
24
+ return str(uuid.uuid5(uuid.NAMESPACE_DNS, email))
25
+
26
+
27
+ def png(color="white"):
28
+ out = io.BytesIO()
29
+ Image.new("RGB", (80, 50), color).save(out, "PNG")
30
+ return out.getvalue()
31
+
32
+
33
+ @pytest.fixture
34
+ def world():
35
+ bank = load_bank()
36
+ store = InMemoryStore()
37
+ lessons = [l["id"] for l in bank.lessons][:3]
38
+ mine = store.create_class("setup", "A", lessons=lessons, teacher_email=TEACHER)
39
+ store.add_member(mine["id"], KID)
40
+ store.add_member(store.create_class("setup", "B", lessons=lessons, teacher_email=OTHER_TEACHER)["id"], STRANGER)
41
+ client = TestClient(create_app(Settings(teachers=frozenset({TEACHER, OTHER_TEACHER})), bank=bank, store=store))
42
+ for who in (KID, STRANGER, TEACHER, OTHER_TEACHER):
43
+ client.get("/api/me", headers=auth(who)) # a first sign-in links the account to the class
44
+ lesson = next(l for l in lessons if any(s["unit"] == l and bank.question_keys(s["id"]) for s in bank.skills))
45
+ return client, store, bank, lesson
46
+
47
+
48
+ def send_work(client, ref, key, who=KID, data=None):
49
+ return client.post(f"/api/work?ref={ref}&key={key}", content=data or png(), headers={**auth(who), "Content-Type": "image/png"})
50
+
51
+
52
+ def quiz(client, lesson, who=KID):
53
+ response = client.post(f"/api/lessons/{lesson}/quiz/start", headers=auth(who))
54
+ assert response.status_code == 200, response.text
55
+ return response.json()
56
+
57
+
58
+ def choose(client, bank, attempt, key, right, who=KID):
59
+ response = client.put(f"/api/attempts/{attempt['id']}/answers", headers=auth(who),
60
+ json={"key": key, "choice": right_index(bank, skill_of(key), key, right)})
61
+ assert response.status_code == 200, response.text
62
+
63
+
64
+ def handed_in(client, bank, lesson, rights):
65
+ attempt = quiz(client, lesson)
66
+ for q, right in zip(attempt["questions"], rights):
67
+ choose(client, bank, attempt, q["key"], right)
68
+ assert send_work(client, attempt["id"], q["key"]).status_code == 201
69
+ client.post(f"/api/attempts/{attempt['id']}/submit", headers=auth(KID))
70
+ return attempt
71
+
72
+
73
+ def test_a_quiz_says_work_is_required_and_lists_the_questions_whose_board_is_saved(world):
74
+ client, store, bank, lesson = world
75
+ attempt = quiz(client, lesson)
76
+ assert attempt["work_required"] is True and attempt["work"] == []
77
+ key = attempt["questions"][0]["key"]
78
+ assert send_work(client, attempt["id"], key).status_code == 201
79
+ assert quiz(client, lesson)["work"] == [key]
80
+ picture = store.get_picture(store.work_of(uid(KID), attempt["id"])[key])
81
+ assert picture["kind"] == "work" and picture["owner_id"] == uid(KID)
82
+
83
+
84
+ def test_work_goes_only_to_your_own_attempt_and_its_own_questions(world):
85
+ client, _, bank, lesson = world
86
+ attempt = quiz(client, lesson)
87
+ assert send_work(client, attempt["id"], attempt["questions"][0]["key"], who=STRANGER).status_code == 404
88
+ assert send_work(client, attempt["id"], "nope").status_code == 404
89
+ assert send_work(client, attempt["id"], attempt["questions"][0]["key"], data=b"not a picture").status_code in (400, 415, 422)
90
+
91
+
92
+ def test_practice_work_is_kept_per_question_and_the_latest_wins(world):
93
+ client, store, bank, lesson = world
94
+ skill = next(s["id"] for s in bank.skills if s["unit"] == lesson and bank.question_keys(s["id"]))
95
+ key = bank.question_keys(skill)[0]
96
+ assert send_work(client, "practice", key).status_code == 201
97
+ first = store.work_of(uid(KID), "practice")[key]
98
+ assert send_work(client, "practice", key, data=png("yellow")).status_code == 201
99
+ second = store.work_of(uid(KID), "practice")[key]
100
+ assert first != second and store.picture_refs(first)["work"] == [] and store.picture_refs(second)["work"]
101
+ assert send_work(client, "practice", "missing-key").status_code == 404
102
+
103
+
104
+ def test_the_class_teacher_sees_the_choices_and_the_board_and_others_do_not(world):
105
+ client, store, bank, lesson = world
106
+ attempt = handed_in(client, bank, lesson, [True] * 13 + [False] * 2)
107
+ listed = client.get("/api/teaching/work", headers=auth(TEACHER)).json()
108
+ assert [i["id"] for i in listed] == [attempt["id"]] and listed[0]["student"] == KID and listed[0]["checked"] is False and listed[0]["grade"] == 87
109
+ assert client.get("/api/teaching/work", headers=auth(OTHER_TEACHER)).json() == []
110
+ view = client.get(f"/api/teaching/work/{attempt['id']}", headers=auth(TEACHER)).json()
111
+ q = view["questions"][0]
112
+ assert sum(c["correct"] for c in q["choices"]) == 1 and q["picked"] is not None and q["auto"] == 1 and q["work"]
113
+ assert client.get(f"/api/pictures/{q['work']}", headers=auth(TEACHER)).status_code == 200
114
+ assert client.get(f"/api/pictures/{q['work']}", headers=auth(OTHER_TEACHER)).status_code == 404
115
+ assert client.get(f"/api/teaching/work/{attempt['id']}", headers=auth(OTHER_TEACHER)).status_code == 404
116
+ assert client.get("/api/teaching/counts", headers=auth(TEACHER)).json()["work"] == 1
117
+
118
+
119
+ def test_points_for_the_way_recompute_the_grade(world):
120
+ client, store, bank, lesson = world
121
+ attempt = handed_in(client, bank, lesson, [True] * 12 + [False] * 3) # 80: not passed
122
+ wrong = [q["key"] for q in attempt["questions"]][12:]
123
+ right = attempt["questions"][0]["key"]
124
+ post = lambda credit: client.post(f"/api/teaching/work/{attempt['id']}", headers=auth(TEACHER), json={"credit": credit})
125
+ got = post({wrong[0]: 1, wrong[1]: 0.5})
126
+ assert got.status_code == 200 and got.json()["grade"] == 90 and got.json()["checked_at"] # 13.5 of 15
127
+ facts = client.get(f"/api/lessons/{lesson}/quiz", headers=auth(KID)).json()
128
+ assert facts["best"] == 90 # the lesson's grade follows
129
+ assert post({right: 0}).json()["grade"] == 83 # a right answer with no way: 12.5 of 15
130
+ assert post({right: None, wrong[1]: None}).json()["grade"] == 87 # back to automatic: 13 of 15
131
+ assert post({wrong[2]: 0.3}).status_code == 422 and post({"nope": 1}).status_code == 422
132
+ assert client.get("/api/teaching/work", headers=auth(TEACHER)).json()[0]["checked"] is True
133
+ assert client.post(f"/api/teaching/work/{attempt['id']}", headers=auth(OTHER_TEACHER), json={"credit": {right: 1}}).status_code == 404
134
+
135
+
136
+ def test_an_open_quiz_is_not_on_the_teachers_list_and_a_replaced_board_is_cleaned_up(world):
137
+ client, store, bank, lesson = world
138
+ attempt = quiz(client, lesson)
139
+ key = attempt["questions"][0]["key"]
140
+ send_work(client, attempt["id"], key)
141
+ old = store.work_of(uid(KID), attempt["id"])[key]
142
+ send_work(client, attempt["id"], key, data=png("blue"))
143
+ assert client.get("/api/teaching/work", headers=auth(TEACHER)).json() == []
144
+ removed = cleanup.run(store, client.app.state.pictures, clock.now() + cleanup.retention.ORPHAN_AGE * 2)
145
+ assert removed["orphans"] == 1 and store.get_picture(old)["deleted_at"] and not store.get_picture(store.work_of(uid(KID), attempt["id"])[key])["deleted_at"]
mathly2/tests/test_boardwork_browser.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The work on the board in a real browser: a quiz asks for the way before a choice, the board goes with the answer, and the teacher gives
2
+ points for the way (board-work 2.1-2.3)."""
3
+ import time
4
+ import uuid
5
+
6
+ import pytest
7
+
8
+ playwright = pytest.importorskip("playwright.sync_api")
9
+
10
+ from mathly2.bank import load_bank
11
+ from mathly2.config import Settings
12
+ from mathly2.main import create_app
13
+ from mathly2.store import InMemoryStore
14
+ from mathly2.tests.serve import offline_formulas, running
15
+ from mathly2.tests.test_home_browser import KID, PHONE, TEACHER, sign_in, teacher_page
16
+
17
+ KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID))
18
+
19
+
20
+ @pytest.fixture(scope="module")
21
+ def bank():
22
+ return load_bank()
23
+
24
+
25
+ @pytest.fixture
26
+ def browser():
27
+ with playwright.sync_playwright() as p:
28
+ b = p.chromium.launch()
29
+ yield b
30
+ b.close()
31
+
32
+
33
+ def draw_line(page):
34
+ box = page.locator(".mx-board canvas").bounding_box()
35
+ x, y = box["x"] + 60, box["y"] + 160
36
+ page.mouse.move(x, y)
37
+ page.mouse.down()
38
+ page.mouse.move(x + 60, y + 30, steps=5)
39
+ page.mouse.move(x + 120, y + 60, steps=5)
40
+ page.mouse.up()
41
+
42
+
43
+ def wait_until(check, seconds=10):
44
+ end = time.time() + seconds
45
+ while time.time() < end:
46
+ if check():
47
+ return
48
+ time.sleep(0.1)
49
+ raise AssertionError("timed out")
50
+
51
+
52
+ def test_a_quiz_asks_for_the_way_first_and_the_teacher_gives_points_for_it(browser, bank):
53
+ lesson = next(l["id"] for l in bank.lessons if any(s["unit"] == l["id"] and bank.question_keys(s["id"]) for s in bank.skills))
54
+ store = InMemoryStore()
55
+ klass = store.create_class("setup", "A", lessons=[lesson], teacher_email=TEACHER)
56
+ store.add_member(klass["id"], KID)
57
+ app = create_app(Settings(teachers=frozenset({TEACHER})), bank=bank, store=store)
58
+ with running(app) as url:
59
+ page = sign_in(browser, url, f"#/quiz/{lesson}")
60
+ page.wait_for_selector("#qz-q")
61
+ page.locator(".qz-choice").first.click()
62
+ page.wait_for_selector("#qz-need-work")
63
+ assert page.locator(".qz-choice.picked").count() == 0 # no choice without the way
64
+ page.click("#qz-open-board")
65
+ page.wait_for_selector(".mx-board.full canvas")
66
+ draw_line(page)
67
+ page.click(".mx-board .mx-board-back")
68
+ page.locator(".qz-choice").first.click()
69
+ page.wait_for_selector(".qz-choice.picked")
70
+ attempt = store.attempts_of(KID_ID, "quiz")[0]
71
+ key = attempt["questions"][0]["key"]
72
+ wait_until(lambda: key in store.work_of(KID_ID, attempt["id"])) # the board went with the answer
73
+ page.click("#qz-submit")
74
+ page.click("#qz-yes")
75
+ page.wait_for_selector("#qz-grade")
76
+ assert page.errors == []
77
+
78
+ teacher = teacher_page(browser, url)
79
+ teacher.click("#teacher-tabs [data-tab='work']")
80
+ teacher.wait_for_selector(f".work-list li[data-attempt='{attempt['id']}']")
81
+ assert "לבדיקה" in teacher.inner_text(".work-list li")
82
+ teacher.click(f"[data-open='{attempt['id']}']")
83
+ teacher.wait_for_selector(f".work-q[data-key='{key}'] img.work-pic:not([hidden])") # the student's board, through the server
84
+ assert teacher.locator(".work-q .no-work").count() == len(attempt["questions"]) - 1
85
+ before = int(teacher.inner_text("#work-grade"))
86
+ second = attempt["questions"][1]["key"] # not answered: half the points for the way
87
+ teacher.click(f".work-q[data-key='{second}'] [data-points='0.5']")
88
+ teacher.click("#work-save")
89
+ teacher.wait_for_selector("#work-check .ex-note")
90
+ after = int(teacher.inner_text("#work-grade"))
91
+ assert after > before and store.get_attempt(attempt["id"])["credit"] == {second: 0.5}
92
+ teacher.click("#work-back")
93
+ teacher.wait_for_selector(".work-list li")
94
+ assert "נבדק" in teacher.inner_text(".work-list li")
95
+ assert teacher.errors == []
96
+
97
+
98
+ def test_a_lesson_round_needs_no_board_but_sends_it_when_there_is_one(browser, bank):
99
+ lesson = next(l["id"] for l in bank.lessons if any(s["unit"] == l["id"] and bank.question_keys(s["id"]) for s in bank.skills))
100
+ store = InMemoryStore()
101
+ store.add_member(store.create_class("setup", "A", lessons=[lesson], teacher_email=TEACHER)["id"], KID)
102
+ with running(create_app(Settings(), bank=bank, store=store)) as url:
103
+ page = sign_in(browser, url, f"#/round/{lesson}")
104
+ page.wait_for_selector(".round-layer #ex-q")
105
+ page.locator(".ex-choice").first.click() # no board: the answer goes through
106
+ page.wait_for_selector(".ex-ok, .ex-bad")
107
+ page.click("#rd-next")
108
+ page.wait_for_function("document.querySelector('#rd-count').textContent.includes('2 מתוך')")
109
+ key = page.locator("#ex-q").get_attribute("data-key")
110
+ page.click("[data-board-toggle]")
111
+ page.wait_for_selector(".mx-board.full canvas")
112
+ draw_line(page)
113
+ page.click(".mx-board .mx-board-back")
114
+ page.locator(".ex-choice").first.click()
115
+ page.wait_for_selector(".ex-ok, .ex-bad")
116
+ rnd = store.attempts_of(KID_ID, "lesson_round")[0]
117
+ wait_until(lambda: key in store.work_of(KID_ID, rnd["id"]))
118
+ assert len(store.work_of(KID_ID, rnd["id"])) == 1 # the first answer had no board
119
+ assert page.errors == []
mathly2/tests/test_permissions.py CHANGED
@@ -48,6 +48,10 @@ NEEDS = { # (method, path) -> permission
48
  ("GET", "/api/home"): "path.use",
49
  ("POST", "/api/lessons/{lesson_id}/round/start"): "path.use",
50
  ("GET", "/api/rounds/{round_id}"): "path.use",
 
 
 
 
51
  ("POST", "/api/rounds/{round_id}/answer"): "path.use",
52
  ("POST", "/api/tests/{test_id}/exercise/{number}/start"): "path.use",
53
  ("POST", "/api/tests/{test_id}/simulation/start"): "path.use",
 
48
  ("GET", "/api/home"): "path.use",
49
  ("POST", "/api/lessons/{lesson_id}/round/start"): "path.use",
50
  ("GET", "/api/rounds/{round_id}"): "path.use",
51
+ ("POST", "/api/work"): "path.use",
52
+ ("GET", "/api/teaching/work"): "class.teach",
53
+ ("GET", "/api/teaching/work/{attempt_id}"): "class.teach",
54
+ ("POST", "/api/teaching/work/{attempt_id}"): "class.teach",
55
  ("POST", "/api/rounds/{round_id}/answer"): "path.use",
56
  ("POST", "/api/tests/{test_id}/exercise/{number}/start"): "path.use",
57
  ("POST", "/api/tests/{test_id}/simulation/start"): "path.use",
mathly2/written.py CHANGED
@@ -59,6 +59,9 @@ def can_read_picture(request: Request, user: dict, picture: dict) -> bool:
59
  if picture["owner_id"] == user["id"] or allowed(user["roles"], "*"):
60
  return True
61
  store, here = request.app.state.store, reads.of(request)
 
 
 
62
  classes = _class_ids_of(request, picture)
63
  if not classes:
64
  return False
 
59
  if picture["owner_id"] == user["id"] or allowed(user["roles"], "*"):
60
  return True
61
  store, here = request.app.state.store, reads.of(request)
62
+ if picture["kind"] == "work": # the board of an answer: the teachers of the student's classes
63
+ from .boardwork import teaches_student
64
+ return teaches_student(request, user, picture["owner_id"])
65
  classes = _class_ids_of(request, picture)
66
  if not classes:
67
  return False
openspec/changes/board-work/proposal.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Proposal
2
+
3
+ ## Why
4
+
5
+ Multiple-choice answers show only the final answer. The teacher (and the parent) want to grade the way too: a student who solved well and slipped at the end deserves points, and a right answer with no work may be a guess.
6
+
7
+ ## What Changes
8
+
9
+ - **The board is saved with every answer**: practice, lesson rounds, lesson quizzes, exercise tests and the simulation. A picture of the question's board goes to the server when the student answers (and again before handing in if it changed). An empty board sends nothing. One picture is kept per student, attempt (or practice) and question.
10
+ - **In quizzes and tests the way is required**: a choice is refused until something is written on the board for that question (or a board for it is already saved), with a prompt and a button that opens the board. Practice and lesson rounds stay free.
11
+ - **The teacher grades the way**: a "בדיקת דרך" tab lists the handed-in quizzes and tests of the teacher's students (not checked first). Opening one shows every question with its choices (the right one marked), the student's choice and board, and points buttons: automatic, 0, ½, full. Saving recomputes the grade (in halves), so a lesson quiz can become passed or not. The tab counts the attempts not checked yet.
12
+ - Work pictures are private: the student and the teachers of the student's classes (and developers) read them. They follow the answer pictures' retention (removed after the school year) and a replaced one is cleaned up as an orphan.
13
+
14
+ ## Capabilities
15
+
16
+ ### New Capabilities
17
+ - `board-work`
18
+
19
+ ### Modified Capabilities
20
+ - `grades`: a graded attempt's grade includes the teacher's points for the way.
21
+
22
+ ## Impact
23
+
24
+ - New `mathly2/boardwork.py`, `static/boardwork.js`, `static/teacher_boardwork.js`; `math-board.js` (`hasWork`, `workSig`, `pictureOf`), `exercise.js`, `round.js`, `quiz.js`, `teacher.js`; `attempts.py` (credit in the grade), `store.py` (`save_work`, `work_of`, credit on attempts), `written.py` (who reads a work picture), `cleanup.py`, `assignments.py` (the tab's count).
25
+ - Database: migration `20261120090000_m2_board_work.sql` (new `m2_work`, `credit`/`checked_at`/`checked_by` on `m2_attempts`, picture kind `work`). Apply before deploying.
26
+ - Storage: one small picture per answer with a board.
openspec/changes/board-work/specs/board-work/spec.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## ADDED Requirements
2
+
3
+ ### Requirement: The board goes with every answer
4
+ When a student answers a question in practice, a lesson round, a lesson quiz, an exercise test or the simulation, and the question's board has anything on it besides the copy of the question, a picture of the board SHALL be saved with the answer. Before handing in a quiz or a test, the boards that changed since they were saved SHALL be saved again. An empty board SHALL save nothing. Only the latest picture per student, attempt (or practice) and question SHALL be kept.
5
+
6
+ #### Scenario: A lesson round
7
+ - **WHEN** a student writes on the board and answers a question of a lesson round
8
+ - **THEN** the board's picture is saved for that round and question
9
+
10
+ #### Scenario: No board in practice
11
+ - **WHEN** a student answers a practice question without writing on the board
12
+ - **THEN** the answer is accepted and no picture is saved
13
+
14
+ ### Requirement: The way is required in quizzes and tests
15
+ In a lesson quiz, an exercise test and the simulation, a choice SHALL NOT be saved until the question's board has something written on it or a board for it is already saved. The sheet SHALL say that the way is graded too and offer a button that opens the board.
16
+
17
+ #### Scenario: Choosing first
18
+ - **WHEN** a student taps a choice in a quiz with nothing on the board for that question
19
+ - **THEN** the choice is not saved, and the sheet asks to write the way on the board and offers to open it
20
+
21
+ ### Requirement: The teacher grades the way
22
+ A teacher SHALL have a "בדיקת דרך" tab with the handed-in quizzes, exercise tests and simulations of the students of their classes, those not checked yet first, and its count of those not checked. Opening one SHALL show every question with its choices, the right one marked, the student's choice and board (or that there is none), and points: automatic (1 for right, 0 for wrong), 0, ½ or full. Saving SHALL recompute the attempt's grade from the points and mark it checked.
23
+
24
+ #### Scenario: Half for the way
25
+ - **WHEN** a student got 12 of 15 right and the teacher gives a wrong answer full points and another half
26
+ - **THEN** the grade becomes 90 and the lesson's grade follows
27
+
28
+ #### Scenario: Another teacher
29
+ - **WHEN** a teacher who does not teach the student opens the attempt or its board
30
+ - **THEN** it is not found
31
+
32
+ ### Requirement: Private work pictures
33
+ A work picture SHALL be read only by its student, the teachers of the student's classes and developers, through the server. Work pictures SHALL be removed after the school year, like answer pictures, and a replaced one SHALL be removed by the hourly cleanup.
34
+
35
+ #### Scenario: A new board for the same question
36
+ - **WHEN** a student saves a second board for a question
37
+ - **THEN** the first picture is no longer referred to and the cleanup removes it
openspec/changes/board-work/tasks.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tasks
2
+
3
+ ## 1. Server
4
+ - [x] 1.1 Migration: `m2_work`, credit on attempts, picture kind `work`
5
+ - [x] 1.2 Upload of an answer's board (practice or an attempt), latest wins
6
+ - [x] 1.3 The teacher's list, attempt view and points; the grade in halves; the tab's count
7
+ - [x] 1.4 Who reads a work picture; retention and cleanup
8
+
9
+ ## 2. Screens
10
+ - [x] 2.1 The board's picture of any question; sent after an answer in practice, rounds, quizzes and tests, and before handing in
11
+ - [x] 2.2 A quiz or test asks for the way before a choice
12
+ - [x] 2.3 The teacher's "בדיקת דרך" tab
13
+
14
+ ## 3. Wrap-up
15
+ - [x] 3.1 API and browser tests; the full suite