forge
Explore
Log in

Don't you dare go Hollow

📊 keep charts truthful

Browse files at this commit

e0964664ce9a690a5c3f8b4ea95a355892fde297Burak BoduroğluParent: e7c5b53
  • fix
    • 📊 keep charts truthful
Show full message
fix(dashboard): 📊 keep charts truthful

- remove categorical sparklines, inferred priority, and refresh controls

- label capacity and progress data by their real API meaning

- scope question links and deadline navigation by role
.claude/skills/dashboard-design/SKILL.mdmodified+11 -6
@@ -10,20 +10,25 @@ Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status
1010 - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes.
1111 - **Charts are allowed, on real data only.** The homepage follows the Knowvio-style
1212 layout: a Highlights stat-card row, a Progress-overview chart, an Activity/attendance
13- split, and an Upcoming-deadlines table. Charts use the `Chart*` components in
14- `src/components/ui/` (accent = `hsl(var(--primary))`, semantic tints for status).
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).
1516 **Every chart/stat must be backed by a live API field** — no fabricated trends,
16- streak counters, or `+%` delta badges the backend can't produce. Hide a panel when
17- its data source is empty for the current role rather than faking it.
17+ streak counters, sparklines, or `+%` delta badges the backend can't produce.
18+ Categorical series use bars, with a plain empty state when no records exist.
1819 - **Layout order (top → bottom):**
1920 1. Compact header — greeting, role chip (neutral), date.
2021 2. **Highlights** — role-scoped stat cards (icon + label + mono value).
2122 3. **Progress overview** chart + **Activity split** on `lg+`.
2223 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments).
23- 5. Optional role-scoped workspace links / recent list.
24+ 5. Optional teacher+ Question Bank / Question Pool links.
2425 - **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3` (progress spans 2).
2526 - **Role scoping:** stat/chart set matches nav/role matrix (student personal tools +
2627 marks/attendance; teacher teaching tools; manager+ management; parent children/meals).
2728 Show only panels whose data exists for the role.
2829 - **Deadlines table:** active / today / soon items only, semantic status badge, rows
29- navigate to detail. Empty state is plain text, not a create CTA.
30+ navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA.
31+- **Semantics:** student progress = per-course averages; staff progress =
32+ `Course.capacity` labeled as course capacity, never enrollment/class size.
33+- **Role privacy:** question navigation is teacher+ only. Student/parent deadlines
34+ span full width. No inferred priority or manual refresh.
.codex/skills/dashboard-design/SKILL.mdmodified+11 -6
@@ -10,20 +10,25 @@ Reference: `src/pages/dashboard-page.tsx`. The homepage is a **read-only status
1010 - **No mutations:** no create/edit/delete buttons, no primary CTAs that open forms. Links only navigate to existing list/detail routes.
1111 - **Charts are allowed, on real data only.** The homepage follows the Knowvio-style
1212 layout: a Highlights stat-card row, a Progress-overview chart, an Activity/attendance
13- split, and an Upcoming-deadlines table. Charts use the `Chart*` components in
14- `src/components/ui/` (accent = `hsl(var(--primary))`, semantic tints for status).
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).
1516 **Every chart/stat must be backed by a live API field** — no fabricated trends,
16- streak counters, or `+%` delta badges the backend can't produce. Hide a panel when
17- its data source is empty for the current role rather than faking it.
17+ streak counters, sparklines, or `+%` delta badges the backend can't produce.
18+ Categorical series use bars, with a plain empty state when no records exist.
1819 - **Layout order (top → bottom):**
1920 1. Compact header — greeting, role chip (neutral), date.
2021 2. **Highlights** — role-scoped stat cards (icon + label + mono value).
2122 3. **Progress overview** chart + **Activity split** on `lg+`.
2223 4. **Upcoming deadlines** `DataTable` (exams / events / homework / appointments).
23- 5. Optional role-scoped workspace links / recent list.
24+ 5. Optional teacher+ Question Bank / Question Pool links.
2425 - **Grid:** stat row `1 → 2 sm → 4 lg`; charts `lg:grid-cols-3` (progress spans 2).
2526 - **Role scoping:** stat/chart set matches nav/role matrix (student personal tools +
2627 marks/attendance; teacher teaching tools; manager+ management; parent children/meals).
2728 Show only panels whose data exists for the role.
2829 - **Deadlines table:** active / today / soon items only, semantic status badge, rows
29- navigate to detail. Empty state is plain text, not a create CTA.
30+ navigate by pointer, Enter, or Space. Empty state is plain text, not a create CTA.
31+- **Semantics:** student progress = per-course averages; staff progress =
32+ `Course.capacity` labeled as course capacity, never enrollment/class size.
33+- **Role privacy:** question navigation is teacher+ only. Student/parent deadlines
34+ span full width. No inferred priority or manual refresh.
src/components/ui/chart-area-trend.tsxdeleted+0 -204
@@ -1,204 +0,0 @@
1-import { For, Show, createSignal, type Component } from "solid-js";
2-import { cn } from "@/lib/cn";
3-import { useT } from "@/stores/preferences-context";
4-
5-export type ChartAreaTrendItem = {
6- label: string;
7- value: number;
8- formattedValue?: string;
9-};
10-
11-export type ChartAreaTrendProps = {
12- title: string;
13- subtitle?: string;
14- items: ChartAreaTrendItem[];
15- class?: string;
16- minScale?: number;
17- maxScale?: number;
18- unit?: string;
19-};
20-
21-export const ChartAreaTrend: Component<ChartAreaTrendProps> = (props) => {
22- const [hoverIndex, setHoverIndex] = createSignal<number | null>(null);
23- const t = useT();
24-
25- const values = () => props.items.map((i) => i.value);
26- const minVal = () => props.minScale ?? Math.min(0, ...values());
27- const maxVal = () => props.maxScale ?? Math.max(1, ...values());
28-
29- const width = 360;
30- const height = 120;
31- const paddingX = 20;
32- const paddingTop = 15;
33- const paddingBottom = 25;
34-
35- const points = () => {
36- const list = props.items;
37- if (list.length === 0) return [];
38- const min = minVal();
39- const max = maxVal();
40- const range = max - min || 1;
41- const stepX = (width - paddingX * 2) / Math.max(1, list.length - 1);
42- const usableH = height - paddingTop - paddingBottom;
43-
44- return list.map((item, i) => {
45- const x = paddingX + i * stepX;
46- const normalized = (item.value - min) / range;
47- const y = height - paddingBottom - normalized * usableH;
48- return { x, y, item, index: i };
49- });
50- };
51-
52- const linePath = () => {
53- const pts = points();
54- if (pts.length === 0) return "";
55- return pts.reduce((acc, p, idx) => (idx === 0 ? `M ${p.x} ${p.y}` : `${acc} L ${p.x} ${p.y}`), "");
56- };
57-
58- const areaPath = () => {
59- const pts = points();
60- if (pts.length === 0) return "";
61- const first = pts[0];
62- const last = pts[pts.length - 1];
63- const bottomY = height - paddingBottom;
64- return `${linePath()} L ${last.x} ${bottomY} L ${first.x} ${bottomY} Z`;
65- };
66-
67- return (
68- <div class={cn("flex flex-col space-y-3 rounded-2xl border border-border/60 bg-card p-4 shadow-xs dark:border-white/8", props.class)}>
69- <div class="flex items-start justify-between gap-2">
70- <div class="space-y-0.5 min-w-0">
71- <h3 class="truncate text-sm font-semibold tracking-tight text-foreground">{props.title}</h3>
72- <Show when={props.subtitle}>
73- <p class="truncate text-xs text-muted-foreground">{props.subtitle}</p>
74- </Show>
75- </div>
76- <Show when={props.items.length > 0}>
77- <div class="mono tabular-nums text-xs font-semibold text-primary bg-primary/10 px-2 py-0.5 rounded-full border border-primary/20">
78- {hoverIndex() !== null
79- ? (props.items[hoverIndex()!]?.formattedValue ?? `${props.items[hoverIndex()!]?.value}${props.unit ?? ""}`)
80- : (props.items[props.items.length - 1]?.formattedValue ?? `${props.items[props.items.length - 1]?.value}${props.unit ?? ""}`)}
81- </div>
82- </Show>
83- </div>
84-
85- <Show
86- when={props.items.length > 0}
87- fallback={
88- <div class="flex flex-col items-center justify-center py-8 px-4 text-center">
89- <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-muted/40 border border-border/50 text-muted-foreground/60 mb-2">
90- <svg class="h-5 w-5 stroke-[1.5]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
91- <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
92- </svg>
93- </div>
94- <p class="text-xs font-semibold text-foreground/80">{t("dashboard.chartEmpty")}</p>
95- <p class="text-[11px] text-muted-foreground mt-0.5">{t("dashboard.chartEmptyHint")}</p>
96- </div>
97- }
98- >
99- <div class="relative w-full overflow-hidden">
100- <svg viewBox={`0 0 ${width} ${height}`} class="w-full h-32 overflow-visible">
101- <defs>
102- <linearGradient id="areaGradient" x1="0" y1="0" x2="0" y2="1">
103- <stop offset="0%" stop-color="hsl(var(--primary))" stop-opacity="0.35" />
104- <stop offset="100%" stop-color="hsl(var(--primary))" stop-opacity="0.0" />
105- </linearGradient>
106- </defs>
107-
108- {/* Horizontal Grid lines */}
109- <line x1={paddingX} y1={paddingTop} x2={width - paddingX} y2={paddingTop} stroke="currentColor" stroke-opacity="0.08" stroke-dasharray="3 3" />
110- <line x1={paddingX} y1={(paddingTop + height - paddingBottom) / 2} x2={width - paddingX} y2={(paddingTop + height - paddingBottom) / 2} stroke="currentColor" stroke-opacity="0.08" stroke-dasharray="3 3" />
111- <line x1={paddingX} y1={height - paddingBottom} x2={width - paddingX} y2={height - paddingBottom} stroke="currentColor" stroke-opacity="0.12" />
112-
113- {/* Hover Vertical Guideline */}
114- <Show when={hoverIndex() !== null && points()[hoverIndex()!]}>
115- {(p) => (
116- <line
117- x1={p().x}
118- y1={paddingTop}
119- x2={p().x}
120- y2={height - paddingBottom}
121- stroke="hsl(var(--primary))"
122- stroke-opacity="0.3"
123- stroke-dasharray="3 3"
124- stroke-width="1.5"
125- />
126- )}
127- </Show>
128-
129- {/* Filled Area */}
130- <path d={areaPath()} fill="url(#areaGradient)" />
131-
132- {/* Trend Line */}
133- <path d={linePath()} fill="none" stroke="hsl(var(--primary))" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round" />
134-
135- {/* Data Points */}
136- <For each={points()}>
137- {(p) => (
138- <g class="cursor-pointer group" onMouseEnter={() => setHoverIndex(p.index)} onMouseLeave={() => setHoverIndex(null)}>
139- <circle
140- cx={p.x}
141- cy={p.y}
142- r={hoverIndex() === p.index ? "5.5" : "3.5"}
143- class={cn(
144- "transition-all duration-200 fill-background stroke-primary stroke-[2.5]",
145- hoverIndex() === p.index && "fill-primary stroke-background shadow-lg stroke-3",
146- )}
147- />
148- <text
149- x={p.x}
150- y={height - 8}
151- text-anchor="middle"
152- class={cn(
153- "text-[10px] transition-colors font-medium",
154- hoverIndex() === p.index ? "fill-primary font-bold" : "fill-muted-foreground"
155- )}
156- >
157- {p.item.label}
158- </text>
159- </g>
160- )}
161- </For>
162-
163- {/* Floating Active Hover Tooltip */}
164- <Show when={hoverIndex() !== null && points()[hoverIndex()!]}>
165- {(p) => {
166- const text = p().item.formattedValue ?? `${p().item.value}${props.unit ?? ""}`;
167- const rectW = 64;
168- const rectH = 20;
169- const tooltipX = Math.max(paddingX, Math.min(width - paddingX - rectW, p().x - rectW / 2));
170- const tooltipY = Math.max(2, p().y - 26);
171- return (
172- <g class="pointer-events-none transition-all duration-150">
173- <circle
174- cx={p().x}
175- cy={p().y}
176- r="8.5"
177- class="fill-primary/20 stroke-primary/40 stroke-1"
178- />
179- <rect
180- x={tooltipX}
181- y={tooltipY}
182- width={rectW}
183- height={rectH}
184- rx="5"
185- class="fill-card stroke-primary/40 stroke shadow-md dark:fill-zinc-900"
186- />
187- <text
188- x={tooltipX + rectW / 2}
189- y={tooltipY + 13.5}
190- text-anchor="middle"
191- class="fill-foreground font-semibold text-[10px] mono tabular-nums"
192- >
193- {text}
194- </text>
195- </g>
196- );
197- }}
198- </Show>
199- </svg>
200- </div>
201- </Show>
202- </div>
203- );
204-};
src/components/ui/chart-bar.tsxmodified+3 -8
@@ -30,9 +30,9 @@ export const ChartBar: Component<ChartBarProps> = (props) => {
3030 };
3131
3232 return (
33- <div class={cn("flex flex-col gap-3.5 rounded-3xl border border-border/60 bg-card/60 p-4 sm:p-5 dark:border-white/8 dark:bg-card/40 shadow-xs backdrop-blur-xs", props.class)}>
33+ <div class={cn("flex flex-col gap-4 rounded-2xl border border-border bg-card p-4 shadow-xs", props.class)}>
3434 <Show when={props.title}>
35- <div class="flex items-center justify-between gap-2 border-b border-border/40 pb-3">
35+ <div class="border-b border-border pb-3">
3636 <div>
3737 <h3 class="text-sm font-semibold tracking-tight text-foreground">{props.title}</h3>
3838 <Show when={props.subtitle}>
@@ -45,12 +45,7 @@ export const ChartBar: Component<ChartBarProps> = (props) => {
4545 <Show
4646 when={props.items.length > 0}
4747 fallback={
48- <div class="flex flex-col items-center justify-center py-8 px-4 text-center">
49- <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-muted/40 border border-border/50 text-muted-foreground/60 mb-2">
50- <svg class="h-5 w-5 stroke-[1.5]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
51- <path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z" />
52- </svg>
53- </div>
48+ <div class="px-4 py-8 text-center">
5449 <p class="text-xs font-semibold text-foreground/80">{t("dashboard.chartEmpty")}</p>
5550 <p class="text-[11px] text-muted-foreground mt-0.5">{t("dashboard.chartEmptyHint")}</p>
5651 </div>
src/components/ui/chart-progress-ring.tsxmodified+3 -9
@@ -24,9 +24,9 @@ export const ChartProgressRing: Component<ChartProgressRingProps> = (props) => {
2424 const calculatedTotal = () => props.total ?? props.segments.reduce((acc, s) => acc + s.value, 0);
2525
2626 return (
27- <div class={cn("flex flex-col gap-3.5 rounded-3xl border border-border/60 bg-card/60 p-4 sm:p-5 dark:border-white/8 dark:bg-card/40 shadow-xs backdrop-blur-xs", props.class)}>
27+ <div class={cn("flex flex-col gap-4 rounded-2xl border border-border bg-card p-4 shadow-xs", props.class)}>
2828 <Show when={props.title}>
29- <div class="flex items-center justify-between gap-2 border-b border-border/40 pb-3">
29+ <div class="border-b border-border pb-3">
3030 <div>
3131 <h3 class="text-sm font-semibold tracking-tight text-foreground">{props.title}</h3>
3232 <Show when={props.subtitle}>
@@ -39,13 +39,7 @@ export const ChartProgressRing: Component<ChartProgressRingProps> = (props) => {
3939 <Show
4040 when={calculatedTotal() > 0}
4141 fallback={
42- <div class="flex flex-col items-center justify-center py-8 px-4 text-center">
43- <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-muted/40 border border-border/50 text-muted-foreground/60 mb-2">
44- <svg class="h-5 w-5 stroke-[1.5]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
45- <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6a7.5 7.5 0 107.5 7.5h-7.5V6z" />
46- <path stroke-linecap="round" stroke-linejoin="round" d="M13.5 10.5H21A7.5 7.5 0 0013.5 3v7.5z" />
47- </svg>
48- </div>
42+ <div class="px-4 py-8 text-center">
4943 <p class="text-xs font-semibold text-foreground/80">{t("dashboard.chartEmpty")}</p>
5044 <p class="text-[11px] text-muted-foreground mt-0.5">{t("dashboard.chartEmptyHint")}</p>
5145 </div>
src/pages/dashboard-page.test.tsxadded+149 -0
@@ -0,0 +1,149 @@
1+import { cleanup, fireEvent, render, screen } from "@solidjs/testing-library";
2+import type { JSX } from "solid-js";
3+import DashboardPage from "@/pages/dashboard-page";
4+import { PreferencesProvider } from "@/stores/preferences-context";
5+
6+const { navigate, authUser } = vi.hoisted(() => ({
7+ navigate: vi.fn(),
8+ authUser: { role: "student" },
9+}));
10+
11+vi.mock("@tanstack/solid-router", () => ({
12+ Link: (props: { to: string; children: JSX.Element; class?: string }) => (
13+ <a href={props.to} class={props.class}>{props.children}</a>
14+ ),
15+ Navigate: () => null,
16+ useNavigate: () => navigate,
17+}));
18+vi.mock("@/stores/auth-context", () => ({
19+ useAuth: () => ({
20+ user: () => ({
21+ id: "u-1",
22+ username: "demo",
23+ role: authUser.role,
24+ name: "Demo",
25+ surname: "User",
26+ }),
27+ loading: () => false,
28+ error: () => undefined,
29+ refresh: async () => undefined,
30+ }),
31+}));
32+
33+const now = Date.UTC(2026, 6, 28, 9);
34+const page = <T,>(items: T[]) => ({ items, total: items.length, limit: 50, offset: 0 });
35+const course = { id: "course-1", title: "Algebra", capacity: 24 };
36+
37+vi.mock("@/api/time/getTime", () => ({ getTime: async () => ({ now }) }));
38+vi.mock("@/api/courses", () => ({ getCourses: async () => page([course]) }));
39+vi.mock("@/api/reports", () => ({
40+ getMyCourses: async () => page([course]),
41+ getMyMarks: async () => ({
42+ overall_average: 82.5,
43+ courses: [{ course, results: [], average: 82.5 }],
44+ }),
45+ getMyAttendance: async () => ({
46+ events: { total: 3, present: 2, absent: 1, late: 0, excused: 0 },
47+ sessions: { total: 2, present: 1, absent: 0, late: 1, excused: 0 },
48+ }),
49+}));
50+vi.mock("@/api/exams", () => ({
51+ getExams: async () => page([{
52+ id: "exam-1",
53+ title: "Exam deadline",
54+ starts_at: now + 1_000,
55+ ends_at: now + 3_000,
56+ }]),
57+}));
58+vi.mock("@/api/events", () => ({
59+ getEvents: async () => page([{
60+ id: "event-1",
61+ title: "Event deadline",
62+ starts_at: now + 2_000,
63+ ends_at: now + 4_000,
64+ }]),
65+}));
66+vi.mock("@/api/homework", () => ({
67+ getHomework: async () => page([{
68+ id: "homework-1",
69+ title: "Homework deadline",
70+ due_at: now + 5_000,
71+ }]),
72+}));
73+vi.mock("@/api/appointments", () => ({
74+ getAppointments: async () => page([{
75+ id: "appointment-1",
76+ status: "approved",
77+ starts_at: now + 6_000,
78+ ends_at: now + 7_000,
79+ teacher: { username: "teacher", display_name: "Teacher Name" },
80+ }]),
81+}));
82+vi.mock("@/api/parents", () => ({
83+ getMyStudents: async () => page([{ id: "child-1" }]),
84+}));
85+vi.mock("@/api/meals", () => ({
86+ getMealMenus: async () => page([{ id: "menu-1" }]),
87+}));
88+
89+afterEach(() => {
90+ cleanup();
91+ navigate.mockReset();
92+});
93+
94+function renderDashboard(role: string) {
95+ authUser.role = role;
96+ return render(() => (
97+ <PreferencesProvider>
98+ <DashboardPage />
99+ </PreferencesProvider>
100+ ));
101+}
102+
103+test("student sees truthful charts, full-width deadlines, and no teaching resources", async () => {
104+ const view = renderDashboard("student");
105+
106+ expect(await screen.findByText("Course averages")).toBeTruthy();
107+ expect(screen.getByText("Attendance split")).toBeTruthy();
108+ expect(screen.queryByText("Teaching resources")).toBeNull();
109+ expect(screen.getByRole("link", { name: "Appointments" })).toBeTruthy();
110+ expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-3");
111+ expect(view.container.querySelector("polyline")).toBeNull();
112+ expect(screen.queryByText("Priority")).toBeNull();
113+ expect(screen.queryByText("Refresh data")).toBeNull();
114+ expect(screen.queryByText("Ask a question")).toBeNull();
115+
116+ fireEvent.click(await screen.findByRole("button", { name: /Event deadline/ }));
117+ fireEvent.keyDown(screen.getByRole("button", { name: /Homework deadline/ }), { key: "Enter" });
118+ fireEvent.keyDown(screen.getByRole("button", { name: /Exam deadline/ }), { key: " " });
119+ fireEvent.click(screen.getByRole("button", { name: /Teacher Name/ }));
120+
121+ expect(navigate).toHaveBeenCalledWith({ to: "/events/$id", params: { id: "event-1" } });
122+ expect(navigate).toHaveBeenCalledWith({ to: "/homework/$id", params: { id: "homework-1" } });
123+ expect(navigate).toHaveBeenCalledWith({ to: "/exams/$id", params: { id: "exam-1" } });
124+ expect(navigate).toHaveBeenCalledWith({ to: "/appointments" });
125+});
126+
127+test("teacher sees capacities and useful teaching-resource links", async () => {
128+ renderDashboard("teacher");
129+
130+ expect(await screen.findByText("Course capacities")).toBeTruthy();
131+ expect(screen.queryByText("Class sizes")).toBeNull();
132+ expect(screen.getByText("Workload split")).toBeTruthy();
133+ expect(screen.getByText("Teaching resources")).toBeTruthy();
134+ expect(screen.getByRole("link", { name: /Build and reuse question templates/ })).toBeTruthy();
135+ expect(screen.getByRole("link", { name: /Review questions submitted by students/ })).toBeTruthy();
136+ expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-2");
137+});
138+
139+test("parent sees family highlights and appointment deadlines without staff charts", async () => {
140+ renderDashboard("parent");
141+
142+ expect(await screen.findByText("Children")).toBeTruthy();
143+ expect(screen.getAllByText("Appointments").length).toBeGreaterThan(0);
144+ expect(screen.getByText("Meal menus")).toBeTruthy();
145+ expect(screen.queryByText("Progress overview")).toBeNull();
146+ expect(screen.queryByText("Teaching resources")).toBeNull();
147+ expect(await screen.findByRole("button", { name: /Teacher Name/ })).toBeTruthy();
148+ expect(screen.getByRole("heading", { name: "Upcoming deadlines" }).closest("section")?.className).toContain("lg:col-span-3");
149+});
src/pages/dashboard-page.tsxmodified+59 -139
@@ -1,5 +1,5 @@
1-import { For, Show, Suspense, createMemo, createResource, createSignal, type Component } from "solid-js";
2-import { Link } from "@tanstack/solid-router";
1+import { For, Show, Suspense, createMemo, createResource, type Component } from "solid-js";
2+import { Link, useNavigate } from "@tanstack/solid-router";
33 import type { ColumnDef } from "@tanstack/solid-table";
44 import type { Role } from "@/api/client";
55 import { formatApiError } from "@/api/client";
@@ -14,21 +14,16 @@ import { getMyAttendance, getMyCourses, getMyMarks } from "@/api/reports";
1414 import { getTime } from "@/api/time/getTime";
1515 import { RouteGuard } from "@/components/layout/route-guard";
1616 import { Badge } from "@/components/ui/badge";
17-import { ChartAreaTrend } from "@/components/ui/chart-area-trend";
1817 import { ChartBar } from "@/components/ui/chart-bar";
1918 import { ChartProgressRing } from "@/components/ui/chart-progress-ring";
2019 import { DataTable } from "@/components/ui/data-table";
2120 import {
22- IconArchive,
2321 IconBook,
2422 IconCalendarDays,
2523 IconChart,
2624 IconClipboardCheck,
2725 IconExam,
28- IconHelpCircle,
2926 IconHomework,
30- IconRefresh,
31- IconSearch,
3227 IconUsers,
3328 IconUtensils,
3429 } from "@/components/ui/icons";
@@ -36,6 +31,7 @@ import { PageSpinner } from "@/components/ui/page-spinner";
3631 import type { MessageKey } from "@/i18n/messages";
3732 import { cn } from "@/lib/cn";
3833 import { formatDateTime } from "@/lib/format";
34+import { hasMinRole } from "@/lib/roles";
3935 import { useAuth } from "@/stores/auth-context";
4036 import { usePreferences, useT } from "@/stores/preferences-context";
4137
@@ -57,36 +53,8 @@ type StatCardData = {
5753 labelKey: MessageKey;
5854 value: string;
5955 Icon: Component<{ class?: string }>;
60- spark?: number[];
6156 };
6257
63-// Tiny real-data sparkline; renders nothing when there's no series.
64-function StatSpark(props: { values: number[] }) {
65- const pts = () => {
66- const v = props.values;
67- if (v.length < 2) return "";
68- const min = Math.min(...v);
69- const max = Math.max(...v);
70- const range = max - min || 1;
71- const w = 64;
72- const h = 24;
73- return v
74- .map((val, i) => {
75- const x = (i / (v.length - 1)) * w;
76- const y = h - ((val - min) / range) * h;
77- return `${x.toFixed(1)},${y.toFixed(1)}`;
78- })
79- .join(" ");
80- };
81- return (
82- <Show when={pts()}>
83- <svg viewBox="0 0 64 24" class="h-6 w-16 shrink-0 overflow-visible" preserveAspectRatio="none">
84- <polyline points={pts()} fill="none" stroke="hsl(var(--primary))" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" />
85- </svg>
86- </Show>
87- );
88-}
89-
9058 const roleKeys: Record<Role, MessageKey> = {
9159 student: "role.student",
9260 parent: "role.parent",
@@ -113,63 +81,47 @@ function scheduleStatus(startsAt: number | null, endsAt: number | null, now: num
11381 export default function DashboardPage() {
11482 const auth = useAuth();
11583 const t = useT();
84+ const navigate = useNavigate();
11685 const { locale } = usePreferences();
11786 const user = () => auth.user()!;
11887 const role = () => user().role;
119- const [clock, clockQ] = createResource(() => getTime().catch(() => ({ now: Date.now() })));
120- const [courses, coursesQ] = createResource(
88+ const [clock] = createResource(() => getTime().catch(() => ({ now: Date.now() })));
89+ const [courses] = createResource(
12190 () => role() === "parent" ? null : role(),
12291 (currentRole) => currentRole === "student"
12392 ? getMyCourses({ kind: "course", limit: 12 })
12493 : getCourses({ kind: "course", limit: 12 }),
12594 );
126- const [events, eventsQ] = createResource(
95+ const [events] = createResource(
12796 () => role() === "parent" ? null : clock()?.now,
12897 (now) => getEvents({ ends_after: now, limit: 50 }),
12998 );
130- const [exams, examsQ] = createResource(
99+ const [exams] = createResource(
131100 () => role() === "parent" ? null : role(),
132101 () => getExams({ limit: 50 }),
133102 );
134- const [homework, homeworkQ] = createResource(
103+ const [homework] = createResource(
135104 () => role() === "parent" ? null : clock()?.now,
136105 (now) => getHomework({ due_after: now, limit: 50 }),
137106 );
138- const [children, childrenQ] = createResource(
107+ const [children] = createResource(
139108 () => role() === "parent" ? true : null,
140109 () => getMyStudents({ limit: 12 }),
141110 );
142- const [appointments, appointmentsQ] = createResource(
143- () => role() === "parent" ? true : null,
144- () => getAppointments({ limit: 20 }),
145- );
146- const [menus, menusQ] = createResource(
111+ const [appointments] = createResource(() => getAppointments({ limit: 20 }));
112+ const [menus] = createResource(
147113 () => clock()?.now,
148114 (now) => getMealMenus({ from: new Date(now).toISOString().slice(0, 10), limit: 1 }),
149115 );
150- const [marks, marksQ] = createResource(
116+ const [marks] = createResource(
151117 () => role() === "student" ? true : null,
152118 () => getMyMarks(),
153119 );
154- const [attendance, attendanceQ] = createResource(
120+ const [attendance] = createResource(
155121 () => role() === "student" ? true : null,
156122 () => getMyAttendance(),
157123 );
158124
159- const [refreshing, setRefreshing] = createSignal(false);
160- const refresh = async () => {
161- if (refreshing()) return;
162- setRefreshing(true);
163- try {
164- await Promise.all(
165- [clockQ, coursesQ, eventsQ, examsQ, homeworkQ, childrenQ, appointmentsQ, menusQ, marksQ, attendanceQ]
166- .map((q) => q.refetch()),
167- );
168- } finally {
169- setRefreshing(false);
170- }
171- };
172-
173125 const fullName = () => [user().name, user().surname].filter(Boolean).join(" ") || user().username;
174126 const now = () => clock()?.now ?? Date.now();
175127
@@ -181,30 +133,19 @@ export default function DashboardPage() {
181133 return total ? Math.round((present / total) * 100) : null;
182134 });
183135
184- const capacities = () =>
185- (courses()?.items ?? []).map((c) => c.capacity).filter((n): n is number => n != null);
186- const courseAvgValues = () =>
187- (marks()?.courses ?? []).filter((c) => c.average != null).map((c) => c.average!);
188- const attendanceValues = () => {
189- const report = attendance();
190- if (!report) return [];
191- const sum = (k: "present" | "absent" | "late" | "excused") => report.events[k] + report.sessions[k];
192- return [sum("present"), sum("late"), sum("excused"), sum("absent")];
193- };
194-
195136 const stats = createMemo<StatCardData[]>(() => {
196137 const r = role();
197138 if (r === "student") {
198139 return [
199- { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook, spark: capacities() },
140+ { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook },
200141 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },
201- { labelKey: "dashboard.stats.average", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart, spark: courseAvgValues() },
202- { labelKey: "dashboard.stats.attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck, spark: attendanceValues() },
142+ { labelKey: "dashboard.stats.average", value: marks()?.overall_average == null ? "—" : marks()!.overall_average!.toFixed(1), Icon: IconChart },
143+ { labelKey: "dashboard.stats.attendance", value: attendanceRate() == null ? "—" : `${attendanceRate()}%`, Icon: IconClipboardCheck },
203144 ];
204145 }
205146 if (r === "teacher") {
206147 return [
207- { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook, spark: capacities() },
148+ { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook },
208149 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },
209150 { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays },
210151 { labelKey: "dashboard.stats.homework", value: String(homework()?.total ?? 0), Icon: IconHomework },
@@ -218,20 +159,20 @@ export default function DashboardPage() {
218159 ];
219160 }
220161 return [
221- { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook, spark: capacities() },
162+ { labelKey: "dashboard.stats.courses", value: String(courses()?.total ?? 0), Icon: IconBook },
222163 { labelKey: "dashboard.stats.exams", value: String(exams()?.total ?? 0), Icon: IconExam },
223164 { labelKey: "dashboard.stats.events", value: String(events()?.total ?? 0), Icon: IconCalendarDays },
224165 { labelKey: "dashboard.stats.meals", value: String(menus()?.total ?? 0), Icon: IconUtensils },
225166 ];
226167 });
227168
228- // Progress panel — student: per-course averages; teacher/manager/admin: class sizes.
169+ // Progress panel — student: per-course averages; teacher/manager/admin: course capacities.
229170 const courseAverages = createMemo(() =>
230171 (marks()?.courses ?? [])
231172 .filter((c) => c.average != null)
232- .map((c) => ({ label: c.course.title, value: c.average!, formattedValue: c.average!.toFixed(1) })),
173+ .map((c) => ({ id: c.course.id, label: c.course.title, value: c.average!, formattedValue: c.average!.toFixed(1) })),
233174 );
234- const classSizes = createMemo(() =>
175+ const courseCapacities = createMemo(() =>
235176 (courses()?.items ?? [])
236177 .filter((c) => c.capacity != null)
237178 .map((c) => ({ id: c.id, label: c.title, value: c.capacity! })),
@@ -327,23 +268,21 @@ export default function DashboardPage() {
327268 );
328269 },
329270 },
330- {
331- id: "priority",
332- header: t("dashboard.col.priority"),
333- enableSorting: false,
334- meta: { headerClass },
335- cell: (info) => {
336- const high = info.row.original.status !== "soon";
337- return (
338- <span class={cn("text-xs font-semibold", high ? "text-rose-600 dark:text-rose-400" : "text-amber-600 dark:text-amber-400")}>
339- {high ? t("dashboard.priority.high") : t("dashboard.priority.medium")}
340- </span>
341- );
342- },
343- },
344271 ]);
345272
346273 const deadlineSearch = (row: DeadlineRow, q: string) => row.title.toLowerCase().includes(q.toLowerCase());
274+ const openDeadline = (row: DeadlineRow) => {
275+ switch (row.kind) {
276+ case "exam":
277+ return navigate({ to: "/exams/$id", params: { id: row.id } });
278+ case "event":
279+ return navigate({ to: "/events/$id", params: { id: row.id } });
280+ case "homework":
281+ return navigate({ to: "/homework/$id", params: { id: row.id } });
282+ case "appointment":
283+ return navigate({ to: "/appointments" });
284+ }
285+ };
347286
348287 const error = createMemo(() => {
349288 const problem = courses.error || events.error || exams.error || homework.error || children.error || appointments.error || menus.error || marks.error || attendance.error;
@@ -383,9 +322,8 @@ export default function DashboardPage() {
383322 </span>
384323 <p class="min-w-0 flex-1 truncate text-xs font-medium text-muted-foreground">{t(stat.labelKey)}</p>
385324 </div>
386- <div class="mt-3 flex items-end justify-between gap-2">
325+ <div class="mt-3">
387326 <p class="mono tabular-nums text-2xl font-bold tracking-tight">{stat.value}</p>
388- <Show when={stat.spark}>{(s) => <StatSpark values={s()} />}</Show>
389327 </div>
390328 </div>
391329 )}
@@ -396,12 +334,11 @@ export default function DashboardPage() {
396334 <Show when={role() !== "parent"}>
397335 <div class="grid gap-3 lg:grid-cols-3">
398336 <Show when={role() === "student"}>
399- <ChartAreaTrend
337+ <ChartBar
400338 class="lg:col-span-2"
401339 title={t("dashboard.progressOverview")}
402340 subtitle={t("dashboard.courseAverages")}
403341 items={courseAverages()}
404- minScale={0}
405342 maxScale={100}
406343 />
407344 </Show>
@@ -409,8 +346,8 @@ export default function DashboardPage() {
409346 <ChartBar
410347 class="lg:col-span-2"
411348 title={t("dashboard.progressOverview")}
412- subtitle={t("dashboard.classSizes")}
413- items={classSizes()}
349+ subtitle={t("dashboard.courseCapacities")}
350+ items={courseCapacities()}
414351 />
415352 </Show>
416353 <Show when={role() === "student"}>
@@ -431,8 +368,16 @@ export default function DashboardPage() {
431368 </Show>
432369
433370 <div class="grid gap-3 lg:grid-cols-3">
434- <section class={cn("flex flex-col gap-4 rounded-2xl border border-border bg-card p-4 shadow-xs", role() !== "parent" ? "lg:col-span-2" : "lg:col-span-3")} aria-labelledby="deadlines-heading">
435- <h2 id="deadlines-heading" class="text-base font-semibold tracking-tight">{t("dashboard.deadlines")}</h2>
371+ <section class={cn("flex flex-col gap-4 rounded-2xl border border-border bg-card p-4 shadow-xs", hasMinRole(role(), "teacher") ? "lg:col-span-2" : "lg:col-span-3")} aria-labelledby="deadlines-heading">
372+ <div class="flex items-center justify-between gap-3">
373+ <h2 id="deadlines-heading" class="text-base font-semibold tracking-tight">{t("dashboard.deadlines")}</h2>
374+ <Link
375+ to="/appointments"
376+ 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"
377+ >
378+ {t("nav.appointments")}
379+ </Link>
380+ </div>
436381 <DataTable
437382 columns={deadlineColumns()}
438383 data={deadlines()}
@@ -440,60 +385,35 @@ export default function DashboardPage() {
440385 searchPredicate={deadlineSearch}
441386 filterPlaceholder={t("dashboard.deadlines")}
442387 empty={t("dashboard.upcomingEmpty")}
388+ onRowClick={openDeadline}
443389 />
444390 </section>
445391
446- <Show when={role() !== "parent"}>
392+ <Show when={hasMinRole(role(), "teacher")}>
447393 <section class="flex flex-col gap-4 rounded-2xl border border-border bg-card p-4 shadow-xs lg:col-span-1" aria-labelledby="review-heading">
448394 <div class="space-y-1">
449- <h2 id="review-heading" class="text-base font-semibold tracking-tight">{t("nav.questionBank")}</h2>
450- <p class="text-sm text-muted-foreground">{t("dashboard.questionHubDesc")}</p>
395+ <h2 id="review-heading" class="text-base font-semibold tracking-tight">{t("dashboard.teachingResources")}</h2>
396+ <p class="text-sm text-muted-foreground">{t("dashboard.teachingResourcesDesc")}</p>
451397 </div>
452- <Link
453- to="/question-bank"
454- class="flex h-10 items-center gap-2 rounded-xl border border-border bg-muted/30 px-3 text-sm text-muted-foreground outline-hidden transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring"
455- >
456- <IconSearch class="h-4 w-4 shrink-0" />
457- <span class="truncate">{t("dashboard.questionHubPlaceholder")}</span>
458- </Link>
459- <div class="flex items-center gap-2">
460- <For each={[IconArchive, IconHelpCircle, IconExam, IconBook, IconChart]}>
461- {(Icon) => (
462- <span class="flex h-9 w-9 items-center justify-center rounded-full border border-border bg-muted/30 text-muted-foreground">
463- <Icon class="h-4 w-4" />
464- </span>
465- )}
466- </For>
467- </div>
468- <div class="mt-auto grid grid-cols-2 gap-2">
398+ <div class="grid gap-2">
469399 <Link
470400 to="/question-bank"
471- class="flex h-10 items-center justify-center rounded-xl border border-border bg-card text-sm font-semibold outline-hidden transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring"
401+ 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"
472402 >
473- {t("nav.questionBank")}
403+ <span class="text-sm font-semibold">{t("nav.questionBank")}</span>
404+ <span class="mt-0.5 block text-xs text-muted-foreground">{t("dashboard.questionBankDesc")}</span>
474405 </Link>
475406 <Link
476407 to="/questions"
477- class="flex h-10 items-center justify-center rounded-xl bg-primary text-sm font-semibold text-primary-foreground outline-hidden transition-colors hover:bg-primary/90 focus-visible:ring-2 focus-visible:ring-ring"
408+ 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"
478409 >
479- {t("dashboard.askQuestion")}
410+ <span class="text-sm font-semibold">{t("nav.questions")}</span>
411+ <span class="mt-0.5 block text-xs text-muted-foreground">{t("dashboard.questionPoolDesc")}</span>
480412 </Link>
481413 </div>
482414 </section>
483415 </Show>
484416 </div>
485-
486- <div class="flex justify-center pt-2">
487- <button
488- type="button"
489- onClick={() => void refresh()}
490- disabled={refreshing()}
491- class="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-card px-4 text-xs font-semibold text-muted-foreground outline-hidden transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60"
492- >
493- <IconRefresh class={cn("h-3.5 w-3.5", refreshing() && "animate-spin")} />
494- {t("dashboard.refresh")}
495- </button>
496- </div>
497417 </Suspense>
498418 </div>
499419 </RouteGuard>