From c3fc1e3040b0af7fd23433de4f78f0ddda366a14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 12 Jul 2026 02:16:42 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9C=A8=20add=20typed=20API=20client,?= =?UTF-8?q?=20session=20auth,=20and=20shared=20helpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Core plumbing every page builds on: - types.ts mirrors the backend DTOs and validation limits, with the role ladder and the atLeast() privilege check - api.ts wraps every endpoint over one request primitive; failures throw ApiError carrying the backend message, status, and Retry-After - auth.tsx fetches /auth/me once and mutates the session resource in place on login/register/logout; exposes can(role) for gating UI - action.ts wraps mutations with pending/error signals for forms - format.ts converts between unix milliseconds and datetime-local --- src/lib/action.ts | 49 +++++++++++++ src/lib/api.ts | 175 ++++++++++++++++++++++++++++++++++++++++++++++ src/lib/auth.tsx | 71 +++++++++++++++++++ src/lib/format.ts | 42 +++++++++++ src/lib/types.ts | 149 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 486 insertions(+) create mode 100644 src/lib/action.ts create mode 100644 src/lib/api.ts create mode 100644 src/lib/auth.tsx create mode 100644 src/lib/format.ts create mode 100644 src/lib/types.ts diff --git a/src/lib/action.ts b/src/lib/action.ts new file mode 100644 index 0000000..9aea5d4 --- /dev/null +++ b/src/lib/action.ts @@ -0,0 +1,49 @@ +// Tiny mutation helper: wraps an async action with pending/error signals so +// forms get busy-state and failure display without repeating try/catch. + +import { batch, createSignal, type Accessor } from "solid-js"; +import { ApiError } from "./api"; + +export interface Action { + run: (...args: Args) => Promise; + pending: Accessor; + error: Accessor; + clearError: () => void; +} + +export function createAction( + action: (...args: Args) => Promise, +): Action { + const [pending, setPending] = createSignal(false); + const [error, setError] = createSignal(null); + + return { + pending, + error, + clearError: () => setError(null), + run: async (...args) => { + batch(() => { + setPending(true); + setError(null); + }); + try { + await action(...args); + return true; + } catch (err) { + setError(describe(err)); + return false; + } finally { + setPending(false); + } + }, + }; +} + +function describe(err: unknown): string { + if (err instanceof ApiError) { + return err.retryAfterSecs !== undefined + ? `${err.message} — retry in ${err.retryAfterSecs}s` + : err.message; + } + return err instanceof Error ? err.message : "something went wrong"; +} diff --git a/src/lib/api.ts b/src/lib/api.ts new file mode 100644 index 0000000..c6e3aa5 --- /dev/null +++ b/src/lib/api.ts @@ -0,0 +1,175 @@ +// Typed HTTP client for the Hezarfen backend. One `request` primitive, then a +// thin endpoint map per resource. Failures always throw `ApiError` carrying the +// backend's `{ "error": "..." }` message and the HTTP status. + +import type { + AppEvent, + Attendance, + AttendanceStatus, + Course, + Enrollment, + Exam, + ExamResult, + ExamStatistics, + MarksReport, + Note, + Role, + User, +} from "./types"; + +const BASE = import.meta.env.VITE_API_URL ?? "/api"; + +export class ApiError extends Error { + constructor( + readonly status: number, + message: string, + readonly retryAfterSecs?: number, + ) { + super(message); + this.name = "ApiError"; + } +} + +async function request(method: string, path: string, body?: unknown): Promise { + let res: Response; + try { + res = await fetch(BASE + path, { + method, + credentials: "include", + headers: body === undefined ? undefined : { "content-type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch { + throw new ApiError(0, "network error — is the backend up?"); + } + + if (!res.ok) { + let message = res.statusText.toLowerCase() || "request failed"; + try { + message = ((await res.json()) as { error: string }).error; + } catch { + // Non-JSON error body; keep the status text. + } + const retryAfter = Number(res.headers.get("retry-after")); + throw new ApiError(res.status, message, Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined); + } + + return res.status === 204 ? (undefined as T) : res.json(); +} + +const get = (path: string) => request("GET", path); +const post = (path: string, body?: unknown) => request("POST", path, body); +const patch = (path: string, body: unknown) => request("PATCH", path, body); +const del = (path: string) => request("DELETE", path); + +export interface Credentials { + username: string; + password: string; +} + +export const auth = { + me: () => get("/auth/me"), + register: (credentials: Credentials) => post("/auth/register", credentials), + login: (credentials: Credentials) => post("/auth/login", credentials), + logout: () => post("/auth/logout"), +}; + +/** Partial profile update: omit a field to keep it, send `""` to clear it. */ +export interface ProfilePatch { + name?: string; + surname?: string; + email?: string; + phone?: string; + /** `YYYY-MM-DD`. */ + birth_date?: string; +} + +export const users = { + list: () => get("/users"), + get: (id: string) => get(`/users/${id}`), + setRole: (id: string, role: Role) => patch(`/users/${id}/role`, { role }), + /** The caller's own profile. */ + updateMyProfile: (body: ProfilePatch) => patch("/users/me", body), + /** Any user's profile; admin only. */ + updateProfile: (id: string, body: ProfilePatch) => patch(`/users/${id}/profile`, body), +}; + +export const notes = { + list: () => get("/notes"), + create: (body: { title: string; content?: string }) => post("/notes", body), + update: (id: string, body: { title?: string; content?: string }) => + patch(`/notes/${id}`, body), + remove: (id: string) => del(`/notes/${id}`), +}; + +export const events = { + list: () => get("/events"), + get: (id: string) => get(`/events/${id}`), + create: (body: { + title: string; + description?: string; + starts_at?: number; + ends_at?: number; + }) => post("/events", body), + /** `null` clears a timestamp; omitting a field keeps it. */ + update: ( + id: string, + body: { + title?: string; + description?: string; + starts_at?: number | null; + ends_at?: number | null; + }, + ) => patch(`/events/${id}`, body), + remove: (id: string) => del(`/events/${id}`), + + attendance: (id: string) => get(`/events/${id}/attendance`), + mark: (id: string, status: AttendanceStatus, userId?: string) => + post(`/events/${id}/attendance`, { status, user_id: userId }), + unmark: (id: string, userId: string) => del(`/events/${id}/attendance/${userId}`), +}; + +export const courses = { + list: () => get("/courses"), + /** The caller's enrolled courses. */ + mine: () => get("/courses/me"), + get: (id: string) => get(`/courses/${id}`), + create: (body: { title: string; description?: string }) => post("/courses", body), + update: (id: string, body: { title?: string; description?: string }) => + patch(`/courses/${id}`, body), + remove: (id: string) => del(`/courses/${id}`), + + roster: (id: string) => get(`/courses/${id}/enrollments`), + enroll: (id: string, userId: string) => + post(`/courses/${id}/enrollments`, { user_id: userId }), + unenroll: (id: string, userId: string) => del(`/courses/${id}/enrollments/${userId}`), + + exams: (id: string) => get(`/courses/${id}/exams`), + createExam: ( + id: string, + body: { title: string; description?: string; kind: string; weight: number }, + ) => post(`/courses/${id}/exams`, body), +}; + +export const exams = { + list: () => get("/exams"), + get: (id: string) => get(`/exams/${id}`), + // Creation lives under the course: `courses.createExam`. + update: ( + id: string, + body: { title?: string; description?: string; kind?: string; weight?: number }, + ) => patch(`/exams/${id}`, body), + remove: (id: string) => del(`/exams/${id}`), + + results: (id: string) => get(`/exams/${id}/results`), + myResult: (id: string) => get(`/exams/${id}/result`), + grade: (id: string, userId: string, mark: number) => + post(`/exams/${id}/results`, { mark, user_id: userId }), + removeResult: (id: string, userId: string) => del(`/exams/${id}/results/${userId}`), + statistics: (id: string) => get(`/exams/${id}/statistics`), +}; + +export const marks = { + mine: () => get("/marks/me"), + forUser: (id: string) => get(`/marks/${id}`), +}; diff --git a/src/lib/auth.tsx b/src/lib/auth.tsx new file mode 100644 index 0000000..3103e7b --- /dev/null +++ b/src/lib/auth.tsx @@ -0,0 +1,71 @@ +// Session state for the whole app. `/auth/me` is fetched exactly once at +// startup; login/register/logout mutate the resource in place from the +// server's response, so every consumer updates instantly with no refetch. + +import { + createContext, + createResource, + useContext, + type Accessor, + type ParentProps, +} from "solid-js"; +import { ApiError, auth, type Credentials } from "./api"; +import { atLeast, type Role, type User } from "./types"; + +interface AuthValue { + /** `undefined` while the initial /auth/me is in flight, `null` when logged out. */ + user: Accessor; + login: (credentials: Credentials) => Promise; + register: (credentials: Credentials) => Promise; + logout: () => Promise; + /** Replace the session user with a fresh server response (e.g. a profile save). */ + update: (user: User) => void; + /** True when the current user's role is `required` or higher. */ + can: (required: Role) => boolean; +} + +const AuthContext = createContext(); + +async function fetchMe(): Promise { + try { + return await auth.me(); + } catch (err) { + if (err instanceof ApiError && err.status === 401) return null; + throw err; + } +} + +export function AuthProvider(props: ParentProps) { + const [me, { mutate }] = createResource(fetchMe); + + const value: AuthValue = { + user: () => (me.state === "ready" ? me() : me.latest ?? undefined), + login: async (credentials) => { + mutate(await auth.login(credentials)); + }, + register: async (credentials) => { + // Register does not set a session cookie; log in right after. + await auth.register(credentials); + mutate(await auth.login(credentials)); + }, + logout: async () => { + await auth.logout(); + mutate(null); + }, + update: (user) => { + mutate(user); + }, + can: (required) => { + const current = me.latest; + return current != null && atLeast(current.role, required); + }, + }; + + return {props.children}; +} + +export function useAuth(): AuthValue { + const value = useContext(AuthContext); + if (!value) throw new Error("useAuth must be used inside "); + return value; +} diff --git a/src/lib/format.ts b/src/lib/format.ts new file mode 100644 index 0000000..29aa812 --- /dev/null +++ b/src/lib/format.ts @@ -0,0 +1,42 @@ +// Time helpers: the API speaks unix milliseconds, +// speaks "YYYY-MM-DDTHH:mm" in local time. + +const formatter = new Intl.DateTimeFormat(undefined, { + dateStyle: "medium", + timeStyle: "short", +}); + +export function formatMillis(millis: number | null): string { + return millis === null ? "—" : formatter.format(new Date(millis)); +} + +/** Human line for an event's time window. */ +export function formatWindow(starts: number | null, ends: number | null): string { + if (starts === null && ends === null) return "Unscheduled"; + if (starts !== null && ends !== null) + return `${formatMillis(starts)} → ${formatMillis(ends)}`; + return starts !== null ? formatMillis(starts) : `Until ${formatMillis(ends)}`; +} + +/** Unix ms → value for a datetime-local input ("" when null). */ +export function toInputValue(millis: number | null): string { + if (millis === null) return ""; + const date = new Date(millis); + const pad = (n: number) => String(n).padStart(2, "0"); + return ( + `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` + + `T${pad(date.getHours())}:${pad(date.getMinutes())}` + ); +} + +/** datetime-local input value → unix ms, null when empty. */ +export function fromInputValue(value: string): number | null { + return value === "" ? null : new Date(value).getTime(); +} + +/** The local date as "YYYY-MM-DD" — e.g. the max for a birth-date input. */ +export function today(): string { + const date = new Date(); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; +} diff --git a/src/lib/types.ts b/src/lib/types.ts new file mode 100644 index 0000000..476c08d --- /dev/null +++ b/src/lib/types.ts @@ -0,0 +1,149 @@ +// Wire types and validation limits, mirroring the backend's DTOs and +// `constant.rs`. Keep these in sync with hezarfen_backend. + +export type Role = "student" | "teacher" | "manager" | "admin"; + +/** Privilege order, lowest to highest — index = rank. */ +export const ROLES: readonly Role[] = ["student", "teacher", "manager", "admin"]; + +export function atLeast(role: Role, required: Role): boolean { + return ROLES.indexOf(role) >= ROLES.indexOf(required); +} + +export interface User { + id: string; + username: string; + role: Role; + /** Personal info — null until filled in. `birth_date` is `YYYY-MM-DD`. */ + name: string | null; + surname: string | null; + email: string | null; + phone: string | null; + birth_date: string | null; +} + +export interface Note { + id: string; + title: string; + content: string; +} + +export interface AppEvent { + id: string; + creator: string; + title: string; + description: string; + /** Unix milliseconds, or null when unscheduled. */ + starts_at: number | null; + ends_at: number | null; +} + +export const ATTENDANCE_STATUSES = ["present", "absent", "late", "excused"] as const; +export type AttendanceStatus = (typeof ATTENDANCE_STATUSES)[number]; + +export interface Attendance { + id: string; + event: string; + user: string; + status: AttendanceStatus; + marked_by: string; +} + +export interface Course { + id: string; + creator: string; + title: string; + description: string; +} + +export interface Enrollment { + id: string; + course: string; + user: string; + enrolled_by: string; +} + +/** Informational metadata only — `weight` drives the course average. */ +export const EXAM_KINDS = [ + "homework", + "quiz", + "midterm", + "final", + "project", + "oral", +] as const; +export type ExamKind = (typeof EXAM_KINDS)[number]; + +export interface Exam { + id: string; + creator: string; + course: string; + title: string; + description: string; + kind: ExamKind; + /** Counts `weight` times into the course average, 1–100. */ + weight: number; +} + +export interface ExamResult { + id: string; + exam: string; + user: string; + /** 0–100 inclusive. */ + mark: number; + graded_by: string; +} + +export interface ExamStatistics { + exam: string; + /** Number of graded results. */ + graded: number; + /** Plain mean of the graded marks; null while nothing is graded. */ + average: number | null; + min: number | null; + max: number | null; +} + +/** One graded exam inside a course block of the marks report. */ +export interface MarkEntry { + exam: string; + title: string; + kind: ExamKind; + weight: number; + mark: number; + graded_by: string; +} + +export interface CourseMarks { + course: Course; + /** Graded results only — ungraded exams don't appear. */ + results: MarkEntry[]; + /** Σ(mark×weight) / Σ(weight); null while nothing is graded. */ + average: number | null; +} + +export interface MarksReport { + user: string; + courses: CourseMarks[]; + /** Plain mean of the non-null course averages; null while none exist. */ + overall_average: number | null; +} + +export const LIMITS = { + username: { min: 3, max: 32 }, + password: { min: 6, max: 128 }, + personName: 100, + email: 254, + /** Digit count; a leading `+`, spaces, dashes, and parentheses are allowed. */ + phoneDigits: { min: 7, max: 15 }, + noteTitle: 200, + noteContent: 10_000, + eventTitle: 200, + eventDescription: 2_000, + examTitle: 200, + examDescription: 2_000, + courseTitle: 200, + courseDescription: 2_000, + mark: { min: 0, max: 100 }, + weight: { min: 1, max: 100 }, +} as const;