forge
Explore
Log in

Don't you dare go Hollow

πŸ“Š truthful dashboard charts and a role-scoped activity heatmap

Browse files at this commit

7f602db0a09cdd7269e466a065e35a6a07c75c92Burak BoduroğluParent: 58b098f
  • feat
    • πŸ“Š truthful dashboard charts and a role-scoped activity heatmap
Show full message
feat: πŸ“Š truthful dashboard charts and a role-scoped activity heatmap
- replace the staff "course capacities" and "workload split" panels β€” a
  capacity bar and a count-of-unrelated-resources ring β€” with a success
  trend built from the backend's own per-exam average, plus the same
  averages grouped by course
- students get that trend too, from their own marks ordered by each
  exam's date; marks whose exam falls outside the fetched page carry no
  date and are left out rather than guessed into the sequence
- exam statistics are grader-only, so the resource stays gated on
  teacher+ and caps at the 8 most recent non-draft past exams, since
  there is no bulk statistics endpoint
- deadlines table is now one standalone full-width section for every
  role: no side panel, no column span, no "Appointments" shortcut, and
  the teacher-only teaching-resource links are gone
- new ChartHeatmap: GitHub-contribution-style calendar over 26 weeks,
  laid out as a single grid so week columns share the card's full width
  and weekday labels stay aligned; future days render as invisible
  placeholders instead of dashed outlines
- heatmap source is role-scoped β€” a student's own pomodoro focus
  minutes, a parent's appointments, teacher+ dated exams/events/homework
