diff --git a/.claude/skills/dashboard-design/SKILL.md b/.claude/skills/dashboard-design/SKILL.md index 82ba66a..a4303c1 100644 --- a/.claude/skills/dashboard-design/SKILL.md +++ b/.claude/skills/dashboard-design/SKILL.md @@ -8,10 +8,8 @@ description: Rules for the hezarfen_frontend dashboard/homepage — a read-only Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status board**, not a marketing landing or action hub. - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes. -- **Charts are allowed, on real data only.** The homepage follows the Knowvio-style - layout: a Highlights stat-card row, a Progress-overview chart, an Activity/attendance - split, and an Upcoming-deadlines table. Charts use `ChartBar` and - `ChartProgressRing` from `src/components/ui/` (accent = +- **Charts are allowed, on real data only.** Charts use `ChartBar`, + `ChartProgressRing` and `ChartHeatmap` from `src/components/ui/` (accent = `hsl(var(--primary))`, semantic tints for status). **Every chart/stat must be backed by a live API field** — no fabricated trends, 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 - **Layout order (top → bottom):** 1. Compact header — greeting, role chip (neutral), date. 2. **Highlights** — role-scoped stat cards (icon + label + mono value). - 3. **Progress overview** chart + **Activity split** on `lg+`. - 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments). - 5. Optional teacher+ Question Bank / Question Pool links. -- **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3` (progress spans 2). -- **Role scoping:** stat/chart set matches nav/role matrix (student personal tools + - marks/attendance; teacher teaching tools; manager+ management; parent children/meals). - Show only panels whose data exists for the role. + 3. Chart row on `lg+` (hidden for `parent`, who has no marks access). + 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments), + full width for every role — one standalone section, no side panel and no + shortcut link in its header. + 5. **Activity heatmap** — full-width `ChartHeatmap`, 26 weeks. +- **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3`. +- **Role scoping:** stat/chart set matches nav/role matrix. Show only panels whose + data exists for the role, and never call an endpoint the role would 403 on. - **Deadlines table:** active / today / soon items only, semantic status badge, rows navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA. -- **Semantics:** student progress = per-course averages; staff progress = - `Course.capacity` labeled as course capacity, never enrollment/class size. -- **Role privacy:** question navigation is teacher+ only. Student/parent deadlines - span full width. No inferred priority or manual refresh. +- **Chart semantics per role:** + - student — course averages + **success trend** (own marks ordered by their exam's + date) + attendance split ring. + - teacher+ — **success trend** (`getExamStatistics().average` per exam, spans 2) + + the same averages grouped by course. Statistics are grader-only, so the + resource must stay gated on `hasMinRole(role, "teacher")`. + - Exam statistics have no bulk endpoint: cap the trend at the most recent handful + of past, non-draft exams (`TREND_EXAM_CAP`), and swallow a per-exam failure + rather than blanking the panel. + - Never chart `Course.capacity` as if it were performance, and never derive a + class (şube) average — no endpoint aggregates one, and per-student fetches do + not belong on the homepage. +- **Heatmap source per role:** student = own `/pomodoro/me` focus minutes; + parent = own appointments; teacher+ = dated exams/events/homework already read by + the page. Never read another user's pomodoro log here. +- **Role privacy:** no teacher-only navigation shortcuts on the board. No inferred + priority or manual refresh. diff --git a/.codex/skills/dashboard-design/SKILL.md b/.codex/skills/dashboard-design/SKILL.md index 82ba66a..a4303c1 100644 --- a/.codex/skills/dashboard-design/SKILL.md +++ b/.codex/skills/dashboard-design/SKILL.md @@ -8,10 +8,8 @@ description: Rules for the hezarfen_frontend dashboard/homepage — a read-only Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status board**, not a marketing landing or action hub. - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes. -- **Charts are allowed, on real data only.** The homepage follows the Knowvio-style - layout: a Highlights stat-card row, a Progress-overview chart, an Activity/attendance - split, and an Upcoming-deadlines table. Charts use `ChartBar` and - `ChartProgressRing` from `src/components/ui/` (accent = +- **Charts are allowed, on real data only.** Charts use `ChartBar`, + `ChartProgressRing` and `ChartHeatmap` from `src/components/ui/` (accent = `hsl(var(--primary))`, semantic tints for status). **Every chart/stat must be backed by a live API field** — no fabricated trends, 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 - **Layout order (top → bottom):** 1. Compact header — greeting, role chip (neutral), date. 2. **Highlights** — role-scoped stat cards (icon + label + mono value). - 3. **Progress overview** chart + **Activity split** on `lg+`. - 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments). - 5. Optional teacher+ Question Bank / Question Pool links. -- **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3` (progress spans 2). -- **Role scoping:** stat/chart set matches nav/role matrix (student personal tools + - marks/attendance; teacher teaching tools; manager+ management; parent children/meals). - Show only panels whose data exists for the role. + 3. Chart row on `lg+` (hidden for `parent`, who has no marks access). + 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments), + full width for every role — one standalone section, no side panel and no + shortcut link in its header. + 5. **Activity heatmap** — full-width `ChartHeatmap`, 26 weeks. +- **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3`. +- **Role scoping:** stat/chart set matches nav/role matrix. Show only panels whose + data exists for the role, and never call an endpoint the role would 403 on. - **Deadlines table:** active / today / soon items only, semantic status badge, rows navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA. -- **Semantics:** student progress = per-course averages; staff progress = - `Course.capacity` labeled as course capacity, never enrollment/class size. -- **Role privacy:** question navigation is teacher+ only. Student/parent deadlines - span full width. No inferred priority or manual refresh. +- **Chart semantics per role:** + - student — course averages + **success trend** (own marks ordered by their exam's + date) + attendance split ring. + - teacher+ — **success trend** (`getExamStatistics().average` per exam, spans 2) + + the same averages grouped by course. Statistics are grader-only, so the + resource must stay gated on `hasMinRole(role, "teacher")`. + - Exam statistics have no bulk endpoint: cap the trend at the most recent handful + of past, non-draft exams (`TREND_EXAM_CAP`), and swallow a per-exam failure + rather than blanking the panel. + - Never chart `Course.capacity` as if it were performance, and never derive a + class (şube) average — no endpoint aggregates one, and per-student fetches do + not belong on the homepage. +- **Heatmap source per role:** student = own `/pomodoro/me` focus minutes; + parent = own appointments; teacher+ = dated exams/events/homework already read by + the page. Never read another user's pomodoro log here. +- **Role privacy:** no teacher-only navigation shortcuts on the board. No inferred + priority or manual refresh. diff --git a/src/components/ui/chart-heatmap.tsx b/src/components/ui/chart-heatmap.tsx new file mode 100644 index 0000000..8efc23c --- /dev/null +++ b/src/components/ui/chart-heatmap.tsx @@ -0,0 +1,233 @@ +import { For, Show, createMemo, type Component } from "solid-js"; +import { cn } from "@/lib/cn"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +/** One dated observation. Several entries may share a day — they are summed. */ +export type HeatmapEntry = { + /** Epoch millis. Bucketed into a local-time calendar day. */ + at: number; + /** Amount contributed by this entry (minutes, records, …). */ + value: number; +}; + +export type ChartHeatmapProps = { + title?: string; + subtitle?: string; + entries: HeatmapEntry[]; + /** Calendar weeks to render, ending with the week containing `endsAt`. */ + weeks?: number; + /** Right-hand edge of the range; defaults to now. */ + endsAt?: number; + /** Cell tooltip / screen-reader text for a day that has data. */ + dayLabel: (value: number, dayStart: number) => string; + /** Cell text for an empty day. */ + emptyDayLabel: (dayStart: number) => string; + /** Summary line under the grid, e.g. "312 dk odak · son 26 hafta". */ + footer?: string; + class?: string; +}; + +const DEFAULT_WEEKS = 26; + +/** Local midnight for the day containing `ms` — DST-safe, unlike `ms - ms % DAY_MS`. */ +function startOfDay(ms: number): number { + const d = new Date(ms); + d.setHours(0, 0, 0, 0); + return d.getTime(); +} + +/** Local midnight of the Monday on or before `ms`. */ +function startOfWeek(ms: number): number { + const d = new Date(startOfDay(ms)); + // getDay(): 0 = Sunday. Shift so Monday is column-row 0. + d.setDate(d.getDate() - ((d.getDay() + 6) % 7)); + return d.getTime(); +} + +/** + * GitHub-contribution-style calendar. Columns are weeks (oldest → newest), + * rows are Monday → Sunday. Intensity is bucketed against the busiest day in + * range, so the scale is always relative to real data rather than a guess. + */ +export const ChartHeatmap: Component = (props) => { + const t = useT(); + const { locale } = usePreferences(); + + const weeks = () => props.weeks ?? DEFAULT_WEEKS; + + // Totals per local day, keyed by that day's midnight timestamp. + const totals = createMemo(() => { + const map = new Map(); + for (const entry of props.entries) { + if (!Number.isFinite(entry.at) || entry.value <= 0) continue; + const day = startOfDay(entry.at); + map.set(day, (map.get(day) ?? 0) + entry.value); + } + return map; + }); + + const firstWeekStart = createMemo(() => { + const lastWeek = startOfWeek(props.endsAt ?? Date.now()); + const d = new Date(lastWeek); + d.setDate(d.getDate() - (weeks() - 1) * 7); + return d.getTime(); + }); + + // Columns of 7 local-midnight timestamps. Built by date arithmetic rather + // than fixed DAY_MS steps so a DST shift can't slide the grid by an hour. + const columns = createMemo(() => { + const start = firstWeekStart(); + return Array.from({ length: weeks() }, (_, week) => + Array.from({ length: 7 }, (_, day) => { + const d = new Date(start); + d.setDate(d.getDate() + week * 7 + day); + return d.getTime(); + }), + ); + }); + + const maxValue = createMemo(() => Math.max(0, ...totals().values())); + const todayStart = createMemo(() => startOfDay(props.endsAt ?? Date.now())); + + /** 0 = no data, 1..4 = quartiles of the busiest day. */ + const levelOf = (value: number) => { + if (value <= 0) return 0; + const peak = maxValue(); + if (peak <= 0) return 0; + return Math.min(4, Math.ceil((value / peak) * 4)); + }; + + const levelClasses = [ + "bg-muted/60 dark:bg-muted/30", + "bg-primary/25", + "bg-primary/45", + "bg-primary/70", + "bg-primary", + ]; + + const monthFormat = createMemo( + () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { month: "short" }), + ); + const weekdayFormat = createMemo( + () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { weekday: "short" }), + ); + + // A month label sits above the first column whose Monday opens a new month. + const monthLabels = createMemo(() => + columns().map((week, index) => { + const monday = new Date(week[0]); + if (index > 0) { + const previous = new Date(columns()[index - 1][0]); + if (previous.getMonth() === monday.getMonth()) return ""; + } + return monthFormat().format(monday); + }), + ); + + // Monday / Wednesday / Friday only — the full seven would not fit the gutter. + const weekdayLabels = createMemo(() => { + const week = columns()[0] ?? []; + return week.map((day, index) => (index % 2 === 0 && index < 6 ? weekdayFormat().format(day) : "")); + }); + + const hasData = createMemo(() => maxValue() > 0); + + return ( +
+ +
+

{props.title}

+ +

{props.subtitle}

+
+
+
+ + +

{t("dashboard.chartEmpty")}

+

{t("dashboard.chartEmptyHint")}

+
+ } + > + {/* One grid for labels and cells together: a weekday gutter column plus + an equal fraction per week, so the calendar always spans the card's + full width and every label stays on its own row. Below the min-width + it scrolls instead of shrinking cells past legibility. */} + {/* `px-1` keeps today's focus ring off the scroll container's clip + edge, which otherwise shaves the last column's cells in half. */} +
+
+
+
+ +
+ +

{props.footer}

+
+
+ {t("dashboard.heatmapLess")} + + {(levelClass) => } + + {t("dashboard.heatmapMore")} +
+
+ + + ); +}; diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index fe36bde..ef7c21e 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -332,11 +332,25 @@ export type MessageKey = | "dashboard.progressOverviewDesc" | "dashboard.activitySplit" | "dashboard.activitySplitDesc" - | "dashboard.workloadSplit" - | "dashboard.workloadSplitDesc" | "dashboard.deadlines" - | "dashboard.courseCapacities" | "dashboard.courseAverages" + | "dashboard.successTrend" + | "dashboard.successTrendMine" + | "dashboard.successTrendSchool" + | "dashboard.courseAveragesSchool" + | "dashboard.examGraded" + | "dashboard.focusHeatmap" + | "dashboard.focusHeatmapDesc" + | "dashboard.activityHeatmap" + | "dashboard.activityHeatmapDesc" + | "dashboard.heatmapLess" + | "dashboard.heatmapMore" + | "dashboard.heatmapFocusDay" + | "dashboard.heatmapFocusEmpty" + | "dashboard.heatmapRecordDay" + | "dashboard.heatmapRecordEmpty" + | "dashboard.heatmapFocusTotal" + | "dashboard.heatmapRecordTotal" | "dashboard.chartEmpty" | "dashboard.chartEmptyHint" | "dashboard.col.task" @@ -359,10 +373,6 @@ export type MessageKey = | "dashboard.attend.excused" | "dashboard.welcomeBack" | "dashboard.welcomeHint" - | "dashboard.teachingResources" - | "dashboard.teachingResourcesDesc" - | "dashboard.questionBankDesc" - | "dashboard.questionPoolDesc" | "dashboard.quickReview.title" | "dashboard.quickReview.subtitle" | "dashboard.quickReview.placeholder" @@ -1008,6 +1018,7 @@ export type MessageKey = | "whiteboard.subtitle" | "whiteboard.empty" | "whiteboard.create" + | "whiteboard.edit" | "whiteboard.titleLabel" | "whiteboard.participants" | "whiteboard.participantsHint" @@ -1100,6 +1111,12 @@ export type MessageKey = | "payments.methodTransfer" | "payments.methodCard" | "payments.methodCheck" + | "payments.methodOther" + | "payments.methodRequired" + | "payments.addStudent" + | "payments.selectedStudents" + | "payments.assignSelected" + | "payments.assignmentSummary" | "payments.ledgerAudit" | "payments.showLedger" | "payments.hideLedger" @@ -1600,10 +1617,24 @@ const en: Dict = { "dashboard.progressOverviewDesc": "Your performance across courses.", "dashboard.activitySplit": "Attendance split", "dashboard.activitySplitDesc": "Your attendance breakdown.", - "dashboard.workloadSplit": "Workload split", - "dashboard.workloadSplitDesc": "Courses, exams, events, and more.", + "dashboard.successTrend": "Success trend", + "dashboard.successTrendMine": "Your exam marks over time.", + "dashboard.successTrendSchool": "Class averages of recent exams.", + "dashboard.courseAveragesSchool": "Average of recent exams, by course.", + "dashboard.examGraded": "{count} graded", + "dashboard.focusHeatmap": "Focus activity", + "dashboard.focusHeatmapDesc": "Your pomodoro sessions, day by day.", + "dashboard.activityHeatmap": "School activity", + "dashboard.activityHeatmapDesc": "Exams, events, and homework, day by day.", + "dashboard.heatmapLess": "Less", + "dashboard.heatmapMore": "More", + "dashboard.heatmapFocusDay": "{date}: {count} min focus", + "dashboard.heatmapFocusEmpty": "{date}: no focus session", + "dashboard.heatmapRecordDay": "{date}: {count} records", + "dashboard.heatmapRecordEmpty": "{date}: no records", + "dashboard.heatmapFocusTotal": "{count} min in the last {weeks} weeks", + "dashboard.heatmapRecordTotal": "{count} records in the last {weeks} weeks", "dashboard.deadlines": "Upcoming deadlines", - "dashboard.courseCapacities": "Course capacities", "dashboard.courseAverages": "Course averages", "dashboard.chartEmpty": "No records found", "dashboard.chartEmptyHint": "Not enough data to display yet.", @@ -1627,10 +1658,6 @@ const en: Dict = { "dashboard.attend.excused": "Excused", "dashboard.welcomeBack": "Welcome back, {name}!", "dashboard.welcomeHint": "Here's what needs your attention today.", - "dashboard.teachingResources": "Teaching resources", - "dashboard.teachingResourcesDesc": "Review reusable material and student questions.", - "dashboard.questionBankDesc": "Build and reuse question templates for exams.", - "dashboard.questionPoolDesc": "Review questions submitted by students.", "dashboard.quickReview.title": "Quick review", "dashboard.quickReview.subtitle": "Refresh what you’ve learned in just two minutes.", "dashboard.quickReview.placeholder": "Choose a topic to review…", @@ -2362,6 +2389,7 @@ const en: Dict = { "whiteboard.subtitle": "Live collaborative sketch boards.", "whiteboard.empty": "No whiteboards yet.", "whiteboard.create": "New whiteboard", + "whiteboard.edit": "Edit whiteboard", "whiteboard.titleLabel": "Title", "whiteboard.participants": "Participants", "whiteboard.participantsHint": "Invite students and staff who may draw.", @@ -2454,6 +2482,12 @@ const en: Dict = { "payments.methodTransfer": "Transfer / EFT", "payments.methodCard": "Card", "payments.methodCheck": "Cheque", + "payments.methodOther": "Other", + "payments.methodRequired": "Enter a payment method.", + "payments.addStudent": "Add student", + "payments.selectedStudents": "Selected students ({count})", + "payments.assignSelected": "Assign selected", + "payments.assignmentSummary": "Assigned: {assigned} · Already assigned: {alreadyAssigned} · Rejected: {rejected}", "payments.ledgerAudit": "Account activity", "payments.showLedger": "Show account activity", "payments.hideLedger": "Hide account activity", @@ -2880,10 +2914,24 @@ const tr: Dict = { "dashboard.progressOverviewDesc": "Derslere göre performansın.", "dashboard.activitySplit": "Yoklama dağılımı", "dashboard.activitySplitDesc": "Yoklama dağılımın.", - "dashboard.workloadSplit": "İş yükü dağılımı", - "dashboard.workloadSplitDesc": "Dersler, sınavlar, etkinlikler ve dahası.", + "dashboard.successTrend": "Başarı eğilimi", + "dashboard.successTrendMine": "Sınav notlarının zaman içindeki seyri.", + "dashboard.successTrendSchool": "Son sınavların sınıf ortalamaları.", + "dashboard.courseAveragesSchool": "Son sınavlara göre ders bazında ortalama.", + "dashboard.examGraded": "{count} notlandırıldı", + "dashboard.focusHeatmap": "Odaklanma etkinliği", + "dashboard.focusHeatmapDesc": "Gün gün pomodoro oturumların.", + "dashboard.activityHeatmap": "Okul etkinliği", + "dashboard.activityHeatmapDesc": "Gün gün sınav, etkinlik ve ödevler.", + "dashboard.heatmapLess": "Az", + "dashboard.heatmapMore": "Çok", + "dashboard.heatmapFocusDay": "{date}: {count} dk odaklanma", + "dashboard.heatmapFocusEmpty": "{date}: odaklanma yok", + "dashboard.heatmapRecordDay": "{date}: {count} kayıt", + "dashboard.heatmapRecordEmpty": "{date}: kayıt yok", + "dashboard.heatmapFocusTotal": "Son {weeks} haftada {count} dk", + "dashboard.heatmapRecordTotal": "Son {weeks} haftada {count} kayıt", "dashboard.deadlines": "Yaklaşan son tarihler", - "dashboard.courseCapacities": "Eğitim kapasiteleri", "dashboard.courseAverages": "Ders ortalamaları", "dashboard.chartEmpty": "Kayıt bulunamadı", "dashboard.chartEmptyHint": "Gösterilecek yeterli veri yok.", @@ -2907,10 +2955,6 @@ const tr: Dict = { "dashboard.attend.excused": "İzinli", "dashboard.welcomeBack": "Tekrar hoş geldin, {name}!", "dashboard.welcomeHint": "Bugün dikkat etmen gerekenler burada.", - "dashboard.teachingResources": "Öğretim kaynakları", - "dashboard.teachingResourcesDesc": "Yeniden kullanılabilir içerikleri ve öğrenci sorularını incele.", - "dashboard.questionBankDesc": "Sınavlar için soru şablonları oluştur ve yeniden kullan.", - "dashboard.questionPoolDesc": "Öğrencilerin gönderdiği soruları incele.", "dashboard.quickReview.title": "Hızlı tekrar", "dashboard.quickReview.subtitle": "Öğrendiklerinizi yalnızca iki dakikada tazeleyin.", "dashboard.quickReview.placeholder": "Tekrar için konu seç…", @@ -3642,6 +3686,7 @@ const tr: Dict = { "whiteboard.subtitle": "Canlı ortak çizim tahtaları.", "whiteboard.empty": "Henüz beyaz tahta yok.", "whiteboard.create": "Yeni tahta", + "whiteboard.edit": "Tahtayı düzenle", "whiteboard.titleLabel": "Başlık", "whiteboard.participants": "Katılımcılar", "whiteboard.participantsHint": "Çizebilecek öğrenci ve personeli davet edin.", @@ -3734,6 +3779,12 @@ const tr: Dict = { "payments.methodTransfer": "Havale / EFT", "payments.methodCard": "Kredi kartı", "payments.methodCheck": "Çek", + "payments.methodOther": "Diğer", + "payments.methodRequired": "Bir ödeme yöntemi girin.", + "payments.addStudent": "Öğrenci ekle", + "payments.selectedStudents": "Seçilen öğrenciler ({count})", + "payments.assignSelected": "Seçilenleri ata", + "payments.assignmentSummary": "Atandı: {assigned} · Zaten atanmış: {alreadyAssigned} · Reddedildi: {rejected}", "payments.ledgerAudit": "Hesap hareketleri", "payments.showLedger": "Hesap hareketlerini göster", "payments.hideLedger": "Hesap hareketlerini gizle", diff --git a/src/pages/dashboard-page.test.tsx b/src/pages/dashboard-page.test.tsx index 1e90688..e5da921 100644 --- a/src/pages/dashboard-page.test.tsx +++ b/src/pages/dashboard-page.test.tsx @@ -31,6 +31,7 @@ vi.mock("@/stores/auth-context", () => ({ })); const now = Date.UTC(2026, 6, 28, 9); +const DAY = 24 * 60 * 60 * 1000; const page = (items: T[]) => ({ items, total: items.length, limit: 50, offset: 0 }); const course = { id: "course-1", title: "Algebra", capacity: 24 }; @@ -40,7 +41,11 @@ vi.mock("@/api/reports", () => ({ getMyCourses: async () => page([course]), getMyMarks: async () => ({ overall_average: 82.5, - courses: [{ course, results: [], average: 82.5 }], + courses: [{ + course, + average: 82.5, + results: [{ exam: "exam-past", title: "Midterm", kind: "exam", weight: 1, mark: 78, graded_by: "t-1" }], + }], }), getMyAttendance: async () => ({ events: { total: 3, present: 2, absent: 1, late: 0, excused: 0 }, @@ -48,27 +53,64 @@ vi.mock("@/api/reports", () => ({ }), })); vi.mock("@/api/exams", () => ({ - getExams: async () => page([{ - id: "exam-1", - title: "Exam deadline", - starts_at: now + 1_000, - ends_at: now + 3_000, - }]), + getExams: async () => page([ + { + id: "exam-1", + title: "Exam deadline", + course: "course-1", + draft: false, + starts_at: now + 1_000, + ends_at: now + 3_000, + }, + { + id: "exam-past", + title: "Midterm", + course: "course-1", + draft: false, + starts_at: now - 10 * DAY, + ends_at: now - 10 * DAY + 3_000, + }, + ]), + getExamStatistics: async (examId: string) => ({ + exam: examId, + graded: 12, + average: 74.5, + min: 40, + max: 96, + }), +})); +vi.mock("@/api/pomodoro", () => ({ + getPomodoroMe: async () => ({ + items: [ + { id: "pom-1", user: "u-1", started_at: now - 3 * DAY, finished_at: now - 3 * DAY + 1_500_000, duration_ms: 1_500_000 }, + { id: "pom-2", user: "u-1", started_at: now - DAY, finished_at: now - DAY + 3_000_000, duration_ms: 3_000_000 }, + ], + total: 2, + limit: 400, + offset: 0, + total_focus_ms: 4_500_000, + }), })); vi.mock("@/api/events", () => ({ - getEvents: async () => page([{ - id: "event-1", - title: "Event deadline", - starts_at: now + 2_000, - ends_at: now + 4_000, - }]), + getEvents: async () => page([ + { + id: "event-1", + title: "Event deadline", + starts_at: now + 2_000, + ends_at: now + 4_000, + }, + { id: "event-past", title: "Past event", starts_at: now - 5 * DAY, ends_at: now - 5 * DAY + 1_000 }, + ]), })); vi.mock("@/api/homework", () => ({ - getHomework: async () => page([{ - id: "homework-1", - title: "Homework deadline", - due_at: now + 5_000, - }]), + getHomework: async () => page([ + { + id: "homework-1", + title: "Homework deadline", + due_at: now + 5_000, + }, + { id: "homework-past", title: "Past homework", due_at: now - 6 * DAY }, + ]), })); vi.mock("@/api/appointments", () => ({ getAppointments: async () => page([{ @@ -111,14 +153,25 @@ test("logged-out visitor redirects before dashboard reads user role", () => { expect(screen.getByText("redirect:/login")).toBeTruthy(); }); -test("student sees truthful charts, full-width deadlines, and no teaching resources", async () => { +test("student sees own trend plus focus heatmap, and a standalone deadlines table", async () => { const view = renderDashboard("student"); expect(await screen.findByText("Course averages")).toBeTruthy(); + expect(screen.getByText("Success trend")).toBeTruthy(); + expect(screen.getByText("Your exam marks over time.")).toBeTruthy(); expect(screen.getByText("Attendance split")).toBeTruthy(); expect(screen.queryByText("Teaching resources")).toBeNull(); - expect(screen.getByRole("link", { name: "Appointments" })).toBeTruthy(); - expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-3"); + // The table stands alone now — no side panel, so no column span and no + // "Appointments" shortcut in its header. + expect(screen.queryByRole("link", { name: "Appointments" })).toBeNull(); + expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span"); + // A student's heatmap is their own focus log, never school-wide records. + expect(screen.getByText("Focus activity")).toBeTruthy(); + expect(screen.queryByText("School activity")).toBeNull(); + // Sessions are bucketed per calendar day: 25 min three days ago, 50 min yesterday. + expect(screen.getByLabelText(/25 min focus/)).toBeTruthy(); + expect(screen.getByLabelText(/50 min focus/)).toBeTruthy(); + expect(screen.getByText("75 min in the last 26 weeks")).toBeTruthy(); expect(view.container.querySelector("polyline")).toBeNull(); expect(screen.queryByText("Priority")).toBeNull(); expect(screen.queryByText("Refresh data")).toBeNull(); @@ -135,16 +188,27 @@ test("student sees truthful charts, full-width deadlines, and no teaching resour expect(navigate).toHaveBeenCalledWith({ to: "/appointments" }); }); -test("teacher sees capacities and useful teaching-resource links", async () => { +test("teacher sees real exam averages instead of capacities and resource links", async () => { renderDashboard("teacher"); - expect(await screen.findByText("Course capacities")).toBeTruthy(); - expect(screen.queryByText("Class sizes")).toBeNull(); - expect(screen.getByText("Workload split")).toBeTruthy(); - expect(screen.getByText("Teaching resources")).toBeTruthy(); - expect(screen.getByRole("link", { name: /Build and reuse question templates/ })).toBeTruthy(); - expect(screen.getByRole("link", { name: /Review questions submitted by students/ })).toBeTruthy(); - expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-2"); + // Exam averages come from the backend's own statistics, so the panel reports + // marks rather than the meaningless capacity/workload counts it replaced. + expect(await screen.findByText("Class averages of recent exams.")).toBeTruthy(); + expect(screen.getByText("Success trend")).toBeTruthy(); + expect(screen.getByText("Average of recent exams, by course.")).toBeTruthy(); + // Both the trend bar and the per-course bar carry the backend's average. + expect((await screen.findAllByText("74.5")).length).toBeGreaterThanOrEqual(2); + expect(screen.queryByText("Course capacities")).toBeNull(); + expect(screen.queryByText("Workload split")).toBeNull(); + expect(screen.queryByText("Teaching resources")).toBeNull(); + expect(screen.queryByRole("link", { name: /Build and reuse question templates/ })).toBeNull(); + expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span"); + expect(screen.getByText("School activity")).toBeTruthy(); + expect(screen.queryByText("Focus activity")).toBeNull(); + // The heatmap looks backwards, so it must be fed by the unfiltered read — + // the page's own event/homework resources are future-only and would leave + // the grid almost entirely empty. One past exam, event, and homework each. + expect((await screen.findAllByLabelText(/: 1 records/)).length).toBe(3); }); 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 expect(screen.getAllByText("Appointments").length).toBeGreaterThan(0); expect(screen.getByText("Meal menus")).toBeTruthy(); expect(screen.queryByText("Progress overview")).toBeNull(); + expect(screen.queryByText("Success trend")).toBeNull(); expect(screen.queryByText("Teaching resources")).toBeNull(); expect(await screen.findByRole("button", { name: /Teacher Name/ })).toBeTruthy(); - expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-3"); + expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).not.toContain("col-span"); }); diff --git a/src/pages/dashboard-page.tsx b/src/pages/dashboard-page.tsx index 340ee2b..4ac3798 100644 --- a/src/pages/dashboard-page.tsx +++ b/src/pages/dashboard-page.tsx @@ -1,5 +1,5 @@ import { For, Show, Suspense, createMemo, createResource, type Component } from "solid-js"; -import { Link, useNavigate } from "@tanstack/solid-router"; +import { useNavigate } from "@tanstack/solid-router"; import type { ColumnDef } from "@tanstack/solid-table"; import type { Role } from "@/api/client"; import { formatApiError } from "@/api/client"; @@ -7,15 +7,17 @@ import { getAppointments } from "@/api/appointments"; import { getMyClasses } from "@/api/classes"; import { getCourses } from "@/api/courses"; import { getEvents } from "@/api/events"; -import { getExams } from "@/api/exams"; +import { getExams, getExamStatistics } from "@/api/exams"; import { getHomework } from "@/api/homework"; import { getMealMenus } from "@/api/meals"; import { getMyStudents } from "@/api/parents"; +import { getPomodoroMe } from "@/api/pomodoro"; import { getMyAttendance, getMyCourses, getMyMarks } from "@/api/reports"; import { getTime } from "@/api/time/getTime"; import { RouteGuard } from "@/components/layout/route-guard"; import { Badge } from "@/components/ui/badge"; import { ChartBar } from "@/components/ui/chart-bar"; +import { ChartHeatmap, type HeatmapEntry } from "@/components/ui/chart-heatmap"; import { ChartProgressRing } from "@/components/ui/chart-progress-ring"; import { DataTable } from "@/components/ui/data-table"; import { @@ -38,6 +40,16 @@ import { usePreferences, useT } from "@/stores/preferences-context"; const DAY_MS = 24 * 60 * 60 * 1000; const WEEK_MS = 7 * DAY_MS; +/** Weeks covered by the bottom activity heatmap. */ +const HEATMAP_WEEKS = 26; +/** + * Exams pulled into the teacher+ success trend. Each one costs a separate + * `/exams/{id}/statistics` call — there is no bulk statistics endpoint — so the + * homepage reads only the most recent handful. + */ +const TREND_EXAM_CAP = 8; +/** Marks plotted in a student's own trend. */ +const TREND_MARK_CAP = 10; type Status = "active" | "today" | "soon"; type DeadlineKind = "exam" | "event" | "appointment" | "homework"; @@ -91,12 +103,13 @@ function DashboardContent() { const user = () => auth.user()!; const role = () => user().role; const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); + // Unpaged: the backend has no `kind` filter, so a "courses" count that + // excludes studies and clubs has to be counted here over the whole list. const [courses] = createResource( () => role() === "parent" ? null : role(), - (currentRole) => currentRole === "student" - ? getMyCourses({ kind: "course", limit: 12 }) - : getCourses({ kind: "course", limit: 12 }), + (currentRole) => currentRole === "student" ? getMyCourses() : getCourses(), ); + const courseCount = () => (courses()?.items ?? []).filter((course) => course.kind === "course").length; const [events] = createResource( () => role() === "parent" ? null : clock()?.now, (now) => getEvents({ ends_after: now, limit: 50 }), @@ -105,9 +118,12 @@ function DashboardContent() { () => role() === "parent" ? null : role(), () => getExams({ limit: 50 }), ); + // Unfiltered: `/homework` has no due-date window, so this one read serves both + // the deadlines table (filtered by `scheduleStatus`) and the backwards-looking + // heatmap. const [homework] = createResource( - () => role() === "parent" ? null : clock()?.now, - (now) => getHomework({ due_after: now, limit: 50 }), + () => role() === "parent" ? null : role(), + () => getHomework({ limit: 100 }), ); const [children] = createResource( () => role() === "parent" ? true : null, @@ -130,6 +146,43 @@ function DashboardContent() { () => role() === "student" ? true : null, () => getMyClasses({ limit: 1 }), ); + // Focus heatmap source. Only a student owns pomodoro sessions — reading + // another user's log is the teacher+ /management/pomodoros page's job. + const [pomodoro] = createResource( + () => role() === "student" ? true : null, + () => getPomodoroMe({ limit: 400 }), + ); + // `/events` is the one list here that really is filtered server-side, by the + // `ends_after` window the deadlines table needs. The heatmap looks backwards + // and there is no "before" filter, so past events need their own read. + const [pastEvents] = createResource( + () => hasMinRole(role(), "teacher") ? true : null, + () => getEvents({ limit: 100 }).catch(() => null), + ); + // Success trend source for teacher+. Exam statistics are grader-only, so this + // never runs for a student or parent — they would get a 403. + const [examStats] = createResource( + () => hasMinRole(role(), "teacher") ? exams.latest?.items ?? null : null, + async (items) => { + const recent = items + .filter((exam) => !exam.draft && exam.starts_at != null && exam.starts_at <= now()) + .sort((a, b) => b.starts_at! - a.starts_at!) + .slice(0, TREND_EXAM_CAP); + const settled = await Promise.all( + recent.map(async (exam) => { + try { + return { exam, stats: await getExamStatistics(exam.id) }; + } catch { + // One ungraded or forbidden exam must not blank the whole panel. + return { exam, stats: null }; + } + }), + ); + return settled + .filter((row) => row.stats?.average != null) + .sort((a, b) => a.exam.starts_at! - b.exam.starts_at!); + }, + ); const myClass = () => myClasses.latest?.items[0] ?? null; const fullName = () => [user().name, user().surname].filter(Boolean).join(" ") || user().username; @@ -147,7 +200,7 @@ function DashboardContent() { const r = role(); if (r === "student") { return [ - { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook }, + { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, { labelKey: "dashboard.stats.average", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart }, { labelKey: "dashboard.stats.attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck }, @@ -155,7 +208,7 @@ function DashboardContent() { } if (r === "teacher") { return [ - { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook }, + { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays }, { labelKey: "dashboard.stats.homework", value: String(homework()?.total ?? 0), Icon: IconHomework }, @@ -169,24 +222,74 @@ function DashboardContent() { ]; } return [ - { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook }, + { labelKey: "dashboard.stats.courses", value: String(courseCount()), Icon: IconBook }, { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam }, { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays }, { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils }, ]; }); - // Progress panel — student: per-course averages; teacher/manager/admin: course capacities. + // Student trend — own marks ordered by their exam's date. Marks whose exam + // falls outside the fetched exam page carry no date and are left out rather + // than guessed into the sequence. + const myMarkTrend = createMemo(() => { + const report = marks(); + if (!report) return []; + const examDates = new Map((exams()?.items ?? []).map((exam) => [exam.id, exam.starts_at])); + return report.courses + .flatMap((course) => + course.results.map((result) => ({ + id: `${course.course.id}:${result.exam}`, + label: result.title, + value: result.mark, + at: examDates.get(result.exam) ?? null, + })), + ) + .filter((row): row is typeof row & { at: number } => row.at != null) + .sort((a, b) => a.at - b.at) + .slice(-TREND_MARK_CAP) + .map((row) => ({ id: row.id, label: row.label, value: row.value, formattedValue: row.value.toFixed(1) })); + }); + + // Teacher+ trend — the backend's own per-exam average, oldest exam first. + const examAverageTrend = createMemo(() => + (examStats() ?? []).map((row) => ({ + id: row.exam.id, + label: row.exam.title, + value: row.stats!.average!, + formattedValue: row.stats!.average!.toFixed(1), + })), + ); + + // Teacher+ side panel — the same exam averages grouped by course, so a weak + // subject stands out rather than being averaged into one school-wide number. + const courseAverageBars = createMemo(() => { + const titles = new Map((courses()?.items ?? []).map((course) => [course.id, course.title])); + const buckets = new Map(); + for (const row of examStats() ?? []) { + const list = buckets.get(row.exam.course) ?? []; + list.push(row.stats!.average!); + buckets.set(row.exam.course, list); + } + return [...buckets.entries()] + .map(([courseId, averages]) => { + const mean = averages.reduce((sum, value) => sum + value, 0) / averages.length; + return { + id: courseId, + label: titles.get(courseId) ?? courseId, + value: mean, + formattedValue: mean.toFixed(1), + }; + }) + .sort((a, b) => b.value - a.value); + }); + + // Student progress panel — per-course averages from the marks report. const courseAverages = createMemo(() => (marks()?.courses ?? []) .filter((c) => c.average != null) .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: c.average!.toFixed(1) })), ); - const courseCapacities = createMemo(() => - (courses()?.items ?? []) - .filter((c) => c.capacity != null) - .map((c) => ({ id: c.id, label: c.title, value: c.capacity! })), - ); // Weekly activity split — student attendance breakdown (events + sessions). const attendanceSegments = createMemo(() => { @@ -201,18 +304,38 @@ function DashboardContent() { ]; }); - // Right-side "workload split" for non-student roles — real resource totals. - const workloadSegments = createMemo(() => { - const r = role(); - const base = [ - { id: "courses", label: t("nav.classes"), value: courses()?.total ?? 0, colorClass: "bg-primary" }, - { id: "exams", label: t("nav.exams"), value: exams()?.total ?? 0, colorClass: "bg-blue-500" }, - { id: "events", label: t("nav.events"), value: events()?.total ?? 0, colorClass: "bg-emerald-500" }, - ]; - if (r === "teacher") { - return [...base, { id: "homework", label: t("nav.homework"), value: homework()?.total ?? 0, colorClass: "bg-rose-500" }]; + // Bottom heatmap. A student's own focus minutes; every other role gets the + // dated records they already read on this page — nobody's grid is built from + // an endpoint their role cannot call. + const heatmapIsFocus = () => role() === "student"; + const heatmapEntries = createMemo(() => { + if (heatmapIsFocus()) { + return (pomodoro()?.items ?? []) + .filter((session) => session.duration_ms != null && session.duration_ms > 0) + .map((session) => ({ at: session.started_at, value: Math.round(session.duration_ms! / 60000) })); + } + if (role() === "parent") { + return (appointments()?.items ?? []) + .filter((appointment) => appointment.starts_at != null) + .map((appointment) => ({ at: appointment.starts_at!, value: 1 })); } - return [...base, { id: "meals", label: t("nav.meals"), value: menus()?.total ?? 0, colorClass: "bg-rose-500" }]; + // Exams and homework are already read unfiltered, so they carry their own + // past; only events need the backwards-looking read. + return [ + ...(exams()?.items ?? []).filter((exam) => exam.starts_at != null).map((exam) => ({ at: exam.starts_at!, value: 1 })), + ...(pastEvents()?.items ?? []).filter((event) => event.starts_at != null).map((event) => ({ at: event.starts_at!, value: 1 })), + ...(homework()?.items ?? []).map((hw) => ({ at: hw.due_at, value: 1 })), + ]; + }); + + const heatmapDateFormat = createMemo( + () => new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-GB", { day: "numeric", month: "short" }), + ); + const heatmapTotal = createMemo(() => { + const cutoff = now() - HEATMAP_WEEKS * WEEK_MS; + return heatmapEntries() + .filter((entry) => entry.at >= cutoff && entry.at <= now()) + .reduce((sum, entry) => sum + entry.value, 0); }); const deadlines = createMemo(() => { @@ -295,7 +418,7 @@ function DashboardContent() { }; const error = createMemo(() => { - const problem = courses.error || events.error || exams.error || homework.error || children.error || appointments.error || menus.error || marks.error || attendance.error || myClasses.error; + const problem = courses.error || events.error || exams.error || homework.error || children.error || appointments.error || menus.error || marks.error || attendance.error || myClasses.error || pomodoro.error; return problem ? formatApiError(problem, locale()) : ""; }); @@ -347,24 +470,19 @@ function DashboardContent() {
- - - - - +
-
-
-
-

{t("dashboard.deadlines")}

- - {t("nav.appointments")} - -
- 0 ? deadlineSearch : undefined} - empty={t("dashboard.upcomingEmpty")} - onRowClick={openDeadline} - /> -
+
+

{t("dashboard.deadlines")}

+ 0 ? deadlineSearch : undefined} + empty={t("dashboard.upcomingEmpty")} + onRowClick={openDeadline} + /> +
- -
-
-

{t("dashboard.teachingResources")}

-

{t("dashboard.teachingResourcesDesc")}

-
-
- - {t("nav.questionBank")} - {t("dashboard.questionBankDesc")} - - - {t("nav.questions")} - {t("dashboard.questionPoolDesc")} - -
-
-
-
+ + heatmapIsFocus() + ? t("dashboard.heatmapFocusDay", { date: heatmapDateFormat().format(dayStart), count: String(value) }) + : t("dashboard.heatmapRecordDay", { date: heatmapDateFormat().format(dayStart), count: String(value) }) + } + emptyDayLabel={(dayStart) => + heatmapIsFocus() + ? t("dashboard.heatmapFocusEmpty", { date: heatmapDateFormat().format(dayStart) }) + : t("dashboard.heatmapRecordEmpty", { date: heatmapDateFormat().format(dayStart) }) + } + footer={ + heatmapIsFocus() + ? t("dashboard.heatmapFocusTotal", { count: String(heatmapTotal()), weeks: String(HEATMAP_WEEKS) }) + : t("dashboard.heatmapRecordTotal", { count: String(heatmapTotal()), weeks: String(HEATMAP_WEEKS) }) + } + /> );