3v324v23 commited on
Commit
66fd359
·
1 Parent(s): 9e0df41

feat: Implement skill learning and mastery features

Browse files

- Added a proposal for a new skill learning system that includes a structured four-stage learning process: worked examples, faded examples, practice, and feedback.
- Introduced specifications for the learning path, allowing students to access lessons in any order, track daily goals, and view their progress.
- Developed specifications for skill mastery, defining the criteria for mastering skills and ensuring mastery does not decay over time.
- Created tasks for implementing the new features, including database migrations, API endpoints, and student screens.
- Added a new build for test preparation, including features for exercise tests, readiness meters, and real test management.
- Defined specifications for exercise tests that focus on weak skills, simulation tests, and student screens for managing assignments and grades.
- Ensured all new features adhere to the app's design principles, including right-to-left layout and server-side grade management.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. docs/project.prd +6 -0
  2. docs/tasks/prd-mathly.md +84 -74
  3. mathly2/Dockerfile +18 -0
  4. mathly2/Dockerfile.dockerignore +4 -0
  5. mathly2/README.md +64 -0
  6. mathly2/__init__.py +1 -0
  7. mathly2/auth.py +87 -0
  8. mathly2/bank.py +108 -0
  9. mathly2/classes.py +98 -0
  10. mathly2/clock.py +20 -0
  11. mathly2/config.py +40 -0
  12. mathly2/content/math_algebra9.json +0 -0
  13. mathly2/main.py +72 -0
  14. mathly2/requirements-dev.txt +7 -0
  15. mathly2/requirements.txt +5 -0
  16. mathly2/scripts/__init__.py +0 -0
  17. mathly2/scripts/content_gaps.py +65 -0
  18. mathly2/static/api.js +17 -0
  19. mathly2/static/app.css +55 -0
  20. mathly2/static/app.js +58 -0
  21. mathly2/static/index.html +17 -0
  22. mathly2/static/math-tex.js +116 -0
  23. mathly2/static/math.js +4 -0
  24. mathly2/static/session.js +36 -0
  25. mathly2/static/student.js +14 -0
  26. mathly2/static/teacher.js +78 -0
  27. mathly2/store.py +161 -0
  28. mathly2/supabase/migrations/20261107090000_m2_classes.sql +26 -0
  29. mathly2/tests/__init__.py +0 -0
  30. mathly2/tests/conftest.py +5 -0
  31. mathly2/tests/serve.py +28 -0
  32. mathly2/tests/test_auth.py +100 -0
  33. mathly2/tests/test_bank.py +76 -0
  34. mathly2/tests/test_classes.py +88 -0
  35. mathly2/tests/test_clock.py +34 -0
  36. mathly2/tests/test_content_gaps.py +25 -0
  37. mathly2/tests/test_health.py +9 -0
  38. mathly2/tests/test_lessons.py +17 -0
  39. mathly2/tests/test_migrations.py +60 -0
  40. mathly2/tests/test_no_content_before_sign_in.py +49 -0
  41. mathly2/tests/test_shell_browser.py +97 -0
  42. mathly2/tests/test_store.py +96 -0
  43. mathly2/tests/test_student_class.py +53 -0
  44. openspec/changes/add-assignment-worksheets/design.md +0 -71
  45. openspec/changes/add-assignment-worksheets/proposal.md +0 -39
  46. openspec/changes/add-assignment-worksheets/specs/assignment-worksheets/spec.md +0 -122
  47. openspec/changes/add-assignment-worksheets/tasks.md +0 -38
  48. openspec/changes/add-class-assignments/design.md +0 -44
  49. openspec/changes/add-class-assignments/proposal.md +0 -39
  50. openspec/changes/add-class-assignments/specs/class-assignments/spec.md +0 -88
docs/project.prd CHANGED
@@ -1,3 +1,9 @@
 
 
 
 
 
 
1
  Glossary:
2
 
3
  - skill (מיומנות): a specific topic like פירוק טרינום
 
1
+ The app is written from scratch. Kept from the current app:
2
+ - the exercises (app/math_algebra9.json)
3
+ - the drawing board (static/math-board.js, static/board-math.js, static/vendor/mathlive)
4
+
5
+
6
+
7
  Glossary:
8
 
9
  - skill (מיומנות): a specific topic like פירוק טרינום
docs/tasks/prd-mathly.md CHANGED
@@ -15,10 +15,8 @@ Mathly solves this with two tools:
15
 
16
  Teachers give and check assignments, set tests, and see the class's progress per skill and per lesson.
17
 
18
- Much of the app already exists. Each requirement below is tagged:
19
- - **[exists]** – already built; keep as is.
20
- - **[change]** – already built, but must change to match this PRD.
21
- - **[new]** – not built yet.
22
 
23
  ### Glossary
24
 
@@ -49,9 +47,10 @@ Much of the app already exists. Each requirement below is tagged:
49
  - As a student, I want to see how many days are left until my test, how ready I am, and what to do today, so I don't have to plan by myself.
50
  - As a student, I want to practice with timed, mixed tests before the real test, so the real test doesn't surprise me.
51
  - As a student, I want one full simulation of the real test, so I know where I stand while there is still time to fix gaps.
 
52
 
53
  **Teacher**
54
- - As a teacher, I want to give an assignment from a file, from the classroom smart board, or from a photo, so I can use whatever material I already have.
55
  - As a teacher, I want to check submitted assignments and give a grade and feedback.
56
  - As a teacher, I want to set a test date and the lessons it covers, so the app prepares my students for it.
57
  - As a teacher, I want to see who has taken the simulation test.
@@ -64,46 +63,39 @@ Much of the app already exists. Each requirement below is tagged:
64
 
65
  Each skill takes the student through four stages, in this order.
66
 
67
- 1. **[change] Worked example.** The system must show a fully solved example of the skill, one step at a time.
68
- After each step, the system must ask the student "why this step?" (multiple choice or short answer) before revealing the next one.
69
- *Today the worked example exists inside the help window and shows the explanation of each step, but does not ask the student.*
70
- 2. **[new] Faded examples.** The system must show solved examples with steps removed: first one step missing, then two, and so on.
71
- The student must fill in each missing step. A wrong step gets immediate feedback (see 4).
72
- 3. **[change] Practice.** The system must give the student practice questions on the skill.
73
- 4. **[change] Feedback on mistakes.** After a wrong answer, the system must:
74
- - show feedback that names the specific mistake (e.g. "the sign changed when moving the term across"), not only "wrong";
75
  - not reveal the correct answer;
76
- - give the student a **similar** question (same skill, different numbers or wording), not the same question again.
77
- *Today the same question comes back after the others.*
78
- 5. **[change] Mastery.** A skill must become **mastered** when the student answers 3 questions correctly in a row,
79
  on the first try, without opening help or the worked example, and these answers are spread over at least 2 different calendar days.
80
- *Today a star turns gold after several correct first-try answers in a row, with no "2 days" rule.*
81
- 6. **[change] Skill states.** Every skill, for every student, must be in one of these states:
82
  - **not started** – no answers yet;
83
  - **learning** – at least one answer, not yet mastered;
84
  - **mastered** – met the rule in requirement 5.
85
  A mastered skill stays mastered. It must **not** fade or decay over time.
86
- *Today a star fades after two weeks without practice. Remove the fading, and remove the "mixed review" that is triggered by it.*
87
- 7. **[exists] All lessons open.** The student must be able to open any lesson, and any skill inside it, at any time, in any order.
88
- 8. **[exists] Daily goal and streak.** 5 correct answers per day builds a streak.
89
- 9. **[exists] Collection.** Each skill is a star; each completed lesson draws a constellation. The collection tab shows them.
90
 
91
  ### 4.2 Quizzes (בוחן)
92
 
93
- 10. **[exists] Quiz per lesson.** Each lesson has a quiz. The student can retake it; the best grade counts; every retake draws new questions.
94
  The quiz's best grade is the lesson's grade.
95
- 11. **[change] One quiz type only.** The retakeable quiz is the only quiz. The system must remove the end-of-lesson summary quiz (בוחן מסכם):
96
- it is taken once, opened by the teacher, and is today the lesson's official grade.
97
- *Today each lesson has two quizzes: a retakeable practice quiz (בוחן חיזוק, not graded) and the summary quiz.*
98
- 12. **[exists] After a quiz,** the system must list the skills where the student lost points, so they can practice them before retaking.
99
 
100
  ### 4.3 Test countdown
101
 
102
- 13. **[change] Setting a test.** The teacher must be able to set a test: date + the lessons it covers (+ an optional note),
103
  plus the real test's **number of questions** and **time limit**. These start with defaults
104
  (12 questions, 90 minutes) that the teacher can change.
105
- *Today date, lessons and note exist; number of questions and time limit are new.*
106
- 14. **[change] The countdown plan.** From the moment a test is set, the system must show the student a plan that depends on the days left:
107
 
108
  | Days before the test | What the app asks the student to do |
109
  |---|---|
@@ -115,21 +107,19 @@ Each skill takes the student through four stages, in this order.
115
 
116
  The day numbers are **recommendations**: the student can start each step earlier or later.
117
  If the test is set less than 9 days ahead, the system must keep the same order and shorten the gaps evenly.
118
- 15. **[change] Home screen reminder.** The home screen must show, for the nearest test:
119
  days left, the readiness meter (see 4.6), and **one task for today** taken from the plan.
120
  When several tests are coming up, "today's task" comes from the **closest** one.
121
 
122
  ### 4.4 Exercise tests (מבחן תרגול)
123
 
124
- 16. **[change] Created by the app.** When the teacher sets a test, the system must create 2 exercise tests for every student in the class and place them on the student's countdown.
125
- 17. **[change] Teacher can assign one.** The teacher must be able to send an exercise test to the whole class as an assignment.
126
- *Today only admins can assign exercise tests to a class.*
127
- 18. **[exists] Retakes.** The student can start or retake an exercise test at any time. Each retake draws new questions; the best grade counts.
128
- 19. **[change] Like the simulation.** Exercise tests must have the same number of questions and the same time limit as the simulation
129
- (that is, as the real test, requirement 13), mix questions from all covered lessons, and not show the skill name.
130
  Feedback comes **only at the end**, not after each question.
131
- *Today exercise tests 1 and 2 give feedback after each question.*
132
- 20. **[change] Question mix.** The system must pick questions in these proportions:
133
 
134
  | Exercise test | Weak skills | Other covered skills |
135
  |---|---|---|
@@ -139,79 +129,95 @@ Each skill takes the student through four stages, in this order.
139
  "Weak skill" = a skill in the "learning" state, or one the student answered wrong in a previous exercise test.
140
  Skills in the "not started" state must not appear; instead, the card must list them as "practice these first".
141
  If the student has fewer weak skills than needed, fill the rest from the other covered skills.
142
- 21. **[exists] Result links back.** After an exercise test, the system must show the weak skills it found and link each one to its place in the path.
143
 
144
  ### 4.5 Simulation test (מבחן סימולציה)
145
 
146
- 22. **[new] Required, one attempt.** Every student must take one simulation test per real test. It can be taken only once.
147
- 23. **[new] Like the real test.** The simulation must cover all the lessons of the real test, with the number of questions and the time limit the teacher set for the real test (requirement 13),
148
  no skill names, and no feedback until the end.
149
- 24. **[new] Window.** The simulation becomes available ~5 days before the test and stays available until the test day.
150
  It must be shown as **required** on the student's home screen until it is taken.
151
- 25. **[new] After the simulation,** the system must list the skills that failed and turn them into the review tasks of the last days (requirement 14).
152
 
153
  ### 4.6 Readiness meter
154
 
155
- 26. **[change] Readiness meter.** For each upcoming test, the system must show the student (and the teacher) a readiness meter made of:
156
  - % of the covered skills that are mastered;
157
  - the best grade of each exercise test;
158
  - the simulation test grade (once taken).
159
- *Today the test-prep screen shows readiness per skill and recent quiz grades.*
160
 
161
  ### 4.7 Student screens
162
 
163
- 27. **[exists] Home:** my assignments (המשימות שלי) from the teacher; the upcoming-test reminder (requirement 15); continue the path.
164
- 28. **[exists] Path:** all lessons and skills.
165
- 29. **[change] Grades:** all quiz (best grade), exercise test, simulation and homework grades.
166
- *Today it also lists summary quizzes, marked ★; remove them.*
167
- 30. **[exists] Collection:** stars, constellations, and the class test calendar.
 
168
 
169
  ### 4.8 Teacher screens
170
 
171
- 31. **[change] Give an assignment.** The teacher must be able to create an assignment and load its content from:
172
- - the computer (file upload: PDF or images) – **[exists]**;
173
- - a photo taken with the device camera – **[new]** for assignments (exists today only for lesson resources);
174
- - the app's drawing board (static/math-board.js, the same board students solve on) – **[new]** for assignments:
175
- the teacher draws or writes the assignment on the board, and it is saved as the assignment's page(s).
176
- 32. **[exists] Check assignments.** The teacher must be able to open each student's submission, give a grade (0–100) and a note, or send it back for correction.
177
- 33. **[change] Tests tab.** The teacher must be able to set a test (requirement 13) and see, for each test, which students have taken the simulation test and which have not.
178
- 34. **[new] Class heat map.**
179
  - Rows: students. Columns: skills (grouped by lesson).
180
  - Each cell is colored by the skill state: not started / learning / mastered.
181
  - Tabs for the period: **Sep–Dec** and **Jan–Jun**. A period shows the skills of the lessons taught in it, and states as they were at the end of the period (or today, for the current period).
182
- 35. **[new] Student lesson coverage.**
183
  - Rows: students. Columns: lessons.
184
  - Each cell shows the % of the lesson's skills the student has mastered, and the student's best quiz (בוחן) grade for that lesson.
185
  - Same period tabs: **Sep–Dec** and **Jan–Jun**.
186
 
187
  ## 5. Non-Goals (Out of Scope)
188
 
 
189
  - Skills do not decay or need re-mastering over time.
190
  - Lessons are never locked; the app does not force an order.
 
191
  - The app does not grade the real school test or import its grades.
192
  - The app does not replace the teacher's lesson plan or teach new material in class.
193
  - No student-to-student features (chat, leaderboards).
194
 
195
  ## 6. Design Considerations
196
 
197
- - Hebrew, right-to-left. Works on phones first.
198
- - Keep the existing look: the path as constellations, a skill as a star, the collection tab.
199
- - Mastered skills should look clearly different from "learning" ones (today: gold star). With fading removed, there is no "dim" star.
200
  - Heat map colors must be readable in light and dark mode and must not rely on color alone (add a symbol or text in each cell).
201
  - The "one task for today" on home must be a single, obvious button.
202
 
203
  ## 7. Technical Considerations
204
 
