feat(push): implement admin notification system with audience targeting and broadcast capabilities
Browse files- app/main.py +41 -0
- app/push.py +23 -0
- openspec/changes/add-focused-learner-home/.openspec.yaml +2 -0
- openspec/changes/add-focused-learner-home/design.md +92 -0
- openspec/changes/add-focused-learner-home/proposal.md +33 -0
- openspec/changes/add-focused-learner-home/specs/learner-home/spec.md +105 -0
- openspec/changes/add-focused-learner-home/specs/progress-and-practice/spec.md +23 -0
- openspec/changes/add-focused-learner-home/tasks.md +42 -0
- static/index.html +55 -2
- tests/test_push.py +61 -0
app/main.py
CHANGED
|
@@ -2250,6 +2250,47 @@ def create_app(scorer: Scorer | None = None, tts: SawtakTTS | None = None,
|
|
| 2250 |
"title": "๐ ืืชืืืืจืืช ืคืืขืืืช"}
|
| 2251 |
return {"devices": len(rows), "sent": sum(p.send(r, message) for r in rows)}
|
| 2252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2253 |
@app.get("/api/library", dependencies=[Depends(require("library.view"))])
|
| 2254 |
def library(user: dict | None = Depends(signed_in)):
|
| 2255 |
"""The video library, which stands outside the path and is one for every level and class: id, title, url
|
|
|
|
| 2250 |
"title": "๐ ืืชืืืืจืืช ืคืืขืืืช"}
|
| 2251 |
return {"devices": len(rows), "sent": sum(p.send(r, message) for r in rows)}
|
| 2252 |
|
| 2253 |
+
def push_audience(a: SupabaseAuth, actor: dict | None, rows: list[dict]) -> tuple[dict[str, list[dict]], list[dict]]:
|
| 2254 |
+
"""An admin's reach: the subscriptions of each class they manage (its students and teachers), and those of
|
| 2255 |
+
"everyone": every subscription for a developer, else those of their classes together."""
|
| 2256 |
+
by_class = {}
|
| 2257 |
+
for c in managed_classes(a, actor, fresh=True):
|
| 2258 |
+
people = set(c["emails"]) | {e.lower() for e in c.get("teachers") or []}
|
| 2259 |
+
by_class[c["name"]] = [r for r in rows if r["email"] in people]
|
| 2260 |
+
developer = not actor or "developer" in actor.get("roles", ()) or not hasattr(a, "access_for")
|
| 2261 |
+
everyone = rows if developer else list({r["endpoint"]: r for v in by_class.values() for r in v}.values())
|
| 2262 |
+
return by_class, everyone
|
| 2263 |
+
|
| 2264 |
+
@app.get("/api/push/audience")
|
| 2265 |
+
def push_audience_counts(a: SupabaseAuth = Depends(admin_only), actor: dict | None = Depends(signed_in)):
|
| 2266 |
+
"""How many devices get an admin's message: {"all": n, "classes": {name: n}}."""
|
| 2267 |
+
p = push_on()
|
| 2268 |
+
try:
|
| 2269 |
+
by_class, everyone = push_audience(a, actor, p.every())
|
| 2270 |
+
except AuthUnavailable as e:
|
| 2271 |
+
raise HTTPException(503, str(e))
|
| 2272 |
+
return {"all": len(everyone), "classes": {name: len(v) for name, v in by_class.items()}}
|
| 2273 |
+
|
| 2274 |
+
@app.post("/api/push/broadcast")
|
| 2275 |
+
def push_broadcast(body: dict = Body(...), a: SupabaseAuth = Depends(admin_only), actor: dict | None = Depends(signed_in)):
|
| 2276 |
+
"""An admin's notification ({"title", "body", "class": a class's name, or "" for everyone}) sent now."""
|
| 2277 |
+
p = push_on()
|
| 2278 |
+
try:
|
| 2279 |
+
msg = pushes.message(str(body.get("title") or ""), str(body.get("body") or ""))
|
| 2280 |
+
except ValueError as e:
|
| 2281 |
+
raise HTTPException(400, str(e))
|
| 2282 |
+
target = str(body.get("class") or "")
|
| 2283 |
+
try:
|
| 2284 |
+
by_class, everyone = push_audience(a, actor, p.every())
|
| 2285 |
+
except AuthUnavailable as e:
|
| 2286 |
+
raise HTTPException(503, str(e))
|
| 2287 |
+
if target and target not in by_class:
|
| 2288 |
+
raise HTTPException(404, "no such class")
|
| 2289 |
+
rows = by_class[target] if target else everyone
|
| 2290 |
+
sent = p.send_many(rows, msg)
|
| 2291 |
+
a.log_event("push", actor, f"{msg['title']} โ {target or 'ืืืื'}", {"class": target, "devices": len(rows), "sent": sent})
|
| 2292 |
+
return {"devices": len(rows), "sent": sent}
|
| 2293 |
+
|
| 2294 |
@app.get("/api/library", dependencies=[Depends(require("library.view"))])
|
| 2295 |
def library(user: dict | None = Depends(signed_in)):
|
| 2296 |
"""The video library, which stands outside the path and is one for every level and class: id, title, url
|
app/push.py
CHANGED
|
@@ -127,6 +127,18 @@ class Push:
|
|
| 127 |
log.warning("push to %s failed: %s", row.get("email"), e)
|
| 128 |
return False
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
def mine(self, email: str) -> list[dict]:
|
| 131 |
return self._rows("&" + urllib.parse.urlencode({"email": f"eq.{email.lower()}"}))
|
| 132 |
|
|
@@ -144,6 +156,17 @@ class Push:
|
|
| 144 |
return sent
|
| 145 |
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
def payload(videos: list[dict]) -> dict:
|
| 148 |
"""What the service worker shows: the day's video (or how many there are)."""
|
| 149 |
body = videos[0]["title"] if len(videos) == 1 else f"{len(videos)} ืกืจืืื ืื ืืืฉืื: " + " ยท ".join(v["title"] for v in videos)
|
|
|
|
| 127 |
log.warning("push to %s failed: %s", row.get("email"), e)
|
| 128 |
return False
|
| 129 |
|
| 130 |
+
def every(self) -> list[dict]:
|
| 131 |
+
"""Every subscription (an admin's message goes to some of them)."""
|
| 132 |
+
return self._rows()
|
| 133 |
+
|
| 134 |
+
def send_many(self, rows: list[dict], message: dict) -> int:
|
| 135 |
+
"""One notification to each, a few at a time; how many went."""
|
| 136 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 137 |
+
if not rows:
|
| 138 |
+
return 0
|
| 139 |
+
with ThreadPoolExecutor(max_workers=min(8, len(rows))) as pool:
|
| 140 |
+
return sum(pool.map(lambda r: self.send(r, message), rows))
|
| 141 |
+
|
| 142 |
def mine(self, email: str) -> list[dict]:
|
| 143 |
return self._rows("&" + urllib.parse.urlencode({"email": f"eq.{email.lower()}"}))
|
| 144 |
|
|
|
|
| 156 |
return sent
|
| 157 |
|
| 158 |
|
| 159 |
+
MAX_TITLE, MAX_BODY = 60, 240
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def message(title: str, body: str) -> dict:
|
| 163 |
+
"""An admin's notification; ValueError when it is empty or too long. Each has its own tag, so one does not replace another."""
|
| 164 |
+
title, body = " ".join(title.split()), body.strip()
|
| 165 |
+
if not title or len(title) > MAX_TITLE or len(body) > MAX_BODY:
|
| 166 |
+
raise ValueError(f"a title of 1-{MAX_TITLE} characters, and a message of up to {MAX_BODY}")
|
| 167 |
+
return {"title": title, "body": body, "url": "/", "tag": f"msg-{datetime.now().timestamp():.0f}"}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
def payload(videos: list[dict]) -> dict:
|
| 171 |
"""What the service worker shows: the day's video (or how many there are)."""
|
| 172 |
body = videos[0]["title"] if len(videos) == 1 else f"{len(videos)} ืกืจืืื ืื ืืืฉืื: " + " ยท ".join(v["title"] for v in videos)
|
openspec/changes/add-focused-learner-home/.openspec.yaml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema: spec-driven
|
| 2 |
+
created: 2026-10-24
|
openspec/changes/add-focused-learner-home/design.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Design
|
| 2 |
+
|
| 3 |
+
## Context
|
| 4 |
+
|
| 5 |
+
See `proposal.md` for motivation. The browser currently chooses one active class, renders its entire path, marks the first unfinished topic as current, and scrolls that topic into view. Class selection is remembered locally by class name, while phrase scores are restored from the server for signed-in learners. Classes expose a list of lesson IDs but `/api/me` does not expose their IDs or any per-student, per-class navigation state.
|
| 6 |
+
|
| 7 |
+
Homework and ten-item daily practice already exist. The focused home should compose those capabilities rather than create a second progress system. Supabase is optional, so loss of server persistence must not make practice unavailable.
|
| 8 |
+
|
| 9 |
+
## Goals / Non-Goals
|
| 10 |
+
|
| 11 |
+
**Goals:**
|
| 12 |
+
|
| 13 |
+
- Establish a stable current lesson for each student/class pair before presenting recommendations.
|
| 14 |
+
- Make a small recommendation set the normal student entry point while retaining the full path.
|
| 15 |
+
- Synchronize the selection across devices without allowing a student to read or modify another student's state.
|
| 16 |
+
- Reuse existing progress, homework, topic-opening, and daily-practice behavior.
|
| 17 |
+
- Work in the existing single-page, mobile-first RTL interface with touch and keyboard.
|
| 18 |
+
|
| 19 |
+
**Non-Goals:**
|
| 20 |
+
|
| 21 |
+
- Letting a teacher set or override every student's current lesson.
|
| 22 |
+
- Automatically advancing the class lesson when one student completes it.
|
| 23 |
+
- Adding notification categories, schedules, or permission prompts.
|
| 24 |
+
- Replacing the existing path, homework model, completion rules, scoring, or paid tutor behavior.
|
| 25 |
+
|
| 26 |
+
## Decisions
|
| 27 |
+
|
| 28 |
+
### Store one current lesson per authenticated student and class
|
| 29 |
+
|
| 30 |
+
Add a server-managed `learner_class_state` table with `email`, `class_id`, `current_lesson`, and `updated_at`, unique on `(email, class_id)`. Keep row-level security enabled and revoke direct client roles, following the existing server-secret persistence pattern. The API derives the normalized email from the authenticated session; it never accepts an email from the request body.
|
| 31 |
+
|
| 32 |
+
Using the email matches current class membership and avoids introducing a second identity mapping in this change. A separate table is preferred to embedding selections in `classes`, because the state belongs to one learner and must not change the class for everyone. It is preferred to browser-only storage because signed-in progress is already expected to follow learners across devices.
|
| 33 |
+
|
| 34 |
+
### Return state with class bootstrap data and update it through a narrow endpoint
|
| 35 |
+
|
| 36 |
+
Include each class's stable numeric `id` and saved `current_lesson` in `/api/me`. Add `PUT /api/me/classes/{class_id}/current-lesson` with `{ "lesson": "<lesson-id>" }`.
|
| 37 |
+
|
| 38 |
+
The update endpoint must verify that the caller is a student member of the class, the class resolves to exactly one course level, and the lesson belongs to both that class and level. It upserts only the caller's row. Returning the state in `/api/me` avoids an extra startup request; a dedicated mutation keeps class administration separate from learner-owned state.
|
| 39 |
+
|
| 40 |
+
### Treat ambiguous class levels as a configuration error
|
| 41 |
+
|
| 42 |
+
The existing class model stores lesson IDs rather than a level field. Determine the class level from those lessons. If there are no resolvable lessons or they span multiple levels, onboarding shows a corrective message instead of guessing or exposing unrelated lessons. Existing classes are not rewritten automatically.
|
| 43 |
+
|
| 44 |
+
Adding a new `level` column to `classes` was considered, but it would duplicate information already encoded by the class lesson set and require a broader class migration. Enforcing a single-level invariant throughout class administration can be a follow-up if legacy data reveals ambiguity.
|
| 45 |
+
|
| 46 |
+
### Use account-scoped local fallback state
|
| 47 |
+
|
| 48 |
+
When the state endpoint is unavailable, keep the selected lesson in browser storage under a versioned key containing the subject, normalized signed-in email, and class ID. Server state wins when it is available. A locally saved selection may be retried on a later authenticated load if it is still valid for the class.
|
| 49 |
+
|
| 50 |
+
Do not use the current unscoped `ihki.class` pattern for lesson state: another account on the same device must not inherit it. Open mode has no authenticated student/class pair and continues to use the current path behavior rather than showing this onboarding.
|
| 51 |
+
|
| 52 |
+
### Build recommendations with a deterministic priority
|
| 53 |
+
|
| 54 |
+
Render no more than three distinct actions:
|
| 55 |
+
|
| 56 |
+
1. the nearest-due incomplete homework, when one exists;
|
| 57 |
+
2. the first unfinished activity in the selected current lesson;
|
| 58 |
+
3. a short review of up to five weak, previously practiced items, or another valid short activity from the current lesson.
|
| 59 |
+
|
| 60 |
+
Omit an action when its target cannot be opened. Do not silently fill the home with arbitrary later lessons. If the current lesson is complete, offer review plus a clear action to change the selected lesson. Existing topic and homework entry functions remain the execution paths, preventing recommendation state from becoming a second completion ledger.
|
| 61 |
+
|
| 62 |
+
The existing ten-sentence daily session remains available, but its new-material source prefers the selected current lesson after homework. The focused home's short activity is separately capped at five items so its displayed workload is truthful.
|
| 63 |
+
|
| 64 |
+
### Make the full path secondary and position by lesson
|
| 65 |
+
|
| 66 |
+
The focused home becomes the default student view after class selection and onboarding. A visible full-path action calls the existing path renderer with a lesson anchor. Position the selected lesson heading or its first unfinished topic in the viewport, even if an earlier lesson remains unfinished. Preserve navigation to all lessons assigned to the class.
|
| 67 |
+
|
| 68 |
+
### Keep onboarding separate from notification consent
|
| 69 |
+
|
| 70 |
+
Do not request browser notification permission during first-use onboarding. Reminder types and preferences need their own product and delivery rules; combining them with the required lesson question would add pressure and complexity to the learner's first task.
|
| 71 |
+
|
| 72 |
+
### Accessibility and interaction
|
| 73 |
+
|
| 74 |
+
Use native buttons or radios with Hebrew labels, an explicit confirmation action, visible focus, and a dialog or screen title announced to assistive technology. On opening, focus the prompt heading or selected option; after confirmation, focus the focused-home heading without unexpected scrolling. All controls must remain usable in RTL layout, by touch, and without a mouse. Respect reduced-motion settings when changing views or positioning the path.
|
| 75 |
+
|
| 76 |
+
## Risks / Trade-offs
|
| 77 |
+
|
| 78 |
+
- **[A student may choose the wrong lesson]** -> Keep a visible change-lesson action and never delete progress when the selection changes.
|
| 79 |
+
- **[Legacy classes may span multiple levels]** -> Detect ambiguity, show a corrective state, and avoid guessing; do not block unrelated class and teacher functions.
|
| 80 |
+
- **[Server persistence may fail after a local selection]** -> Keep account-scoped local state, continue learning, and retry only after validating it against current class data.
|
| 81 |
+
- **[Recommendations could duplicate the same homework/topic]** -> Deduplicate by target and apply the fixed priority order before rendering.
|
| 82 |
+
- **[A focused home can hide the learner's broader progress]** -> Keep the full path one explicit action away and preserve all existing progress visualization there.
|
| 83 |
+
- **[Email changes would orphan preference rows]** -> Accept this limitation because membership currently uses email; a future stable-user-ID migration should migrate this table with other learner-owned records.
|
| 84 |
+
|
| 85 |
+
## Migration Plan
|
| 86 |
+
|
| 87 |
+
1. Add the `learner_class_state` table, constraints, index/uniqueness, RLS, and revoked direct-client access.
|
| 88 |
+
2. Deploy server reads and the authenticated update endpoint while leaving the existing path as the entry view.
|
| 89 |
+
3. Deploy browser onboarding, local fallback, focused recommendations, and lesson-positioned path access.
|
| 90 |
+
4. Verify existing classes resolve to one level and document remediation for ambiguous legacy classes.
|
| 91 |
+
5. Roll back the browser entry-point change first if necessary; the additive endpoint and table can remain without affecting the existing path. Remove them only after confirming no deployed client uses them.
|
| 92 |
+
|
openspec/changes/add-focused-learner-home/proposal.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Proposal
|
| 2 |
+
|
| 3 |
+
## Why
|
| 4 |
+
|
| 5 |
+
The full learning path asks learners to orient themselves among many lessons and topics before they can act, so a learner whose class is currently on lesson 5 can feel lost or repeatedly scroll past earlier work. The application should establish the learner's current class lesson once and use it to present a small, clear set of useful next actions.
|
| 6 |
+
|
| 7 |
+
## What Changes
|
| 8 |
+
|
| 9 |
+
- Add first-use onboarding for each student and class that asks which lesson the class is currently studying, with choices restricted to that class's single level.
|
| 10 |
+
- Persist the selected current lesson per student and class, restore it across devices when server persistence is available, and retain it locally when it is not.
|
| 11 |
+
- Add a focused learner home that presents at most three recommended actions, prioritizing unfinished homework, continuing the selected lesson, and a short review or practice activity.
|
| 12 |
+
- Keep the complete learning path available as a secondary view and open it around the selected current lesson rather than requiring manual scrolling from the beginning.
|
| 13 |
+
- Allow the learner to change the current lesson without deleting existing progress.
|
| 14 |
+
- Preserve RTL, touch, keyboard, and no-mouse use throughout onboarding and the focused home.
|
| 15 |
+
- Keep notification preferences and new reminder types out of scope; they will be planned as a separate change. Teacher-controlled current-lesson assignment, changes to scoring, and paid AI behavior are also out of scope.
|
| 16 |
+
|
| 17 |
+
## Capabilities
|
| 18 |
+
|
| 19 |
+
### New Capabilities
|
| 20 |
+
|
| 21 |
+
- `learner-home`: Current-lesson onboarding, per-class resume context, focused recommendations, and access to the full path.
|
| 22 |
+
|
| 23 |
+
### Modified Capabilities
|
| 24 |
+
|
| 25 |
+
- `progress-and-practice`: Use the learner's selected current lesson, rather than the first unfinished lesson across the path, when choosing new material for daily practice.
|
| 26 |
+
|
| 27 |
+
## Impact
|
| 28 |
+
|
| 29 |
+
- Browser UI and state in `static/index.html`, including sign-in/class selection, initial navigation, path positioning, and daily-practice selection.
|
| 30 |
+
- FastAPI endpoints in `app/main.py` and Supabase access in `app/auth.py` for reading and updating a student's per-class current lesson.
|
| 31 |
+
- A Supabase migration for learner/class onboarding state; only the authenticated learner may change or read their own selection, while existing class membership remains authoritative.
|
| 32 |
+
- Local browser storage as a degraded fallback when Supabase is absent or temporarily unavailable; local state must be scoped so one signed-in learner cannot inherit another learner's selection.
|
| 33 |
+
- Existing progress and homework data are read but not replaced or deleted. No new paid API usage or third-party dependency is introduced.
|
openspec/changes/add-focused-learner-home/specs/learner-home/spec.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Spec Delta
|
| 2 |
+
|
| 3 |
+
## Purpose
|
| 4 |
+
|
| 5 |
+
Define how a learner establishes their current class lesson and receives a small, accessible set of relevant next actions instead of navigating the complete course path first.
|
| 6 |
+
|
| 7 |
+
## ADDED Requirements
|
| 8 |
+
|
| 9 |
+
### Requirement: Per-class current-lesson onboarding
|
| 10 |
+
The application SHALL require an authenticated student to select the current lesson the first time they enter a class for which they have no saved selection, and SHALL restrict the choices to lessons in that class's single level.
|
| 11 |
+
|
| 12 |
+
#### Scenario: Student enters a class for the first time
|
| 13 |
+
- **GIVEN** the student has no saved current lesson for the selected class
|
| 14 |
+
- **WHEN** the student enters the learning experience
|
| 15 |
+
- **THEN** the application asks which lesson the class is currently studying
|
| 16 |
+
- **AND** offers only lessons belonging to that class's level
|
| 17 |
+
- **AND** waits for a selection before showing the focused learner home
|
| 18 |
+
|
| 19 |
+
#### Scenario: Student has multiple classes
|
| 20 |
+
- **GIVEN** the student belongs to more than one class
|
| 21 |
+
- **WHEN** the student selects a class with no saved current lesson
|
| 22 |
+
- **THEN** the application asks for the current lesson of that class
|
| 23 |
+
- **AND** keeps that selection independent of selections for the student's other classes
|
| 24 |
+
|
| 25 |
+
#### Scenario: Class configuration does not identify one level
|
| 26 |
+
- **GIVEN** the selected class contains lessons from zero or multiple levels
|
| 27 |
+
- **WHEN** current-lesson onboarding would begin
|
| 28 |
+
- **THEN** the application explains that the class configuration must be corrected
|
| 29 |
+
- **AND** does not offer lessons from an ambiguous level
|
| 30 |
+
|
| 31 |
+
### Requirement: Current-lesson persistence
|
| 32 |
+
The application SHALL associate the selected current lesson with the authenticated student and class, restore it across devices when server persistence is available, and allow the student to change it without altering learning progress.
|
| 33 |
+
|
| 34 |
+
#### Scenario: Student returns on another device
|
| 35 |
+
- **GIVEN** the student previously selected lesson 5 for the class
|
| 36 |
+
- **AND** server persistence is available
|
| 37 |
+
- **WHEN** the student enters that class on another device
|
| 38 |
+
- **THEN** lesson 5 is restored as the current lesson
|
| 39 |
+
- **AND** onboarding is not shown again
|
| 40 |
+
|
| 41 |
+
#### Scenario: Student changes the current lesson
|
| 42 |
+
- **GIVEN** the student's current lesson is lesson 5
|
| 43 |
+
- **WHEN** the student changes it to lesson 6
|
| 44 |
+
- **THEN** lesson 6 becomes the source of focused recommendations
|
| 45 |
+
- **AND** progress already recorded for lesson 5 remains unchanged
|
| 46 |
+
|
| 47 |
+
#### Scenario: Server persistence is unavailable
|
| 48 |
+
- **GIVEN** the server cannot read or save the current-lesson selection
|
| 49 |
+
- **WHEN** the student selects a lesson
|
| 50 |
+
- **THEN** the application retains the selection on that device when browser storage is available
|
| 51 |
+
- **AND** keeps the learning experience usable
|
| 52 |
+
- **AND** does not expose one student's selection to another student using the device
|
| 53 |
+
|
| 54 |
+
### Requirement: Focused learner home
|
| 55 |
+
The application SHALL make a focused home the student's primary post-onboarding view and SHALL show no more than three recommended actions derived from the selected class, current lesson, homework, and progress.
|
| 56 |
+
|
| 57 |
+
#### Scenario: Incomplete homework exists
|
| 58 |
+
- **GIVEN** the selected class has incomplete homework
|
| 59 |
+
- **WHEN** the focused home is shown
|
| 60 |
+
- **THEN** an action for the nearest-due incomplete homework is included
|
| 61 |
+
- **AND** its due or overdue state is visible
|
| 62 |
+
|
| 63 |
+
#### Scenario: Current lesson has unfinished work
|
| 64 |
+
- **GIVEN** the current lesson contains unfinished activities
|
| 65 |
+
- **WHEN** the focused home is shown
|
| 66 |
+
- **THEN** the primary non-homework action continues unfinished work in that lesson
|
| 67 |
+
- **AND** the learner does not need to scroll through earlier lessons
|
| 68 |
+
|
| 69 |
+
#### Scenario: Current lesson is complete
|
| 70 |
+
- **GIVEN** the learner has completed the selected current lesson
|
| 71 |
+
- **WHEN** the focused home is shown
|
| 72 |
+
- **THEN** the application offers a short review or allows the learner to select a different current lesson
|
| 73 |
+
- **AND** does not silently advance the class's current lesson
|
| 74 |
+
|
| 75 |
+
### Requirement: Short recommended activity
|
| 76 |
+
At least one focused-home action SHALL describe a bounded activity of no more than five items and SHALL show its workload before the learner starts it.
|
| 77 |
+
|
| 78 |
+
#### Scenario: Learner starts a short activity
|
| 79 |
+
- **WHEN** the learner activates the short recommendation
|
| 80 |
+
- **THEN** the session contains no more than five items
|
| 81 |
+
- **AND** completion is clearly announced when the session ends
|
| 82 |
+
|
| 83 |
+
#### Scenario: Recommended material is unavailable
|
| 84 |
+
- **GIVEN** the current lesson has insufficient available material for the recommendation
|
| 85 |
+
- **WHEN** the focused home is built
|
| 86 |
+
- **THEN** the application offers another valid action or omits that recommendation
|
| 87 |
+
- **AND** never shows an action that cannot be started
|
| 88 |
+
|
| 89 |
+
### Requirement: Full-path access and positioning
|
| 90 |
+
The focused home SHALL provide access to the complete learning path, and the path SHALL open at the selected current lesson while preserving access to earlier and later class lessons.
|
| 91 |
+
|
| 92 |
+
#### Scenario: Learner opens the complete path
|
| 93 |
+
- **GIVEN** the student's current lesson is lesson 5
|
| 94 |
+
- **WHEN** the learner chooses the complete path
|
| 95 |
+
- **THEN** the path positions lesson 5 in view
|
| 96 |
+
- **AND** earlier and later lessons assigned to the class remain accessible
|
| 97 |
+
|
| 98 |
+
### Requirement: Accessible focused navigation
|
| 99 |
+
Current-lesson onboarding and focused-home actions SHALL support RTL layout, touch, keyboard-only operation, visible focus, and meaningful accessible names.
|
| 100 |
+
|
| 101 |
+
#### Scenario: Keyboard-only onboarding
|
| 102 |
+
- **WHEN** a learner completes onboarding without a pointing device
|
| 103 |
+
- **THEN** every lesson option and confirmation action is reachable and operable by keyboard
|
| 104 |
+
- **AND** focus moves predictably into the focused home after selection
|
| 105 |
+
|
openspec/changes/add-focused-learner-home/specs/progress-and-practice/spec.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Spec Delta
|
| 2 |
+
|
| 3 |
+
## MODIFIED Requirements
|
| 4 |
+
|
| 5 |
+
### Requirement: Daily practice session
|
| 6 |
+
The browser SHALL build a ten-sentence daily session from weak practiced sentences and new course-ordered sentences, preferring homework and the selected class's current lesson before other unfinished lessons.
|
| 7 |
+
|
| 8 |
+
#### Scenario: One pool has too few sentences
|
| 9 |
+
- **WHEN** either the weak or new sentence pool cannot supply its half
|
| 10 |
+
- **THEN** the other pool fills the remaining places
|
| 11 |
+
- **AND** story lines are excluded
|
| 12 |
+
|
| 13 |
+
#### Scenario: Current lesson is selected
|
| 14 |
+
- **GIVEN** the learner selected a current lesson for the active class
|
| 15 |
+
- **AND** no incomplete homework takes priority
|
| 16 |
+
- **WHEN** the browser chooses new sentences for daily practice
|
| 17 |
+
- **THEN** it chooses available unpracticed sentences from the selected current lesson before other lessons
|
| 18 |
+
|
| 19 |
+
#### Scenario: No current lesson is available
|
| 20 |
+
- **GIVEN** the learner has no usable current-lesson selection
|
| 21 |
+
- **WHEN** daily practice is available without completing onboarding
|
| 22 |
+
- **THEN** the browser falls back to the first unfinished lesson
|
| 23 |
+
|
openspec/changes/add-focused-learner-home/tasks.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tasks
|
| 2 |
+
|
| 3 |
+
## 1. Learner/class state persistence
|
| 4 |
+
|
| 5 |
+
- [ ] 1.1 Add the documented Supabase migration for `learner_class_state`, including the `(email, class_id)` uniqueness rule, timestamps, RLS, and revoked client roles; verify the SQL applies cleanly to a test Supabase project.
|
| 6 |
+
- [ ] 1.2 Add authenticated persistence methods for reading and upserting only a learner's own per-class current lesson; verify focused unit tests cover normalization, missing-table behavior, and unavailable Supabase.
|
| 7 |
+
|
| 8 |
+
## 2. Current-lesson API contract
|
| 9 |
+
|
| 10 |
+
- [ ] 2.1 Include stable class IDs and the caller's saved `current_lesson` in `/api/me`; verify API tests cover no selection, one selection, and independent selections for multiple classes.
|
| 11 |
+
- [ ] 2.2 Add `PUT /api/me/classes/{class_id}/current-lesson` and validate authentication, class membership, a single resolvable class level, and lesson membership; verify API tests cover valid update plus unauthenticated, foreign-class, ambiguous-level, and invalid-lesson rejection.
|
| 12 |
+
- [ ] 2.3 Document the new table, migration, endpoint behavior, and degraded persistence behavior in `README.md`; verify the documented SQL and request shape agree with the implementation.
|
| 13 |
+
|
| 14 |
+
## 3. Current-lesson onboarding
|
| 15 |
+
|
| 16 |
+
- [ ] 3.1 Add the RTL current-lesson prompt after active-class selection, restricted to the class's one level, and block the focused home until a choice is made; verify browser-facing tests cover first entry, returning entry, multiple classes, and ambiguous class configuration.
|
| 17 |
+
- [ ] 3.2 Persist the selection through the authenticated endpoint with a versioned, subject/account/class-scoped local fallback; verify tests demonstrate that switching accounts or classes cannot reuse another selection and that server state wins when restored.
|
| 18 |
+
- [ ] 3.3 Add a visible change-current-lesson action that preserves all recorded progress; verify changing lessons updates recommendations while existing best scores and completion state remain intact.
|
| 19 |
+
- [ ] 3.4 Manually complete onboarding in Hebrew RTL on narrow mobile and desktop widths using touch and keyboard only; verify visible focus, accessible names, predictable focus movement, and reduced-motion behavior.
|
| 20 |
+
|
| 21 |
+
## 4. Focused learner home
|
| 22 |
+
|
| 23 |
+
- [ ] 4.1 Add the focused home as the default authenticated student entry view and reuse existing topic and homework launch paths; verify automated UI logic tests show no more than three distinct, startable actions.
|
| 24 |
+
- [ ] 4.2 Implement deterministic recommendation priority for nearest-due incomplete homework, unfinished work in the selected lesson, and a review or short activity; verify tests cover incomplete homework, no homework, completed current lesson, insufficient material, and duplicate-target removal.
|
| 25 |
+
- [ ] 4.3 Implement a short recommended session capped at five items with its workload shown before start and a clear completion state; verify tests cover item limits and empty/insufficient pools.
|
| 26 |
+
- [ ] 4.4 Manually exercise the focused home in Hebrew RTL on a phone-sized viewport with complete and incomplete lessons; verify homework status, primary action, short-task size, touch targets, keyboard order, and screen-reader labels.
|
| 27 |
+
|
| 28 |
+
## 5. Path and daily-practice integration
|
| 29 |
+
|
| 30 |
+
- [ ] 5.1 Add explicit full-path navigation that positions the selected current lesson or its first unfinished topic in view while retaining every assigned class lesson; verify tests cover lesson 5 with unfinished earlier lessons and manual reduced-motion navigation.
|
| 31 |
+
- [ ] 5.2 Update daily-practice new-item selection to prefer homework and then the selected current lesson before other unfinished lessons; verify focused tests retain the existing ten-item balance and fallback behavior.
|
| 32 |
+
- [ ] 5.3 Preserve the existing path-first behavior for teachers and open mode, and avoid requesting notification permission during lesson onboarding; verify browser tests cover both entry modes and confirm no notification prompt is triggered by onboarding.
|
| 33 |
+
|
| 34 |
+
## 6. Integration verification
|
| 35 |
+
|
| 36 |
+
- [ ] 6.1 Run the focused server and browser test selections, then the full test suite, and verify no regressions in class selection, homework, progress restoration, daily practice, or push notifications.
|
| 37 |
+
|
| 38 |
+
## Workflow follow-up
|
| 39 |
+
|
| 40 |
+
- Archive the change after implementation review and deployment migration checks are complete.
|
| 41 |
+
- Plan notification categories and reminder preferences as a separate OpenSpec change.
|
| 42 |
+
|
static/index.html
CHANGED
|
@@ -326,6 +326,13 @@ body.memory-game{overflow:hidden}
|
|
| 326 |
#vids button.back{display:inline-flex;align-self:flex-start;gap:6px;padding:6px 12px;border-radius:10px;background:var(--olive);border-color:var(--olive);color:var(--on-olive);font:700 15px var(--f-body)}
|
| 327 |
#dailyDlg{width:min(92vw,380px)}
|
| 328 |
#pushDlg{width:min(92vw,380px);text-align:center}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
#pushDlg .push-bell{font-size:44px;line-height:1;margin:4px 0 8px}
|
| 330 |
#pushDlg h2{font:400 24px/1.2 var(--f-display);margin:0 0 6px}
|
| 331 |
#pushDlg .row{justify-content:center}
|
|
@@ -955,6 +962,7 @@ body.manage #manage{width:100%;max-width:none}
|
|
| 955 |
.wrote{margin:0;padding:0 16px 8px;padding-inline-start:3em;color:var(--muted);font-size:15px}
|
| 956 |
#mClasses{display:flex;flex-direction:column;gap:inherit}
|
| 957 |
#mClasses>.btn{align-self:flex-start}
|
|
|
|
| 958 |
#mClasses .card>.btn{align-self:flex-start}
|
| 959 |
/* a student's own screen takes the class's place in the panel: the way back, their figures, their lessons, their sentences */
|
| 960 |
#manage.student :is(#mTabs,#mHead,#mLessons,#mRoster),#manage:not(.student) #mStudent{display:none}
|
|
@@ -1721,6 +1729,16 @@ html.a11y-reduce-motion *,html.a11y-reduce-motion *::before,html.a11y-reduce-mot
|
|
| 1721 |
<div class="picks" id="picks"></div>
|
| 1722 |
<button class="btn" id="pickMates" hidden>ืืชืืืืืื ืืืืชื</button>
|
| 1723 |
</dialog>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1724 |
<dialog id="pushDlg" aria-labelledby="pushTitle" aria-describedby="pushText">
|
| 1725 |
<div class="push-bell" aria-hidden="true">๐</div>
|
| 1726 |
<h2 id="pushTitle">ืชืืืืจืช ืืกืจืืื ืืืืื</h2>
|
|
@@ -2080,6 +2098,40 @@ function pushRow(){
|
|
| 2080 |
};
|
| 2081 |
return row;
|
| 2082 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2083 |
/* On entering, once: a prompt to turn the reminder on. "Not now" asks again after PUSH_AGAIN days; it waits for any
|
| 2084 |
dialog already open (choosing a class) to close. */
|
| 2085 |
const PUSH_AGAIN=7;
|
|
@@ -5460,7 +5512,7 @@ function drawSystemActivity(box){
|
|
| 5460 |
if(systemActivityError){ card.append(mark("note","ืื ื ืืชื ืืืขืื ืคืขืืืืช ืืืจืื ื: "+systemActivityError,"p")); return; }
|
| 5461 |
if(!SYSTEM_ACTIVITY){ card.append(mark("note","ืืืขื ืคืขืืืืชโฆ","p")); return; }
|
| 5462 |
if(SYSTEM_ACTIVITY.setup){ const code=mark("",SYSTEM_ACTIVITY.setup,"code"); code.dir="ltr"; card.append(mark("setup","ืืื ืืืชืืื ืืฉืืืจ ืคืขืืืืช, ืืฉ ืืืฆืืจ ืืช ืืืืื system_events ืึพSupabase:","p"),code); return; }
|
| 5463 |
-
const events=SYSTEM_ACTIVITY.events||[], labels={exercise:["๐๏ธ","ืืื ืช ืชืจืืืืื"],game:["๐ฎ","ืืฉืืงืื"],permission:["๐","ืฉืื ืื ืืจืฉืืืช"],content:["โ","ืืืกืคืช ืชืื ืื"]}, feed=mark("system-feed","");
|
| 5464 |
if(!events.length){ card.append(mark("note","ืขืืืื ืื ื ืจืฉืื ืคืขืืืืช.","p")); return; }
|
| 5465 |
const difficult=new Map;
|
| 5466 |
for(const event of events){
|
|
@@ -5759,7 +5811,8 @@ function drawClasses(classes){
|
|
| 5759 |
top.append(mark("","ืขืื ืืื ืืืชืืช","h2"),mark("","ืขื ืฉื ืคืชืืช ืืืชื, ืื ืืฉืืื ืืืื ืืืืื ืก, ืืชืืช โืชืืืืืืโ ืืืคืืข ืื ืื ืฉื ืื ืก. ืืืืืชื ืืจืืฉืื ื ื ืื ืกืื ืจืง ืืชืืืืืื ืฉืืืืชืืช ืืืืืจืื.","p"));
|
| 5760 |
none.append(top); box.append(none);
|
| 5761 |
}
|
| 5762 |
-
const add=mark("btn primary","+ ืืืชื ืืืฉื","button")
|
|
|
|
| 5763 |
for(const c of classes){
|
| 5764 |
const card=mark("card",""), top=mark("chead",""), name=mark("","","h2"), n=document.createElement("bdi"), edit=mark("btn","ืขืจืืื","button"), del=mark("btn danger","ืืืืงื","button");
|
| 5765 |
n.textContent=c.name; name.append(n); edit.onclick=()=>editClass(c); del.onclick=()=>deleteClass(c); top.append(name,edit,del);
|
|
|
|
| 326 |
#vids button.back{display:inline-flex;align-self:flex-start;gap:6px;padding:6px 12px;border-radius:10px;background:var(--olive);border-color:var(--olive);color:var(--on-olive);font:700 15px var(--f-body)}
|
| 327 |
#dailyDlg{width:min(92vw,380px)}
|
| 328 |
#pushDlg{width:min(92vw,380px);text-align:center}
|
| 329 |
+
#notifyDlg{width:min(92vw,440px)}
|
| 330 |
+
.notify-form{display:flex;flex-direction:column;gap:12px}
|
| 331 |
+
.notify-form label{display:flex;flex-direction:column;gap:4px;font:700 14px var(--f-body)}
|
| 332 |
+
.notify-form :is(select,input,textarea){padding:9px 12px;border:1px solid var(--line);border-radius:10px;background:var(--surface);color:var(--ink);font:500 16px/1.4 var(--f-body);resize:vertical}
|
| 333 |
+
.notify-form :is(select,input,textarea):focus{outline:2px solid var(--olive);outline-offset:1px}
|
| 334 |
+
.notify-note{margin:0;min-height:1.3em;color:var(--muted);font:600 14px/1.4 var(--f-body)}
|
| 335 |
+
.notify-note.ok{color:var(--olive)}
|
| 336 |
#pushDlg .push-bell{font-size:44px;line-height:1;margin:4px 0 8px}
|
| 337 |
#pushDlg h2{font:400 24px/1.2 var(--f-display);margin:0 0 6px}
|
| 338 |
#pushDlg .row{justify-content:center}
|
|
|
|
| 962 |
.wrote{margin:0;padding:0 16px 8px;padding-inline-start:3em;color:var(--muted);font-size:15px}
|
| 963 |
#mClasses{display:flex;flex-direction:column;gap:inherit}
|
| 964 |
#mClasses>.btn{align-self:flex-start}
|
| 965 |
+
#mClasses>.mbar{display:flex;flex-wrap:wrap;gap:8px}
|
| 966 |
#mClasses .card>.btn{align-self:flex-start}
|
| 967 |
/* a student's own screen takes the class's place in the panel: the way back, their figures, their lessons, their sentences */
|
| 968 |
#manage.student :is(#mTabs,#mHead,#mLessons,#mRoster),#manage:not(.student) #mStudent{display:none}
|
|
|
|
| 1729 |
<div class="picks" id="picks"></div>
|
| 1730 |
<button class="btn" id="pickMates" hidden>ืืชืืืืืื ืืืืชื</button>
|
| 1731 |
</dialog>
|
| 1732 |
+
<dialog id="notifyDlg" aria-labelledby="notifyTitle">
|
| 1733 |
+
<div class="dlg-head"><h2 id="notifyTitle">ืฉืืืืช ืืชืจืื<small>ืืืืขื ืืืืคืื ืื ืืืืฉื ืฉื ืื ืฉืืคืขืื ืชืืืืจืืช</small></h2><button class="btn" id="notifyClose">ืกืืืจื</button></div>
|
| 1734 |
+
<form id="notifyForm" class="notify-form">
|
| 1735 |
+
<label>ืืื<select id="notifyTo"></select></label>
|
| 1736 |
+
<label>ืืืชืจืช<input id="notifyHead" maxlength="60" required placeholder="ืืืฉื: ืืื ืฉืืขืืจ ืืืจ"></label>
|
| 1737 |
+
<label>ืืืืขื<textarea id="notifyBody" maxlength="240" rows="3" placeholder="ืื ืืืื"></textarea></label>
|
| 1738 |
+
<p class="notify-note" id="notifyNote" aria-live="polite"></p>
|
| 1739 |
+
<div class="row"><button class="btn primary" id="notifySend">ืฉืืืื</button></div>
|
| 1740 |
+
</form>
|
| 1741 |
+
</dialog>
|
| 1742 |
<dialog id="pushDlg" aria-labelledby="pushTitle" aria-describedby="pushText">
|
| 1743 |
<div class="push-bell" aria-hidden="true">๐</div>
|
| 1744 |
<h2 id="pushTitle">ืชืืืืจืช ืืกืจืืื ืืืืื</h2>
|
|
|
|
| 2098 |
};
|
| 2099 |
return row;
|
| 2100 |
}
|
| 2101 |
+
/* An admin's notification, to everyone they manage or to one class (POST /api/push/broadcast). The counts are of the
|
| 2102 |
+
devices that turned the reminders on. */
|
| 2103 |
+
async function openNotify(classes){
|
| 2104 |
+
const dlg=$("notifyDlg"), to=$("notifyTo"), note=$("notifyNote"), send=$("notifySend"), head=$("notifyHead"), body=$("notifyBody");
|
| 2105 |
+
let counts={all:0,classes:{}};
|
| 2106 |
+
const draw=()=>{
|
| 2107 |
+
const keep=to.value; to.replaceChildren();
|
| 2108 |
+
const opt=(value,label)=>{ const o=document.createElement("option"); o.value=value; o.textContent=label; to.append(o); };
|
| 2109 |
+
opt("",`ืื ืืืฉืชืืฉืื ยท ${counts.all} ืืืฉืืจืื`);
|
| 2110 |
+
for(const c of classes) opt(c.name,`ืืืชืช ${c.name} ยท ${counts.classes[c.name]??0} ืืืฉืืจืื`);
|
| 2111 |
+
to.value=[...to.options].some(o=>o.value===keep)?keep:"";
|
| 2112 |
+
};
|
| 2113 |
+
note.className="notify-note"; note.textContent="ืืืขืโฆ"; send.disabled=true; draw(); dlg.showModal(); head.focus();
|
| 2114 |
+
try{
|
| 2115 |
+
const res=await api("/api/push/audience"), d=await res.json().catch(()=>({}));
|
| 2116 |
+
if(!res.ok) throw new Error(d.detail||res.status);
|
| 2117 |
+
counts=d; draw(); note.textContent=""; send.disabled=false;
|
| 2118 |
+
}catch(e){ note.textContent="ืื ื ืืชื ืืฉืืื ืืจืืข: "+e.message; }
|
| 2119 |
+
$("notifyClose").onclick=()=>dlg.close();
|
| 2120 |
+
$("notifyForm").onsubmit=async ev=>{
|
| 2121 |
+
ev.preventDefault(); if(!head.value.trim()) return head.focus();
|
| 2122 |
+
const n=to.value?counts.classes[to.value]??0:counts.all, who=to.value?`ืืืชืช ${to.value}`:"ืื ืืืฉืชืืฉืื";
|
| 2123 |
+
if(!n){ note.textContent=`ื${who} ืขืื ืืฃ ืืื ืื ืืคืขืื ืืชืจืืืช.`; return; }
|
| 2124 |
+
if(!confirm(`ืืฉืืื ืืช ืืืชืจืื ื${who} (${n} ืืืฉืืจืื)?`)) return;
|
| 2125 |
+
send.disabled=true; note.className="notify-note"; note.textContent="ืฉืืืโฆ";
|
| 2126 |
+
try{
|
| 2127 |
+
const res=await api("/api/push/broadcast",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:head.value,body:body.value,class:to.value})}), d=await res.json().catch(()=>({}));
|
| 2128 |
+
if(!res.ok) throw new Error(d.detail||res.status);
|
| 2129 |
+
note.className="notify-note ok"; note.textContent=`ื ืฉืื ื-${d.sent} ืืชืื ${d.devices} ืืืฉืืจืื โ`+(d.sent<d.devices?" (ืืืฉืืจืื ืฉืื ืงืืืื ืื ืจืื ืืืืื ืืช ืืืชืจืืืช)":"");
|
| 2130 |
+
head.value=body.value="";
|
| 2131 |
+
}catch(e){ note.textContent="ืืฉืืืื ื ืืฉืื: "+e.message; }
|
| 2132 |
+
finally{ send.disabled=false; }
|
| 2133 |
+
};
|
| 2134 |
+
}
|
| 2135 |
/* On entering, once: a prompt to turn the reminder on. "Not now" asks again after PUSH_AGAIN days; it waits for any
|
| 2136 |
dialog already open (choosing a class) to close. */
|
| 2137 |
const PUSH_AGAIN=7;
|
|
|
|
| 5512 |
if(systemActivityError){ card.append(mark("note","ืื ื ืืชื ืืืขืื ืคืขืืืืช ืืืจืื ื: "+systemActivityError,"p")); return; }
|
| 5513 |
if(!SYSTEM_ACTIVITY){ card.append(mark("note","ืืืขื ืคืขืืืืชโฆ","p")); return; }
|
| 5514 |
if(SYSTEM_ACTIVITY.setup){ const code=mark("",SYSTEM_ACTIVITY.setup,"code"); code.dir="ltr"; card.append(mark("setup","ืืื ืืืชืืื ืืฉืืืจ ืคืขืืืืช, ืืฉ ืืืฆืืจ ืืช ืืืืื system_events ืึพSupabase:","p"),code); return; }
|
| 5515 |
+
const events=SYSTEM_ACTIVITY.events||[], labels={exercise:["๐๏ธ","ืืื ืช ืชืจืืืืื"],game:["๐ฎ","ืืฉืืงืื"],permission:["๐","ืฉืื ืื ืืจืฉืืืช"],content:["โ","ืืืกืคืช ืชืื ืื"],push:["๐","ืฉืืืืช ืืชืจืื"]}, feed=mark("system-feed","");
|
| 5516 |
if(!events.length){ card.append(mark("note","ืขืืืื ืื ื ืจืฉืื ืคืขืืืืช.","p")); return; }
|
| 5517 |
const difficult=new Map;
|
| 5518 |
for(const event of events){
|
|
|
|
| 5811 |
top.append(mark("","ืขืื ืืื ืืืชืืช","h2"),mark("","ืขื ืฉื ืคืชืืช ืืืชื, ืื ืืฉืืื ืืืื ืืืืื ืก, ืืชืืช โืชืืืืืืโ ืืืคืืข ืื ืื ืฉื ืื ืก. ืืืืืชื ืืจืืฉืื ื ื ืื ืกืื ืจืง ืืชืืืืืื ืฉืืืืชืืช ืืืืืจืื.","p"));
|
| 5812 |
none.append(top); box.append(none);
|
| 5813 |
}
|
| 5814 |
+
const add=mark("btn primary","+ ืืืชื ืืืฉื","button"), notify=mark("btn","๐ ืฉืืืืช ืืชืจืื","button"), bar=mark("mbar","");
|
| 5815 |
+
add.onclick=newClass; notify.onclick=()=>openNotify(classes); bar.append(add,notify); box.append(bar);
|
| 5816 |
for(const c of classes){
|
| 5817 |
const card=mark("card",""), top=mark("chead",""), name=mark("","","h2"), n=document.createElement("bdi"), edit=mark("btn","ืขืจืืื","button"), del=mark("btn danger","ืืืืงื","button");
|
| 5818 |
n.textContent=c.name; name.append(n); edit.onclick=()=>editClass(c); del.onclick=()=>deleteClass(c); top.append(name,edit,del);
|
tests/test_push.py
CHANGED
|
@@ -93,3 +93,64 @@ def test_gone_subscription_is_deleted(monkeypatch):
|
|
| 93 |
monkeypatch.setattr("pywebpush.webpush", boom)
|
| 94 |
assert p.send(rows[0], {"title": "t"}) is False
|
| 95 |
assert p.auth.rows == []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
monkeypatch.setattr("pywebpush.webpush", boom)
|
| 94 |
assert p.send(rows[0], {"title": "t"}) is False
|
| 95 |
assert p.auth.rows == []
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_message_is_checked_and_tagged_apart():
|
| 99 |
+
m = pushes.message(" ืืื ืฉืืขืืจ ืืืจ ", "ื ืชืจืื ืืืื ืจืืฉืื")
|
| 100 |
+
assert m["title"] == "ืืื ืฉืืขืืจ ืืืจ" and m["tag"].startswith("msg-") and m["url"] == "/"
|
| 101 |
+
for title, body in (("", "x"), ("x" * 61, ""), ("ok", "x" * 241)):
|
| 102 |
+
with pytest.raises(ValueError):
|
| 103 |
+
pushes.message(title, body)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# the admin's message, through the app
|
| 107 |
+
from test_lab import FakeAuth as LabAuth # noqa: E402
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class BroadcastAuth(LabAuth):
|
| 111 |
+
secret = "sb_secret_x"
|
| 112 |
+
|
| 113 |
+
def __init__(self):
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.events = []
|
| 116 |
+
self.subs = [{"endpoint": f"https://p/{e}", "email": e, "p256dh": "k", "auth": "a"}
|
| 117 |
+
for e in ("s@b.c", "s2@b.c", "other@b.c", "t@b.c")]
|
| 118 |
+
|
| 119 |
+
def classes(self, fresh=False):
|
| 120 |
+
return [{"id": 1, "name": "ื1", "emails": ["s@b.c", "s2@b.c"], "teachers": ["t@b.c"], "lessons": []},
|
| 121 |
+
{"id": 2, "name": "ื2", "emails": ["nobody@b.c"], "lessons": []}]
|
| 122 |
+
|
| 123 |
+
def _admin(self, path, method="GET", body=None, prefer=""):
|
| 124 |
+
return self.subs if method == "GET" else None
|
| 125 |
+
|
| 126 |
+
def log_event(self, kind, user, label="", details=None):
|
| 127 |
+
self.events.append((kind, label, details))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_admin_sends_to_everyone_or_to_a_class(monkeypatch, tmp_path):
|
| 131 |
+
from fastapi.testclient import TestClient
|
| 132 |
+
from test_scoring import emissions, scorer_for
|
| 133 |
+
from app.main import create_app
|
| 134 |
+
from app.tts import SawtakTTS
|
| 135 |
+
from app.tutor import Tutor
|
| 136 |
+
|
| 137 |
+
async def no_loop(*a, **k):
|
| 138 |
+
return None
|
| 139 |
+
monkeypatch.setenv("VAPID_PRIVATE_KEY", pushes.new_private_key())
|
| 140 |
+
monkeypatch.setattr(pushes, "loop", no_loop)
|
| 141 |
+
sent = []
|
| 142 |
+
monkeypatch.setattr(pushes.Push, "send", lambda self, row, msg: sent.append((row["email"], msg["title"])) or True)
|
| 143 |
+
auth = BroadcastAuth()
|
| 144 |
+
teacher, student = {"Authorization": "Bearer teacher"}, {"Authorization": "Bearer student"}
|
| 145 |
+
with TestClient(create_app(scorer_for(emissions(["ฤง"])), SawtakTTS("k", cache_dir=tmp_path), auth=auth,
|
| 146 |
+
tutor=Tutor(object()))) as c:
|
| 147 |
+
assert c.get("/api/push/audience", headers=teacher).json() == {"all": 4, "classes": {"ื1": 3, "ื2": 0}}
|
| 148 |
+
r = c.post("/api/push/broadcast", headers=teacher, json={"title": "ืฉืืื", "body": "", "class": "ื1"})
|
| 149 |
+
assert r.json() == {"devices": 3, "sent": 3}
|
| 150 |
+
assert sorted(e for e, _ in sent) == ["s2@b.c", "s@b.c", "t@b.c"]
|
| 151 |
+
sent.clear()
|
| 152 |
+
assert c.post("/api/push/broadcast", headers=teacher, json={"title": "ืืืืื"}).json() == {"devices": 4, "sent": 4}
|
| 153 |
+
assert c.post("/api/push/broadcast", headers=teacher, json={"title": "x", "class": "ืืื"}).status_code == 404
|
| 154 |
+
assert c.post("/api/push/broadcast", headers=teacher, json={"title": ""}).status_code == 400
|
| 155 |
+
assert c.post("/api/push/broadcast", headers=student, json={"title": "x"}).status_code == 403
|
| 156 |
+
assert [e[0] for e in auth.events] == ["push", "push"]
|