.claude/skills/dashboard-design/SKILL.mdmodified+27 -15
@@ -8,10 +8,8 @@ description: Rules for the hezarfen_frontend dashboard/homepage β€” a read-only
8 Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status board**, not a marketing landing or action hub.8 Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status board**, not a marketing landing or action hub.
9 9
10 - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes.10 - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes.
11-- **Charts are allowed, on real data only.** The homepage follows the Knowvio-style11+- **Charts are allowed, on real data only.** Charts use `ChartBar`,
12- layout: a Highlights stat-card row, a Progress-overview chart, an Activity/attendance12+ `ChartProgressRing` and `ChartHeatmap` from `src/components/ui/` (accent =
13- split, and an Upcoming-deadlines table. Charts use `ChartBar` and
14- `ChartProgressRing` from `src/components/ui/` (accent =
15 `hsl(var(--primary))`, semantic tints for status).13 `hsl(var(--primary))`, semantic tints for status).
16 **Every chart/stat must be backed by a live API field** β€” no fabricated trends,14 **Every chart/stat must be backed by a live API field** β€” no fabricated trends,
17 streak counters, sparklines, or `+%` delta badges the backend can't produce.15 streak counters, sparklines, or `+%` delta badges the backend can't produce.
@@ -19,16 +17,30 @@ Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status
19 - **Layout order (top β†’ bottom):**17 - **Layout order (top β†’ bottom):**
20 1. Compact header β€” greeting, role chip (neutral), date.18 1. Compact header β€” greeting, role chip (neutral), date.
21 2. **Highlights** β€” role-scoped stat cards (icon + label + mono value).19 2. **Highlights** β€” role-scoped stat cards (icon + label + mono value).
22- 3. **Progress overview** chart + **Activity split** on `lg+`.20+ 3. Chart row on `lg+` (hidden for `parent`, who has no marks access).
23- 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments).21+ 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments),
24- 5. Optional teacher+ Question Bank / Question Pool links.22+ full width for every role β€” one standalone section, no side panel and no
25-- **Grid:** stat row `1 β†’ 2 sm β†’ 4 lg`; charts `lg:grid-cols-3` (progress spans 2).23+ shortcut link in its header.
26-- **Role scoping:** stat/chart set matches nav/role matrix (student personal tools +24+ 5. **Activity heatmap** β€” full-width `ChartHeatmap`, 26 weeks.
27- marks/attendance; teacher teaching tools; manager+ management; parent children/meals).25+- **Grid:** stat row `1 β†’ 2 sm β†’ 4 lg`; charts `lg:grid-cols-3`.
28- Show only panels whose data exists for the role.26+- **Role scoping:** stat/chart set matches nav/role matrix. Show only panels whose
27+ data exists for the role, and never call an endpoint the role would 403 on.
29 - **Deadlines table:** active / today / soon items only, semantic status badge, rows28 - **Deadlines table:** active / today / soon items only, semantic status badge, rows
30 navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA.29 navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA.
31-- **Semantics:** student progress = per-course averages; staff progress =30+- **Chart semantics per role:**
32- `Course.capacity` labeled as course capacity, never enrollment/class size.31+ - student β€” course averages + **success trend** (own marks ordered by their exam's
33-- **Role privacy:** question navigation is teacher+ only. Student/parent deadlines32+ date) + attendance split ring.
34- span full width. No inferred priority or manual refresh.33+ - teacher+ β€” **success trend** (`getExamStatistics().average` per exam, spans 2)
34+ + the same averages grouped by course. Statistics are grader-only, so the
35+ resource must stay gated on `hasMinRole(role, "teacher")`.
36+ - Exam statistics have no bulk endpoint: cap the trend at the most recent handful
37+ of past, non-draft exams (`TREND_EXAM_CAP`), and swallow a per-exam failure
38+ rather than blanking the panel.
39+ - Never chart `Course.capacity` as if it were performance, and never derive a
40+ class (şube) average β€” no endpoint aggregates one, and per-student fetches do
41+ not belong on the homepage.
42+- **Heatmap source per role:** student = own `/pomodoro/me` focus minutes;
43+ parent = own appointments; teacher+ = dated exams/events/homework already read by
44+ the page. Never read another user's pomodoro log here.
45+- **Role privacy:** no teacher-only navigation shortcuts on the board. No inferred
46+ priority or manual refresh.
.codex/skills/dashboard-design/SKILL.mdmodified+27 -15
@@ -8,10 +8,8 @@ description: Rules for the hezarfen_frontend dashboard/homepage β€” a read-only
8 Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status board**, not a marketing landing or action hub.8 Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status board**, not a marketing landing or action hub.
9 9
10 - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes.10 - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes.
11-- **Charts are allowed, on real data only.** The homepage follows the Knowvio-style11+- **Charts are allowed, on real data only.** Charts use `ChartBar`,
12- layout: a Highlights stat-card row, a Progress-overview chart, an Activity/attendance12+ `ChartProgressRing` and `ChartHeatmap` from `src/components/ui/` (accent =
13- split, and an Upcoming-deadlines table. Charts use `ChartBar` and
14- `ChartProgressRing` from `src/components/ui/` (accent =
15 `hsl(var(--primary))`, semantic tints for status).13 `hsl(var(--primary))`, semantic tints for status).
16 **Every chart/stat must be backed by a live API field** β€” no fabricated trends,14 **Every chart/stat must be backed by a live API field** β€” no fabricated trends,
17 streak counters, sparklines, or `+%` delta badges the backend can't produce.15 streak counters, sparklines, or `+%` delta badges the backend can't produce.
@@ -19,16 +17,30 @@ Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status
19 - **Layout order (top β†’ bottom):**17 - **Layout order (top β†’ bottom):**
20 1. Compact header β€” greeting, role chip (neutral), date.18 1. Compact header β€” greeting, role chip (neutral), date.
21 2. **Highlights** β€” role-scoped stat cards (icon + label + mono value).19 2. **Highlights** β€” role-scoped stat cards (icon + label + mono value).
22- 3. **Progress overview** chart + **Activity split** on `lg+`.20+ 3. Chart row on `lg+` (hidden for `parent`, who has no marks access).
23- 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments).21+ 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments),
24- 5. Optional teacher+ Question Bank / Question Pool links.22+ full width for every role β€” one standalone section, no side panel and no
25-- **Grid:** stat row `1 β†’ 2 sm β†’ 4 lg`; charts `lg:grid-cols-3` (progress spans 2).23+ shortcut link in its header.
26-- **Role scoping:** stat/chart set matches nav/role matrix (student personal tools +24+ 5. **Activity heatmap** β€” full-width `ChartHeatmap`, 26 weeks.
27- marks/attendance; teacher teaching tools; manager+ management; parent children/meals).25+- **Grid:** stat row `1 β†’ 2 sm β†’ 4 lg`; charts `lg:grid-cols-3`.
28- Show only panels whose data exists for the role.26+- **Role scoping:** stat/chart set matches nav/role matrix. Show only panels whose
27+ data exists for the role, and never call an endpoint the role would 403 on.
29 - **Deadlines table:** active / today / soon items only, semantic status badge, rows28 - **Deadlines table:** active / today / soon items only, semantic status badge, rows
30 navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA.29 navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA.
31-- **Semantics:** student progress = per-course averages; staff progress =30+- **Chart semantics per role:**
32- `Course.capacity` labeled as course capacity, never enrollment/class size.31+ - student β€” course averages + **success trend** (own marks ordered by their exam's
33-- **Role privacy:** question navigation is teacher+ only. Student/parent deadlines32+ date) + attendance split ring.
34- span full width. No inferred priority or manual refresh.33+ - teacher+ β€” **success trend** (`getExamStatistics().average` per exam, spans 2)
34+ + the same averages grouped by course. Statistics are grader-only, so the
35+ resource must stay gated on `hasMinRole(role, "teacher")`.
36+ - Exam statistics have no bulk endpoint: cap the trend at the most recent handful
37+ of past, non-draft exams (`TREND_EXAM_CAP`), and swallow a per-exam failure
38+ rather than blanking the panel.
39+ - Never chart `Course.capacity` as if it were performance, and never derive a
40+ class (şube) average β€” no endpoint aggregates one, and per-student fetches do
41+ not belong on the homepage.
42+- **Heatmap source per role:** student = own `/pomodoro/me` focus minutes;
43+ parent = own appointments; teacher+ = dated exams/events/homework already read by
44+ the page. Never read another user's pomodoro log here.
45+- **Role privacy:** no teacher-only navigation shortcuts on the board. No inferred
46+ priority or manual refresh.
src/components/ui/chart-heatmap.tsxadded+233 -0
@@ -0,0 +1,233 @@
1+import { For, Show, createMemo, type Component } from "solid-js";
2+import { cn } from "@/lib/cn";
3+import { usePreferences, useT } from "@/stores/preferences-context";
4+
5+/** One dated observation. Several entries may share a day β€” they are summed. */
6+export type HeatmapEntry = {
7+ /** Epoch millis. Bucketed into a local-time calendar day. */
8+ at: number;
9+ /** Amount contributed by this entry (minutes, records, …). */
10+ value: number;
11+};
12+
13+export type ChartHeatmapProps = {
14+ title?: string;
15+ subtitle?: string;
16+ entries: HeatmapEntry[];
17+ /** Calendar weeks to render, ending with the week containing `endsAt`. */
18+ weeks?: number;
19+ /** Right-hand edge of the range; defaults to now. */
20+ endsAt?: number;
21+ /** Cell tooltip / screen-reader text for a day that has data. */
22+ dayLabel: (value: number, dayStart: number) => string;
23+ /** Cell text for an empty day. */
24+ emptyDayLabel: (dayStart: number) => string;
25+ /** Summary line under the grid, e.g. "312 dk odak Β· son 26 hafta". */
26+ footer?: string;
27+ class?: string;
28+};
29+
30+const DEFAULT_WEEKS = 26;
31+
32+/** Local midnight for the day containing `ms` β€” DST-safe, unlike `ms - ms % DAY_MS`. */
33+function startOfDay(ms: number): number {
34+ const d = new Date(ms);
35+ d.setHours(0, 0, 0, 0);
36+ return d.getTime();
37+}
38+
39+/** Local midnight of the Monday on or before `ms`. */
40+function startOfWeek(ms: number): number {
41+ const d = new Date(startOfDay(ms));
42+ // getDay(): 0 = Sunday. Shift so Monday is column-row 0.
43+ d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
44+ return d.getTime();
45+}
46+
47+/**
48+ * GitHub-contribution-style calendar. Columns are weeks (oldest β†’ newest),
49+ * rows are Monday β†’ Sunday. Intensity is bucketed against the busiest day in
50+ * range, so the scale is always relative to real data rather than a guess.
51+ */
52+export const ChartHeatmap: Component<ChartHeatmapProps> = (props) => {
53+ const t = useT();
54+ const { locale } = usePreferences();
55+
56+ const weeks = () => props.weeks ?? DEFAULT_WEEKS;
57+
58+ // Totals per local day, keyed by that day's midnight timestamp.
59+ const totals = createMemo(() => {
60+ const map = new Map<number, number>();
61+ for (const entry of props.entries) {
62+ if (!Number.isFinite(entry.at) || entry.value <= 0) continue;
63+ const day = startOfDay(entry.at);
64+ map.set(day, (map.get(day) ?? 0) + entry.value);
65+ }
66+ return map;
67+ });
68+
69+ const firstWeekStart = createMemo(() => {
70+ const lastWeek = startOfWeek(props.endsAt ?? Date.now());
71+ const d = new Date(lastWeek);
72+ d.setDate(d.getDate() - (weeks() - 1) * 7);
73+ return d.getTime();
74+ });
75+
76+ // Columns of 7 local-midnight timestamps. Built by date arithmetic rather
77+ // than fixed DAY_MS steps so a DST shift can't slide the grid by an hour.
78+ const columns = createMemo(() => {
79+ const start = firstWeekStart();
80+ return Array.from({ length: weeks() }, (_, week) =>
81+ Array.from({ length: 7 }, (_, day) => {
82+ const d = new Date(start);
83+ d.setDate(d.getDate() + week * 7 + day);
84+ return d.getTime();
85+ }),
86+ );
87+ });
88+
89+ const maxValue = createMemo(() => Math.max(0, ...totals().values()));
90+ const todayStart = createMemo(() => startOfDay(props.endsAt ?? Date.now()));
91+
92+ /** 0 = no data, 1..4 = quartiles of the busiest day. */
93+ const levelOf = (value: number) => {
94+ if (value <= 0) return 0;
95+ const peak = maxValue();
96+ if (peak <= 0) return 0;
97+ return Math.min(4, Math.ceil((value / peak) * 4));
98+ };
99+
100+ const levelClasses = [
101+ "bg-muted/60 dark:bg-muted/30",
102+ "bg-primary/25",
103+ "bg-primary/45",
104+ "bg-primary/70",
105+ "bg-primary",
106+ ];
107+
108+ const monthFormat = createMemo(
109+ () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { month: "short" }),
110+ );
111+ const weekdayFormat = createMemo(
112+ () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { weekday: "short" }),
113+ );
114+
115+ // A month label sits above the first column whose Monday opens a new month.
116+ const monthLabels = createMemo(() =>
117+ columns().map((week, index) => {
118+ const monday = new Date(week[0]);
119+ if (index > 0) {
120+ const previous = new Date(columns()[index - 1][0]);
121+ if (previous.getMonth() === monday.getMonth()) return "";
122+ }
123+ return monthFormat().format(monday);
124+ }),
125+ );
126+
127+ // Monday / Wednesday / Friday only β€” the full seven would not fit the gutter.
128+ const weekdayLabels = createMemo(() => {
129+ const week = columns()[0] ?? [];
130+ return week.map((day, index) => (index % 2 === 0 && index < 6 ? weekdayFormat().format(day) : ""));
131+ });
132+
133+ const hasData = createMemo(() => maxValue() > 0);
134+
135+ return (
136+ <div class={cn("flex flex-col gap-4 rounded-lg border border-border bg-card p-4 shadow-sm", props.class)}>
137+ <Show when={props.title}>
138+ <div class="border-b border-border pb-3">
139+ <h3 class="text-sm font-semibold tracking-tight text-foreground">{props.title}</h3>
140+ <Show when={props.subtitle}>
141+ <p class="mt-0.5 text-xs text-muted-foreground">{props.subtitle}</p>
142+ </Show>
143+ </div>
144+ </Show>
145+
146+ <Show
147+ when={hasData()}
148+ fallback={
149+ <div class="px-4 py-8 text-center">
150+ <p class="text-xs font-semibold text-foreground/80">{t("dashboard.chartEmpty")}</p>
151+ <p class="mt-0.5 text-[11px] text-muted-foreground">{t("dashboard.chartEmptyHint")}</p>
152+ </div>
153+ }
154+ >
155+ {/* One grid for labels and cells together: a weekday gutter column plus
156+ an equal fraction per week, so the calendar always spans the card's
157+ full width and every label stays on its own row. Below the min-width
158+ it scrolls instead of shrinking cells past legibility. */}
159+ {/* `px-1` keeps today's focus ring off the scroll container's clip
160+ edge, which otherwise shaves the last column's cells in half. */}
161+ <div class="overflow-x-auto px-1 pb-1">
162+ <div
163+ class="grid min-w-[460px] gap-1"
164+ style={{ "grid-template-columns": `auto repeat(${weeks()}, minmax(0, 1fr))` }}
165+ >
166+ <span aria-hidden="true" />
167+ <For each={monthLabels()}>
168+ {(label) => (
169+ <span class="text-[9px] leading-none text-muted-foreground">{label}</span>
170+ )}
171+ </For>
172+
173+ <For each={weekdayLabels()}>
174+ {(weekdayLabel, dayIndex) => (
175+ <>
176+ <span class="pr-1 text-right text-[9px] leading-none text-muted-foreground">
177+ {weekdayLabel}
178+ </span>
179+ <For each={columns()}>
180+ {(week) => {
181+ const day = week[dayIndex()];
182+ const value = () => totals().get(day) ?? 0;
183+ // Days after today are outside the observable range β€”
184+ // drawn as an empty slot so the last week keeps its shape.
185+ const future = () => day > todayStart();
186+ const label = () =>
187+ value() > 0 ? props.dayLabel(value(), day) : props.emptyDayLabel(day);
188+ return (
189+ <Show
190+ when={!future()}
191+ fallback={
192+ // Days after today simply do not exist yet. They hold
193+ // the last column's shape but stay invisible β€” an
194+ // outlined placeholder reads as a half-drawn cell.
195+ <span aria-hidden="true" class="aspect-square w-full" />
196+ }
197+ >
198+ <span
199+ class={cn(
200+ "aspect-square w-full rounded-[3px] transition-colors",
201+ levelClasses[levelOf(value())],
202+ day === todayStart() && "ring-1 ring-ring",
203+ )}
204+ title={label()}
205+ aria-label={label()}
206+ role="img"
207+ />
208+ </Show>
209+ );
210+ }}
211+ </For>
212+ </>
213+ )}
214+ </For>
215+ </div>
216+ </div>
217+
218+ <div class="flex flex-wrap items-center justify-between gap-2 border-t border-border pt-3">
219+ <Show when={props.footer}>
220+ <p class="text-[11px] text-muted-foreground">{props.footer}</p>
221+ </Show>
222+ <div class="ml-auto flex items-center gap-1.5">
223+ <span class="text-[10px] text-muted-foreground">{t("dashboard.heatmapLess")}</span>
224+ <For each={levelClasses}>
225+ {(levelClass) => <span class={cn("h-3 w-3 rounded-[3px]", levelClass)} />}
226+ </For>
227+ <span class="text-[10px] text-muted-foreground">{t("dashboard.heatmapMore")}</span>
228+ </div>
229+ </div>
230+ </Show>
231+ </div>
232+ );
233+};
src/i18n/messages.tsmodified+72 -21
@@ -332,11 +332,25 @@ export type MessageKey =
332 | "dashboard.progressOverviewDesc"332 | "dashboard.progressOverviewDesc"
333 | "dashboard.activitySplit"333 | "dashboard.activitySplit"
334 | "dashboard.activitySplitDesc"334 | "dashboard.activitySplitDesc"
335- | "dashboard.workloadSplit"
336- | "dashboard.workloadSplitDesc"
337 | "dashboard.deadlines"335 | "dashboard.deadlines"
338- | "dashboard.courseCapacities"
339 | "dashboard.courseAverages"336 | "dashboard.courseAverages"
337+ | "dashboard.successTrend"
338+ | "dashboard.successTrendMine"
339+ | "dashboard.successTrendSchool"
340+ | "dashboard.courseAveragesSchool"
341+ | "dashboard.examGraded"
342+ | "dashboard.focusHeatmap"
343+ | "dashboard.focusHeatmapDesc"
344+ | "dashboard.activityHeatmap"
345+ | "dashboard.activityHeatmapDesc"
346+ | "dashboard.heatmapLess"
347+ | "dashboard.heatmapMore"
348+ | "dashboard.heatmapFocusDay"
349+ | "dashboard.heatmapFocusEmpty"
350+ | "dashboard.heatmapRecordDay"
351+ | "dashboard.heatmapRecordEmpty"
352+ | "dashboard.heatmapFocusTotal"
353+ | "dashboard.heatmapRecordTotal"
340 | "dashboard.chartEmpty"354 | "dashboard.chartEmpty"
341 | "dashboard.chartEmptyHint"355 | "dashboard.chartEmptyHint"
342 | "dashboard.col.task"356 | "dashboard.col.task"
@@ -359,10 +373,6 @@ export type MessageKey =
359 | "dashboard.attend.excused"373 | "dashboard.attend.excused"
360 | "dashboard.welcomeBack"374 | "dashboard.welcomeBack"
361 | "dashboard.welcomeHint"375 | "dashboard.welcomeHint"
362- | "dashboard.teachingResources"
363- | "dashboard.teachingResourcesDesc"
364- | "dashboard.questionBankDesc"
365- | "dashboard.questionPoolDesc"
366 | "dashboard.quickReview.title"376 | "dashboard.quickReview.title"
367 | "dashboard.quickReview.subtitle"377 | "dashboard.quickReview.subtitle"
368 | "dashboard.quickReview.placeholder"378 | "dashboard.quickReview.placeholder"
@@ -1008,6 +1018,7 @@ export type MessageKey =
1008 | "whiteboard.subtitle"1018 | "whiteboard.subtitle"
1009 | "whiteboard.empty"1019 | "whiteboard.empty"
1010 | "whiteboard.create"1020 | "whiteboard.create"
1021+ | "whiteboard.edit"
1011 | "whiteboard.titleLabel"1022 | "whiteboard.titleLabel"
1012 | "whiteboard.participants"1023 | "whiteboard.participants"
1013 | "whiteboard.participantsHint"1024 | "whiteboard.participantsHint"
@@ -1100,6 +1111,12 @@ export type MessageKey =
1100 | "payments.methodTransfer"1111 | "payments.methodTransfer"
1101 | "payments.methodCard"1112 | "payments.methodCard"
1102 | "payments.methodCheck"1113 | "payments.methodCheck"
1114+ | "payments.methodOther"
1115+ | "payments.methodRequired"
1116+ | "payments.addStudent"
1117+ | "payments.selectedStudents"
1118+ | "payments.assignSelected"
1119+ | "payments.assignmentSummary"
1103 | "payments.ledgerAudit"1120 | "payments.ledgerAudit"
1104 | "payments.showLedger"1121 | "payments.showLedger"
1105 | "payments.hideLedger"1122 | "payments.hideLedger"
@@ -1600,10 +1617,24 @@ const en: Dict = {
1600 "dashboard.progressOverviewDesc": "Your performance across courses.",1617 "dashboard.progressOverviewDesc": "Your performance across courses.",
1601 "dashboard.activitySplit": "Attendance split",1618 "dashboard.activitySplit": "Attendance split",
1602 "dashboard.activitySplitDesc": "Your attendance breakdown.",1619 "dashboard.activitySplitDesc": "Your attendance breakdown.",
1603- "dashboard.workloadSplit": "Workload split",1620+ "dashboard.successTrend": "Success trend",
1604- "dashboard.workloadSplitDesc": "Courses, exams, events, and more.",1621+ "dashboard.successTrendMine": "Your exam marks over time.",
1622+ "dashboard.successTrendSchool": "Class averages of recent exams.",
1623+ "dashboard.courseAveragesSchool": "Average of recent exams, by course.",
1624+ "dashboard.examGraded": "{count} graded",
1625+ "dashboard.focusHeatmap": "Focus activity",
1626+ "dashboard.focusHeatmapDesc": "Your pomodoro sessions, day by day.",
1627+ "dashboard.activityHeatmap": "School activity",
1628+ "dashboard.activityHeatmapDesc": "Exams, events, and homework, day by day.",
1629+ "dashboard.heatmapLess": "Less",
1630+ "dashboard.heatmapMore": "More",
1631+ "dashboard.heatmapFocusDay": "{date}: {count} min focus",
1632+ "dashboard.heatmapFocusEmpty": "{date}: no focus session",
1633+ "dashboard.heatmapRecordDay": "{date}: {count} records",
1634+ "dashboard.heatmapRecordEmpty": "{date}: no records",
1635+ "dashboard.heatmapFocusTotal": "{count} min in the last {weeks} weeks",
1636+ "dashboard.heatmapRecordTotal": "{count} records in the last {weeks} weeks",
1605 "dashboard.deadlines": "Upcoming deadlines",1637 "dashboard.deadlines": "Upcoming deadlines",
1606- "dashboard.courseCapacities": "Course capacities",
1607 "dashboard.courseAverages": "Course averages",1638 "dashboard.courseAverages": "Course averages",
1608 "dashboard.chartEmpty": "No records found",1639 "dashboard.chartEmpty": "No records found",
1609 "dashboard.chartEmptyHint": "Not enough data to display yet.",1640 "dashboard.chartEmptyHint": "Not enough data to display yet.",
@@ -1627,10 +1658,6 @@ const en: Dict = {
1627 "dashboard.attend.excused": "Excused",1658 "dashboard.attend.excused": "Excused",
1628 "dashboard.welcomeBack": "Welcome back, {name}!",1659 "dashboard.welcomeBack": "Welcome back, {name}!",
1629 "dashboard.welcomeHint": "Here's what needs your attention today.",1660 "dashboard.welcomeHint": "Here's what needs your attention today.",
1630- "dashboard.teachingResources": "Teaching resources",
1631- "dashboard.teachingResourcesDesc": "Review reusable material and student questions.",
1632- "dashboard.questionBankDesc": "Build and reuse question templates for exams.",
1633- "dashboard.questionPoolDesc": "Review questions submitted by students.",
1634 "dashboard.quickReview.title": "Quick review",1661 "dashboard.quickReview.title": "Quick review",
1635 "dashboard.quickReview.subtitle": "Refresh what you’ve learned in just two minutes.",1662 "dashboard.quickReview.subtitle": "Refresh what you’ve learned in just two minutes.",
1636 "dashboard.quickReview.placeholder": "Choose a topic to review…",1663 "dashboard.quickReview.placeholder": "Choose a topic to review…",
@@ -2362,6 +2389,7 @@ const en: Dict = {
2362 "whiteboard.subtitle": "Live collaborative sketch boards.",2389 "whiteboard.subtitle": "Live collaborative sketch boards.",
2363 "whiteboard.empty": "No whiteboards yet.",2390 "whiteboard.empty": "No whiteboards yet.",
2364 "whiteboard.create": "New whiteboard",2391 "whiteboard.create": "New whiteboard",
2392+ "whiteboard.edit": "Edit whiteboard",
2365 "whiteboard.titleLabel": "Title",2393 "whiteboard.titleLabel": "Title",
2366 "whiteboard.participants": "Participants",2394 "whiteboard.participants": "Participants",
2367 "whiteboard.participantsHint": "Invite students and staff who may draw.",2395 "whiteboard.participantsHint": "Invite students and staff who may draw.",
@@ -2454,6 +2482,12 @@ const en: Dict = {
2454 "payments.methodTransfer": "Transfer / EFT",2482 "payments.methodTransfer": "Transfer / EFT",
2455 "payments.methodCard": "Card",2483 "payments.methodCard": "Card",
2456 "payments.methodCheck": "Cheque",2484 "payments.methodCheck": "Cheque",
2485+ "payments.methodOther": "Other",
2486+ "payments.methodRequired": "Enter a payment method.",
2487+ "payments.addStudent": "Add student",
2488+ "payments.selectedStudents": "Selected students ({count})",
2489+ "payments.assignSelected": "Assign selected",
2490+ "payments.assignmentSummary": "Assigned: {assigned} Β· Already assigned: {alreadyAssigned} Β· Rejected: {rejected}",
2457 "payments.ledgerAudit": "Account activity",2491 "payments.ledgerAudit": "Account activity",
2458 "payments.showLedger": "Show account activity",2492 "payments.showLedger": "Show account activity",
2459 "payments.hideLedger": "Hide account activity",2493 "payments.hideLedger": "Hide account activity",
@@ -2880,10 +2914,24 @@ const tr: Dict = {
2880 "dashboard.progressOverviewDesc": "Derslere gΓΆre performansΔ±n.",2914 "dashboard.progressOverviewDesc": "Derslere gΓΆre performansΔ±n.",
2881 "dashboard.activitySplit": "Yoklama dağılımı",2915 "dashboard.activitySplit": "Yoklama dağılımı",
2882 "dashboard.activitySplitDesc": "Yoklama dağılımın.",2916 "dashboard.activitySplitDesc": "Yoklama dağılımın.",
2883- "dashboard.workloadSplit": "İş yükü dağılımı",2917+ "dashboard.successTrend": "Başarı eğilimi",
2884- "dashboard.workloadSplitDesc": "Dersler, sΔ±navlar, etkinlikler ve dahasΔ±.",2918+ "dashboard.successTrendMine": "SΔ±nav notlarΔ±nΔ±n zaman iΓ§indeki seyri.",
2919+ "dashboard.successTrendSchool": "Son sΔ±navlarΔ±n sΔ±nΔ±f ortalamalarΔ±.",
2920+ "dashboard.courseAveragesSchool": "Son sΔ±navlara gΓΆre ders bazΔ±nda ortalama.",
2921+ "dashboard.examGraded": "{count} notlandΔ±rΔ±ldΔ±",
2922+ "dashboard.focusHeatmap": "Odaklanma etkinliği",
2923+ "dashboard.focusHeatmapDesc": "GΓΌn gΓΌn pomodoro oturumlarΔ±n.",
2924+ "dashboard.activityHeatmap": "Okul etkinliği",
2925+ "dashboard.activityHeatmapDesc": "GΓΌn gΓΌn sΔ±nav, etkinlik ve ΓΆdevler.",
2926+ "dashboard.heatmapLess": "Az",
2927+ "dashboard.heatmapMore": "Γ‡ok",
2928+ "dashboard.heatmapFocusDay": "{date}: {count} dk odaklanma",
2929+ "dashboard.heatmapFocusEmpty": "{date}: odaklanma yok",
2930+ "dashboard.heatmapRecordDay": "{date}: {count} kayΔ±t",
2931+ "dashboard.heatmapRecordEmpty": "{date}: kayΔ±t yok",
2932+ "dashboard.heatmapFocusTotal": "Son {weeks} haftada {count} dk",
2933+ "dashboard.heatmapRecordTotal": "Son {weeks} haftada {count} kayΔ±t",
2885 "dashboard.deadlines": "Yaklaşan son tarihler",2934 "dashboard.deadlines": "Yaklaşan son tarihler",
2886- "dashboard.courseCapacities": "Eğitim kapasiteleri",
2887 "dashboard.courseAverages": "Ders ortalamalarΔ±",2935 "dashboard.courseAverages": "Ders ortalamalarΔ±",
2888 "dashboard.chartEmpty": "KayΔ±t bulunamadΔ±",2936 "dashboard.chartEmpty": "KayΔ±t bulunamadΔ±",
2889 "dashboard.chartEmptyHint": "GΓΆsterilecek yeterli veri yok.",2937 "dashboard.chartEmptyHint": "GΓΆsterilecek yeterli veri yok.",
@@ -2907,10 +2955,6 @@ const tr: Dict = {
2907 "dashboard.attend.excused": "Δ°zinli",2955 "dashboard.attend.excused": "Δ°zinli",
2908 "dashboard.welcomeBack": "Tekrar hoş geldin, {name}!",2956 "dashboard.welcomeBack": "Tekrar hoş geldin, {name}!",
2909 "dashboard.welcomeHint": "BugΓΌn dikkat etmen gerekenler burada.",2957 "dashboard.welcomeHint": "BugΓΌn dikkat etmen gerekenler burada.",
2910- "dashboard.teachingResources": "Γ–ΔŸretim kaynaklarΔ±",
2911- "dashboard.teachingResourcesDesc": "Yeniden kullanılabilir içerikleri ve âğrenci sorularını incele.",
2912- "dashboard.questionBankDesc": "Sınavlar için soru şablonları oluştur ve yeniden kullan.",
2913- "dashboard.questionPoolDesc": "Γ–ΔŸrencilerin gΓΆnderdiği sorularΔ± incele.",
2914 "dashboard.quickReview.title": "HΔ±zlΔ± tekrar",2958 "dashboard.quickReview.title": "HΔ±zlΔ± tekrar",
2915 "dashboard.quickReview.subtitle": "Γ–ΔŸrendiklerinizi yalnΔ±zca iki dakikada tazeleyin.",2959 "dashboard.quickReview.subtitle": "Γ–ΔŸrendiklerinizi yalnΔ±zca iki dakikada tazeleyin.",
2916 "dashboard.quickReview.placeholder": "Tekrar iΓ§in konu seç…",2960 "dashboard.quickReview.placeholder": "Tekrar iΓ§in konu seç…",
@@ -3642,6 +3686,7 @@ const tr: Dict = {
3642 "whiteboard.subtitle": "CanlΔ± ortak Γ§izim tahtalarΔ±.",3686 "whiteboard.subtitle": "CanlΔ± ortak Γ§izim tahtalarΔ±.",
3643 "whiteboard.empty": "HenΓΌz beyaz tahta yok.",3687 "whiteboard.empty": "HenΓΌz beyaz tahta yok.",
3644 "whiteboard.create": "Yeni tahta",3688 "whiteboard.create": "Yeni tahta",
3689+ "whiteboard.edit": "TahtayΔ± dΓΌzenle",
3645 "whiteboard.titleLabel": "Başlık",3690 "whiteboard.titleLabel": "Başlık",
3646 "whiteboard.participants": "KatΔ±lΔ±mcΔ±lar",3691 "whiteboard.participants": "KatΔ±lΔ±mcΔ±lar",
3647 "whiteboard.participantsHint": "Γ‡izebilecek âğrenci ve personeli davet edin.",3692 "whiteboard.participantsHint": "Γ‡izebilecek âğrenci ve personeli davet edin.",
@@ -3734,6 +3779,12 @@ const tr: Dict = {
3734 "payments.methodTransfer": "Havale / EFT",3779 "payments.methodTransfer": "Havale / EFT",
3735 "payments.methodCard": "Kredi kartΔ±",3780 "payments.methodCard": "Kredi kartΔ±",
3736 "payments.methodCheck": "Γ‡ek",3781 "payments.methodCheck": "Γ‡ek",
3782+ "payments.methodOther": "Diğer",
3783+ "payments.methodRequired": "Bir ΓΆdeme yΓΆntemi girin.",
3784+ "payments.addStudent": "Γ–ΔŸrenci ekle",
3785+ "payments.selectedStudents": "Seçilen âğrenciler ({count})",
3786+ "payments.assignSelected": "SeΓ§ilenleri ata",
3787+ "payments.assignmentSummary": "Atandı: {assigned} · Zaten atanmış: {alreadyAssigned} · Reddedildi: {rejected}",
3737 "payments.ledgerAudit": "Hesap hareketleri",3788 "payments.ledgerAudit": "Hesap hareketleri",
3738 "payments.showLedger": "Hesap hareketlerini gΓΆster",3789 "payments.showLedger": "Hesap hareketlerini gΓΆster",
3739 "payments.hideLedger": "Hesap hareketlerini gizle",3790 "payments.hideLedger": "Hesap hareketlerini gizle",
src/pages/dashboard-page.test.tsxmodified+95 -30
@@ -31,6 +31,7 @@ vi.mock("@/stores/auth-context", () => ({
31 }));31 }));
32 32
33 const now = Date.UTC(2026, 6, 28, 9);33 const now = Date.UTC(2026, 6, 28, 9);
34+const DAY = 24 * 60 * 60 * 1000;
34 const page = <T,>(items: T[]) => ({ items, total: items.length, limit: 50, offset: 0 });35 const page = <T,>(items: T[]) => ({ items, total: items.length, limit: 50, offset: 0 });
35 const course = { id: "course-1", title: "Algebra", capacity: 24 };36 const course = { id: "course-1", title: "Algebra", capacity: 24 };
36 37
@@ -40,7 +41,11 @@ vi.mock("@/api/reports", () => ({
40 getMyCourses: async () => page([course]),41 getMyCourses: async () => page([course]),
41 getMyMarks: async () => ({42 getMyMarks: async () => ({
42 overall_average: 82.5,43 overall_average: 82.5,
43- courses: [{ course, results: [], average: 82.5 }],44+ courses: [{
45+ course,
46+ average: 82.5,
47+ results: [{ exam: "exam-past", title: "Midterm", kind: "exam", weight: 1, mark: 78, graded_by: "t-1" }],
48+ }],
44 }),49 }),
45 getMyAttendance: async () => ({50 getMyAttendance: async () => ({
46 events: { total: 3, present: 2, absent: 1, late: 0, excused: 0 },51 events: { total: 3, present: 2, absent: 1, late: 0, excused: 0 },
@@ -48,27 +53,64 @@ vi.mock("@/api/reports", () => ({
48 }),53 }),
49 }));54 }));
50 vi.mock("@/api/exams", () => ({55 vi.mock("@/api/exams", () => ({
51- getExams: async () => page([{56+ getExams: async () => page([
52- id: "exam-1",57+ {
53- title: "Exam deadline",58+ id: "exam-1",
54- starts_at: now + 1_000,59+ title: "Exam deadline",
55- ends_at: now + 3_000,60+ course: "course-1",
56- }]),61+ draft: false,
62+ starts_at: now + 1_000,
63+ ends_at: now + 3_000,
64+ },
65+ {
66+ id: "exam-past",
67+ title: "Midterm",
68+ course: "course-1",
69+ draft: false,
70+ starts_at: now - 10 * DAY,
71+ ends_at: now - 10 * DAY + 3_000,
72+ },
73+ ]),
74+ getExamStatistics: async (examId: string) => ({
75+ exam: examId,
76+ graded: 12,
77+ average: 74.5,
78+ min: 40,
79+ max: 96,
80+ }),
81+}));
82+vi.mock("@/api/pomodoro", () => ({
83+ getPomodoroMe: async () => ({
84+ items: [
85+ { id: "pom-1", user: "u-1", started_at: now - 3 * DAY, finished_at: now - 3 * DAY + 1_500_000, duration_ms: 1_500_000 },
86+ { id: "pom-2", user: "u-1", started_at: now - DAY, finished_at: now - DAY + 3_000_000, duration_ms: 3_000_000 },
87+ ],
88+ total: 2,
89+ limit: 400,
90+ offset: 0,
91+ total_focus_ms: 4_500_000,
92+ }),
57 }));93 }));
58 vi.mock("@/api/events", () => ({94 vi.mock("@/api/events", () => ({
59- getEvents: async () => page([{95+ getEvents: async () => page([
60- id: "event-1",96+ {
61- title: "Event deadline",97+ id: "event-1",
62- starts_at: now + 2_000,98+ title: "Event deadline",
63- ends_at: now + 4_000,99+ starts_at: now + 2_000,
64- }]),100+ ends_at: now + 4_000,
101+ },
102+ { id: "event-past", title: "Past event", starts_at: now - 5 * DAY, ends_at: now - 5 * DAY + 1_000 },
103+ ]),
65 }));104 }));
66 vi.mock("@/api/homework", () => ({105 vi.mock("@/api/homework", () => ({
67- getHomework: async () => page([{106+ getHomework: async () => page([
68- id: "homework-1",107+ {
69- title: "Homework deadline",108+ id: "homework-1",
70- due_at: now + 5_000,109+ title: "Homework deadline",
71- }]),110+ due_at: now + 5_000,
111+ },
112+ { id: "homework-past", title: "Past homework", due_at: now - 6 * DAY },
113+ ]),
72 }));114 }));
73 vi.mock("@/api/appointments", () => ({115 vi.mock("@/api/appointments", () => ({
74 getAppointments: async () => page([{116 getAppointments: async () => page([{
@@ -111,14 +153,25 @@ test("logged-out visitor redirects before dashboard reads user role", () => {
111 expect(screen.getByText("redirect:/login")).toBeTruthy();153 expect(screen.getByText("redirect:/login")).toBeTruthy();
112 });154 });
113 155
114-test("student sees truthful charts, full-width deadlines, and no teaching resources", async () => {156+test("student sees own trend plus focus heatmap, and a standalone deadlines table", async () => {
115 const view = renderDashboard("student");157 const view = renderDashboard("student");
116 158
117 expect(await screen.findByText("Course averages")).toBeTruthy();159 expect(await screen.findByText("Course averages")).toBeTruthy();
160+ expect(screen.getByText("Success trend")).toBeTruthy();
161+ expect(screen.getByText("Your exam marks over time.")).toBeTruthy();
118 expect(screen.getByText("Attendance split")).toBeTruthy();162 expect(screen.getByText("Attendance split")).toBeTruthy();
119 expect(screen.queryByText("Teaching resources")).toBeNull();163 expect(screen.queryByText("Teaching resources")).toBeNull();
120- expect(screen.getByRole("link", { name: "Appointments" })).toBeTruthy();164+ // The table stands alone now β€” no side panel, so no column span and no
121- expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-3");165+ // "Appointments" shortcut in its header.
166+ expect(screen.queryByRole("link", { name: "Appointments" })).toBeNull();
167+ expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span");
168+ // A student's heatmap is their own focus log, never school-wide records.
169+ expect(screen.getByText("Focus activity")).toBeTruthy();
170+ expect(screen.queryByText("School activity")).toBeNull();
171+ // Sessions are bucketed per calendar day: 25 min three days ago, 50 min yesterday.
172+ expect(screen.getByLabelText(/25 min focus/)).toBeTruthy();
173+ expect(screen.getByLabelText(/50 min focus/)).toBeTruthy();
174+ expect(screen.getByText("75 min in the last 26 weeks")).toBeTruthy();
122 expect(view.container.querySelector("polyline")).toBeNull();175 expect(view.container.querySelector("polyline")).toBeNull();
123 expect(screen.queryByText("Priority")).toBeNull();176 expect(screen.queryByText("Priority")).toBeNull();
124 expect(screen.queryByText("Refresh data")).toBeNull();177 expect(screen.queryByText("Refresh data")).toBeNull();
@@ -135,16 +188,27 @@ test("student sees truthful charts, full-width deadlines, and no teaching resour
135 expect(navigate).toHaveBeenCalledWith({ to: "/appointments" });188 expect(navigate).toHaveBeenCalledWith({ to: "/appointments" });
136 });189 });
137 190
138-test("teacher sees capacities and useful teaching-resource links", async () => {191+test("teacher sees real exam averages instead of capacities and resource links", async () => {
139 renderDashboard("teacher");192 renderDashboard("teacher");
140 193
141- expect(await screen.findByText("Course capacities")).toBeTruthy();194+ // Exam averages come from the backend's own statistics, so the panel reports
142- expect(screen.queryByText("Class sizes")).toBeNull();195+ // marks rather than the meaningless capacity/workload counts it replaced.
143- expect(screen.getByText("Workload split")).toBeTruthy();196+ expect(await screen.findByText("Class averages of recent exams.")).toBeTruthy();
144- expect(screen.getByText("Teaching resources")).toBeTruthy();197+ expect(screen.getByText("Success trend")).toBeTruthy();
145- expect(screen.getByRole("link", { name: /Build and reuse question templates/ })).toBeTruthy();198+ expect(screen.getByText("Average of recent exams, by course.")).toBeTruthy();
146- expect(screen.getByRole("link", { name: /Review questions submitted by students/ })).toBeTruthy();199+ // Both the trend bar and the per-course bar carry the backend's average.
147- expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-2");200+ expect((await screen.findAllByText("74.5")).length).toBeGreaterThanOrEqual(2);
201+ expect(screen.queryByText("Course capacities")).toBeNull();
202+ expect(screen.queryByText("Workload split")).toBeNull();
203+ expect(screen.queryByText("Teaching resources")).toBeNull();
204+ expect(screen.queryByRole("link", { name: /Build and reuse question templates/ })).toBeNull();
205+ expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span");
206+ expect(screen.getByText("School activity")).toBeTruthy();
207+ expect(screen.queryByText("Focus activity")).toBeNull();
208+ // The heatmap looks backwards, so it must be fed by the unfiltered read β€”
209+ // the page's own event/homework resources are future-only and would leave
210+ // the grid almost entirely empty. One past exam, event, and homework each.
211+ expect((await screen.findAllByLabelText(/: 1 records/)).length).toBe(3);
148 });212 });
149 213
150 test("parent sees family highlights and appointment deadlines without staff charts", async () => {214 test("parent sees family highlights and appointment deadlines without staff charts", async () => {
@@ -154,7 +218,8 @@ test("parent sees family highlights and appointment deadlines without staff char
154 expect(screen.getAllByText("Appointments").length).toBeGreaterThan(0);218 expect(screen.getAllByText("Appointments").length).toBeGreaterThan(0);
155 expect(screen.getByText("Meal menus")).toBeTruthy();219 expect(screen.getByText("Meal menus")).toBeTruthy();
156 expect(screen.queryByText("Progress overview")).toBeNull();220 expect(screen.queryByText("Progress overview")).toBeNull();
221+ expect(screen.queryByText("Success trend")).toBeNull();
157 expect(screen.queryByText("Teaching resources")).toBeNull();222 expect(screen.queryByText("Teaching resources")).toBeNull();
158 expect(await screen.findByRole("button", { name: /Teacher Name/ })).toBeTruthy();223 expect(await screen.findByRole("button", { name: /Teacher Name/ })).toBeTruthy();
159- expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-3");224+ expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span");
160 });225 });
src/pages/dashboard-page.tsxmodified+202 -87
@@ -1,5 +1,5 @@
1 import { For, Show, Suspense, createMemo, createResource, type Component } from "solid-js";1 import { For, Show, Suspense, createMemo, createResource, type Component } from "solid-js";
2-import { Link, useNavigate } from "@tanstack/solid-router";2+import { useNavigate } from "@tanstack/solid-router";
3 import type { ColumnDef } from "@tanstack/solid-table";3 import type { ColumnDef } from "@tanstack/solid-table";
4 import type { Role } from "@/api/client";4 import type { Role } from "@/api/client";
5 import { formatApiError } from "@/api/client";5 import { formatApiError } from "@/api/client";
@@ -7,15 +7,17 @@ import { getAppointments } from "@/api/appointments";
7 import { getMyClasses } from "@/api/classes";7 import { getMyClasses } from "@/api/classes";
8 import { getCourses } from "@/api/courses";8 import { getCourses } from "@/api/courses";
9 import { getEvents } from "@/api/events";9 import { getEvents } from "@/api/events";
10-import { getExams } from "@/api/exams";10+import { getExams, getExamStatistics } from "@/api/exams";
11 import { getHomework } from "@/api/homework";11 import { getHomework } from "@/api/homework";
12 import { getMealMenus } from "@/api/meals";12 import { getMealMenus } from "@/api/meals";
13 import { getMyStudents } from "@/api/parents";13 import { getMyStudents } from "@/api/parents";
14+import { getPomodoroMe } from "@/api/pomodoro";
14 import { getMyAttendance, getMyCourses, getMyMarks } from "@/api/reports";15 import { getMyAttendance, getMyCourses, getMyMarks } from "@/api/reports";
15 import { getTime } from "@/api/time/getTime";16 import { getTime } from "@/api/time/getTime";
16 import { RouteGuard } from "@/components/layout/route-guard";17 import { RouteGuard } from "@/components/layout/route-guard";
17 import { Badge } from "@/components/ui/badge";18 import { Badge } from "@/components/ui/badge";
18 import { ChartBar } from "@/components/ui/chart-bar";19 import { ChartBar } from "@/components/ui/chart-bar";
20+import { ChartHeatmap, type HeatmapEntry } from "@/components/ui/chart-heatmap";
19 import { ChartProgressRing } from "@/components/ui/chart-progress-ring";21 import { ChartProgressRing } from "@/components/ui/chart-progress-ring";
20 import { DataTable } from "@/components/ui/data-table";22 import { DataTable } from "@/components/ui/data-table";
21 import {23 import {
@@ -38,6 +40,16 @@ import { usePreferences, useT } from "@/stores/preferences-context";
38 40
39 const DAY_MS = 24 * 60 * 60 * 1000;41 const DAY_MS = 24 * 60 * 60 * 1000;
40 const WEEK_MS = 7 * DAY_MS;42 const WEEK_MS = 7 * DAY_MS;
43+/** Weeks covered by the bottom activity heatmap. */
44+const HEATMAP_WEEKS = 26;
45+/**
46+ * Exams pulled into the teacher+ success trend. Each one costs a separate
47+ * `/exams/{id}/statistics` call β€” there is no bulk statistics endpoint β€” so the
48+ * homepage reads only the most recent handful.
49+ */
50+const TREND_EXAM_CAP = 8;
51+/** Marks plotted in a student's own trend. */
52+const TREND_MARK_CAP = 10;
41 53
42 type Status = "active" | "today" | "soon";54 type Status = "active" | "today" | "soon";
43 type DeadlineKind = "exam" | "event" | "appointment" | "homework";55 type DeadlineKind = "exam" | "event" | "appointment" | "homework";
@@ -91,12 +103,13 @@ function DashboardContent() {
91 const user = () => auth.user()!;103 const user = () => auth.user()!;
92 const role = () => user().role;104 const role = () => user().role;
93 const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() })));105 const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() })));
106+ // Unpaged: the backend has no `kind` filter, so a "courses" count that
107+ // excludes studies and clubs has to be counted here over the whole list.
94 const [courses] = createResource(108 const [courses] = createResource(
95 () => role() === "parent" ? null : role(),109 () => role() === "parent" ? null : role(),
96- (currentRole) => currentRole === "student"110+ (currentRole) => currentRole === "student" ? getMyCourses() : getCourses(),
97- ? getMyCourses({ kind: "course", limit: 12 })
98- : getCourses({ kind: "course", limit: 12 }),
99 );111 );
112+ const courseCount = () => (courses()?.items ?? []).filter((course) => course.kind === "course").length;
100 const [events] = createResource(113 const [events] = createResource(
101 () => role() === "parent" ? null : clock()?.now,114 () => role() === "parent" ? null : clock()?.now,
102 (now) => getEvents({ ends_after: now, limit: 50 }),115 (now) => getEvents({ ends_after: now, limit: 50 }),
@@ -105,9 +118,12 @@ function DashboardContent() {
105 () => role() === "parent" ? null : role(),118 () => role() === "parent" ? null : role(),
106 () => getExams({ limit: 50 }),119 () => getExams({ limit: 50 }),
107 );120 );
121+ // Unfiltered: `/homework` has no due-date window, so this one read serves both
122+ // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking
123+ // heatmap.
108 const [homework] = createResource(124 const [homework] = createResource(
109- () => role() === "parent" ? null : clock()?.now,125+ () => role() === "parent" ? null : role(),
110- (now) => getHomework({ due_after: now, limit: 50 }),126+ () => getHomework({ limit: 100 }),
111 );127 );
112 const [children] = createResource(128 const [children] = createResource(
113 () => role() === "parent" ? true : null,129 () => role() === "parent" ? true : null,
@@ -130,6 +146,43 @@ function DashboardContent() {
130 () => role() === "student" ? true : null,146 () => role() === "student" ? true : null,
131 () => getMyClasses({ limit: 1 }),147 () => getMyClasses({ limit: 1 }),
132 );148 );
149+ // Focus heatmap source. Only a student owns pomodoro sessions β€” reading
150+ // another user's log is the teacher+ /management/pomodoros page's job.
151+ const [pomodoro] = createResource(
152+ () => role() === "student" ? true : null,
153+ () => getPomodoroMe({ limit: 400 }),
154+ );
155+ // `/events` is the one list here that really is filtered server-side, by the
156+ // `ends_after` window the deadlines table needs. The heatmap looks backwards
157+ // and there is no "before" filter, so past events need their own read.
158+ const [pastEvents] = createResource(
159+ () => hasMinRole(role(), "teacher") ? true : null,
160+ () => getEvents({ limit: 100 }).catch(() => null),
161+ );
162+ // Success trend source for teacher+. Exam statistics are grader-only, so this
163+ // never runs for a student or parent β€” they would get a 403.
164+ const [examStats] = createResource(
165+ () => hasMinRole(role(), "teacher") ? exams.latest?.items ?? null : null,
166+ async (items) => {
167+ const recent = items
168+ .filter((exam) => !exam.draft && exam.starts_at != null && exam.starts_at <= now())
169+ .sort((a, b) => b.starts_at! - a.starts_at!)
170+ .slice(0, TREND_EXAM_CAP);
171+ const settled = await Promise.all(
172+ recent.map(async (exam) => {
173+ try {
174+ return { exam, stats: await getExamStatistics(exam.id) };
175+ } catch {
176+ // One ungraded or forbidden exam must not blank the whole panel.
177+ return { exam, stats: null };
178+ }
179+ }),
180+ );
181+ return settled
182+ .filter((row) => row.stats?.average != null)
183+ .sort((a, b) => a.exam.starts_at! - b.exam.starts_at!);
184+ },
185+ );
133 const myClass = () => myClasses.latest?.items[0] ?? null;186 const myClass = () => myClasses.latest?.items[0] ?? null;
134 187
135 const fullName = () => [user().name, user().surname].filter(Boolean).join(" ") || user().username;188 const fullName = () => [user().name, user().surname].filter(Boolean).join(" ") || user().username;
@@ -147,7 +200,7 @@ function DashboardContent() {
147 const r = role();200 const r = role();
148 if (r === "student") {201 if (r === "student") {
149 return [202 return [
150- { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook },203+ { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook },
151 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },204 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },
152 { labelKey: "dashboard.stats.average", value: marks()?.overall_average == null ? "β€”" : marks()!.overall_average!.toFixed(1), Icon: IconChart },205 { labelKey: "dashboard.stats.average", value: marks()?.overall_average == null ? "β€”" : marks()!.overall_average!.toFixed(1), Icon: IconChart },
153 { labelKey: "dashboard.stats.attendance", value: attendanceRate() == null ? "β€”" : `${attendanceRate()}%`, Icon: IconClipboardCheck },206 { labelKey: "dashboard.stats.attendance", value: attendanceRate() == null ? "β€”" : `${attendanceRate()}%`, Icon: IconClipboardCheck },
@@ -155,7 +208,7 @@ function DashboardContent() {
155 }208 }
156 if (r === "teacher") {209 if (r === "teacher") {
157 return [210 return [
158- { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook },211+ { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook },
159 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },212 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },
160 { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays },213 { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays },
161 { labelKey: "dashboard.stats.homework", value: String(homework()?.total ?? 0), Icon: IconHomework },214 { labelKey: "dashboard.stats.homework", value: String(homework()?.total ?? 0), Icon: IconHomework },
@@ -169,24 +222,74 @@ function DashboardContent() {
169 ];222 ];
170 }223 }
171 return [224 return [
172- { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook },225+ { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook },
173 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },226 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },
174 { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays },227 { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays },
175 { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils },228 { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils },
176 ];229 ];
177 });230 });
178 231
179- // Progress panel β€” student: per-course averages; teacher/manager/admin: course capacities.232+ // Student trend β€” own marks ordered by their exam's date. Marks whose exam
233+ // falls outside the fetched exam page carry no date and are left out rather
234+ // than guessed into the sequence.
235+ const myMarkTrend = createMemo(() => {
236+ const report = marks();
237+ if (!report) return [];
238+ const examDates = new Map((exams()?.items ?? []).map((exam) => [exam.id, exam.starts_at]));
239+ return report.courses
240+ .flatMap((course) =>
241+ course.results.map((result) => ({
242+ id: `${course.course.id}:${result.exam}`,
243+ label: result.title,
244+ value: result.mark,
245+ at: examDates.get(result.exam) ?? null,
246+ })),
247+ )
248+ .filter((row): row is typeof row & { at: number } => row.at != null)
249+ .sort((a, b) => a.at - b.at)
250+ .slice(-TREND_MARK_CAP)
251+ .map((row) => ({ id: row.id, label: row.label, value: row.value, formattedValue: row.value.toFixed(1) }));
252+ });
253+
254+ // Teacher+ trend β€” the backend's own per-exam average, oldest exam first.
255+ const examAverageTrend = createMemo(() =>
256+ (examStats() ?? []).map((row) => ({
257+ id: row.exam.id,
258+ label: row.exam.title,
259+ value: row.stats!.average!,
260+ formattedValue: row.stats!.average!.toFixed(1),
261+ })),
262+ );
263+
264+ // Teacher+ side panel β€” the same exam averages grouped by course, so a weak
265+ // subject stands out rather than being averaged into one school-wide number.
266+ const courseAverageBars = createMemo(() => {
267+ const titles = new Map((courses()?.items ?? []).map((course) => [course.id, course.title]));
268+ const buckets = new Map<string, number[]>();
269+ for (const row of examStats() ?? []) {
270+ const list = buckets.get(row.exam.course) ?? [];
271+ list.push(row.stats!.average!);
272+ buckets.set(row.exam.course, list);
273+ }
274+ return [...buckets.entries()]
275+ .map(([courseId, averages]) => {
276+ const mean = averages.reduce((sum, value) => sum + value, 0) / averages.length;
277+ return {
278+ id: courseId,
279+ label: titles.get(courseId) ?? courseId,
280+ value: mean,
281+ formattedValue: mean.toFixed(1),
282+ };
283+ })
284+ .sort((a, b) => b.value - a.value);
285+ });
286+
287+ // Student progress panel β€” per-course averages from the marks report.
180 const courseAverages = createMemo(() =>288 const courseAverages = createMemo(() =>
181 (marks()?.courses ?? [])289 (marks()?.courses ?? [])
182 .filter((c) => c.average != null)290 .filter((c) => c.average != null)
183 .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: c.average!.toFixed(1) })),291 .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: c.average!.toFixed(1) })),
184 );292 );
185- const courseCapacities = createMemo(() =>
186- (courses()?.items ?? [])
187- .filter((c) => c.capacity != null)
188- .map((c) => ({ id: c.id, label: c.title, value: c.capacity! })),
189- );
190 293
191 // Weekly activity split β€” student attendance breakdown (events + sessions).294 // Weekly activity split β€” student attendance breakdown (events + sessions).
192 const attendanceSegments = createMemo(() => {295 const attendanceSegments = createMemo(() => {
@@ -201,18 +304,38 @@ function DashboardContent() {
201 ];304 ];
202 });305 });
203 306
204- // Right-side "workload split" for non-student roles β€” real resource totals.307+ // Bottom heatmap. A student's own focus minutes; every other role gets the
205- const workloadSegments = createMemo(() => {308+ // dated records they already read on this page β€” nobody's grid is built from
206- const r = role();309+ // an endpoint their role cannot call.
207- const base = [310+ const heatmapIsFocus = () => role() === "student";
208- { id: "courses", label: t("nav.classes"), value: courses()?.total ?? 0, colorClass: "bg-primary" },311+ const heatmapEntries = createMemo<HeatmapEntry[]>(() => {
209- { id: "exams", label: t("nav.exams"), value: exams()?.total ?? 0, colorClass: "bg-blue-500" },312+ if (heatmapIsFocus()) {
210- { id: "events", label: t("nav.events"), value: events()?.total ?? 0, colorClass: "bg-emerald-500" },313+ return (pomodoro()?.items ?? [])
211- ];314+ .filter((session) => session.duration_ms != null && session.duration_ms > 0)
212- if (r === "teacher") {315+ .map((session) => ({ at: session.started_at, value: Math.round(session.duration_ms! / 60000) }));
213- return [...base, { id: "homework", label: t("nav.homework"), value: homework()?.total ?? 0, colorClass: "bg-rose-500" }];316+ }
317+ if (role() === "parent") {
318+ return (appointments()?.items ?? [])
319+ .filter((appointment) => appointment.starts_at != null)
320+ .map((appointment) => ({ at: appointment.starts_at!, value: 1 }));
214 }321 }
215- return [...base, { id: "meals", label: t("nav.meals"), value: menus()?.total ?? 0, colorClass: "bg-rose-500" }];322+ // Exams and homework are already read unfiltered, so they carry their own
323+ // past; only events need the backwards-looking read.
324+ return [
325+ ...(exams()?.items ?? []).filter((exam) => exam.starts_at != null).map((exam) => ({ at: exam.starts_at!, value: 1 })),
326+ ...(pastEvents()?.items ?? []).filter((event) => event.starts_at != null).map((event) => ({ at: event.starts_at!, value: 1 })),
327+ ...(homework()?.items ?? []).map((hw) => ({ at: hw.due_at, value: 1 })),
328+ ];
329+ });
330+
331+ const heatmapDateFormat = createMemo(
332+ () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { day: "numeric", month: "short" }),
333+ );
334+ const heatmapTotal = createMemo(() => {
335+ const cutoff = now() - HEATMAP_WEEKS * WEEK_MS;
336+ return heatmapEntries()
337+ .filter((entry) => entry.at >= cutoff && entry.at <= now())
338+ .reduce((sum, entry) => sum + entry.value, 0);
216 });339 });
217 340
218 const deadlines = createMemo<DeadlineRow[]>(() => {341 const deadlines = createMemo<DeadlineRow[]>(() => {
@@ -295,7 +418,7 @@ function DashboardContent() {
295 };418 };
296 419
297 const error = createMemo(() => {420 const error = createMemo(() => {
298- const problem = courses.error || events.error || exams.error || homework.error || children.error || appointments.error || menus.error || marks.error || attendance.error || myClasses.error;421+ const problem = courses.error || events.error || exams.error || homework.error || children.error || appointments.error || menus.error || marks.error || attendance.error || myClasses.error || pomodoro.error;
299 return problem ? formatApiError(problem, locale()) : "";422 return problem ? formatApiError(problem, locale()) : "";
300 });423 });
301 424
@@ -347,24 +470,19 @@ function DashboardContent() {
347 <div class="grid gap-3 lg:grid-cols-3">470 <div class="grid gap-3 lg:grid-cols-3">
348 <Show when={role() === "student"}>471 <Show when={role() === "student"}>
349 <ChartBar472 <ChartBar
350- class="lg:col-span-2"
351 title={t("dashboard.progressOverview")}473 title={t("dashboard.progressOverview")}
352 subtitle={t("dashboard.courseAverages")}474 subtitle={t("dashboard.courseAverages")}
353 items={courseAverages()}475 items={courseAverages()}
354 maxScale={100}476 maxScale={100}
355 itemsPerPage={5}477 itemsPerPage={5}
356 />478 />
357- </Show>
358- <Show when={role() !== "student"}>
359 <ChartBar479 <ChartBar
360- class="lg:col-span-2"480+ title={t("dashboard.successTrend")}
361- title={t("dashboard.progressOverview")}481+ subtitle={t("dashboard.successTrendMine")}
362- subtitle={t("dashboard.courseCapacities")}482+ items={myMarkTrend()}
363- items={courseCapacities()}483+ maxScale={100}
364 itemsPerPage={5}484 itemsPerPage={5}
365 />485 />
366- </Show>
367- <Show when={role() === "student"}>
368 <ChartProgressRing486 <ChartProgressRing
369 title={t("dashboard.activitySplit")}487 title={t("dashboard.activitySplit")}
370 subtitle={t("dashboard.activitySplitDesc")}488 subtitle={t("dashboard.activitySplitDesc")}
@@ -373,62 +491,59 @@ function DashboardContent() {
373 />491 />
374 </Show>492 </Show>
375 <Show when={role() !== "student"}>493 <Show when={role() !== "student"}>
376- <ChartProgressRing494+ <ChartBar
377- title={t("dashboard.workloadSplit")}495+ class="lg:col-span-2"
378- subtitle={t("dashboard.workloadSplitDesc")}496+ title={t("dashboard.successTrend")}
379- segments={workloadSegments()}497+ subtitle={t("dashboard.successTrendSchool")}
380- itemsPerPage={3}498+ items={examAverageTrend()}
499+ maxScale={100}
500+ itemsPerPage={5}
501+ />
502+ <ChartBar
503+ title={t("dashboard.courseAverages")}
504+ subtitle={t("dashboard.courseAveragesSchool")}
505+ items={courseAverageBars()}
506+ maxScale={100}
507+ itemsPerPage={5}
381 />508 />
382 </Show>509 </Show>
383 </div>510 </div>
384 </Show>511 </Show>
385 512
386- <div class="grid gap-3 lg:grid-cols-3">513+ <section class="flex flex-col gap-4 rounded-lg border border-border bg-card p-4 shadow-xs" aria-labelledby="deadlines-heading">
387- <section class={cn("flex flex-col gap-4 rounded-lg border border-border bg-card p-4 shadow-xs", hasMinRole(role(), "teacher") ? "lg:col-span-2" : "lg:col-span-3")} aria-labelledby="deadlines-heading">514+ <h2 id="deadlines-heading" class="text-base font-semibold tracking-tight">{t("dashboard.deadlines")}</h2>
388- <div class="flex items-center justify-between gap-3">515+ <DataTable
389- <h2 id="deadlines-heading" class="text-base font-semibold tracking-tight">{t("dashboard.deadlines")}</h2>516+ columns={deadlineColumns()}
390- <Link517+ data={deadlines()}
391- to="/appointments"518+ enableColumnVisibility={false}
392- class="shrink-0 rounded-lg px-2 py-1 text-xs font-semibold text-muted-foreground outline-hidden transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"519+ searchPredicate={deadlines().length > 0 ? deadlineSearch : undefined}
393- >520+ empty={t("dashboard.upcomingEmpty")}
394- {t("nav.appointments")}521+ onRowClick={openDeadline}
395- </Link>522+ />
396- </div>523+ </section>
397- <DataTable
398- columns={deadlineColumns()}
399- data={deadlines()}
400- enableColumnVisibility={false}
401- searchPredicate={deadlines().length > 0 ? deadlineSearch : undefined}
402- empty={t("dashboard.upcomingEmpty")}
403- onRowClick={openDeadline}
404- />
405- </section>
406 524
407- <Show when={hasMinRole(role(), "teacher")}>525+ <ChartHeatmap
408- <section class="flex flex-col gap-4 rounded-lg border border-border bg-card p-4 shadow-xs lg:col-span-1" aria-labelledby="review-heading">526+ title={heatmapIsFocus() ? t("dashboard.focusHeatmap") : t("dashboard.activityHeatmap")}
409- <div class="space-y-1">527+ subtitle={heatmapIsFocus() ? t("dashboard.focusHeatmapDesc") : t("dashboard.activityHeatmapDesc")}
410- <h2 id="review-heading" class="text-base font-semibold tracking-tight">{t("dashboard.teachingResources")}</h2>528+ entries={heatmapEntries()}
411- <p class="text-sm text-muted-foreground">{t("dashboard.teachingResourcesDesc")}</p>529+ weeks={HEATMAP_WEEKS}
412- </div>530+ endsAt={now()}
413- <div class="grid gap-2">531+ dayLabel={(value, dayStart) =>
414- <Link532+ heatmapIsFocus()
415- to="/question-bank"533+ ? t("dashboard.heatmapFocusDay", { date: heatmapDateFormat().format(dayStart), count: String(value) })
416- class="rounded-xl border border-border bg-card p-3 outline-hidden transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring"534+ : t("dashboard.heatmapRecordDay", { date: heatmapDateFormat().format(dayStart), count: String(value) })
417- >535+ }
418- <span class="text-sm font-semibold">{t("nav.questionBank")}</span>536+ emptyDayLabel={(dayStart) =>
419- <span class="mt-0.5 block text-xs text-muted-foreground">{t("dashboard.questionBankDesc")}</span>537+ heatmapIsFocus()
420- </Link>538+ ? t("dashboard.heatmapFocusEmpty", { date: heatmapDateFormat().format(dayStart) })
421- <Link539+ : t("dashboard.heatmapRecordEmpty", { date: heatmapDateFormat().format(dayStart) })
422- to="/questions"540+ }
423- class="rounded-xl border border-border bg-card p-3 outline-hidden transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring"541+ footer={
424- >542+ heatmapIsFocus()
425- <span class="text-sm font-semibold">{t("nav.questions")}</span>543+ ? t("dashboard.heatmapFocusTotal", { count: String(heatmapTotal()), weeks: String(HEATMAP_WEEKS) })
426- <span class="mt-0.5 block text-xs text-muted-foreground">{t("dashboard.questionPoolDesc")}</span>544+ : t("dashboard.heatmapRecordTotal", { count: String(heatmapTotal()), weeks: String(HEATMAP_WEEKS) })
427- </Link>545+ }
428- </div>546+ />
429- </section>
430- </Show>
431- </div>
432 </Suspense>547 </Suspense>
433 </div>548 </div>
434 );549 );