205
- - Grades that matter (quiz, simulation) must be computed and stored on the server, so a student cannot change them from the device.
206
- Today some progress data (skill progress, practice tests) is reported by the student's device; the heat map and coverage views should mark device-reported data the same way the class report does today.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  - Mastery (requirement 5) needs the date of each answer, so the server can check the "2 different days" rule.
208
- - "Similar question" (requirement 4) requires each skill to have enough questions, or question templates with changing numbers.
209
- - The simulation's timer must be kept on the server (like the end-of-lesson quiz today), so refreshing or closing the app does not reset it.
210
- - Removing the summary quiz (requirement 11) affects existing code: the "summary quizzes" tab in the class report,
211
- opening/closing windows, extra attempts, publishing results, the AI-queue and "to review" entries for it, and the ★ grades.
212
- Its server-kept timer and server-side grading should be reused for the simulation test (and for the retakeable quiz's grade) before the rest is removed.
213
- Decide what happens to summary-quiz grades already stored (see Open Questions).
214
- - Removing star fading affects existing code: the fading logic, "mixed review", and any "fading" status in the class report and test prep.
215
 
216
  ## 8. Success Metrics
217
 
@@ -222,5 +228,9 @@ Each skill takes the student through four stages, in this order.
222
 
223
  ## 9. Open Questions
224
 
225
- 1. **Existing summary-quiz grades:** when the summary quiz is removed, should grades students already got stay visible (read-only), or be dropped?
226
- 2. **Default time limit:** 90 minutes was chosen as the default for a real test. Is that right for most tests, or should it be 45?
 
 
 
 
 
15
 
16
  Teachers give and check assignments, set tests, and see the class's progress per skill and per lesson.
17
 
18
+ **The app is written from scratch.** Only two parts of the current app are kept (see 7.1):
19
+ the **exercise bank** and the **drawing board**. Everything else – screens, server, database, sign-in – is new.
 
 
20
 
21
  ### Glossary
22
 
 
47
  - As a student, I want to see how many days are left until my test, how ready I am, and what to do today, so I don't have to plan by myself.
48
  - As a student, I want to practice with timed, mixed tests before the real test, so the real test doesn't surprise me.
49
  - As a student, I want one full simulation of the real test, so I know where I stand while there is still time to fix gaps.
50
+ - As a student, I want to solve on a drawing board when a question needs a full solution, and hand it in from there.
51
 
52
  **Teacher**
53
+ - As a teacher, I want to give an assignment from a file, from a photo, or by writing it on the drawing board, so I can use whatever material I already have.
54
  - As a teacher, I want to check submitted assignments and give a grade and feedback.
55
  - As a teacher, I want to set a test date and the lessons it covers, so the app prepares my students for it.
56
  - As a teacher, I want to see who has taken the simulation test.
 
63
 
64
  Each skill takes the student through four stages, in this order.
65
 
66
+ 1. **Worked example.** The system must show a fully solved example of the skill, one step at a time.
67
+ After each step, the system must ask the student "why this step?" (multiple choice) before revealing the next one.
68
+ 2. **Faded examples.** The system must show solved examples with steps removed: first one step missing, then two, and so on.
69
+ The student must fill in each missing step. A wrong step gets immediate feedback (see requirement 4).
70
+ 3. **Practice.** The system must give the student practice questions on the skill, taken from the exercise bank.
71
+ 4. **Feedback on mistakes.** After a wrong answer, the system must:
72
+ - show feedback that names the specific mistake, using the mistake attached to the chosen wrong answer in the exercise bank
73
+ (its name and tip, e.g. "טעות סימן באיבר האמצעי");
74
  - not reveal the correct answer;
75
+ - give the student a **similar** question (same skill, a different question), not the same question again.
76
+ 5. **Mastery.** A skill must become **mastered** when the student answers 3 questions correctly in a row,
 
77
  on the first try, without opening help or the worked example, and these answers are spread over at least 2 different calendar days.
78
+ 6. **Skill states.** Every skill, for every student, must be in one of these states:
 
79
  - **not started** – no answers yet;
80
  - **learning** – at least one answer, not yet mastered;
81
  - **mastered** – met the rule in requirement 5.
82
  A mastered skill stays mastered. It must **not** fade or decay over time.
83
+ 7. **All lessons open.** The student must be able to open any lesson, and any skill inside it, at any time, in any order.
84
+ 8. **Daily goal and streak.** 5 correct answers per day builds a streak.
85
+ 9. **Collection.** The student must have a collection screen that shows what they achieved: each mastered skill and each completed lesson.
 
86
 
87
  ### 4.2 Quizzes (בוחן)
88
 
89
+ 10. **Quiz per lesson.** Each lesson must have a quiz. The student can retake it; the best grade counts; every retake draws new questions.
90
  The quiz's best grade is the lesson's grade.
91
+ 11. **After a quiz,** the system must list the skills where the student lost points, so they can practice them before retaking.
 
 
 
92
 
93
  ### 4.3 Test countdown
94
 
95
+ 12. **Setting a test.** The teacher must be able to set a test: date + the lessons it covers (+ an optional note),
96
  plus the real test's **number of questions** and **time limit**. These start with defaults
97
  (12 questions, 90 minutes) that the teacher can change.
98
+ 13. **The countdown plan.** From the moment a test is set, the system must show the student a plan that depends on the days left:
 
99
 
100
  | Days before the test | What the app asks the student to do |
101
  |---|---|
 
107
 
108
  The day numbers are **recommendations**: the student can start each step earlier or later.
109
  If the test is set less than 9 days ahead, the system must keep the same order and shorten the gaps evenly.
110
+ 14. **Home screen reminder.** The home screen must show, for the nearest test:
111
  days left, the readiness meter (see 4.6), and **one task for today** taken from the plan.
112
  When several tests are coming up, "today's task" comes from the **closest** one.
113
 
114
  ### 4.4 Exercise tests (מבחן תרגול)
115
 
116
+ 15. **Created by the app.** When the teacher sets a test, the system must create 2 exercise tests for every student in the class and place them on the student's countdown.
117
+ 16. **Teacher can assign one.** The teacher must be able to send an exercise test to the whole class as an assignment.
118
+ 17. **Retakes.** The student can start or retake an exercise test at any time. Each retake draws new questions; the best grade counts.
119
+ 18. **Like the simulation.** Exercise tests must have the same number of questions and the same time limit as the simulation
120
+ (that is, as the real test, requirement 12), mix questions from all covered lessons, and not show the skill name.
 
121
  Feedback comes **only at the end**, not after each question.
122
+ 19. **Question mix.** The system must pick questions in these proportions:
 
123
 
124
  | Exercise test | Weak skills | Other covered skills |
125
  |---|---|---|
 
129
  "Weak skill" = a skill in the "learning" state, or one the student answered wrong in a previous exercise test.
130
  Skills in the "not started" state must not appear; instead, the card must list them as "practice these first".
131
  If the student has fewer weak skills than needed, fill the rest from the other covered skills.
132
+ 20. **Result links back.** After an exercise test, the system must show the weak skills it found and link each one to its place in the path.
133
 
134
  ### 4.5 Simulation test (מבחן סימולציה)
135
 
136
+ 21. **Required, one attempt.** Every student must take one simulation test per real test. It can be taken only once.
137
+ 22. **Like the real test.** The simulation must cover all the lessons of the real test, with the number of questions and the time limit the teacher set for the real test (requirement 12),
138
  no skill names, and no feedback until the end.
139
+ 23. **Window.** The simulation becomes available ~5 days before the test and stays available until the test day.
140
  It must be shown as **required** on the student's home screen until it is taken.
141
+ 24. **After the simulation,** the system must list the skills that failed and turn them into the review tasks of the last days (requirement 13).
142
 
143
  ### 4.6 Readiness meter
144
 
145
+ 25. **Readiness meter.** For each upcoming test, the system must show the student (and the teacher) a readiness meter made of:
146
  - % of the covered skills that are mastered;
147
  - the best grade of each exercise test;
148
  - the simulation test grade (once taken).
 
149
 
150
  ### 4.7 Student screens
151
 
152
+ 26. **Home:** my assignments (המשימות שלי) from the teacher; the upcoming-test reminder (requirement 14); continue the path.
153
+ 27. **Path:** all lessons and skills, each skill showing its state.
154
+ 28. **Grades:** all quiz (best grade), exercise test, simulation and assignment grades.
155
+ 29. **Collection:** see requirement 9.
156
+ 30. **Drawing board.** Wherever a question needs a written solution (open questions, assignments), the student must be able to
157
+ solve on the drawing board and hand in the board as their answer.
158
 
159
  ### 4.8 Teacher screens
160
 
161
+ 31. **Give an assignment.** The teacher must be able to create an assignment (title, note, due date) and load its content from:
162
+ - the computer (file upload: PDF or images);
163
+ - a photo taken with the device camera;
164
+ - the drawing board: the teacher writes or draws the assignment on the board, and it is saved as the assignment's page(s).
165
+ 32. **Check assignments.** The teacher must be able to open each student's submission, give a grade (0–100) and a note, or send it back for correction.
166
+ 33. **Tests tab.** The teacher must be able to set a test (requirement 12) and see, for each test, which students have taken the simulation test and which have not.
167
+ 34. **Class heat map.**
 
168
  - Rows: students. Columns: skills (grouped by lesson).
169
  - Each cell is colored by the skill state: not started / learning / mastered.
170
  - Tabs for the period: **Sep–Dec** and **Jan–Jun**. A period shows the skills of the lessons taught in it, and states as they were at the end of the period (or today, for the current period).
171
+ 35. **Student lesson coverage.**
172
  - Rows: students. Columns: lessons.
173
  - Each cell shows the % of the lesson's skills the student has mastered, and the student's best quiz (בוחן) grade for that lesson.
174
  - Same period tabs: **Sep–Dec** and **Jan–Jun**.
175
 
176
  ## 5. Non-Goals (Out of Scope)
177
 
178
+ - Reusing any part of the current app other than the exercise bank and the drawing board.
179
  - Skills do not decay or need re-mastering over time.
180
  - Lessons are never locked; the app does not force an order.
181
+ - There is no one-time summary quiz (בוחן מסכם).
182
  - The app does not grade the real school test or import its grades.
183
  - The app does not replace the teacher's lesson plan or teach new material in class.
184
  - No student-to-student features (chat, leaderboards).
185
 
186
  ## 6. Design Considerations
187
 
188
+ - Hebrew, right-to-left. Works on phones first; the teacher views (heat map, coverage) must also work well on a computer.
189
+ - Math is written in LaTeX inside `$…$` in the exercise bank; the app must render it.
190
+ - Mastered skills must look clearly different from "learning" and "not started" ones.
191
  - Heat map colors must be readable in light and dark mode and must not rely on color alone (add a symbol or text in each cell).
192
  - The "one task for today" on home must be a single, obvious button.
193
 
194
  ## 7. Technical Considerations
195
 
196
+ ### 7.1 What is kept from the current app
197
+
198
+ **Exercise bank** – `app/math_algebra9.json` (9th grade algebra/geometry):
199
+ - `units`: 24 lessons (id, name, month, and for 4 of them a `quiz` with open questions, points, minutes and the skills each question tests).
200
+ - `skills`: 96 skills (id, lesson, name, short name, description, prerequisites, month, `questions`).
201
+ - `questions`: 1,050 multiple-choice questions. Each wrong choice has a `mistake` id.
202
+ - `mistakes`: 244 mistakes, each with a name, a tip, and the skill to go back to (`back`).
203
+
204
+ **Drawing board** – `static/math-board.js` (the board), `static/board-math.js` (typed math on the board) and
205
+ `static/vendor/mathlive/` (the math keyboard library, MIT license, loaded by board-math.js).
206
+ It exposes `window.MathlyBoard` and turns a sketch into a picture for handing in.
207
+
208
+ ### 7.2 Notes for the new build
209
+
210
+ - **Content gaps in the bank.** The new app needs content the bank does not have yet:
211
+ - worked examples and faded examples (requirements 1–2): no skill has one today;
212
+ - "why this step?" choices for each step of a worked example;
213
+ - quizzes for 20 of the 24 lessons (requirement 10);
214
+ - one skill has no questions;
215
+ - enough questions per skill for "similar question" (requirement 4) and for retakes that draw new questions.
216
+ `scripts/draft_examples.py` from the current app drafts worked examples with AI for a teacher to approve; it may be reused as a tool.
217
+ - Grades that matter (quiz, exercise test, simulation) must be computed and stored on the server, so a student cannot change them from the device.
218
  - Mastery (requirement 5) needs the date of each answer, so the server can check the "2 different days" rule.
219
+ - The simulation's timer must be kept on the server, so refreshing or closing the app does not reset it.
220
+ - Open questions in quizzes and assignments need checking: by the teacher (requirement 32), possibly with AI help (see Open Questions).
 
 
 
 
 
221
 
222
  ## 8. Success Metrics
223
 
 
228
 
229
  ## 9. Open Questions
230
 
231
+ 1. **Default time limit:** 90 minutes was chosen as the default for a real test. Is that right for most tests, or should it be 45?
232
+ 2. **Existing data:** should students, classes and progress from the current app move to the new one, or does the new app start empty?
233
+ 3. **Sign-in and roles:** keep sign-in with the school's Google accounts? Is there an admin role (creates classes, adds students), or does the teacher do that?
234
+ 4. **Subjects:** math only, or also science (the current app has a small science part)?
235
+ 5. **Checking open answers:** does the teacher check everything by hand, or should AI suggest a grade for the teacher to approve?
236
+ 6. **Tech stack and location:** same repository (new folder) or a new one? Any preferred stack, or keep Python + Supabase?
mathly2/Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # Build from the repository root: docker build -f mathly2/Dockerfile -t mathly2 .
3
+ # CPU image; runs on Hugging Face Spaces (Docker SDK), Render, Fly, or any VM.
4
+ FROM python:3.11-slim
5
+
6
+ # Spaces runs the container as uid 1000
7
+ RUN useradd -m -u 1000 user
8
+ ENV HOME=/home/user PYTHONUNBUFFERED=1
9
+ WORKDIR /home/user/app
10
+
11
+ COPY mathly2/requirements.txt mathly2/requirements.txt
12
+ RUN pip install --no-cache-dir -r mathly2/requirements.txt
13
+
14
+ USER user
15
+ COPY --chown=user mathly2 ./mathly2
16
+
17
+ EXPOSE 7860
18
+ CMD ["sh", "-c", "uvicorn mathly2.main:app --host 0.0.0.0 --port ${PORT:-7860}"]
mathly2/Dockerfile.dockerignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *
2
+ !mathly2
3
+ mathly2/tests
4
+ mathly2/**/__pycache__
mathly2/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Mathly 2
2
+
3
+ The rebuilt Mathly app. Requirements: `docs/tasks/prd-mathly.md`; specs and plans: `openspec/`.
4
+ The current app (`app/`, `static/`) is separate and keeps running until this one replaces it.
5
+
6
+ ## Run locally
7
+
8
+ Run these from the repository root.
9
+
10
+ ```bash
11
+ python3 -m venv venv
12
+ venv/bin/python -m pip install -r mathly2/requirements-dev.txt
13
+ venv/bin/python -m uvicorn mathly2.main:app --port 7861
14
+ ```
15
+
16
+ Open <http://localhost:7861>. With the Supabase settings empty, the app uses an in-memory store and a
17
+ "dev only" sign-in that takes an email address; nothing is saved after a restart.
18
+ Add teachers with `TEACHER_EMAILS=you@school.example venv/bin/python -m uvicorn …`.
19
+
20
+ ## Tests
21
+
22
+ ```bash
23
+ venv/bin/python -m playwright install chromium # once, for the browser tests
24
+ venv/bin/python -m pytest mathly2/tests
25
+ ```
26
+
27
+ ## Settings
28
+
29
+ | Setting | Meaning |
30
+ |---|---|
31
+ | `SUPABASE_URL` | The Supabase project's URL |
32
+ | `SUPABASE_PUBLISHABLE_KEY` | The publishable key. Sent to the browser for Google sign-in |
33
+ | `SUPABASE_SECRET_KEY` | The secret key. Server only; never sent to the browser |
34
+ | `TEACHER_EMAILS` | Teachers' email addresses, separated by commas, spaces or new lines |
35
+ | `PORT` | The port in the container (default 7860) |
36
+
37
+ Set all three Supabase values or none. With none, the app runs locally with the in-memory store and the
38
+ "dev only" sign-in; with only some, the server refuses to start (so a half-configured deployment can never
39
+ accept any email address as a sign-in).
40
+
41
+ ## Database
42
+
43
+ Run the files in `mathly2/supabase/migrations/` in order (the Supabase SQL editor or `supabase db push`).
44
+ They add only tables named `m2_…`, which only the server can read or write; the current app's tables are untouched.
45
+ Turn on Google sign-in in the Supabase project and add the app's address to its redirect URLs.
46
+
47
+ ## Docker
48
+
49
+ Build from the repository root:
50
+
51
+ ```bash
52
+ docker build -f mathly2/Dockerfile -t mathly2 .
53
+ docker run --rm -p 7860:7860 mathly2 # then open http://localhost:7860
54
+ ```
55
+
56
+ Add `-e SUPABASE_URL=… -e SUPABASE_PUBLISHABLE_KEY=… -e SUPABASE_SECRET_KEY=… -e TEACHER_EMAILS=…` for a real run.
57
+ A Hugging Face Space needs the Dockerfile at the top of its repository: create the Space from a copy of this repository
58
+ whose root `Dockerfile` is `mathly2/Dockerfile` with the `mathly2/` paths unchanged, and set the settings above as Space secrets.
59
+
60
+ ## Content the bank still lacks
61
+
62
+ ```bash
63
+ venv/bin/python -m mathly2.scripts.content_gaps
64
+ ```
mathly2/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Mathly 2: the rebuilt app (see docs/tasks/prd-mathly.md)."""
mathly2/auth.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Who is calling. The browser signs in with Google through Supabase and sends its access token;
2
+ the server asks Supabase who the token belongs to. Teachers are the emails in TEACHER_EMAILS; everyone else is a student."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import threading
8
+ import time
9
+ import urllib.error
10
+ import urllib.request
11
+ import uuid
12
+
13
+ from fastapi import Depends, HTTPException, Request
14
+
15
+ TIMEOUT = 10
16
+ CACHE_SECONDS = 300
17
+ EMAIL = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,255}\.[^@\s]{2,}$")
18
+
19
+
20
+ class AuthUnavailable(RuntimeError):
21
+ """Supabase could not be reached."""
22
+
23
+
24
+ class SupabaseAuthenticator:
25
+ def __init__(self, url: str, key: str) -> None:
26
+ self.url, self.key = url.rstrip("/"), key
27
+ self._cache: dict[str, tuple[float, dict]] = {}
28
+ self._lock = threading.Lock()
29
+
30
+ def user(self, token: str) -> dict | None:
31
+ now = time.monotonic()
32
+ with self._lock:
33
+ cached = self._cache.get(token)
34
+ if cached and cached[0] > now:
35
+ return cached[1]
36
+ request = urllib.request.Request(self.url + "/auth/v1/user",
37
+ headers={"Authorization": f"Bearer {token}", "apikey": self.key, "User-Agent": "mathly2/1.0"})
38
+ try:
39
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
40
+ data = json.load(response)
41
+ except urllib.error.HTTPError as exc:
42
+ if exc.code in (400, 401, 403):
43
+ return None
44
+ raise AuthUnavailable(f"supabase answered {exc.code}") from exc
45
+ except (urllib.error.URLError, TimeoutError, ValueError) as exc:
46
+ raise AuthUnavailable(str(exc)) from exc
47
+ email = str(data.get("email") or "").strip().lower()
48
+ # An email nobody confirmed could belong to someone else: never trust it, least of all for teacher rights.
49
+ if not data.get("id") or not email or not (data.get("email_confirmed_at") or data.get("confirmed_at")):
50
+ return None
51
+ user = {"id": data["id"], "email": email}
52
+ with self._lock:
53
+ self._cache[token] = (now + CACHE_SECONDS, user)
54
+ return user
55
+
56
+
57
+ class DevAuthenticator:
58
+ """Local development only (no Supabase settings): the token is "dev:<email>" and is trusted as it is."""
59
+
60
+ def user(self, token: str) -> dict | None:
61
+ if not token.startswith("dev:"):
62
+ return None
63
+ email = token[4:].strip().lower()
64
+ if not EMAIL.match(email):
65
+ return None
66
+ return {"id": str(uuid.uuid5(uuid.NAMESPACE_DNS, email)), "email": email}
67
+
68
+
69
+ def current_user(request: Request) -> dict:
70
+ header = request.headers.get("authorization", "")
71
+ token = header[7:].strip() if header.lower().startswith("bearer ") else ""
72
+ if not token:
73
+ raise HTTPException(401, "sign in required")
74
+ try:
75
+ user = request.app.state.authenticator.user(token)
76
+ except AuthUnavailable:
77
+ raise HTTPException(503, "sign-in service unavailable, try again") from None
78
+ if not user:
79
+ raise HTTPException(401, "sign in required")
80
+ role = "teacher" if user["email"] in request.app.state.settings.teachers else "student"
81
+ return {**user, "role": role}
82
+
83
+
84
+ def teacher_only(user: dict = Depends(current_user)) -> dict:
85
+ if user["role"] != "teacher":
86
+ raise HTTPException(403, "teachers only")
87
+ return user
mathly2/bank.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The exercise bank: lessons (units), skills, questions and mistakes. Loaded once and checked on start-up."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ BANK_PATH = Path(__file__).parent / "content" / "math_algebra9.json"
9
+
10
+
11
+ class BankError(RuntimeError):
12
+ """The bank is broken; the message lists every problem found."""
13
+
14
+
15
+ def check_bank(data: dict) -> list[str]:
16
+ """Every problem found in a bank, as short messages. An empty list means the bank is sound."""
17
+ problems: list[str] = []
18
+ for key in ("units", "skills", "mistakes"):
19
+ if key not in data:
20
+ return [f"missing '{key}'"]
21
+
22
+ def duplicates(kind: str, ids: list[str]) -> None:
23
+ seen: set[str] = set()
24
+ for item in ids:
25
+ if item in seen:
26
+ problems.append(f"duplicate {kind} id '{item}'")
27
+ seen.add(item)
28
+
29
+ unit_ids = [u.get("id") for u in data["units"]]
30
+ skill_ids = [s.get("id") for s in data["skills"]]
31
+ duplicates("lesson", unit_ids)
32
+ duplicates("skill", skill_ids)
33
+ units, skills, mistakes = set(unit_ids), set(skill_ids), data["mistakes"]
34
+
35
+ for unit in data["units"]:
36
+ for number, question in enumerate((unit.get("quiz") or {}).get("questions", []), 1):
37
+ for skill in question.get("skills", []):
38
+ if skill not in skills:
39
+ problems.append(f"lesson '{unit['id']}' quiz question {number}: unknown skill '{skill}'")
40
+
41
+ for skill in data["skills"]:
42
+ sid = skill["id"]
43
+ if skill.get("unit") not in units:
44
+ problems.append(f"skill '{sid}': unknown lesson '{skill.get('unit')}'")
45
+ for pre in skill.get("prereqs", []):
46
+ if pre not in skills:
47
+ problems.append(f"skill '{sid}': unknown prerequisite '{pre}'")
48
+ for number, question in enumerate(skill.get("questions", []), 1):
49
+ where = f"skill '{sid}' question {number}"
50
+ choices = question.get("choices", [])
51
+ if len(choices) < 2:
52
+ problems.append(f"{where}: fewer than 2 choices")
53
+ right = sum(1 for c in choices if c.get("correct"))
54
+ if right != 1:
55
+ problems.append(f"{where}: {right} correct choices, expected 1")
56
+ for choice in choices:
57
+ mistake = choice.get("mistake")
58
+ if mistake is not None and mistake not in mistakes:
59
+ problems.append(f"{where}: unknown mistake '{mistake}'")
60
+
61
+ for mid, mistake in mistakes.items():
62
+ # `back` is filled in for only some mistakes today (see scripts/content_gaps.py); check it when given.
63
+ back = mistake.get("back")
64
+ if back and back not in skills:
65
+ problems.append(f"mistake '{mid}': unknown skill to go back to '{back}'")
66
+ return problems
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class Bank:
71
+ data: dict
72
+
73
+ @property
74
+ def lessons(self) -> list[dict]:
75
+ return self.data["units"]
76
+
77
+ @property
78
+ def skills(self) -> list[dict]:
79
+ return self.data["skills"]
80
+
81
+ @property
82
+ def mistakes(self) -> dict:
83
+ return self.data["mistakes"]
84
+
85
+ def lessons_with_skills(self) -> list[dict]:
86
+ """Lessons with their skills, without any questions (those are served by later endpoints,
87
+ which hide which choice is correct)."""
88
+ by_lesson: dict[str, list[dict]] = {}
89
+ for skill in self.skills:
90
+ by_lesson.setdefault(skill["unit"], []).append({
91
+ "id": skill["id"], "name": skill["name"], "short": skill.get("short", skill["name"]),
92
+ "description": skill.get("description", ""), "prereqs": skill.get("prereqs", []),
93
+ "month": skill.get("month", ""),
94
+ })
95
+ return [{
96
+ "id": lesson["id"], "name": lesson["name"], "when": lesson.get("when", ""),
97
+ "has_quiz": bool(lesson.get("quiz")), "skills": by_lesson.get(lesson["id"], []),
98
+ } for lesson in self.lessons]
99
+
100
+
101
+ def load_bank(path: Path = BANK_PATH) -> Bank:
102
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
103
+ problems = check_bank(data)
104
+ if problems:
105
+ shown = "\n - ".join(problems[:20])
106
+ more = f"\n … and {len(problems) - 20} more" if len(problems) > 20 else ""
107
+ raise BankError(f"The exercise bank {path} has {len(problems)} problem(s):\n - {shown}{more}")
108
+ return Bank(data)
mathly2/classes.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A teacher's classes and their students."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ from fastapi import APIRouter, Depends, HTTPException, Request
7
+ from pydantic import BaseModel, Field
8
+
9
+ from .auth import EMAIL, teacher_only
10
+ from .store import ClassExists, MemberExists
11
+
12
+ MAX_EMAILS = 200
13
+ router = APIRouter(prefix="/api/classes")
14
+
15
+
16
+ class NewClass(BaseModel):
17
+ name: str = Field(max_length=200)
18
+
19
+
20
+ class NewStudents(BaseModel):
21
+ emails: str = Field(max_length=20000) # pasted text: addresses separated by spaces, commas, semicolons or new lines
22
+
23
+
24
+ def parse_emails(text: str) -> tuple[list[str], list[str]]:
25
+ """(valid, invalid) addresses from pasted text: lower-case, without repeats, in the order given."""
26
+ valid: list[str] = []
27
+ invalid: list[str] = []
28
+ for part in re.split(r"[\s,;]+", text.strip().lower()):
29
+ if not part:
30
+ continue
31
+ bucket = valid if EMAIL.match(part) and len(part) <= 254 else invalid
32
+ if part not in bucket:
33
+ bucket.append(part)
34
+ return valid, invalid
35
+
36
+
37
+ def own_class(request: Request, class_id: int, user: dict) -> dict:
38
+ row = request.app.state.store.get_class(class_id)
39
+ if not row or row["teacher_email"] != user["email"]:
40
+ raise HTTPException(404, "הכיתה לא נמצאה")
41
+ return row
42
+
43
+
44
+ @router.get("")
45
+ def list_classes(request: Request, user: dict = Depends(teacher_only)) -> list[dict]:
46
+ return [{"id": c["id"], "name": c["name"], "students": c["students"]}
47
+ for c in request.app.state.store.classes_of(user["email"])]
48
+
49
+
50
+ @router.post("", status_code=201)
51
+ def create_class(body: NewClass, request: Request, user: dict = Depends(teacher_only)) -> dict:
52
+ name = " ".join(body.name.split())
53
+ if not 1 <= len(name) <= 60:
54
+ raise HTTPException(422, "שם הכיתה צריך להיות בין תו אחד ל־60 תווים")
55
+ try:
56
+ row = request.app.state.store.create_class(user["email"], name)
57
+ except ClassExists:
58
+ raise HTTPException(409, "כבר יש לך כיתה בשם הזה") from None
59
+ return {"id": row["id"], "name": row["name"], "students": 0}
60
+
61
+
62
+ @router.get("/{class_id}")
63
+ def show_class(class_id: int, request: Request, user: dict = Depends(teacher_only)) -> dict:
64
+ row = own_class(request, class_id, user)
65
+ members = request.app.state.store.members(class_id)
66
+ return {"id": row["id"], "name": row["name"],
67
+ "students": [{"email": m["email"], "signed_in": bool(m["user_id"])} for m in members]}
68
+
69
+
70
+ @router.post("/{class_id}/students")
71
+ def add_students(class_id: int, body: NewStudents, request: Request, user: dict = Depends(teacher_only)) -> dict:
72
+ own_class(request, class_id, user)
73
+ store = request.app.state.store
74
+ valid, invalid = parse_emails(body.emails)
75
+ if len(valid) > MAX_EMAILS:
76
+ raise HTTPException(422, f"אפשר להוסיף עד {MAX_EMAILS} תלמידים בכל פעם")
77
+ result: dict = {"added": [], "already_here": [], "elsewhere": [], "invalid": invalid}
78
+ for email in valid:
79
+ current = store.membership(email)
80
+ if current is None:
81
+ try:
82
+ store.add_member(class_id, email)
83
+ result["added"].append(email)
84
+ continue
85
+ except MemberExists: # added to another class a moment ago
86
+ current = store.membership(email)
87
+ if current and current["class_id"] == class_id:
88
+ result["already_here"].append(email)
89
+ else:
90
+ result["elsewhere"].append({"email": email, "class_name": current["class_name"] if current else ""})
91
+ return result
92
+
93
+
94
+ @router.delete("/{class_id}/students/{email:path}", status_code=204)
95
+ def remove_student(class_id: int, email: str, request: Request, user: dict = Depends(teacher_only)) -> None:
96
+ own_class(request, class_id, user)
97
+ if not request.app.state.store.remove_member(class_id, email.strip().lower()):
98
+ raise HTTPException(404, "התלמיד לא נמצא בכיתה")
mathly2/clock.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server time. Every rule that depends on days (mastery, the countdown, the simulation window) uses this,
2
+ never the device's clock."""
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime, timezone
6
+ from zoneinfo import ZoneInfo
7
+
8
+ ISRAEL = ZoneInfo("Asia/Jerusalem")
9
+
10
+
11
+ def now() -> datetime:
12
+ return datetime.now(timezone.utc)
13
+
14
+
15
+ def school_day(moment: datetime | None = None) -> date:
16
+ """The calendar day in Israel at `moment` (default: now)."""
17
+ moment = moment or now()
18
+ if moment.tzinfo is None:
19
+ raise ValueError("moment must have a timezone")
20
+ return moment.astimezone(ISRAEL).date()
mathly2/config.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Settings, read from the environment when the app is created."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import re
6
+ from dataclasses import dataclass, field
7
+
8
+
9
+ def _emails(name: str) -> frozenset[str]:
10
+ return frozenset(re.split(r"[\s,;]+", os.environ.get(name, "").strip().lower())) - {""}
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Settings:
15
+ supabase_url: str = ""
16
+ supabase_key: str = "" # publishable key, sent to the browser for Google sign-in
17
+ supabase_secret: str = "" # secret key, server only
18
+ teachers: frozenset[str] = field(default_factory=frozenset)
19
+
20
+ @property
21
+ def supabase_on(self) -> bool:
22
+ return bool(self.supabase_url and self.supabase_key and self.supabase_secret)
23
+
24
+ def check(self) -> "Settings":
25
+ """Either all three Supabase settings are set, or none (local development with the "dev only" sign-in).
26
+ A half-configured server must not fall back to dev sign-in, which trusts any email address."""
27
+ given = [bool(self.supabase_url), bool(self.supabase_key), bool(self.supabase_secret)]
28
+ if any(given) and not all(given):
29
+ raise ValueError("Set all of SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY and SUPABASE_SECRET_KEY, or none of them.")
30
+ return self
31
+
32
+
33
+ def load_settings() -> Settings:
34
+ env = lambda name: os.environ.get(name, "").strip()
35
+ return Settings(
36
+ supabase_url=env("SUPABASE_URL").rstrip("/"),
37
+ supabase_key=env("SUPABASE_PUBLISHABLE_KEY"),
38
+ supabase_secret=env("SUPABASE_SECRET_KEY"),
39
+ teachers=_emails("TEACHER_EMAILS"),
40
+ ).check()
mathly2/content/math_algebra9.json ADDED
The diff for this file is too large to render. See raw diff
 
mathly2/main.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI app: uvicorn mathly2.main:app"""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from fastapi import Depends, FastAPI, HTTPException
8
+ from fastapi.responses import HTMLResponse
9
+ from fastapi.staticfiles import StaticFiles
10
+
11
+ from .auth import DevAuthenticator, SupabaseAuthenticator, current_user
12
+ from .bank import Bank, load_bank
13
+ from . import classes
14
+ from .config import Settings, load_settings
15
+ from .store import InMemoryStore, SupabaseStore
16
+
17
+ STATIC = Path(__file__).parent / "static"
18
+
19
+
20
+ def create_app(settings: Settings | None = None, bank: Bank | None = None, store=None, authenticator=None) -> FastAPI:
21
+ app = FastAPI(title="Mathly 2")
22
+ app.state.settings = settings = (settings or load_settings()).check()
23
+ app.state.bank = bank or load_bank() # a broken bank stops the server from starting
24
+ if settings.supabase_on:
25
+ app.state.store = store or SupabaseStore(settings.supabase_url, settings.supabase_secret)
26
+ app.state.authenticator = authenticator or SupabaseAuthenticator(settings.supabase_url, settings.supabase_key)
27
+ else:
28
+ app.state.store = store or InMemoryStore()
29
+ app.state.authenticator = authenticator or DevAuthenticator()
30
+
31
+ app.include_router(classes.router)
32
+
33
+ @app.get("/api/health")
34
+ def health() -> dict:
35
+ return {"ok": True}
36
+
37
+ def my_class(user: dict) -> dict | None:
38
+ """The student's class. The first time they sign in, their account is linked to the entry the teacher made."""
39
+ if user["role"] != "student":
40
+ return None
41
+ membership = app.state.store.membership(user["email"])
42
+ if membership and not membership["user_id"]:
43
+ app.state.store.link_user(user["email"], user["id"])
44
+ return {"id": membership["class_id"], "name": membership["class_name"]} if membership else None
45
+
46
+ @app.get("/api/me")
47
+ def me(user: dict = Depends(current_user)) -> dict:
48
+ return {"email": user["email"], "role": user["role"], "class": my_class(user)}
49
+
50
+ def in_class_or_teacher(user: dict = Depends(current_user)) -> dict:
51
+ if user["role"] == "student" and not app.state.store.membership(user["email"]):
52
+ raise HTTPException(403, "ask your teacher to add you to a class")
53
+ return user
54
+
55
+ @app.get("/api/lessons")
56
+ def lessons(user: dict = Depends(in_class_or_teacher)) -> list[dict]:
57
+ return app.state.bank.lessons_with_skills()
58
+
59
+ @app.get("/", include_in_schema=False)
60
+ def index() -> HTMLResponse:
61
+ # The browser needs only the public values: the Supabase URL and the publishable key. Never the secret key.
62
+ config = {"supabaseUrl": settings.supabase_url, "supabaseKey": settings.supabase_key,
63
+ "devSignIn": not settings.supabase_on}
64
+ text = json.dumps(config).replace("<", "\\u003c")
65
+ html = (STATIC / "index.html").read_text(encoding="utf-8").replace("__CONFIG__", text)
66
+ return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
67
+
68
+ app.mount("/static", StaticFiles(directory=STATIC), name="static")
69
+ return app
70
+
71
+
72
+ app = create_app()
mathly2/requirements-dev.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ -r requirements.txt
2
+ httpx>=0.27
3
+ pytest>=8
4
+ playwright==1.64.1
5
+ # Optional local PostgreSQL check of the migrations (bundled server; no Docker or project credentials).
6
+ pgserver==0.1.4; sys_platform == 'linux'
7
+ psycopg[binary]==3.3.6
mathly2/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi>=0.110
2
+ uvicorn[standard]>=0.29
3
+ anyio>=4.10,<4.11 # Python 3.10: newer releases can hang Starlette's worker-thread bridge
4
+ python-dotenv>=1.0
5
+ tzdata>=2024.1
mathly2/scripts/__init__.py ADDED
File without changes
mathly2/scripts/content_gaps.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """List the content the bank still lacks. venv/bin/python -m mathly2.scripts.content_gaps [--min-questions N]
2
+
3
+ A skill needs: a worked example whose every step has "why this step?" choices, and faded examples
4
+ (field names below; build-skill-learning fixes the exact shape of their contents).
5
+ A lesson needs a quiz. A skill needs enough questions for similar questions and for retakes.
6
+ Mistakes should say which skill to go back to."""
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import sys
11
+
12
+ from mathly2.bank import load_bank
13
+
14
+ MIN_QUESTIONS = 10
15
+
16
+
17
+ def find_gaps(data: dict, min_questions: int = MIN_QUESTIONS) -> dict[str, list[str]]:
18
+ gaps: dict[str, list[str]] = {
19
+ "skills without a worked example": [],
20
+ "worked-example steps without 'why this step?' choices": [],
21
+ "skills without faded examples": [],
22
+ "lessons without a quiz": [],
23
+ "skills without questions": [],
24
+ f"skills with fewer than {min_questions} questions": [],
25
+ "mistakes without a skill to go back to": [],
26
+ }
27
+ for skill in data["skills"]:
28
+ sid = skill["id"]
29
+ example = skill.get("worked_example")
30
+ if not example:
31
+ gaps["skills without a worked example"].append(sid)
32
+ else:
33
+ for number, step in enumerate(example.get("steps", []), 1):
34
+ if not step.get("why"):
35
+ gaps["worked-example steps without 'why this step?' choices"].append(f"{sid} step {number}")
36
+ if not skill.get("faded_examples"):
37
+ gaps["skills without faded examples"].append(sid)
38
+ count = len(skill.get("questions", []))
39
+ if count == 0:
40
+ gaps["skills without questions"].append(sid)
41
+ elif count < min_questions:
42
+ gaps[f"skills with fewer than {min_questions} questions"].append(f"{sid} ({count})")
43
+ for lesson in data["units"]:
44
+ if not lesson.get("quiz"):
45
+ gaps["lessons without a quiz"].append(lesson["id"])
46
+ for mid, mistake in data["mistakes"].items():
47
+ if not mistake.get("back"):
48
+ gaps["mistakes without a skill to go back to"].append(mid)
49
+ return gaps
50
+
51
+
52
+ def main(argv: list[str] | None = None) -> int:
53
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
54
+ parser.add_argument("--min-questions", type=int, default=MIN_QUESTIONS)
55
+ args = parser.parse_args(argv)
56
+ gaps = find_gaps(load_bank().data, args.min_questions)
57
+ for title, items in gaps.items():
58
+ print(f"{title}: {len(items)}")
59
+ if 0 < len(items) <= 30:
60
+ print(" " + ", ".join(items))
61
+ return 0
62
+
63
+
64
+ if __name__ == "__main__":
65
+ sys.exit(main())
mathly2/static/api.js ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { token } from "./session.js";
2
+
3
+ export class ApiError extends Error {
4
+ constructor(status, message) { super(message); this.status = status; }
5
+ }
6
+
7
+ const MESSAGES = { 503: "שירות ההתחברות לא זמין כרגע, נסו שוב בעוד רגע", 403: "אין הרשאה לפעולה הזו" };
8
+
9
+ export async function api(path, { method = "GET", body } = {}) {
10
+ const headers = { Authorization: "Bearer " + await token() };
11
+ if (body !== undefined) headers["Content-Type"] = "application/json";
12
+ const response = await fetch(path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
13
+ if (response.ok) return response.status === 204 ? null : response.json();
14
+ let detail = "";
15
+ try { detail = (await response.json()).detail; } catch { /* no body */ }
16
+ throw new ApiError(response.status, typeof detail === "string" && detail ? detail : (MESSAGES[response.status] || "משהו השתבש, נסו שוב"));
17
+ }
mathly2/static/app.css ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Phone first: the base styles fit 360px; wider layouts are added with min-width queries. */
2
+ :root {
3
+ --bg: #f7f8fb; --surface: #ffffff; --text: #1b2433; --muted: #5b6678;
4
+ --line: #d9dee8; --accent: #2557d6; --accent-text: #ffffff; --danger: #b3261e;
5
+ --gutter: 16px; --radius: 12px;
6
+ }
7
+ @media (prefers-color-scheme: dark) {
8
+ :root:not([data-theme="light"]) {
9
+ --bg: #11151c; --surface: #1a212c; --text: #e8ecf3; --muted: #9aa5b8;
10
+ --line: #2d3748; --accent: #7aa2ff; --accent-text: #0b1220; --danger: #ff8a80;
11
+ }
12
+ }
13
+ :root[data-theme="dark"] {
14
+ --bg: #11151c; --surface: #1a212c; --text: #e8ecf3; --muted: #9aa5b8;
15
+ --line: #2d3748; --accent: #7aa2ff; --accent-text: #0b1220; --danger: #ff8a80;
16
+ }
17
+ * { box-sizing: border-box; }
18
+ html, body { margin: 0; }
19
+ body {
20
+ background: var(--bg); color: var(--text);
21
+ font: 16px/1.5 system-ui, "Segoe UI", Arial, "Noto Sans Hebrew", sans-serif;
22
+ overflow-x: hidden;
23
+ }
24
+ .top {
25
+ display: flex; align-items: center; justify-content: space-between; gap: 12px;
26
+ padding: 12px var(--gutter); background: var(--surface); border-bottom: 1px solid var(--line);
27
+ }
28
+ .top h1 { margin: 0; font-size: 20px; }
29
+ main { padding: var(--gutter); max-width: 960px; margin: 0 auto; }
30
+ .card {
31
+ background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius);
32
+ padding: var(--gutter); margin-block: 12px;
33
+ }
34
+ .card h2 { margin: 0 0 8px; font-size: 18px; }
35
+ .muted { color: var(--muted); }
36
+ .error { color: var(--danger); }
37
+ button, .button {
38
+ font: inherit; min-height: 44px; padding: 8px 16px; border-radius: 10px; cursor: pointer;
39
+ border: 1px solid var(--line); background: var(--surface); color: var(--text);
40
+ }
41
+ button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
42
+ input, textarea {
43
+ font: inherit; width: 100%; padding: 10px 12px; border-radius: 10px;
44
+ border: 1px solid var(--line); background: var(--bg); color: var(--text);
45
+ }
46
+ textarea { min-height: 120px; }
47
+ label { display: block; margin-block: 8px 4px; font-weight: 600; }
48
+ ul.plain { list-style: none; margin: 0; padding: 0; }
49
+ ul.plain li { padding: 10px 0; border-bottom: 1px solid var(--line); display: flex; gap: 8px; align-items: center; justify-content: space-between; }
50
+ ul.plain li:last-child { border-bottom: 0; }
51
+ .formula { direction: ltr; unicode-bidi: isolate; }
52
+ @media (min-width: 720px) { main { padding: 24px; } }
53
+ .m { font-family: "STIX Two Math", "Cambria Math", serif; direction: ltr; unicode-bidi: isolate; white-space: nowrap; font-size: 1.05em; }
54
+ .m.m-img { font-size: 1.12em; }
55
+ .m-img svg { display: inline-block; overflow: visible; max-width: none; }
mathly2/static/app.js ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // App shell: sign-in, then the screen for the signed-in person's role.
2
+ import { api, ApiError } from "./api.js";
3
+ import { esc } from "./math.js";
4
+ import * as session from "./session.js";
5
+
6
+ const CFG = JSON.parse(document.getElementById("config").textContent);
7
+ const app = document.getElementById("app");
8
+ const nav = document.getElementById("nav");
9
+
10
+ export const view = html => { app.innerHTML = html; };
11
+
12
+ function showSignIn(message = "") {
13
+ nav.innerHTML = "";
14
+ view(`<section class="card" id="signin"><h2>כניסה</h2>
15
+ ${message ? `<p class="error" role="alert">${esc(message)}</p>` : ""}
16
+ ${CFG.devSignIn
17
+ ? `<p class="muted">כניסת פיתוח (dev only): ללא Supabase, כל כתובת מייל מתקבלת.</p>
18
+ <form id="dev"><label for="email">מייל</label><input id="email" type="email" required autocomplete="email" dir="ltr">
19
+ <p><button class="primary" type="submit">כניסה</button></p></form>`
20
+ : `<p><button class="primary" id="google" type="button">כניסה עם Google</button></p>`}</section>`);
21
+ document.getElementById("google")?.addEventListener("click", () => session.signInWithGoogle());
22
+ document.getElementById("dev")?.addEventListener("submit", event => {
23
+ event.preventDefault();
24
+ session.signInDev(document.getElementById("email").value);
25
+ boot();
26
+ });
27
+ }
28
+
29
+ async function signOutAndShow(message) {
30
+ await session.signOut();
31
+ showSignIn(message);
32
+ }
33
+
34
+ function header(me) {
35
+ nav.innerHTML = `<span class="muted" dir="ltr">${esc(me.email)}</span> <button type="button" id="out">יציאה</button>`;
36
+ document.getElementById("out").addEventListener("click", () => signOutAndShow());
37
+ }
38
+
39
+ async function boot() {
40
+ view(`<section class="card"><p class="muted">טוען…</p></section>`);
41
+ try {
42
+ await session.init(CFG);
43
+ } catch {
44
+ return showSignIn("לא הצלחנו לטעון את שירות ההתחברות. בדקו את החיבור לרשת ונסו שוב.");
45
+ }
46
+ if (!await session.token()) return showSignIn();
47
+ try {
48
+ const me = await api("/api/me");
49
+ header(me);
50
+ const screen = await import(me.role === "teacher" ? "./teacher.js" : "./student.js");
51
+ await screen.show(me, view);
52
+ } catch (error) {
53
+ if (error instanceof ApiError && error.status === 401) return signOutAndShow("ההתחברות פגה, יש להיכנס שוב");
54
+ view(`<section class="card"><p class="error" role="alert">${esc(error.message || "משהו השתבש")}</p></section>`);
55
+ }
56
+ }
57
+
58
+ boot();
mathly2/static/index.html ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="he" dir="rtl">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <meta name="color-scheme" content="light dark">
7
+ <title>Mathly</title>
8
+ <link rel="stylesheet" href="/static/app.css">
9
+ </head>
10
+ <body>
11
+ <script id="config" type="application/json">__CONFIG__</script>
12
+ <header class="top"><h1>Mathly</h1><nav id="nav" aria-label="ראשי"></nav></header>
13
+ <main id="app" aria-live="polite"></main>
14
+ <script src="/static/math-tex.js"></script>
15
+ <script type="module" src="/static/app.js"></script>
16
+ </body>
17
+ </html>
mathly2/static/math-tex.js ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Math as pictures. The content writes math as plain text between $…$ (math.js shows it as <span class="m">), e.g.
2
+ "1/(2x) + x² ≥ √3". This file turns that text into TeX (a/b becomes a stacked fraction, √ a root, ² a raised
3
+ exponent) and MathJax draws it as an SVG image in place of the text. The text stays as the picture's label, and
4
+ whatever cannot be read (Hebrew words, unknown signs), or everything when MathJax does not load, keeps showing as text. */
5
+ (()=>{
6
+ const SUP={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁻":"-","⁺":"+","ⁿ":"n","ᵐ":"m"};
7
+ const SUB={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9"};
8
+ const OPS={"−":"-","–":"-","·":"\\cdot ","×":"\\times ","÷":"\\div ","≠":"\\neq ","≥":"\\geq ","≤":"\\leq ","±":"\\pm ",
9
+ "⇒":"\\Rightarrow ","→":"\\to ","↔":"\\leftrightarrow ","∥":"\\parallel ","⊥":"\\perp ","△":"\\triangle ",
10
+ "∢":"\\measuredangle ","∼":"\\sim ","…":"\\ldots ","%":"\\%","π":"\\pi ","α":"\\alpha ","β":"\\beta ","∞":"\\infty ",
11
+ "+":"+","-":"-","=":"=","<":"<",">":">",",":",",":":":","?":"?","!":"!","|":"|","'":"'",".":"."};
12
+ const TOKEN=/\d+(?:\.\d+)?|[A-Za-z]|[⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺ⁿᵐ]+|[₀₁₂₃₄₅₆₇₈₉]+|\s+|./gu;
13
+
14
+ // plain math text to TeX, or null when it cannot be read
15
+ function toTex(src){
16
+ const toks=String(src).match(TOKEN)||[];
17
+ if(!toks.length) return null;
18
+ let i=0;
19
+ const fail=()=>{ throw new Error("unreadable"); };
20
+ // one atom: a number, a letter, a (group) or a √atom; `inner` is a group's content, used inside a fraction or root
21
+ function atom(){
22
+ const k=toks[i++];
23
+ if(k===undefined) fail();
24
+ if(/^[\d.]/.test(k)||/^[A-Za-zΔ]$/.test(k)) return {kind:"a",t:k==="Δ"?"\\Delta ":k};
25
+ if(k==="("||k==="["){
26
+ const c=k==="("?")":"]", inner=join(seq(c)), big=inner.includes("\\frac");
27
+ return {kind:"a",t:big?`\\left${k}${inner}\\right${c}`:`${k}${inner}${c}`,inner};
28
+ }
29
+ if(k==="√"){ const a=atom(); return {kind:"a",t:`\\sqrt{${a.inner??a.t}}`}; }
30
+ i--; return null;
31
+ }
32
+ function seq(close){
33
+ const out=[];
34
+ while(i<toks.length){
35
+ const k=toks[i];
36
+ if(k===close){ i++; return out; }
37
+ if(k===")"||k==="]") fail();
38
+ const a=atom();
39
+ if(a){ out.push(a); continue; }
40
+ i++;
41
+ const prev=out[out.length-1];
42
+ if(/^\s+$/.test(k)) out.push({kind:"s"});
43
+ else if(SUP[k[0]]!==undefined||k==="^"||k==="°"){
44
+ if(prev?.kind!=="a"||prev.sup) fail();
45
+ let up;
46
+ if(k==="°") up="\\circ";
47
+ else if(k==="^"){ const b=atom(); if(!b) fail(); up=b.inner??b.t; }
48
+ else up=[...k].map(c=>SUP[c]).join("");
49
+ prev.t=`${prev.t}^{${up}}`; prev.sup=true; delete prev.inner;
50
+ }
51
+ else if(SUB[k[0]]!==undefined){
52
+ if(prev?.kind!=="a"||prev.sup||prev.sub) fail();
53
+ prev.t=`${prev.t}_{${[...k].map(c=>SUB[c]).join("")}}`; prev.sub=true; delete prev.inner;
54
+ }
55
+ else if(k==="/") out.push({kind:"/"});
56
+ else if(OPS[k]!==undefined) out.push({kind:"o",t:OPS[k]});
57
+ else fail();
58
+ }
59
+ if(close) fail();
60
+ return out;
61
+ }
62
+ // atoms side by side make one term (2x, 3(x + 1)); a / between two terms is a fraction
63
+ function join(items){
64
+ const terms=[];
65
+ for(const it of items){
66
+ const prev=terms[terms.length-1];
67
+ if(it.kind==="a"&&prev?.kind==="a"){ prev.t+=it.t; delete prev.inner; prev.sup=it.sup; }
68
+ else terms.push({...it});
69
+ }
70
+ const near=(j,step)=>{ while(terms[j]?.kind==="s") j+=step; return j; };
71
+ for(let j=0;j<terms.length;j++){
72
+ if(terms[j].kind!=="/") continue;
73
+ const a=near(j-1,-1), b=near(j+1,1), num=terms[a], den=terms[b];
74
+ if(num?.kind!=="a"||den?.kind!=="a") continue;
75
+ terms.splice(a,b-a+1,{kind:"a",t:`\\frac{${num.inner??num.t}}{${den.inner??den.t}}`});
76
+ j=a;
77
+ // a fraction followed by a term (1/2x) already took it as its denominator; one before it is a coefficient
78
+ }
79
+ return terms.map(x=>x.kind==="s"?" ":x.kind==="/"?"/":x.t).join("").replace(/\s+/g," ").trim();
80
+ }
81
+ try{ const tex=join(seq(null)); return tex||null; }catch{ return null; }
82
+ }
83
+
84
+ /* drawing: each span.m once, the same picture reused for the same text */
85
+ const cache=new Map();
86
+ function picture(text){
87
+ if(cache.has(text)) return cache.get(text);
88
+ const tex=toTex(text);
89
+ let svg=null;
90
+ if(tex) try{
91
+ const out=window.MathJax.tex2svg(tex.includes("\\frac")?`\\displaystyle ${tex}`:tex,{display:false}).querySelector("svg");
92
+ if(out&&!out.querySelector("[data-mml-node=merror]")){ out.setAttribute("aria-hidden","true"); out.removeAttribute("role"); svg=out; }
93
+ }catch{}
94
+ cache.set(text,svg);
95
+ return svg;
96
+ }
97
+ function render(scope=document.body){
98
+ if(!window.MathJax?.tex2svg) return;
99
+ for(const el of scope.querySelectorAll("span.m:not([data-tex])")){
100
+ const text=el.textContent, svg=picture(text);
101
+ el.dataset.tex=svg?"1":"0";
102
+ if(!svg) continue;
103
+ el.replaceChildren(svg.cloneNode(true));
104
+ el.setAttribute("role","img"); el.setAttribute("aria-label",text); el.classList.add("m-img");
105
+ }
106
+ }
107
+ globalThis.MathlyTex={toTex,render};
108
+ if(typeof document==="undefined") return;
109
+ let queued=false;
110
+ const watch=new MutationObserver(()=>{ if(queued) return; queued=true; queueMicrotask(()=>{ queued=false; render(); }); });
111
+ window.MathJax={tex:{packages:{"[+]":["ams"]}},svg:{fontCache:"none"},options:{enableMenu:false},
112
+ startup:{typeset:false,ready(){ window.MathJax.startup.defaultReady(); render(); watch.observe(document.body,{childList:true,subtree:true}); }}};
113
+ const s=document.createElement("script");
114
+ s.src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.js"; s.async=true;
115
+ document.head.append(s);
116
+ })();
mathly2/static/math.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ // Shared text helpers. The bank writes math as plain text between $…$ (for example "$x² − 2x − 15$").
2
+ // fmt() escapes the text and wraps each $…$ in <span class="m">, which math-tex.js draws as a formula.
3
+ export const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
4
+ export const fmt = s => esc(s).replace(/\$([^$]+)\$/g, '<span class="m">$1</span>');
mathly2/static/session.js ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Sign-in state. With Supabase settings: Google sign-in through supabase-js. Without them (local development only):
2
+ // a "dev only" sign-in that takes an email address; the server trusts "dev:<email>" tokens only in that mode.
3
+ const DEV_KEY = "mathly2.dev-email";
4
+ let client = null;
5
+
6
+ const load = src => new Promise((ok, fail) => {
7
+ const s = document.createElement("script");
8
+ s.src = src; s.onload = ok; s.onerror = () => fail(new Error("script " + src));
9
+ document.head.append(s);
10
+ });
11
+
12
+ export async function init(cfg) {
13
+ if (!cfg.supabaseUrl) return;
14
+ await load("https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2.45.4/dist/umd/supabase.js");
15
+ client = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseKey);
16
+ }
17
+
18
+ export async function token() {
19
+ if (client) {
20
+ const { data } = await client.auth.getSession(); // supabase-js refreshes an expired token here
21
+ return data.session?.access_token || "";
22
+ }
23
+ try { const email = localStorage.getItem(DEV_KEY); return email ? "dev:" + email : ""; } catch { return ""; }
24
+ }
25
+
26
+ export const signInWithGoogle = () =>
27
+ client.auth.signInWithOAuth({ provider: "google", options: { redirectTo: location.origin + location.pathname } });
28
+
29
+ export function signInDev(email) {
30
+ try { localStorage.setItem(DEV_KEY, email.trim().toLowerCase()); } catch { /* private window: stays signed out */ }
31
+ }
32
+
33
+ export async function signOut() {
34
+ if (client) await client.auth.signOut();
35
+ try { localStorage.removeItem(DEV_KEY); } catch { /* nothing stored */ }
36
+ }
mathly2/static/student.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { api } from "./api.js";
2
+ import { esc } from "./math.js";
3
+
4
+ export async function show(me, view) {
5
+ if (!me.class) {
6
+ view(`<section class="card" id="no-class"><h2>עוד לא בכיתה</h2>
7
+ <p>המורה עוד לא הוסיפה אותך לכיתה. בקשו מהמורה להוסיף את כתובת המייל שבה נכנסתם:</p>
8
+ <p dir="ltr"><b>${esc(me.email)}</b></p></section>`);
9
+ return;
10
+ }
11
+ const lessons = await api("/api/lessons");
12
+ view(`<section class="card"><h2>שלום</h2><p class="muted">הכיתה: ${esc(me.class.name)}. השיעורים (${lessons.length}) יפתחו כאן בהמשך.</p>
13
+ <ul class="plain">${lessons.map(l => `<li><span>${esc(l.name)}</span><span class="muted">${l.skills.length} מיומנויות</span></li>`).join("")}</ul></section>`);
14
+ }
mathly2/static/teacher.js ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Teacher screens: my classes, and one class with its students.
2
+ import { api } from "./api.js";
3
+ import { esc } from "./math.js";
4
+
5
+ let draw; // the app's view() function
6
+
7
+ const note = (text, kind = "muted") => text ? `<p class="${kind}" role="${kind === "error" ? "alert" : "status"}">${text}</p>` : "";
8
+
9
+ async function showClasses(message = "", error = "") {
10
+ const classes = await api("/api/classes");
11
+ draw(`<section class="card"><h2>הכיתות שלי</h2>
12
+ ${classes.length ? `<ul class="plain" id="classes">${classes.map(c =>
13
+ `<li><a href="#class/${c.id}">${esc(c.name)}</a><span class="muted">${c.students} תלמידים</span></li>`).join("")}</ul>`
14
+ : `<p class="muted">עוד אין כיתות. אפשר ליצור את הראשונה כאן.</p>`}</section>
15
+ <section class="card"><h2>כיתה חדשה</h2>${note(esc(error), "error")}${note(esc(message))}
16
+ <form id="new-class"><label for="class-name">שם הכיתה</label>
17
+ <input id="class-name" required maxlength="60" autocomplete="off">
18
+ <p><button class="primary" type="submit">יצירת כיתה</button></p></form></section>`);
19
+ document.getElementById("new-class").addEventListener("submit", async event => {
20
+ event.preventDefault();
21
+ try {
22
+ const created = await api("/api/classes", { method: "POST", body: { name: document.getElementById("class-name").value } });
23
+ await showClasses(`הכיתה "${created.name}" נוצרה`);
24
+ } catch (e) { await showClasses("", e.message); }
25
+ });
26
+ }
27
+
28
+ function report(result) {
29
+ const lines = [];
30
+ if (result.added.length) lines.push(`נוספו ${result.added.length} תלמידים.`);
31
+ if (result.already_here.length) lines.push(`${result.already_here.length} כבר היו בכיתה.`);
32
+ for (const x of result.elsewhere)
33
+ lines.push(`${esc(x.email)} כבר שייך/ת לכיתה "${esc(x.class_name)}" ולא נוסף/ה. תלמיד יכול להיות רק בכיתה אחת.`);
34
+ if (result.invalid.length) lines.push(`לא נראה כמו מייל: ${result.invalid.map(esc).join(", ")}`);
35
+ return lines;
36
+ }
37
+
38
+ async function showClass(id, lines = [], error = "") {
39
+ const cls = await api(`/api/classes/${id}`);
40
+ draw(`<p><a href="#">← הכיתות שלי</a></p>
41
+ <section class="card"><h2>${esc(cls.name)}</h2>
42
+ ${cls.students.length ? `<ul class="plain" id="students">${cls.students.map(s =>
43
+ `<li><span dir="ltr">${esc(s.email)}</span><span class="muted">${s.signed_in ? "נכנס/ה" : "עוד לא נכנס/ה"}</span>
44
+ <button type="button" data-remove="${esc(s.email)}" aria-label="הסרת ${esc(s.email)}">הסרה</button></li>`).join("")}</ul>`
45
+ : `<p class="muted">עוד אין תלמידים בכיתה.</p>`}</section>
46
+ <section class="card"><h2>הוספת תלמידים</h2>${note(esc(error), "error")}
47
+ <div id="report">${lines.map(l => `<p role="status">${l}</p>`).join("")}</div>
48
+ <form id="add"><label for="emails">כתובות מייל (אפשר להדביק רשימה)</label>
49
+ <textarea id="emails" dir="ltr" required></textarea>
50
+ <p><button class="primary" type="submit">הוספה</button></p></form></section>`);
51
+ document.getElementById("add").addEventListener("submit", async event => {
52
+ event.preventDefault();
53
+ try {
54
+ const result = await api(`/api/classes/${id}/students`, { method: "POST", body: { emails: document.getElementById("emails").value } });
55
+ await showClass(id, report(result));
56
+ } catch (e) { await showClass(id, [], e.message); }
57
+ });
58
+ document.getElementById("students")?.addEventListener("click", async event => {
59
+ const email = event.target.closest("[data-remove]")?.dataset.remove;
60
+ if (!email) return;
61
+ try {
62
+ await api(`/api/classes/${id}/students/${encodeURIComponent(email)}`, { method: "DELETE" });
63
+ await showClass(id, [`${esc(email)} הוסר/ה מהכיתה.`]);
64
+ } catch (e) { await showClass(id, [], e.message); }
65
+ });
66
+ }
67
+
68
+ async function route() {
69
+ const match = location.hash.match(/^#class\/(\d+)$/);
70
+ try { await (match ? showClass(Number(match[1])) : showClasses()); }
71
+ catch (e) { draw(`<section class="card"><p class="error" role="alert">${esc(e.message)}</p><p><a href="#">← הכיתות שלי</a></p></section>`); }
72
+ }
73
+
74
+ export async function show(me, view) {
75
+ draw = view;
76
+ addEventListener("hashchange", route);
77
+ await route();
78
+ }
mathly2/store.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Where classes and students are kept. Two stores with the same methods:
2
+ InMemoryStore (tests and local development, lost on restart) and SupabaseStore (PostgREST with the secret key)."""
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import json
7
+ import threading
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from datetime import datetime, timezone
12
+
13
+ TIMEOUT = 10
14
+
15
+
16
+ class StoreUnavailable(RuntimeError):
17
+ """The database could not be reached or refused the request."""
18
+
19
+
20
+ class ClassExists(ValueError):
21
+ """The teacher already has a class with this name."""
22
+
23
+
24
+ class MemberExists(ValueError):
25
+ """The email already belongs to a class."""
26
+
27
+
28
+ def _now() -> str:
29
+ return datetime.now(timezone.utc).isoformat()
30
+
31
+
32
+ class InMemoryStore:
33
+ def __init__(self) -> None:
34
+ self._lock = threading.Lock()
35
+ self._ids = itertools.count(1)
36
+ self._classes: dict[int, dict] = {}
37
+ self._members: dict[str, dict] = {} # email -> row
38
+
39
+ def create_class(self, teacher_email: str, name: str) -> dict:
40
+ with self._lock:
41
+ if any(c["teacher_email"] == teacher_email and c["name"].lower() == name.lower() for c in self._classes.values()):
42
+ raise ClassExists(name)
43
+ row = {"id": next(self._ids), "name": name, "teacher_email": teacher_email, "created_at": _now()}
44
+ self._classes[row["id"]] = row
45
+ return dict(row)
46
+
47
+ def classes_of(self, teacher_email: str) -> list[dict]:
48
+ with self._lock:
49
+ rows = [c for c in self._classes.values() if c["teacher_email"] == teacher_email]
50
+ return [{**c, "students": sum(1 for m in self._members.values() if m["class_id"] == c["id"])} for c in rows]
51
+
52
+ def get_class(self, class_id: int) -> dict | None:
53
+ with self._lock:
54
+ row = self._classes.get(class_id)
55
+ return dict(row) if row else None
56
+
57
+ def members(self, class_id: int) -> list[dict]:
58
+ with self._lock:
59
+ rows = [m for m in self._members.values() if m["class_id"] == class_id]
60
+ return [{"email": m["email"], "user_id": m["user_id"], "added_at": m["added_at"]}
61
+ for m in sorted(rows, key=lambda m: m["added_at"])]
62
+
63
+ def membership(self, email: str) -> dict | None:
64
+ with self._lock:
65
+ row = self._members.get(email)
66
+ if not row:
67
+ return None
68
+ return {**row, "class_name": self._classes[row["class_id"]]["name"]}
69
+
70
+ def add_member(self, class_id: int, email: str) -> None:
71
+ with self._lock:
72
+ if email in self._members:
73
+ raise MemberExists(email)
74
+ self._members[email] = {"class_id": class_id, "email": email, "user_id": None, "added_at": _now()}
75
+
76
+ def remove_member(self, class_id: int, email: str) -> bool:
77
+ with self._lock:
78
+ row = self._members.get(email)
79
+ if not row or row["class_id"] != class_id:
80
+ return False
81
+ del self._members[email]
82
+ return True
83
+
84
+ def link_user(self, email: str, user_id: str) -> None:
85
+ with self._lock:
86
+ row = self._members.get(email)
87
+ if row and not row["user_id"]:
88
+ row["user_id"] = user_id
89
+
90
+
91
+ class SupabaseStore:
92
+ def __init__(self, url: str, secret: str) -> None:
93
+ self.url, self.secret = url.rstrip("/"), secret
94
+
95
+ def _request(self, method: str, table: str, params: dict[str, str] | None = None, body: dict | None = None,
96
+ returning: bool = False):
97
+ query = "&".join(f"{k}={urllib.parse.quote(v, safe='(),.*:')}" for k, v in (params or {}).items())
98
+ headers = {"apikey": self.secret, "Authorization": f"Bearer {self.secret}", "User-Agent": "mathly2/1.0",
99
+ "Content-Type": "application/json"}
100
+ if returning:
101
+ headers["Prefer"] = "return=representation"
102
+ data = json.dumps(body).encode() if body is not None else None
103
+ request = urllib.request.Request(f"{self.url}/rest/v1/{table}" + (f"?{query}" if query else ""),
104
+ data=data, method=method, headers=headers)
105
+ try:
106
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
107
+ raw = response.read()
108
+ except urllib.error.HTTPError as exc:
109
+ if exc.code == 409:
110
+ raise
111
+ raise StoreUnavailable(f"supabase answered {exc.code} for {method} {table}") from exc
112
+ except (urllib.error.URLError, TimeoutError) as exc:
113
+ raise StoreUnavailable(str(exc)) from exc
114
+ return json.loads(raw) if raw else None
115
+
116
+ @staticmethod
117
+ def _eq(value) -> str:
118
+ return f"eq.{value}"
119
+
120
+ def create_class(self, teacher_email: str, name: str) -> dict:
121
+ try:
122
+ rows = self._request("POST", "m2_classes", body={"teacher_email": teacher_email, "name": name}, returning=True)
123
+ except urllib.error.HTTPError as exc:
124
+ raise ClassExists(name) from exc
125
+ return rows[0]
126
+
127
+ def classes_of(self, teacher_email: str) -> list[dict]:
128
+ rows = self._request("GET", "m2_classes", {"teacher_email": self._eq(teacher_email),
129
+ "select": "id,name,teacher_email,created_at,m2_class_members(count)", "order": "created_at"})
130
+ return [{**{k: r[k] for k in ("id", "name", "teacher_email", "created_at")},
131
+ "students": (r.get("m2_class_members") or [{"count": 0}])[0]["count"]} for r in rows]
132
+
133
+ def get_class(self, class_id: int) -> dict | None:
134
+ rows = self._request("GET", "m2_classes", {"id": self._eq(class_id), "select": "id,name,teacher_email,created_at"})
135
+ return rows[0] if rows else None
136
+
137
+ def members(self, class_id: int) -> list[dict]:
138
+ return self._request("GET", "m2_class_members", {"class_id": self._eq(class_id),
139
+ "select": "email,user_id,added_at", "order": "added_at"})
140
+
141
+ def membership(self, email: str) -> dict | None:
142
+ rows = self._request("GET", "m2_class_members", {"email": self._eq(email),
143
+ "select": "class_id,email,user_id,added_at,m2_classes(name)"})
144
+ if not rows:
145
+ return None
146
+ row = rows[0]
147
+ return {**{k: row[k] for k in ("class_id", "email", "user_id", "added_at")}, "class_name": row["m2_classes"]["name"]}
148
+
149
+ def add_member(self, class_id: int, email: str) -> None:
150
+ try:
151
+ self._request("POST", "m2_class_members", body={"class_id": class_id, "email": email})
152
+ except urllib.error.HTTPError as exc:
153
+ raise MemberExists(email) from exc
154
+
155
+ def remove_member(self, class_id: int, email: str) -> bool:
156
+ rows = self._request("DELETE", "m2_class_members", {"class_id": self._eq(class_id), "email": self._eq(email)},
157
+ returning=True)
158
+ return bool(rows)
159
+
160
+ def link_user(self, email: str, user_id: str) -> None:
161
+ self._request("PATCH", "m2_class_members", {"email": self._eq(email), "user_id": "is.null"}, {"user_id": user_id})
mathly2/supabase/migrations/20261107090000_m2_classes.sql ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Mathly 2: classes and their students. Additive (new tables only). Read and written only by the server with
2
+ -- the secret key: row-level security is on, there are no policies, and the browser roles get no grants.
3
+ begin;
4
+ create table public.m2_classes (
5
+ id bigint generated always as identity primary key,
6
+ name text not null check (char_length(name) between 1 and 60),
7
+ teacher_email text not null check (teacher_email = lower(teacher_email)),
8
+ created_at timestamptz not null default now()
9
+ );
10
+ create unique index m2_classes_teacher_name on public.m2_classes (teacher_email, lower(name));
11
+
12
+ -- A student belongs to one class at a time: the email is unique. user_id is filled at the student's first sign-in.
13
+ create table public.m2_class_members (
14
+ class_id bigint not null references public.m2_classes(id) on delete cascade,
15
+ email text primary key check (email = lower(email) and char_length(email) between 3 and 254),
16
+ user_id uuid,
17
+ added_at timestamptz not null default now()
18
+ );
19
+ create index m2_class_members_class on public.m2_class_members (class_id);
20
+ create index m2_class_members_user on public.m2_class_members (user_id) where user_id is not null;
21
+
22
+ alter table public.m2_classes enable row level security;
23
+ alter table public.m2_class_members enable row level security;
24
+ revoke all on public.m2_classes, public.m2_class_members from public, anon, authenticated;
25
+ grant all on public.m2_classes, public.m2_class_members to service_role;
26
+ commit;
mathly2/tests/__init__.py ADDED
File without changes
mathly2/tests/conftest.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Tests run without Supabase regardless of the developer's local environment."""
2
+ import os
3
+
4
+ for name in ("SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SECRET_KEY", "TEACHER_EMAILS"):
5
+ os.environ[name] = ""
mathly2/tests/serve.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the app on a free port in a background thread, for browser tests."""
2
+ from __future__ import annotations
3
+
4
+ import socket
5
+ import threading
6
+ import time
7
+ from contextlib import contextmanager
8
+
9
+ import uvicorn
10
+
11
+
12
+ @contextmanager
13
+ def running(app):
14
+ with socket.socket() as probe:
15
+ probe.bind(("127.0.0.1", 0))
16
+ port = probe.getsockname()[1]
17
+ server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
18
+ thread = threading.Thread(target=server.run, daemon=True)
19
+ thread.start()
20
+ for _ in range(100):
21
+ if server.started:
22
+ break
23
+ time.sleep(0.05)
24
+ try:
25
+ yield f"http://127.0.0.1:{port}"
26
+ finally:
27
+ server.should_exit = True
28
+ thread.join(timeout=5)
mathly2/tests/test_auth.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import json
3
+ import urllib.error
4
+
5
+ import pytest
6
+ from fastapi.testclient import TestClient
7
+
8
+ from mathly2 import auth
9
+ from mathly2.auth import AuthUnavailable, DevAuthenticator, SupabaseAuthenticator
10
+ from mathly2.config import Settings
11
+ from mathly2.main import create_app
12
+
13
+ TEACHER = "teacher@school.test"
14
+
15
+
16
+ @pytest.fixture
17
+ def client():
18
+ return TestClient(create_app(Settings(teachers=frozenset({TEACHER}))))
19
+
20
+
21
+ def sign(email):
22
+ return {"Authorization": f"Bearer dev:{email}"}
23
+
24
+
25
+ def test_no_token_is_refused(client):
26
+ assert client.get("/api/me").status_code == 401
27
+ assert client.get("/api/me", headers={"Authorization": "Bearer nonsense"}).status_code == 401
28
+ assert client.get("/api/me", headers={"Authorization": "Bearer dev:not-an-email"}).status_code == 401
29
+
30
+
31
+ def test_a_listed_teacher_is_a_teacher(client):
32
+ assert client.get("/api/me", headers=sign(TEACHER)).json() == {"email": TEACHER, "role": "teacher", "class": None}
33
+ assert client.get("/api/me", headers=sign("Teacher@School.test")).json()["role"] == "teacher" # case does not matter
34
+
35
+
36
+ def test_everyone_else_is_a_student(client):
37
+ assert client.get("/api/me", headers=sign("kid@school.test")).json() == {"email": "kid@school.test", "role": "student", "class": None}
38
+
39
+
40
+ def test_page_carries_only_public_settings():
41
+ page = TestClient(create_app(Settings())).get("/").text
42
+ assert '"devSignIn": true' in page and "__CONFIG__" not in page
43
+ page = TestClient(create_app(Settings(supabase_url="https://p.test", supabase_key="pub", supabase_secret="SECRET-VALUE"))).get("/").text
44
+ assert '"supabaseKey": "pub"' in page and '"devSignIn": false' in page and "SECRET-VALUE" not in page
45
+
46
+
47
+ def test_half_configured_supabase_does_not_fall_back_to_dev_sign_in():
48
+ with pytest.raises(ValueError, match="all of SUPABASE_URL"):
49
+ create_app(Settings(supabase_url="https://p.test"))
50
+
51
+
52
+ def test_dev_sign_in_is_off_when_supabase_is_on():
53
+ app = create_app(Settings(supabase_url="https://p.test", supabase_key="pub", supabase_secret="sec"))
54
+ assert isinstance(app.state.authenticator, SupabaseAuthenticator)
55
+ assert TestClient(app).get("/api/me", headers=sign("kid@school.test")).status_code in (401, 503)
56
+
57
+
58
+ class Reply(io.BytesIO):
59
+ def __enter__(self): return self
60
+ def __exit__(self, *a): return False
61
+
62
+
63
+ def supabase_returns(monkeypatch, payload=None, error=None):
64
+ calls = []
65
+
66
+ def fake(request, timeout=0):
67
+ calls.append(request)
68
+ if error:
69
+ raise error
70
+ return Reply(json.dumps(payload).encode())
71
+ monkeypatch.setattr(auth.urllib.request, "urlopen", fake)
72
+ return calls
73
+
74
+
75
+ def test_supabase_user_is_checked_with_the_token_and_cached(monkeypatch):
76
+ calls = supabase_returns(monkeypatch, {"id": "u1", "email": "Kid@School.test", "email_confirmed_at": "2026-01-01"})
77
+ a = SupabaseAuthenticator("https://p.test", "pub")
78
+ assert a.user("tok") == {"id": "u1", "email": "kid@school.test"}
79
+ assert a.user("tok")["id"] == "u1"
80
+ assert len(calls) == 1 and calls[0].headers["Authorization"] == "Bearer tok"
81
+
82
+
83
+ def test_an_unconfirmed_email_is_not_trusted(monkeypatch):
84
+ supabase_returns(monkeypatch, {"id": "u1", "email": TEACHER})
85
+ assert SupabaseAuthenticator("https://p.test", "pub").user("tok") is None
86
+
87
+
88
+ def test_rejected_token_and_outage(monkeypatch):
89
+ supabase_returns(monkeypatch, error=urllib.error.HTTPError("u", 401, "no", {}, None))
90
+ assert SupabaseAuthenticator("https://p.test", "pub").user("bad") is None
91
+ supabase_returns(monkeypatch, error=urllib.error.URLError("down"))
92
+ with pytest.raises(AuthUnavailable):
93
+ SupabaseAuthenticator("https://p.test", "pub").user("tok")
94
+
95
+
96
+ def test_outage_gives_503(monkeypatch):
97
+ class Down:
98
+ def user(self, token): raise AuthUnavailable("down")
99
+ app = create_app(Settings(), authenticator=Down())
100
+ assert TestClient(app).get("/api/me", headers={"Authorization": "Bearer x"}).status_code == 503
mathly2/tests/test_bank.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+
4
+ import pytest
5
+
6
+ from mathly2.bank import BANK_PATH, BankError, check_bank, load_bank
7
+
8
+
9
+ @pytest.fixture(scope="module")
10
+ def raw():
11
+ return json.loads(BANK_PATH.read_text(encoding="utf-8"))
12
+
13
+
14
+ def test_real_bank_is_sound_and_has_the_expected_size():
15
+ bank = load_bank()
16
+ assert (len(bank.lessons), len(bank.skills), len(bank.mistakes)) == (24, 96, 244)
17
+ assert sum(len(s.get("questions", [])) for s in bank.skills) == 1050
18
+
19
+
20
+ def broken(raw, change):
21
+ data = copy.deepcopy(raw)
22
+ change(data)
23
+ return check_bank(data)
24
+
25
+
26
+ def test_duplicate_skill_id(raw):
27
+ problems = broken(raw, lambda d: d["skills"][1].update(id=d["skills"][0]["id"]))
28
+ assert any("duplicate skill id" in p for p in problems)
29
+
30
+
31
+ def test_question_with_two_correct_choices(raw):
32
+ def change(d):
33
+ d["skills"][0]["questions"][0]["choices"][1]["correct"] = True
34
+ assert any("2 correct choices" in p for p in broken(raw, change))
35
+
36
+
37
+ def test_question_with_no_correct_choice(raw):
38
+ def change(d):
39
+ for c in d["skills"][0]["questions"][0]["choices"]:
40
+ c.pop("correct", None)
41
+ assert any("0 correct choices" in p for p in broken(raw, change))
42
+
43
+
44
+ def test_unknown_mistake_on_a_choice(raw):
45
+ def change(d):
46
+ d["skills"][0]["questions"][0]["choices"][1]["mistake"] = "nope"
47
+ assert any("unknown mistake 'nope'" in p for p in broken(raw, change))
48
+
49
+
50
+ def test_mistake_pointing_back_to_a_missing_skill(raw):
51
+ def change(d):
52
+ d["mistakes"][next(iter(d["mistakes"]))]["back"] = "missing_skill"
53
+ assert any("missing_skill" in p for p in broken(raw, change))
54
+
55
+
56
+ def test_empty_back_is_allowed_but_a_wrong_one_is_not(raw):
57
+ def change(d):
58
+ d["mistakes"][next(iter(d["mistakes"]))]["back"] = ""
59
+ assert broken(raw, change) == []
60
+
61
+
62
+ def test_skill_in_a_missing_lesson(raw):
63
+ assert any("unknown lesson" in p for p in broken(raw, lambda d: d["skills"][0].update(unit="zz")))
64
+
65
+
66
+ def test_missing_section_is_reported(raw):
67
+ assert check_bank({"units": []}) == ["missing 'skills'"]
68
+
69
+
70
+ def test_broken_bank_stops_loading(tmp_path, raw):
71
+ raw = copy.deepcopy(raw)
72
+ raw["skills"][0]["unit"] = "zz"
73
+ path = tmp_path / "bank.json"
74
+ path.write_text(json.dumps(raw), encoding="utf-8")
75
+ with pytest.raises(BankError, match="unknown lesson"):
76
+ load_bank(path)
mathly2/tests/test_classes.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from fastapi.testclient import TestClient
3
+
4
+ from mathly2.classes import parse_emails
5
+ from mathly2.config import Settings
6
+ from mathly2.main import create_app
7
+
8
+ T1, T2 = "t1@school.test", "t2@school.test"
9
+
10
+
11
+ @pytest.fixture
12
+ def client():
13
+ return TestClient(create_app(Settings(teachers=frozenset({T1, T2}))))
14
+
15
+
16
+ def auth(email):
17
+ return {"Authorization": f"Bearer dev:{email}"}
18
+
19
+
20
+ def make_class(client, teacher=T1, name="ט'3"):
21
+ return client.post("/api/classes", json={"name": name}, headers=auth(teacher))
22
+
23
+
24
+ def test_parse_emails_handles_pasted_lists():
25
+ valid, invalid = parse_emails(" A@x.test, b@x.test;\nc@x.test a@x.test not-an-email ")
26
+ assert valid == ["a@x.test", "b@x.test", "c@x.test"] and invalid == ["not-an-email"]
27
+
28
+
29
+ def test_teacher_creates_and_lists_classes(client):
30
+ created = make_class(client)
31
+ assert created.status_code == 201 and created.json()["name"] == "ט'3"
32
+ assert client.get("/api/classes", headers=auth(T1)).json() == [{"id": created.json()["id"], "name": "ט'3", "students": 0}]
33
+ assert client.get("/api/classes", headers=auth(T2)).json() == []
34
+
35
+
36
+ def test_class_name_is_trimmed_checked_and_unique(client):
37
+ assert make_class(client, name=" ח' 1 ").json()["name"] == "ח' 1"
38
+ assert make_class(client, name="ח' 1").status_code == 409
39
+ assert make_class(client, name=" ").status_code == 422
40
+ assert make_class(client, name="x" * 61).status_code == 422
41
+
42
+
43
+ def test_students_cannot_use_class_endpoints(client):
44
+ kid = auth("kid@school.test")
45
+ assert client.get("/api/classes", headers=kid).status_code == 403
46
+ assert client.post("/api/classes", json={"name": "A"}, headers=kid).status_code == 403
47
+ assert client.get("/api/classes").status_code == 401
48
+
49
+
50
+ def test_add_a_list_of_students(client):
51
+ cid = make_class(client).json()["id"]
52
+ emails = "\n".join(f"s{i}@school.test" for i in range(25))
53
+ result = client.post(f"/api/classes/{cid}/students", json={"emails": emails}, headers=auth(T1)).json()
54
+ assert len(result["added"]) == 25 and not result["elsewhere"] and not result["invalid"]
55
+ shown = client.get(f"/api/classes/{cid}", headers=auth(T1)).json()
56
+ assert len(shown["students"]) == 25 and shown["students"][0] == {"email": "s0@school.test", "signed_in": False}
57
+ assert client.get("/api/classes", headers=auth(T1)).json()[0]["students"] == 25
58
+
59
+
60
+ def test_student_in_another_class_is_reported_not_added_twice(client):
61
+ a = make_class(client, name="A").json()["id"]
62
+ b = make_class(client, T2, "B").json()["id"]
63
+ client.post(f"/api/classes/{a}/students", json={"emails": "s@school.test"}, headers=auth(T1))
64
+ result = client.post(f"/api/classes/{b}/students", json={"emails": "s@school.test new@school.test"}, headers=auth(T2)).json()
65
+ assert result["elsewhere"] == [{"email": "s@school.test", "class_name": "A"}] and result["added"] == ["new@school.test"]
66
+ again = client.post(f"/api/classes/{a}/students", json={"emails": "s@school.test"}, headers=auth(T1)).json()
67
+ assert again["already_here"] == ["s@school.test"] and not again["added"]
68
+
69
+
70
+ def test_a_teacher_cannot_touch_another_teachers_class(client):
71
+ cid = make_class(client).json()["id"]
72
+ assert client.get(f"/api/classes/{cid}", headers=auth(T2)).status_code == 404
73
+ assert client.post(f"/api/classes/{cid}/students", json={"emails": "s@school.test"}, headers=auth(T2)).status_code == 404
74
+ assert client.delete(f"/api/classes/{cid}/students/s@school.test", headers=auth(T2)).status_code == 404
75
+
76
+
77
+ def test_remove_a_student(client):
78
+ cid = make_class(client).json()["id"]
79
+ client.post(f"/api/classes/{cid}/students", json={"emails": "s@school.test"}, headers=auth(T1))
80
+ assert client.delete(f"/api/classes/{cid}/students/S@school.test", headers=auth(T1)).status_code == 204
81
+ assert client.delete(f"/api/classes/{cid}/students/s@school.test", headers=auth(T1)).status_code == 404
82
+ assert client.get(f"/api/classes/{cid}", headers=auth(T1)).json()["students"] == []
83
+
84
+
85
+ def test_too_many_emails_in_one_go(client):
86
+ cid = make_class(client).json()["id"]
87
+ emails = " ".join(f"s{i}@school.test" for i in range(201))
88
+ assert client.post(f"/api/classes/{cid}/students", json={"emails": emails}, headers=auth(T1)).status_code == 422
mathly2/tests/test_clock.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date, datetime, timezone
2
+
3
+ import pytest
4
+
5
+ from mathly2 import clock
6
+
7
+
8
+ def utc(*args):
9
+ return datetime(*args, tzinfo=timezone.utc)
10
+
11
+
12
+ def test_just_before_midnight_in_israel_is_still_today():
13
+ # 2026-11-10 21:59 UTC = 23:59 in Israel (UTC+2 in winter)
14
+ assert clock.school_day(utc(2026, 11, 10, 21, 59)) == date(2026, 11, 10)
15
+
16
+
17
+ def test_just_after_midnight_in_israel_is_tomorrow():
18
+ # 2026-11-10 22:01 UTC = 00:01 on the 11th in Israel
19
+ assert clock.school_day(utc(2026, 11, 10, 22, 1)) == date(2026, 11, 11)
20
+
21
+
22
+ def test_summer_time_shifts_the_boundary():
23
+ # UTC+3 in summer: 21:00 UTC is already the next day
24
+ assert clock.school_day(utc(2026, 7, 10, 20, 59)) == date(2026, 7, 10)
25
+ assert clock.school_day(utc(2026, 7, 10, 21, 0)) == date(2026, 7, 11)
26
+
27
+
28
+ def test_naive_time_is_refused():
29
+ with pytest.raises(ValueError):
30
+ clock.school_day(datetime(2026, 11, 10, 12, 0))
31
+
32
+
33
+ def test_now_has_a_timezone():
34
+ assert clock.now().tzinfo is not None
mathly2/tests/test_content_gaps.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mathly2.bank import load_bank
2
+ from mathly2.scripts.content_gaps import find_gaps
3
+
4
+
5
+ def test_real_bank_gaps():
6
+ gaps = find_gaps(load_bank().data)
7
+ assert len(gaps["skills without a worked example"]) == 96
8
+ assert len(gaps["skills without faded examples"]) == 96
9
+ assert len(gaps["lessons without a quiz"]) == 20
10
+ assert len(gaps["skills without questions"]) == 1
11
+ assert len(gaps["mistakes without a skill to go back to"]) == 204
12
+
13
+
14
+ def test_a_skill_with_an_example_and_all_steps_explained_is_not_listed():
15
+ data = {"units": [{"id": "u", "quiz": {"questions": []}}],
16
+ "skills": [{"id": "s", "unit": "u", "questions": [{}] * 10,
17
+ "worked_example": {"steps": [{"why": ["a", "b"]}]}, "faded_examples": [{}]}],
18
+ "mistakes": {}}
19
+ assert all(not items for items in find_gaps(data).values())
20
+
21
+
22
+ def test_step_without_why_is_listed():
23
+ data = {"units": [], "skills": [{"id": "s", "unit": "u", "worked_example": {"steps": [{"why": ["a"]}, {}]}}],
24
+ "mistakes": {}}
25
+ assert find_gaps(data)["worked-example steps without 'why this step?' choices"] == ["s step 2"]
mathly2/tests/test_health.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi.testclient import TestClient
2
+
3
+ from mathly2.main import create_app
4
+
5
+
6
+ def test_health():
7
+ response = TestClient(create_app()).get("/api/health")
8
+ assert response.status_code == 200
9
+ assert response.json() == {"ok": True}
mathly2/tests/test_lessons.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi.testclient import TestClient
2
+
3
+ from mathly2.config import Settings
4
+ from mathly2.main import create_app
5
+
6
+
7
+ def test_lessons_list_has_every_lesson_and_skill_but_no_questions():
8
+ lessons = TestClient(create_app(Settings(teachers=frozenset({"t@school.test"})))).get("/api/lessons", headers={"Authorization": "Bearer dev:t@school.test"}).json()
9
+ assert len(lessons) == 24
10
+ assert sum(len(lesson["skills"]) for lesson in lessons) == 96
11
+ assert "questions" not in lessons[0]["skills"][0]
12
+ assert lessons[0]["name"] == "טכניקה אלגברית 1"
13
+ assert sum(l["has_quiz"] for l in lessons) == 4
14
+
15
+
16
+ def test_lessons_need_sign_in():
17
+ assert TestClient(create_app()).get("/api/lessons").status_code == 401
mathly2/tests/test_migrations.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Apply the migrations to a real local PostgreSQL and check the browser roles cannot touch the tables."""
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ psycopg = pytest.importorskip("psycopg")
7
+ pgserver = pytest.importorskip("pgserver")
8
+
9
+ MIGRATIONS = sorted((Path(__file__).parent.parent / "supabase" / "migrations").glob("*.sql"))
10
+
11
+
12
+ @pytest.fixture(scope="module")
13
+ def db(tmp_path_factory):
14
+ server = pgserver.get_server(tmp_path_factory.mktemp("postgres") / "data", cleanup_mode="delete")
15
+ with psycopg.connect(server.get_uri(), autocommit=True) as c:
16
+ c.execute("create role anon; create role authenticated; create role service_role bypassrls;")
17
+ c.execute("grant usage on schema public to anon, authenticated, service_role;")
18
+ for path in MIGRATIONS:
19
+ c.execute(path.read_text(encoding="utf-8"))
20
+ yield server.get_uri()
21
+ server.cleanup()
22
+
23
+
24
+ def as_role(uri, role, sql, *params):
25
+ with psycopg.connect(uri, autocommit=True) as c:
26
+ c.execute(f"set role {role}")
27
+ return c.execute(sql, params).fetchall() if sql.lstrip().lower().startswith("select") else c.execute(sql, params)
28
+
29
+
30
+ def test_server_role_can_use_the_tables(db):
31
+ as_role(db, "service_role", "insert into public.m2_classes(name, teacher_email) values ('ט''3', 't@school.test')")
32
+ rows = as_role(db, "service_role", "select name from public.m2_classes")
33
+ assert rows == [("ט'3",)]
34
+
35
+
36
+ @pytest.mark.parametrize("role", ["authenticated", "anon"])
37
+ def test_browser_roles_are_refused(db, role):
38
+ with pytest.raises(psycopg.errors.InsufficientPrivilege):
39
+ as_role(db, role, "insert into public.m2_classes(name, teacher_email) values ('x', 'a@b.test')")
40
+ with pytest.raises(psycopg.errors.InsufficientPrivilege):
41
+ as_role(db, role, "select * from public.m2_class_members")
42
+
43
+
44
+ def test_row_level_security_is_on_and_has_no_policies(db):
45
+ with psycopg.connect(db, autocommit=True) as c:
46
+ on = dict(c.execute("select relname, relrowsecurity from pg_class where relname in ('m2_classes','m2_class_members')").fetchall())
47
+ policies = c.execute("select count(*) from pg_policies where tablename like 'm2_%'").fetchone()[0]
48
+ assert on == {"m2_classes": True, "m2_class_members": True}
49
+ assert policies == 0
50
+
51
+
52
+ def test_a_student_email_can_belong_to_only_one_class(db):
53
+ with psycopg.connect(db, autocommit=True) as c:
54
+ c.execute("insert into public.m2_classes(name, teacher_email) values ('ח''1', 't@school.test')")
55
+ ids = [r[0] for r in c.execute("select id from public.m2_classes order by id").fetchall()]
56
+ c.execute("insert into public.m2_class_members(class_id, email) values (%s, 's@school.test')", (ids[0],))
57
+ with pytest.raises(psycopg.errors.UniqueViolation):
58
+ c.execute("insert into public.m2_class_members(class_id, email) values (%s, 's@school.test')", (ids[1],))
59
+ with pytest.raises(psycopg.errors.CheckViolation):
60
+ c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'UPPER@school.test')", (ids[0],))
mathly2/tests/test_no_content_before_sign_in.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Every /api route except health refuses a caller without a valid token. The routes are read from the app itself,
2
+ so an endpoint added later is covered without touching this test."""
3
+ import re
4
+
5
+ import pytest
6
+ from fastapi.testclient import TestClient
7
+
8
+ from mathly2.config import Settings
9
+ from mathly2.main import create_app
10
+
11
+ PUBLIC = {"/api/health"}
12
+
13
+
14
+ def api_routes(app):
15
+ # Read from the OpenAPI schema: app.routes does not list routes added with include_router.
16
+ for path, methods in app.openapi()["paths"].items():
17
+ if path.startswith("/api"):
18
+ for method in sorted(methods):
19
+ yield method.upper(), path
20
+
21
+
22
+ @pytest.fixture(scope="module")
23
+ def app():
24
+ return create_app(Settings(teachers=frozenset({"t@school.test"})))
25
+
26
+
27
+ def test_there_are_routes_to_check(app):
28
+ assert len(list(api_routes(app))) >= 8
29
+ assert ('DELETE', '/api/classes/{class_id}/students/{email}') in set(api_routes(app))
30
+
31
+
32
+ @pytest.mark.parametrize("headers", [{}, {"Authorization": "Bearer "}, {"Authorization": "Bearer dev:nobody"}, {"Authorization": "Basic abc"}])
33
+ def test_every_api_route_refuses_a_caller_without_a_valid_token(app, headers):
34
+ client = TestClient(app)
35
+ for method, path in api_routes(app):
36
+ if path in PUBLIC:
37
+ continue
38
+ url = re.sub(r"\{[^}]*\}", "1", path)
39
+ response = client.request(method, url, headers=headers, json={} if method in ("POST", "PUT", "PATCH") else None)
40
+ assert response.status_code == 401, f"{method} {path} answered {response.status_code} without a token"
41
+
42
+
43
+ def test_health_stays_public(app):
44
+ assert TestClient(app).get("/api/health").status_code == 200
45
+
46
+
47
+ def test_no_secret_in_the_page():
48
+ page = TestClient(create_app(Settings(supabase_url="https://p.test", supabase_key="pub", supabase_secret="SECRET-VALUE"))).get("/")
49
+ assert "SECRET-VALUE" not in page.text
mathly2/tests/test_shell_browser.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ playwright = pytest.importorskip("playwright.sync_api")
4
+
5
+ from mathly2.main import create_app
6
+ from mathly2.tests.serve import running
7
+
8
+
9
+ def test_phone_shell_is_rtl_hebrew_and_does_not_scroll_sideways():
10
+ with running(create_app()) as url, playwright.sync_playwright() as p:
11
+ browser = p.chromium.launch()
12
+ page = browser.new_page(viewport={"width": 390, "height": 844})
13
+ page.goto(url)
14
+ assert page.get_attribute("html", "dir") == "rtl"
15
+ assert page.get_attribute("html", "lang") == "he"
16
+ page.wait_for_selector("#app .card")
17
+ assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
18
+ browser.close()
19
+
20
+
21
+ def test_dollar_math_is_drawn_as_a_formula():
22
+ with running(create_app()) as url, playwright.sync_playwright() as p:
23
+ browser = p.chromium.launch()
24
+ page = browser.new_page(viewport={"width": 390, "height": 844})
25
+ page.goto(url)
26
+ page.wait_for_function("typeof (window.MathJax && window.MathJax.tex2svg) === 'function'", timeout=30000)
27
+ page.evaluate("""async () => {
28
+ const { fmt } = await import('/static/math.js');
29
+ const box = document.createElement('p');
30
+ box.id = 'probe';
31
+ box.innerHTML = fmt('פתחו: $x² − 2x − 15$ ו־$(x + 3)(x − 5)$');
32
+ document.body.append(box);
33
+ }""")
34
+ page.wait_for_selector("#probe span.m.m-img svg", timeout=10000)
35
+ assert page.locator("#probe span.m.m-img").count() == 2
36
+ assert page.get_attribute("#probe span.m.m-img >> nth=0", "aria-label") == "x² − 2x − 15"
37
+ browser.close()
38
+
39
+
40
+ def test_dev_sign_in_then_sign_out():
41
+ app = create_app(__import__("mathly2.config", fromlist=["Settings"]).Settings(teachers=frozenset({"t@school.test"})))
42
+ with running(app) as url, playwright.sync_playwright() as p:
43
+ browser = p.chromium.launch()
44
+ page = browser.new_page(viewport={"width": 390, "height": 844})
45
+ page.goto(url)
46
+ page.wait_for_selector("#signin form#dev") # signed out: only the sign-in screen
47
+ assert "מיומנויות" not in page.inner_text("body")
48
+ page.fill("#email", "kid@school.test")
49
+ page.click("#dev button")
50
+ page.wait_for_selector("#nav #out")
51
+ assert page.inner_text("#nav").startswith("kid@school.test")
52
+ page.click("#out")
53
+ page.wait_for_selector("#signin")
54
+ browser.close()
55
+
56
+
57
+ def test_teacher_creates_a_class_and_adds_three_students():
58
+ from mathly2.config import Settings
59
+ app = create_app(Settings(teachers=frozenset({"t@school.test"})))
60
+ with running(app) as url, playwright.sync_playwright() as p:
61
+ browser = p.chromium.launch()
62
+ page = browser.new_page(viewport={"width": 390, "height": 844})
63
+ page.goto(url)
64
+ page.fill("#email", "t@school.test")
65
+ page.click("#dev button")
66
+ page.wait_for_selector("#new-class")
67
+ page.fill("#class-name", "ט'3")
68
+ page.click("#new-class button")
69
+ page.wait_for_selector("#classes li")
70
+ page.click("#classes a")
71
+ page.wait_for_selector("#add")
72
+ page.fill("#emails", "a@school.test, b@school.test\nc@school.test")
73
+ page.click("#add button")
74
+ page.wait_for_selector("#students li")
75
+ assert page.locator("#students li").count() == 3
76
+ assert "נוספו 3 תלמידים" in page.inner_text("#report")
77
+ assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
78
+ page.fill("#emails", "a@school.test d@school.test")
79
+ page.click("#add button")
80
+ page.wait_for_selector("#students li >> nth=3")
81
+ assert "כבר היו בכיתה" in page.inner_text("#report")
82
+ page.click("[data-remove='a@school.test']")
83
+ page.wait_for_function("document.querySelectorAll('#students li').length === 3")
84
+ browser.close()
85
+
86
+
87
+ def test_student_not_in_a_class_sees_the_ask_your_teacher_message_with_their_email():
88
+ with running(create_app()) as url, playwright.sync_playwright() as p:
89
+ browser = p.chromium.launch()
90
+ page = browser.new_page(viewport={"width": 390, "height": 844})
91
+ page.goto(url)
92
+ page.fill("#email", "new.kid@school.test")
93
+ page.click("#dev button")
94
+ page.wait_for_selector("#no-class")
95
+ assert "new.kid@school.test" in page.inner_text("#no-class")
96
+ assert "מיומנויות" not in page.inner_text("body")
97
+ browser.close()
mathly2/tests/test_store.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import urllib.error
2
+
3
+ import pytest
4
+
5
+ from mathly2.store import ClassExists, InMemoryStore, MemberExists, SupabaseStore
6
+
7
+
8
+ @pytest.fixture
9
+ def store():
10
+ return InMemoryStore()
11
+
12
+
13
+ def test_classes_belong_to_their_teacher(store):
14
+ a = store.create_class("t1@x.test", "ט'3")
15
+ store.create_class("t2@x.test", "ח'1")
16
+ assert [c["name"] for c in store.classes_of("t1@x.test")] == ["ט'3"]
17
+ assert store.get_class(a["id"])["teacher_email"] == "t1@x.test"
18
+ assert store.get_class(999) is None
19
+
20
+
21
+ def test_class_names_are_unique_per_teacher_ignoring_case(store):
22
+ store.create_class("t@x.test", "Alef")
23
+ with pytest.raises(ClassExists):
24
+ store.create_class("t@x.test", "alef")
25
+ store.create_class("other@x.test", "Alef")
26
+
27
+
28
+ def test_a_student_belongs_to_one_class(store):
29
+ a, b = store.create_class("t@x.test", "A")["id"], store.create_class("t@x.test", "B")["id"]
30
+ store.add_member(a, "s@x.test")
31
+ with pytest.raises(MemberExists):
32
+ store.add_member(b, "s@x.test")
33
+ assert store.membership("s@x.test")["class_name"] == "A"
34
+ assert store.classes_of("t@x.test")[0]["students"] == 1
35
+
36
+
37
+ def test_remove_member_only_from_its_own_class(store):
38
+ a, b = store.create_class("t@x.test", "A")["id"], store.create_class("t@x.test", "B")["id"]
39
+ store.add_member(a, "s@x.test")
40
+ assert store.remove_member(b, "s@x.test") is False
41
+ assert store.remove_member(a, "s@x.test") is True
42
+ assert store.membership("s@x.test") is None
43
+
44
+
45
+ def test_link_user_sets_it_once(store):
46
+ a = store.create_class("t@x.test", "A")["id"]
47
+ store.add_member(a, "s@x.test")
48
+ store.link_user("s@x.test", "u1")
49
+ store.link_user("s@x.test", "u2")
50
+ assert store.membership("s@x.test")["user_id"] == "u1"
51
+ store.link_user("nobody@x.test", "u3") # no such member: ignored
52
+
53
+
54
+ class Recorder(SupabaseStore):
55
+ """SupabaseStore with the network replaced by canned answers; records what it would have sent."""
56
+ def __init__(self, answers):
57
+ super().__init__("https://p.supabase.test", "secret")
58
+ self.answers, self.calls = list(answers), []
59
+
60
+ def _request(self, method, table, params=None, body=None, returning=False):
61
+ self.calls.append((method, table, params, body, returning))
62
+ answer = self.answers.pop(0)
63
+ if isinstance(answer, Exception):
64
+ raise answer
65
+ return answer
66
+
67
+
68
+ def conflict():
69
+ return urllib.error.HTTPError("u", 409, "conflict", {}, None)
70
+
71
+
72
+ def test_supabase_store_requests():
73
+ s = Recorder([[{"id": 1, "name": "A", "teacher_email": "t@x.test", "created_at": "z"}],
74
+ [{"id": 1, "name": "A", "teacher_email": "t@x.test", "created_at": "z", "m2_class_members": [{"count": 3}]}],
75
+ [{"class_id": 1, "email": "s@x.test", "user_id": None, "added_at": "z", "m2_classes": {"name": "A"}}],
76
+ [{"email": "s@x.test"}], []])
77
+ assert s.create_class("t@x.test", "A")["id"] == 1
78
+ assert s.classes_of("t@x.test")[0]["students"] == 3
79
+ assert s.membership("s@x.test")["class_name"] == "A"
80
+ assert s.remove_member(1, "s@x.test") is True
81
+ assert s.remove_member(1, "s@x.test") is False
82
+ assert s.calls[0][:2] == ("POST", "m2_classes") and s.calls[0][3] == {"teacher_email": "t@x.test", "name": "A"}
83
+ assert s.calls[3][2] == {"class_id": "eq.1", "email": "eq.s@x.test"}
84
+
85
+
86
+ def test_supabase_store_turns_conflicts_into_domain_errors():
87
+ with pytest.raises(ClassExists):
88
+ Recorder([conflict()]).create_class("t@x.test", "A")
89
+ with pytest.raises(MemberExists):
90
+ Recorder([conflict()]).add_member(1, "s@x.test")
91
+
92
+
93
+ def test_supabase_link_only_fills_an_empty_user_id():
94
+ s = Recorder([None])
95
+ s.link_user("s@x.test", "u1")
96
+ assert s.calls[0][2] == {"email": "eq.s@x.test", "user_id": "is.null"}
mathly2/tests/test_student_class.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from fastapi.testclient import TestClient
3
+
4
+ from mathly2.config import Settings
5
+ from mathly2.main import create_app
6
+ from mathly2.store import InMemoryStore
7
+
8
+ TEACHER, KID = "t@school.test", "kid@school.test"
9
+
10
+
11
+ def auth(email):
12
+ return {"Authorization": f"Bearer dev:{email}"}
13
+
14
+
15
+ @pytest.fixture
16
+ def setup():
17
+ store = InMemoryStore()
18
+ client = TestClient(create_app(Settings(teachers=frozenset({TEACHER})), store=store))
19
+ return client, store
20
+
21
+
22
+ def test_student_in_no_class_gets_no_class_and_no_lessons(setup):
23
+ client, _ = setup
24
+ me = client.get("/api/me", headers=auth(KID)).json()
25
+ assert me == {"email": KID, "role": "student", "class": None}
26
+ assert client.get("/api/lessons", headers=auth(KID)).status_code == 403
27
+
28
+
29
+ def test_first_sign_in_links_the_account_to_the_class_entry(setup):
30
+ client, store = setup
31
+ cid = client.post("/api/classes", json={"name": "ט'3"}, headers=auth(TEACHER)).json()["id"]
32
+ client.post(f"/api/classes/{cid}/students", json={"emails": KID}, headers=auth(TEACHER))
33
+ assert client.get(f"/api/classes/{cid}", headers=auth(TEACHER)).json()["students"][0]["signed_in"] is False
34
+ me = client.get("/api/me", headers=auth(KID)).json()
35
+ assert me["class"] == {"id": cid, "name": "ט'3"}
36
+ assert store.membership(KID)["user_id"]
37
+ assert client.get(f"/api/classes/{cid}", headers=auth(TEACHER)).json()["students"][0]["signed_in"] is True
38
+ assert len(client.get("/api/lessons", headers=auth(KID)).json()) == 24
39
+
40
+
41
+ def test_a_removed_student_loses_the_lessons(setup):
42
+ client, _ = setup
43
+ cid = client.post("/api/classes", json={"name": "A"}, headers=auth(TEACHER)).json()["id"]
44
+ client.post(f"/api/classes/{cid}/students", json={"emails": KID}, headers=auth(TEACHER))
45
+ assert client.get("/api/lessons", headers=auth(KID)).status_code == 200
46
+ client.delete(f"/api/classes/{cid}/students/{KID}", headers=auth(TEACHER))
47
+ assert client.get("/api/lessons", headers=auth(KID)).status_code == 403
48
+
49
+
50
+ def test_teacher_has_no_class_and_still_sees_lessons(setup):
51
+ client, _ = setup
52
+ assert client.get("/api/me", headers=auth(TEACHER)).json()["class"] is None
53
+ assert client.get("/api/lessons", headers=auth(TEACHER)).status_code == 200
openspec/changes/add-assignment-worksheets/design.md DELETED
@@ -1,71 +0,0 @@
1
- # Design
2
-
3
- ## Context
4
-
5
- - Assignments live in `math_assignments` (`app/assignments.py`): `items` is a jsonb array validated by `clean_assignment` against the class's units, 1 to 20 items. The class teacher or a manager writes them (`class_row`); students read them through `GET /api/math/assignments`.
6
- - Completion is not stored. `assignmentState(a, P, sittings, now)` in `static/math-sky.js` works it out from the progress and the unit-quiz sittings. It is called on the student's home, in the report tab, and in the "needs attention" signal.
7
- - Images already have a safe path: `clean_image` in `app/answer_scans.py` checks type, size and pixel count, re-encodes to JPEG and drops metadata. `app/unit_resources.py` keeps teacher photos in a private Supabase bucket, read and written only with the service key, with a restrictive storage policy.
8
- - Unreferenced answer images are removed by the hourly `python -m app.answer_cleanup`.
9
- - There is no PDF handling in the project today.
10
-
11
- ## Goals / Non-Goals
12
-
13
- **Goals:**
14
- - A worksheet is just another assignment item, so the card, the report, the "needs attention" signal and the late rule all work for it without special cases.
15
- - Every file goes through the server: no public URLs and no storage paths in the browser.
16
- - The feature switches off cleanly when the migration is missing.
17
-
18
- **Non-Goals:**
19
- - AI checking of worksheets.
20
- - Writing on the worksheet in the app (annotating the PDF). Students solve on paper and photograph.
21
- - Teacher annotations on the submission photos. The teacher gives a score and a comment only.
22
- - Returning a checked submission for another try. A later change can add "return for correction".
23
- - Push notifications for new worksheets or checks.
24
- - Reusing a worksheet across classes or assignments. Each upload belongs to one class.
25
-
26
- ## Decisions
27
-
28
- **Item format: `{kind: "worksheet", id}`.** The id points to a row of `math_worksheets`. `clean_assignment` gets the class's worksheet ids and accepts a worksheet item only when its id belongs to the same class. At most 5 worksheet items per assignment, within the existing 20-item limit. An assignment can be only a worksheet. Alternative considered: a separate `worksheets` list next to `items`. Rejected because then every consumer of `items` (the card, the report, the continue button, the attention signal) would need a second path.
29
-
30
- **Upload first, then save the assignment.** `POST /api/classes/{class_id}/worksheets` (multipart: title, files) stores the worksheet with `class_id` and returns `{id, title, pages}`. The form then saves the assignment with the item. A worksheet that no assignment uses for 24 hours is deleted by the hourly cleanup, the same idea as orphan answer images. Alternative considered: upload into an existing assignment (`/assignments/{aid}/worksheets`). Rejected because a new assignment has no id until it is saved, and the form would need two saves.
31
-
32
- **Removing a worksheet.** When an assignment update drops a worksheet item, or the assignment is deleted, the server deletes the worksheet row, its submissions (cascade) and their files. The form shows the number of submissions in its confirmation, from the report data it already has.
33
-
34
- **Tables (migration `<ts>_math_worksheets.sql`).**
35
- - `math_worksheets(id uuid, class_id bigint references classes on delete cascade, title text ≤80, source text check in ('pdf','images'), pages int 1..10, original_key text null, page_keys text[], byte_size int, created_by_email, created_at)`.
36
- - `math_worksheet_submissions(id uuid, worksheet_id uuid references math_worksheets on delete cascade, student_id uuid, student_email text, page_keys text[] 1..10, submitted_at timestamptz, checked_at timestamptz null, score int null check 0..100, comment text ≤1000 default '', checked_by_email text default '', unique(worksheet_id, student_id))`.
37
- - Both service-only (RLS on, all grants revoked from anon/authenticated), like `math_assignments`.
38
- - Bucket `mathly-worksheets`: private, `image/jpeg` and `application/pdf`, 10 MB limit, with a restrictive policy like `mathly-resources`. Keys: `w/<worksheet id>/<n>.jpg`, `w/<worksheet id>/original.pdf`, `s/<worksheet id>/<student id>/<random>/<n>.jpg`.
39
-
40
- **PDF pages rendered on the server with `pypdfium2`.** Phones do not show PDFs inline the same way: Android Chrome downloads them. The server checks the file (starts with `%PDF-`, ≤10 MB, opens, ≤10 pages), renders each page to JPEG at about 1600 px wide, and stores the pages and the original. Rendering runs in the thread pool, with a time limit per page. `pypdfium2` ships a self-contained PDFium wheel, so no system packages are needed on the Space. Alternatives considered: `pdf.js` in the browser (a large vendored library and more work per phone), or PDF only through download (poor on phones).
41
-
42
- **Photos reuse `clean_image`.** Teacher photos and student submissions go through `clean_image` (5 MB, JPEG/PNG/WebP, re-encoded, metadata dropped). The student's phone sends the photos as they are. The hand-in sheet reuses the camera/file picker of the open-answer flow (`static/answer-scans.js`), without its AI step.
43
-
44
- **Routes (`app/worksheets.py`).**
45
- - Teacher (class teacher or manager, same `class_row` rule): `POST /api/classes/{cid}/worksheets`; `GET /api/classes/{cid}/worksheets/{wid}/submissions/{sid}/pages/{n}`; `PUT /api/classes/{cid}/worksheets/{wid}/submissions/{sid}` with `{score, comment}` (sets `checked_at` the first time, keeps it after that).
46
- - Class members and the class teacher: `GET /api/math/worksheets/{wid}/pages/{n}` (JPEG) and `GET /api/math/worksheets/{wid}/original` (PDF worksheets only; for a photo worksheet the download button saves the page images one by one). The worksheet's class must be one of the account's classes, or the account its teacher or a manager; otherwise 404.
47
- - Student: `PUT /api/math/worksheets/{wid}/submission` (multipart files) creates or replaces their submission, refused with 409 `already_checked` after a check; `GET /api/math/worksheets/{wid}/submission/pages/{n}` reads their own pages.
48
- - Pages are served with `Cache-Control: private, max-age=3600`.
49
-
50
- **Data for the page.** `GET /api/math/assignments` adds `worksheets` (`{id, title, pages, source}` for the worksheets in the returned assignments) and `submissions` (the student's own: `{worksheet_id, pages, submitted_at, checked_at, score, comment}`). The report adds the same per student (`worksheet_submissions`) and the worksheets of the class.
51
-
52
- **Completion.** `assignmentState(a, P, server, now)`: the third argument becomes `{sittings, submissions}`. A bare array is still read as `sittings`, so a caller that was not updated keeps working. A worksheet item is done at its submission's `submitted_at`; `known` is false when `submissions` is null (the server could not read them), as for unit quizzes. The three callers pass the new object.
53
-
54
- **Actions log.** `worksheet_added`, `worksheet_submitted`, `worksheet_checked` go to the monitoring feed (`app/monitoring.py` `MON_ACTIONS`), like the assignment actions.
55
-
56
- **Unavailable.** If the tables or bucket are missing, worksheet routes answer 503 `worksheets_unavailable`. The class report and `/api/math/assignments` return `worksheets: null`; the form hides the worksheet option, and a worksheet item whose data is missing shows as "דף העבודה לא זמין" and counts as not known.
57
-
58
- ## Risks / Trade-offs
59
-
60
- - [Parsing untrusted PDFs] → Only class teachers and managers can upload; size, page and time limits; PDFium is maintained and fuzzed. The rendered JPEGs are what students see; the original is only downloaded.
61
- - [Storage and egress] → Up to 10 pages per submission, re-encoded to ≤2400 px JPEG (~300–600 KB). A class of 30 with 5 worksheets a month is in the low GB per year. If egress becomes a concern, submissions can move to the Hugging Face bucket used for answers (`MATHLY_ANSWER_BUCKET`) in a later change.
62
- - [Large uploads on weak phone connections] → The hand-in sheet shows progress, keeps the chosen photos when sending fails, and lets the student try again.
63
- - [Teacher removes a worksheet students already handed in] → Confirmation names the number of submissions.
64
- - [Students cannot fix a checked submission] → Deliberate for now (see Non-Goals). The teacher can still change the score and comment.
65
-
66
- ## Migration Plan
67
-
68
- 1. Add `pypdfium2` to `requirements.txt`.
69
- 2. Apply the additive migration (two tables and the bucket).
70
- 3. Deploy. Without the migration, worksheets are switched off and assignments work as before.
71
- 4. Rollback: previous code. The tables and bucket can stay; old code never reads worksheet items, but it would reject saving an assignment that has one (unknown item kind), so teachers should not edit those assignments until the code is back.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
openspec/changes/add-assignment-worksheets/proposal.md DELETED
@@ -1,39 +0,0 @@
1
- # Proposal
2
-
3
- ## Why
4
-
5
- Assignments (`add-class-assignments`) can only point at practice that already exists in the app: a skill, a unit quiz or a practice exam. Most homework is still a worksheet the teacher wrote or photocopied, handed out on paper or in a WhatsApp group, and collected in class. The teacher cannot give it through Mathly, and cannot see in the משימות tab who handed it in. Letting the teacher attach a worksheet to an assignment, and letting students hand in a photo of their solution, brings that homework into the same place.
6
-
7
- ## What Changes
8
-
9
- - New assignment item kind: **worksheet (דף עבודה)**. In the assignment form the class teacher (or a manager) uploads a PDF (up to 10 pages) or 1 to 10 photos, with a short title. An assignment can have up to 5 worksheets next to its other items.
10
- - A PDF is turned into page images on the server, so every phone shows it the same way. The original PDF is kept so it can be downloaded and printed.
11
- - Students open the worksheet from the **"משימות מהמורה"** card: its pages are shown one under the other, with a button to download the original.
12
- - Students **hand in** their solution as 1 to 10 photos. Until the teacher checks it, the student can replace the submission. After the due date, a submission is still accepted and marked late.
13
- - A worksheet item is **done** when the student has handed in. It is late when handed in after the Jerusalem end of the due date (same rule as the other items).
14
- - In the class report's **"משימות"** tab, the teacher sees for each worksheet who handed in, who is late and who is missing, and how many submissions are waiting to be checked. The teacher opens a submission, sees its pages, and marks it **checked**, with an optional score (0–100) and an optional comment.
15
- - The student sees the check on the assignment card: "נבדק", the score and the comment. A checked submission can no longer be replaced.
16
- - No AI check of worksheets.
17
- - The user guide (both tabs) and README describe the feature.
18
-
19
- ## Capabilities
20
-
21
- ### New Capabilities
22
-
23
- - `assignment-worksheets`: worksheets a class teacher attaches to an assignment, how students open them and hand in a solution, and how the teacher checks submissions.
24
-
25
- ### Modified Capabilities
26
-
27
- (none: there are no main specs yet. `class-assignments` is still an open change. The new item kind and its completion rule are specified in this capability.)
28
-
29
- ## Impact
30
-
31
- - New migration `<ts>_math_worksheets.sql`: tables `math_worksheets` and `math_worksheet_submissions` (service-only, deleted with their class), and a private storage bucket `mathly-worksheets`.
32
- - New module `app/worksheets.py`: upload, read and delete routes for the teacher, read and hand-in routes for students, the check route, and cleanup of worksheets that no assignment uses.
33
- - `app/assignments.py`: `clean_assignment` accepts `{kind: "worksheet", id}` items that belong to the class. Deleting an assignment, or removing a worksheet from it, removes the worksheet and its submissions.
34
- - `app/class_report.py` and `GET /api/math/assignments`: return worksheet submissions (status, times, score, comment), but not storage paths.
35
- - `static/math-sky.js` `assignmentState`: the worksheet item. `static/math.js`: upload in the assignment form, worksheet viewer, hand-in sheet, submission review in the report. `static/math.css`, `static/guide.js`, `README.md`.
36
- - New dependency `pypdfium2` (PDF to page images, self-contained wheel).
37
- - `app/answer_cleanup.py` (hourly job): also removes worksheets that no assignment uses after 24 hours.
38
- - Tests: new `tests/test_worksheets.py`, browser tests for the teacher and student flows, `tests/test_sky_browser.py` for the completion rule.
39
- - Depends on `add-class-assignments` (in place).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
openspec/changes/add-assignment-worksheets/specs/assignment-worksheets/spec.md DELETED
@@ -1,122 +0,0 @@
1
- # Spec Delta
2
-
3
- ## Purpose
4
-
5
- Lets a class teacher hand out a worksheet (a PDF or photos) as part of an assignment, lets students open it and hand in a photographed solution, and lets the teacher check each submission.
6
-
7
- ## ADDED Requirements
8
-
9
- ### Requirement: Class teacher attaches a worksheet to an assignment
10
- The class teacher of a class, or a manager, SHALL be able to add a worksheet item to an assignment of that class. The worksheet has a title of up to 80 characters and is one PDF of up to 10 pages and 10 MB, or 1 to 10 photos (JPEG, PNG or WebP, up to 5 MB each). An assignment SHALL have at most 5 worksheet items. Any other account MUST be refused.
11
-
12
- #### Scenario: Teacher attaches a PDF
13
- - **WHEN** the teacher of 9א uploads a 3-page PDF titled "דף עבודה – פיתגורס" and saves the assignment with it
14
- - **THEN** the assignment has a worksheet item with that title and 3 pages
15
-
16
- #### Scenario: Teacher attaches photos
17
- - **WHEN** the teacher uploads 2 photos as one worksheet
18
- - **THEN** the worksheet has 2 pages, in the order they were chosen
19
-
20
- #### Scenario: File refused
21
- - **WHEN** the teacher uploads a PDF of 11 pages, a file over the size limit, or a file that is not a PDF or an image
22
- - **THEN** the server refuses it with an error naming the limit, and nothing is stored
23
-
24
- #### Scenario: Not the class teacher
25
- - **WHEN** a student or a teacher of another class tries to upload a worksheet for 9א
26
- - **THEN** the server refuses with a forbidden error
27
-
28
- #### Scenario: Worksheet of another class
29
- - **WHEN** an assignment of 9א is saved with a worksheet item uploaded for 9ב
30
- - **THEN** the server rejects the assignment
31
-
32
- ### Requirement: Worksheet files stay private
33
- Worksheet files and submission photos SHALL be readable only through the server, by the class's students (worksheets), the student who handed in (their own submission), and the class teacher or a manager. Responses to the browser MUST NOT contain storage paths. Uploaded images SHALL be stored without their metadata (such as location).
34
-
35
- #### Scenario: Student of another class
36
- - **WHEN** a student who is not in 9א asks for a page of a 9א worksheet
37
- - **THEN** the server answers not found
38
-
39
- #### Scenario: Another student's submission
40
- - **WHEN** a student asks for a page of a classmate's submission
41
- - **THEN** the server answers not found
42
-
43
- ### Requirement: Students open the worksheet
44
- A student SHALL be able to open each worksheet of their classes' assignments from the assignment card, see its pages one under the other, and download the original file (the PDF, or the photos).
45
-
46
- #### Scenario: Student opens a PDF worksheet
47
- - **WHEN** a student of 9א opens "דף עבודה – פיתגורס" from "משימות מהמורה"
48
- - **THEN** the 3 pages are shown as images, with a button to download the PDF
49
-
50
- ### Requirement: Students hand in a solution
51
- A student SHALL be able to hand in a solution to a worksheet as 1 to 10 photos. Until the teacher checks the submission, the student SHALL be able to replace it with a new set of photos; the new set replaces the old one. A submission after the due date SHALL be accepted.
52
-
53
- #### Scenario: Hand in
54
- - **WHEN** a student photographs 2 pages of their solution and sends them
55
- - **THEN** the submission is stored with 2 pages and the time it was handed in
56
-
57
- #### Scenario: Replace before the check
58
- - **WHEN** a student who handed in sends a new set of photos before the teacher checked
59
- - **THEN** only the new set is kept, with the new time
60
-
61
- #### Scenario: Replace after the check
62
- - **WHEN** a student tries to hand in again after the teacher checked the submission
63
- - **THEN** the server refuses, and the checked submission stays as it was
64
-
65
- #### Scenario: Not in the class
66
- - **WHEN** a student who is not in 9א tries to hand in a 9א worksheet
67
- - **THEN** the server answers not found
68
-
69
- ### Requirement: Worksheet item completion
70
- A worksheet item SHALL be done for a student when the student has a submission for it. It SHALL be late when it was handed in after the end of the due date, Jerusalem time. The same rule SHALL be used on the student's card and in the teacher's report.
71
-
72
- #### Scenario: Handed in on time
73
- - **WHEN** the due date is 12/11 and the student handed in on 12/11 at 22:00 Jerusalem time
74
- - **THEN** the item is done and not late
75
-
76
- #### Scenario: Handed in late
77
- - **WHEN** the student handed in on 13/11
78
- - **THEN** the item is done late
79
-
80
- #### Scenario: Not handed in
81
- - **WHEN** the student opened the worksheet but did not hand in
82
- - **THEN** the item is not done
83
-
84
- ### Requirement: Teacher follows and checks submissions
85
- In the class report's assignments tab, the teacher SHALL see for each worksheet which students handed in (on time or late), which are missing, and how many submissions wait for a check. The teacher SHALL be able to open a submission, see its pages, and mark it checked with an optional score from 0 to 100 and an optional comment of up to 1000 characters. The teacher SHALL be able to change the score and comment later.
86
-
87
- #### Scenario: Waiting for a check
88
- - **WHEN** 3 of 20 students handed in and none was checked
89
- - **THEN** the worksheet shows 3 handed in, 17 missing and 3 waiting for a check
90
-
91
- #### Scenario: Teacher checks a submission
92
- - **WHEN** the teacher opens Dana's submission, gives 85 and writes "יפה, שימי לב ליחידות"
93
- - **THEN** the submission is checked, with that score and comment, and is no longer counted as waiting
94
-
95
- #### Scenario: Score out of range
96
- - **WHEN** the teacher sends a score of 120
97
- - **THEN** the server rejects it
98
-
99
- ### Requirement: Student sees the check
100
- After the teacher checks a submission, the student SHALL see on the assignment card that it was checked, with the score and the comment when given.
101
-
102
- #### Scenario: Checked with a comment
103
- - **WHEN** the teacher checked Dana's submission with 85 and a comment
104
- - **THEN** Dana's card shows "נבדק", 85 and the comment
105
-
106
- ### Requirement: Removing a worksheet removes its submissions
107
- When an assignment is deleted, or a worksheet item is removed from it, the worksheet, its files, and its submissions SHALL be deleted. The form SHALL ask for confirmation, naming how many students handed in. A worksheet uploaded but never saved into an assignment SHALL be deleted after 24 hours.
108
-
109
- #### Scenario: Worksheet removed from an assignment
110
- - **WHEN** the teacher removes a worksheet that 4 students handed in, and confirms
111
- - **THEN** the worksheet and the 4 submissions are gone, and the students no longer see the item
112
-
113
- #### Scenario: Upload never saved
114
- - **WHEN** the teacher uploads a worksheet and closes the form without saving
115
- - **THEN** the worksheet is deleted within a day
116
-
117
- ### Requirement: Works without the migration
118
- When the worksheet storage is not set up, the server SHALL answer worksheet routes with an "unavailable" error, the assignment form SHALL not offer worksheets, and the rest of assignments SHALL keep working.
119
-
120
- #### Scenario: Tables missing
121
- - **WHEN** the worksheet migration was not applied and a teacher opens the assignment form
122
- - **THEN** the form has no worksheet option, and assignments without worksheets save as before
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
openspec/changes/add-assignment-worksheets/tasks.md DELETED
@@ -1,38 +0,0 @@
1
- # Tasks
2
-
3
- ## 1. Storage
4
-
5
- - [x] 1.1 Add migration `<ts>_math_worksheets.sql`: `math_worksheets`, `math_worksheet_submissions` (cascade from class and worksheet, unique per worksheet and student, score 0–100, comment ≤1000), service-only grants, private bucket `mathly-worksheets` (JPEG and PDF, 10 MB) with a restrictive policy. Verify it applies on the local test database (pgserver) and that deleting a class removes its worksheets and submissions.
6
- - [x] 1.2 Add `pypdfium2` to `requirements.txt`. Verify `pip install -r requirements.txt` works and a 2-page test PDF renders to 2 JPEGs.
7
-
8
- ## 2. Server
9
-
10
- - [x] 2.1 Add `app/worksheets.py` with the storage adapter (rows and bucket through the service key, 503 `worksheets_unavailable` when missing) and file checks: PDF (header, ≤10 MB, ≤10 pages, render with time limit) and photos through `clean_image`. Verify in `tests/test_worksheets.py`: valid PDF, 11-page PDF, oversized file, non-PDF with a .pdf name, 1 and 11 photos.
11
- - [x] 2.2 Add the teacher upload route `POST /api/classes/{cid}/worksheets` with the class-teacher-or-manager rule. Verify: class teacher 201, other teacher 403, student 403, response has no storage paths.
12
- - [x] 2.3 Accept `{kind: "worksheet", id}` in `clean_assignment` (same class, at most 5), and delete worksheets (rows, submissions, files) dropped by an assignment update or delete. Verify in `tests/test_assignments.py`: worksheet of another class rejected, 6 worksheets rejected, worksheet-only assignment accepted, removing the item deletes the worksheet and its submissions.
13
- - [x] 2.4 Add the page and original routes for class members and the class teacher. Verify: a class student reads pages and the PDF, a student of another class gets 404, the original of a photo worksheet is 404.
14
- - [x] 2.5 Add the student hand-in route (create or replace, 409 `already_checked` after a check) and the route to read their own pages. Verify: hand in, replace before check keeps only the new pages and removes the old files, replace after check refused, another student's pages 404, student outside the class 404.
15
- - [x] 2.6 Add the teacher's submission page route and the check route (`score` 0–100 or empty, `comment` ≤1000, `checked_at` set once). Verify: check, change later keeps the first `checked_at`, score 120 rejected, other teacher 403.
16
- - [x] 2.7 Add `worksheets` and the student's `submissions` to `GET /api/math/assignments`, and the class's worksheets and each student's `worksheet_submissions` to the class report. Verify both answers in tests, with `null` when the tables are missing and no storage paths ever.
17
- - [x] 2.8 Record `worksheet_added`, `worksheet_submitted`, `worksheet_checked` in the actions log. Verify in `tests/test_monitoring.py`.
18
- - [x] 2.9 Extend the hourly cleanup (`app/answer_cleanup.py`) to delete worksheets that no assignment uses after 24 hours, with their files. Verify with a test that an unused 25-hour-old worksheet is removed and a used one or a 1-hour-old one is kept.
19
-
20
- ## 3. Completion
21
-
22
- - [x] 3.1 Extend `assignmentState` in `static/math-sky.js` to take `{sittings, submissions}` (a bare array still read as sittings) and handle worksheet items (done at `submitted_at`, late after the Jerusalem end of the due date, not known when submissions are null). Update the three callers. Verify in `tests/test_sky_browser.py` with the spec's scenarios (on time at 22:00 on the due date, late, not handed in) and that existing assignment tests still pass.
23
-
24
- ## 4. Teacher UI
25
-
26
- - [x] 4.1 Add the worksheet option to the assignment form: title, choose a PDF or photos, upload progress, page count, remove; hidden when worksheets are unavailable. Removing a worksheet, or deleting the assignment, confirms with the number of students who handed in. Verify with a browser test that uploads a PDF, saves, and removes it with the confirmation.
27
- - [x] 4.2 In the report's "משימות" tab, show per worksheet: handed in, late, missing, waiting for a check; and per student a button that opens the submission (pages, score field, comment, save). Verify with a browser test on a 3-student fixture: open, check with a score and comment, counts update.
28
-
29
- ## 5. Student UI
30
-
31
- - [x] 5.1 Show worksheet items on the "משימות מהמורה" card, with a viewer (pages one under the other, download button). The continue button opens the viewer for a worksheet item. Verify with a browser test.
32
- - [x] 5.2 Add the hand-in sheet (take or choose 1–10 photos, reorder or remove, send with progress, keep photos on failure, replace before check) and show "הוגש", "נבדק", the score and the comment on the card. Verify with a browser test: hand in, replace, and see a check from a fixture.
33
- - [x] 5.3 Styles in `static/math.css` for the form, viewer, hand-in sheet and report, in light and dark and at phone width. Verify by screenshot in the browser tests at 390 px.
34
-
35
- ## 6. Docs and integration
36
-
37
- - [x] 6.1 Update `static/guide.js` (student: opening a worksheet and handing in; teacher: attaching a worksheet and checking) and `README.md` (feature, limits, migration, `pypdfium2`). Verify `tests/test_guide_browser.py` passes.
38
- - [x] 6.2 Run the full `pytest` suite and check locally end to end: the teacher attaches a PDF to an assignment, a student opens it and hands in 2 photos, the teacher checks with a score and comment, and the student sees it.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
openspec/changes/add-class-assignments/design.md DELETED
@@ -1,44 +0,0 @@
1
- # Design
2
-
3
- ## Context
4
-
5
- - Classes live in Supabase `classes` (`emails`, `teachers`, `lessons`, `exams` jsonb, `nicknames`), loaded and cached by `app/auth.py` `classes()`. The class exam board is a jsonb column edited by managers.
6
- - Skill completion is in the student's progress (`P.done`), practice exams in `P.quizzes[] {at, n, right, ms, units}`, and unit-quiz sittings on the server after `add-server-quiz-grades`.
7
- - The class report already loads every student's progress, so it can compute completion for each student in the page.
8
-
9
- ## Goals / Non-Goals
10
-
11
- **Goals:**
12
- - Assignments stored on the server per class, editable by the class teacher.
13
- - Completion computed from data that already exists, with no new student-side writes.
14
-
15
- **Non-Goals:**
16
- - Push notifications for new assignments (the existing push in `app/push.py` is scoped to scan requests; a later change can generalize it).
17
- - Assigning to individual students or groups (whole class only for now).
18
- - Grades for assignments.
19
-
20
- ## Decisions
21
-
22
- **Own table, not a jsonb column on `classes`.** `math_assignments(id uuid, class_id int references classes on delete cascade, title, note, due_on date, items jsonb, created_by_email, created_at, updated_at)`. A table keeps edits by the class teacher separate from the manager-owned class row (`save_class` rewrites the whole row) and allows per-assignment timestamps. Alternative considered: `classes.assignments` jsonb like `exams`. Rejected because concurrent edits by the manager and the teacher would overwrite each other.
23
-
24
- **Items format.** `[{kind:"skill", id}, {kind:"unit_quiz", unit}, {kind:"exam", units:[...]}]`, validated on the server against `app/math_algebra9.json` and the class's `lessons`. At most 20 items.
25
-
26
- **Routes (`app/assignments.py`).**
27
- - Teacher: `GET/POST /api/classes/{id}/assignments`, `PUT/DELETE /api/classes/{id}/assignments/{aid}`. The rule: the email is in the class's `teachers`, or the account has `management.access` (same as the class report).
28
- - Student: `GET /api/math/assignments` returns the assignments of all the student's classes with `due_on` in the last 14 days or later, plus the student's unit-quiz sitting times (from `math_quiz_sittings`) so the page can decide unit-quiz completion without another call.
29
-
30
- **Completion computed in the page.** One pure function `assignmentState(assignment, progress, sittings, now)` is used on the student's home and in the report, so both always agree. Due date is the end of `due_on` in Asia/Jerusalem. "Done late" uses the item's completion time where one exists (`P.done[id]`, sitting `submitted_at`, exam `at`).
31
-
32
- **Report.** The report endpoint adds `assignments` for the class and each student's `quiz_sittings` (already added by `add-server-quiz-grades`). The "needs attention" signal list from `add-class-attention-view` gets one more signal fed by `assignmentState`.
33
-
34
- ## Risks / Trade-offs
35
-
36
- - [Skill completion is device-reported] → Same trust level as the rest of the practice data, and labelled as such in the report.
37
- - [A teacher deletes an assignment students were working on] → The form asks for confirmation and states how many students already started it.
38
- - [Time zone at the due-date boundary] → Due dates are dates, and late means after 23:59 Jerusalem time on that date.
39
-
40
- ## Migration Plan
41
-
42
- 1. Apply the additive migration.
43
- 2. Deploy. Without the table, the routes return 503 `assignments_unavailable`, the student card is hidden and the report tab says assignments are unavailable.
44
- 3. Rollback: previous code. The table can stay.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
openspec/changes/add-class-assignments/proposal.md DELETED
@@ -1,39 +0,0 @@
1
- # Proposal
2
-
3
- ## Why
4
-
5
- The teacher can watch the class but cannot ask it to do anything in the app. Homework still happens outside Mathly, so the path's skills, the unit quizzes and the practice exams are disconnected from what the teacher planned for the week. Students decide alone what to practise, and the teacher has no way to check that "practise Pythagoras before Thursday" happened. Assignments make the teacher's plan part of the student's path and give the teacher a reason to open the report.
6
-
7
- ## What Changes
8
-
9
- - The class teacher (or a manager) can create an **assignment (משימה)** for a class: a title, an optional note, a due date, and one or more items:
10
- - **skills** to finish (from the class's units),
11
- - a **unit quiz** to submit,
12
- - a **practice exam** to take over chosen units.
13
- - The teacher can edit or delete an assignment. Students see changes the next time they load.
14
- - Students see **"משימות מהמורה"** on their home screen above the path: each open assignment with its due date, the items, how many are done, and a button that opens the next unfinished item. Overdue assignments are marked. Finished ones move to a "done" list for 14 days.
15
- - Skills on the path that belong to an open assignment get a small marker.
16
- - An item is done when:
17
- - a skill: the skill is finished (at any time, including before the assignment),
18
- - a unit quiz: a sitting for the unit was submitted after the assignment was created (server record from `add-server-quiz-grades`),
19
- - a practice exam: a practice exam covering all the chosen units was taken after the assignment was created.
20
- - The class report gets an **"משימות"** tab: each assignment with how many students finished it, and per student which items are done, late or missing. Students with an overdue unfinished assignment are added to the "needs attention" list (from `add-class-attention-view`).
21
-
22
- ## Capabilities
23
-
24
- ### New Capabilities
25
-
26
- - `class-assignments`: assignments a class teacher gives a class (items, due date), how students see and complete them, and how the teacher follows them.
27
-
28
- ### Modified Capabilities
29
-
30
- (none: there are no main specs yet. The attention signal for overdue assignments is specified here, as a requirement on this capability.)
31
-
32
- ## Impact
33
-
34
- - New migration `<ts>_math_assignments.sql`: table `math_assignments`, service-only.
35
- - New module `app/assignments.py`: CRUD routes for the class teacher and managers, and a read route for students (assignments of their classes).
36
- - `static/math.js`: the teacher's create/edit form, the "משימות" report tab, the student's home card and path markers, completion computed from progress and server sittings.
37
- - `static/math.css`, `static/guide.js` both tabs, `README.md`.
38
- - Tests: new `tests/test_assignments.py`, browser tests.
39
- - Depends on `add-server-quiz-grades` (unit-quiz items) and `add-class-attention-view` (attention signal). Without the latter the signal is simply not shown.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
openspec/changes/add-class-assignments/specs/class-assignments/spec.md DELETED
@@ -1,88 +0,0 @@
1
- # Spec Delta
2
-
3
- ## Purpose
4
-
5
- Lets a class teacher give their class practice to do in the app by a date, shows students what to do next, and shows the teacher who did it.
6
-
7
- ## ADDED Requirements
8
-
9
- ### Requirement: Class teacher creates assignments
10
- The class teacher of a class, or a manager, SHALL be able to create an assignment for that class with a title of up to 80 characters, an optional note of up to 500 characters, a due date, and at least one item. An item is a skill, a unit quiz, or a practice exam over chosen units, and it MUST belong to the class's units. Any other account MUST be refused.
11
-
12
- #### Scenario: Teacher creates an assignment
13
- - **WHEN** the teacher of 9א creates "חזרה לפני המבחן" due 12/11 with skills `g_pyth` and `g_pyth_word` and the unit quiz of unit `g`
14
- - **THEN** the assignment is stored for 9א with its three items and its due date
15
-
16
- #### Scenario: Item outside the class's units
17
- - **WHEN** the teacher adds a skill from a unit that is not open to the class
18
- - **THEN** the server rejects the assignment
19
-
20
- #### Scenario: Not the class teacher
21
- - **WHEN** a student or a teacher of another class tries to create an assignment for 9א
22
- - **THEN** the server refuses with a forbidden error
23
-
24
- #### Scenario: No items
25
- - **WHEN** the teacher saves an assignment with no items
26
- - **THEN** the server rejects it
27
-
28
- ### Requirement: Teacher edits and deletes assignments
29
- The class teacher or a manager SHALL be able to change an assignment's title, note, due date and items, or delete it. Students SHALL see the change the next time their page loads assignments.
30
-
31
- #### Scenario: Due date moved
32
- - **WHEN** the teacher moves the due date from 12/11 to 14/11
33
- - **THEN** students of the class see 14/11 after reloading
34
-
35
- #### Scenario: Assignment deleted
36
- - **WHEN** the teacher deletes an assignment
37
- - **THEN** it no longer appears to students or in the report
38
-
39
- ### Requirement: Students see their open assignments
40
- A student SHALL see on their home screen the assignments of their classes that are not finished, with title, note, due date, items, and how many items are done. An assignment past its due date and not finished SHALL be marked as late. Finished assignments SHALL appear in a separate done list for 14 days after their due date.
41
-
42
- #### Scenario: Open assignment
43
- - **WHEN** a student has an assignment with 3 items, 1 done, due in 2 days
44
- - **THEN** the home screen shows it with "1 מתוך 3" and the due date
45
-
46
- #### Scenario: Late assignment
47
- - **WHEN** the due date has passed and an item is not done
48
- - **THEN** the assignment is shown as late
49
-
50
- #### Scenario: Next item
51
- - **WHEN** the student presses the assignment's continue button
52
- - **THEN** the app opens the first unfinished item (the skill sheet, the unit quiz introduction or a practice exam set to the chosen units)
53
-
54
- ### Requirement: Item completion rules
55
- A skill item SHALL be done when the student has finished the skill, whenever that happened. A unit-quiz item SHALL be done when the server has a sitting of that unit's quiz from the student submitted after the assignment was created. A practice-exam item SHALL be done when the student took a practice exam after the assignment was created that included all the item's units.
56
-
57
- #### Scenario: Skill finished before the assignment
58
- - **WHEN** a student finished `g_pyth` last week and an assignment with `g_pyth` is created today
59
- - **THEN** that item is already done for the student
60
-
61
- #### Scenario: Old unit-quiz sitting
62
- - **WHEN** the student's only sitting of unit `g` was submitted before the assignment was created
63
- - **THEN** the unit-quiz item is not done
64
-
65
- #### Scenario: Practice exam missing a unit
66
- - **WHEN** the item asks for a practice exam over units `t` and `g`, and the student took one over `t` only
67
- - **THEN** the item is not done
68
-
69
- ### Requirement: Assigned skills are marked on the path
70
- Skills that are items of an open assignment SHALL carry a marker on the student's path, with an accessible label naming the assignment.
71
-
72
- #### Scenario: Marker
73
- - **WHEN** `g_pyth` is in an open assignment that the student has not finished
74
- - **THEN** its star on the path has the assignment marker
75
-
76
- ### Requirement: Teacher follows assignment completion
77
- The class report SHALL list the class's assignments with how many students finished each, and for each assignment the students with each item's state: done, not done, or done late (finished after the due date, for items with a completion time).
78
-
79
- #### Scenario: Teacher opens an assignment
80
- - **WHEN** the teacher opens "חזרה לפני המבחן" in the report's assignments tab
81
- - **THEN** they see "18 מתוך 27 סיימו" and a row per student showing which items are done
82
-
83
- ### Requirement: Overdue assignments raise attention
84
- A student with an assignment past its due date and not finished SHALL appear in the report's "needs attention" section, with a reason naming the assignment.
85
-
86
- #### Scenario: Overdue
87
- - **WHEN** a student has not finished an assignment whose due date was yesterday
88
- - **THEN** the student appears in "needs attention" with the reason naming that assignment