forge
Explore
Log in

Don't you dare go Hollow

πŸ“… appointment booking, calendar sync, cancel/reject records

Browse files at this commit

d50ee5bceabbda242bd7c177a9827397e22b961eAhmet Kaan GümüşParent: dc6b2a9
  • feat
    • πŸ“… appointment booking, calendar sync, cancel/reject records
Show full message
feat: πŸ“… appointment booking, calendar sync, cancel/reject records
- mirror the backend appointments contract: 12 endpoints under
  src/api/appointments (publish/list/delete slots, book, list,
  approve/reject/cancel, reschedule + accept/decline), types + LIMITS,
  full API tests
- /appointments page, role-scoped: teachers publish one-off/weekly-repeat
  slots and manage requests; students/parents book, cancel, accept or
  decline a reschedule
- publish/book/reschedule side panels; client-side 52-occurrence cap and
  future-time validation; errors surface inside the panel
- calendar sync: appointments layered into the month calendar grid and the
  right-nav calendar panel (violet accent, .latest reads, 30s poll)
- cancel + reject capture an optional reason; ConfirmDialog gains a reason
  prompt, a configurable icon, and opt-in backdrop dismiss
- cancellation/rejection record (who + reason) shown in a Details dialog
  from the row's three-dot menu
- appointment-status + datetime-input lib helpers; EN/TR i18n; nav item in
  the classes and parent groups; role-scope-matrix doc
AGENTS.mdmodified+1 -1
@@ -38,7 +38,7 @@ instructions. Always written and read in English.
38 `components/events/`, `components/exams/`, `components/users/`,38 `components/events/`, `components/exams/`, `components/users/`,
39 `components/attendance/`, `components/courses/`, `components/marks/`,39 `components/attendance/`, `components/courses/`, `components/marks/`,
40 `components/sessions/`, `components/messages/`, `components/homework/`,40 `components/sessions/`, `components/messages/`, `components/homework/`,
41- `components/layout/`, `components/ui/`.41+ `components/appointments/`, `components/layout/`, `components/ui/`.
42 - Cross-cutting app state lives in `src/stores/` (`auth-context.tsx`,42 - Cross-cutting app state lives in `src/stores/` (`auth-context.tsx`,
43 `preferences-context.tsx`) β€” context providers only, never domain components.43 `preferences-context.tsx`) β€” context providers only, never domain components.
44 School-policy lists (exam kinds, attendance statuses, grade bands) come from44 School-policy lists (exam kinds, attendance statuses, grade bands) come from
docs/role-scope-matrix.mdmodified+4 -0
@@ -16,6 +16,7 @@
16 | Live monitor `/exams/:id/live` | ❌ | βœ… | βœ… | βœ… |16 | Live monitor `/exams/:id/live` | ❌ | βœ… | βœ… | βœ… |
17 | Events `/events` | βœ… | βœ… | βœ… | βœ… |17 | Events `/events` | βœ… | βœ… | βœ… | βœ… |
18 | Event detail `/events/:id` | βœ… | βœ… | βœ… | βœ… |18 | Event detail `/events/:id` | βœ… | βœ… | βœ… | βœ… |
19+| Appointments `/appointments` | βœ… (book + own) | βœ… (publish/manage own) | βœ… (manage all) | βœ… (manage all) |
19 | **Report card `/marks`** | βœ… | ❌ (FE) | ❌ (FE) | ❌ (FE) |20 | **Report card `/marks`** | βœ… | ❌ (FE) | ❌ (FE) | ❌ (FE) |
20 | My attendance `/attendance` | βœ… | βœ… | βœ… | βœ… |21 | My attendance `/attendance` | βœ… | βœ… | βœ… | βœ… |
21 | Student marks lookup `/management/student-marks` | ❌ | βœ… | βœ… | βœ… |22 | Student marks lookup `/management/student-marks` | ❌ | βœ… | βœ… | βœ… |
@@ -64,6 +65,9 @@
64 | Mark own attendance on events | βœ… | βœ… | βœ… | βœ… |65 | Mark own attendance on events | βœ… | βœ… | βœ… | βœ… |
65 | Mark other users' event attendance | ❌ | βœ… | βœ… | βœ… |66 | Mark other users' event attendance | ❌ | βœ… | βœ… | βœ… |
66 | Create / edit / delete events | ❌ | βœ… (creator or manager+) | βœ… | βœ… |67 | Create / edit / delete events | ❌ | βœ… (creator or manager+) | βœ… | βœ… |
68+| Publish / delete appointment slots | ❌ | βœ… (own slots) | βœ… (any) | βœ… (any) |
69+| Approve / reject / reschedule / cancel bookings | ❌ | βœ… (own slots) | βœ… (any) | βœ… (any) |
70+| Book an appointment (+ cancel / accept reschedule) | βœ… (student & parent) | ❌ | ❌ | ❌ |
67 | Enroll students / unenroll any enrollment | ❌ | βœ… (course creator) | βœ… | βœ… |71 | Enroll students / unenroll any enrollment | ❌ | βœ… (course creator) | βœ… | βœ… |
68 | Edit / delete courses | ❌ | βœ… (course creator) | βœ… | βœ… |72 | Edit / delete courses | ❌ | βœ… (course creator) | βœ… | βœ… |
69 | Create / edit / delete course sessions | ❌ | βœ… (course manager) | βœ… | βœ… |73 | Create / edit / delete course sessions | ❌ | βœ… (course manager) | βœ… | βœ… |
src/api/__tests__/appointments/appointments.test.tsadded+190 -0
@@ -0,0 +1,190 @@
1+import { afterEach, describe, expect, it, vi } from "vitest";
2+import { postSlots } from "../../appointments";
3+import { getSlots } from "../../appointments";
4+import { deleteSlotById } from "../../appointments";
5+import { deleteSlotSeries } from "../../appointments";
6+import { postAppointment } from "../../appointments";
7+import { getAppointments } from "../../appointments";
8+import { patchApproveAppointment } from "../../appointments";
9+import { patchRejectAppointment } from "../../appointments";
10+import { patchCancelAppointment } from "../../appointments";
11+import { patchRescheduleAppointment } from "../../appointments";
12+import { patchAcceptReschedule } from "../../appointments";
13+import { patchDeclineReschedule } from "../../appointments";
14+import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch";
15+
16+describe("appointments API", () => {
17+ afterEach(() => {
18+ vi.restoreAllMocks();
19+ });
20+
21+ it("postSlots calls /appointments/slots with data", async () => {
22+ const mockSlots = [{ id: "s1" }];
23+ mockFetchSuccess(mockSlots);
24+
25+ const data = { starts_at: 1000, ends_at: 2000, note: "hi", repeat_weekly: true, until: 5000 };
26+ const result = await postSlots(data);
27+ expect(result).toEqual(mockSlots);
28+
29+ const [url, init] = lastFetchCall();
30+ expect(url).toBe("/api/appointments/slots");
31+ expect(init?.method).toBe("POST");
32+ expect(init?.body).toBe(JSON.stringify(data));
33+ });
34+
35+ it("getSlots calls /appointments/slots with pagination", async () => {
36+ const mockPage = { items: [{ id: "s1" }], total: 1 };
37+ mockFetchSuccess(mockPage);
38+
39+ const result = await getSlots({ limit: 10 });
40+ expect(result).toEqual({ ...mockPage, limit: null, offset: 0 });
41+
42+ const [url, init] = lastFetchCall();
43+ expect(url).toBe("/api/appointments/slots?limit=10");
44+ expect(init?.method).toBe("GET");
45+ });
46+
47+ it("deleteSlotById calls /appointments/slots/:id", async () => {
48+ mockFetch204();
49+
50+ await deleteSlotById("s1");
51+
52+ const [url, init] = lastFetchCall();
53+ expect(url).toBe("/api/appointments/slots/s1");
54+ expect(init?.method).toBe("DELETE");
55+ });
56+
57+ it("deleteSlotSeries calls /appointments/slots/series/:series", async () => {
58+ mockFetch204();
59+
60+ await deleteSlotSeries("ser1");
61+
62+ const [url, init] = lastFetchCall();
63+ expect(url).toBe("/api/appointments/slots/series/ser1");
64+ expect(init?.method).toBe("DELETE");
65+ });
66+
67+ it("postAppointment calls /appointments with data", async () => {
68+ const mockAppt = { id: "a1" };
69+ mockFetchSuccess(mockAppt);
70+
71+ const data = { slot: "s1", reason: "need help" };
72+ const result = await postAppointment(data);
73+ expect(result).toEqual(mockAppt);
74+
75+ const [url, init] = lastFetchCall();
76+ expect(url).toBe("/api/appointments");
77+ expect(init?.method).toBe("POST");
78+ expect(init?.body).toBe(JSON.stringify(data));
79+ });
80+
81+ it("getAppointments calls /appointments with pagination", async () => {
82+ const mockPage = { items: [{ id: "a1" }], total: 1 };
83+ mockFetchSuccess(mockPage);
84+
85+ const result = await getAppointments({ limit: 10 });
86+ expect(result).toEqual({ ...mockPage, limit: null, offset: 0 });
87+
88+ const [url, init] = lastFetchCall();
89+ expect(url).toBe("/api/appointments?limit=10");
90+ expect(init?.method).toBe("GET");
91+ });
92+
93+ it("patchApproveAppointment calls /appointments/:id/approve", async () => {
94+ const mockAppt = { id: "a1", status: "approved" };
95+ mockFetchSuccess(mockAppt);
96+
97+ const result = await patchApproveAppointment("a1");
98+ expect(result).toEqual(mockAppt);
99+
100+ const [url, init] = lastFetchCall();
101+ expect(url).toBe("/api/appointments/a1/approve");
102+ expect(init?.method).toBe("PATCH");
103+ });
104+
105+ it("patchRejectAppointment calls /appointments/:id/reject", async () => {
106+ const mockAppt = { id: "a1", status: "rejected" };
107+ mockFetchSuccess(mockAppt);
108+
109+ const result = await patchRejectAppointment("a1");
110+ expect(result).toEqual(mockAppt);
111+
112+ const [url, init] = lastFetchCall();
113+ expect(url).toBe("/api/appointments/a1/reject");
114+ expect(init?.method).toBe("PATCH");
115+ expect(init?.body).toBeUndefined();
116+ });
117+
118+ it("patchRejectAppointment sends an optional reason body", async () => {
119+ mockFetchSuccess({ id: "a1", status: "rejected" });
120+
121+ await patchRejectAppointment("a1", { reason: "slot no longer available" });
122+
123+ const [url, init] = lastFetchCall();
124+ expect(url).toBe("/api/appointments/a1/reject");
125+ expect(init?.method).toBe("PATCH");
126+ expect(init?.body).toBe(JSON.stringify({ reason: "slot no longer available" }));
127+ });
128+
129+ it("patchCancelAppointment calls /appointments/:id/cancel", async () => {
130+ const mockAppt = { id: "a1", status: "cancelled" };
131+ mockFetchSuccess(mockAppt);
132+
133+ const result = await patchCancelAppointment("a1");
134+ expect(result).toEqual(mockAppt);
135+
136+ const [url, init] = lastFetchCall();
137+ expect(url).toBe("/api/appointments/a1/cancel");
138+ expect(init?.method).toBe("PATCH");
139+ expect(init?.body).toBeUndefined();
140+ });
141+
142+ it("patchCancelAppointment sends an optional reason body", async () => {
143+ mockFetchSuccess({ id: "a1", status: "cancelled" });
144+
145+ await patchCancelAppointment("a1", { reason: "double booked" });
146+
147+ const [url, init] = lastFetchCall();
148+ expect(url).toBe("/api/appointments/a1/cancel");
149+ expect(init?.method).toBe("PATCH");
150+ expect(init?.body).toBe(JSON.stringify({ reason: "double booked" }));
151+ });
152+
153+ it("patchRescheduleAppointment calls /appointments/:id/reschedule with data", async () => {
154+ const mockAppt = { id: "a1" };
155+ mockFetchSuccess(mockAppt);
156+
157+ const data = { starts_at: 3000, ends_at: 4000 };
158+ const result = await patchRescheduleAppointment("a1", data);
159+ expect(result).toEqual(mockAppt);
160+
161+ const [url, init] = lastFetchCall();
162+ expect(url).toBe("/api/appointments/a1/reschedule");
163+ expect(init?.method).toBe("PATCH");
164+ expect(init?.body).toBe(JSON.stringify(data));
165+ });
166+
167+ it("patchAcceptReschedule calls /appointments/:id/reschedule/accept", async () => {
168+ const mockAppt = { id: "a1" };
169+ mockFetchSuccess(mockAppt);
170+
171+ const result = await patchAcceptReschedule("a1");
172+ expect(result).toEqual(mockAppt);
173+
174+ const [url, init] = lastFetchCall();
175+ expect(url).toBe("/api/appointments/a1/reschedule/accept");
176+ expect(init?.method).toBe("PATCH");
177+ });
178+
179+ it("patchDeclineReschedule calls /appointments/:id/reschedule/decline", async () => {
180+ const mockAppt = { id: "a1" };
181+ mockFetchSuccess(mockAppt);
182+
183+ const result = await patchDeclineReschedule("a1");
184+ expect(result).toEqual(mockAppt);
185+
186+ const [url, init] = lastFetchCall();
187+ expect(url).toBe("/api/appointments/a1/reschedule/decline");
188+ expect(init?.method).toBe("PATCH");
189+ });
190+});
src/api/appointments/deleteSlotById.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "../client";
2+
3+export function deleteSlotById(id: string): Promise<void> {
4+ return client<void>(`/appointments/slots/${id}`, { method: "DELETE" });
5+}
src/api/appointments/deleteSlotSeries.tsadded+5 -0
@@ -0,0 +1,5 @@
1+import { client } from "../client";
2+
3+export function deleteSlotSeries(series: string): Promise<void> {
4+ return client<void>(`/appointments/slots/series/${series}`, { method: "DELETE" });
5+}
src/api/appointments/getAppointments.tsadded+8 -0
@@ -0,0 +1,8 @@
1+import { client } from "../client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "../client";
3+import type { Appointment } from "../client";
4+
5+export async function getAppointments(params?: PageParams, signal?: AbortSignal): Promise<Page<Appointment>> {
6+ const data = await client<unknown>(`/appointments${pageQuery(params)}`, { signal });
7+ return normalizePage<Appointment>(data);
8+}
src/api/appointments/getSlots.tsadded+8 -0
@@ -0,0 +1,8 @@
1+import { client } from "../client";
2+import { normalizePage, pageQuery, type Page, type PageParams } from "../client";
3+import type { AppointmentSlot } from "../client";
4+
5+export async function getSlots(params?: PageParams, signal?: AbortSignal): Promise<Page<AppointmentSlot>> {
6+ const data = await client<unknown>(`/appointments/slots${pageQuery(params)}`, { signal });
7+ return normalizePage<AppointmentSlot>(data);
8+}
src/api/appointments/index.tsadded+12 -0
@@ -0,0 +1,12 @@
1+export * from "./postSlots";
2+export * from "./getSlots";
3+export * from "./deleteSlotById";
4+export * from "./deleteSlotSeries";
5+export * from "./postAppointment";
6+export * from "./getAppointments";
7+export * from "./patchApproveAppointment";
8+export * from "./patchRejectAppointment";
9+export * from "./patchCancelAppointment";
10+export * from "./patchRescheduleAppointment";
11+export * from "./patchAcceptReschedule";
12+export * from "./patchDeclineReschedule";
src/api/appointments/patchAcceptReschedule.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { Appointment } from "../client";
3+
4+export function patchAcceptReschedule(id: string): Promise<Appointment> {
5+ return client<Appointment>(`/appointments/${id}/reschedule/accept`, { method: "PATCH" });
6+}
src/api/appointments/patchApproveAppointment.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { Appointment } from "../client";
3+
4+export function patchApproveAppointment(id: string): Promise<Appointment> {
5+ return client<Appointment>(`/appointments/${id}/approve`, { method: "PATCH" });
6+}
src/api/appointments/patchCancelAppointment.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { client } from "../client";
2+import type { Appointment } from "../client";
3+
4+export type CancelAppointmentBody = {
5+ /** Optional free-text reason; blank/omitted records no reason. */
6+ reason?: string;
7+};
8+
9+export function patchCancelAppointment(id: string, body?: CancelAppointmentBody): Promise<Appointment> {
10+ return client<Appointment>(`/appointments/${id}/cancel`, { method: "PATCH", body });
11+}
src/api/appointments/patchDeclineReschedule.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "../client";
2+import type { Appointment } from "../client";
3+
4+export function patchDeclineReschedule(id: string): Promise<Appointment> {
5+ return client<Appointment>(`/appointments/${id}/reschedule/decline`, { method: "PATCH" });
6+}
src/api/appointments/patchRejectAppointment.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { client } from "../client";
2+import type { Appointment } from "../client";
3+
4+export type RejectAppointmentBody = {
5+ /** Optional free-text reason; blank/omitted records no reason. */
6+ reason?: string;
7+};
8+
9+export function patchRejectAppointment(id: string, body?: RejectAppointmentBody): Promise<Appointment> {
10+ return client<Appointment>(`/appointments/${id}/reject`, { method: "PATCH", body });
11+}
src/api/appointments/patchRescheduleAppointment.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { client } from "../client";
2+import type { Appointment } from "../client";
3+
4+export type RescheduleBody = {
5+ starts_at: number;
6+ ends_at: number;
7+};
8+
9+export function patchRescheduleAppointment(id: string, body: RescheduleBody): Promise<Appointment> {
10+ return client<Appointment>(`/appointments/${id}/reschedule`, { method: "PATCH", body });
11+}
src/api/appointments/postAppointment.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { client } from "../client";
2+import type { Appointment } from "../client";
3+
4+export type BookAppointmentBody = {
5+ slot: string;
6+ reason: string;
7+};
8+
9+export function postAppointment(body: BookAppointmentBody): Promise<Appointment> {
10+ return client<Appointment>("/appointments", { method: "POST", body });
11+}
src/api/appointments/postSlots.tsadded+14 -0
@@ -0,0 +1,14 @@
1+import { client } from "../client";
2+import type { AppointmentSlot } from "../client";
3+
4+export type PublishSlotsBody = {
5+ starts_at: number;
6+ ends_at: number;
7+ note?: string | null;
8+ repeat_weekly?: boolean;
9+ until?: number | null;
10+};
11+
12+export function postSlots(body: PublishSlotsBody): Promise<AppointmentSlot[]> {
13+ return client<AppointmentSlot[]>("/appointments/slots", { method: "POST", body });
14+}
src/api/client/types.tsmodified+37 -0
@@ -88,6 +88,43 @@ export type EventRegistration = {
88 registered_by: PersonRef;88 registered_by: PersonRef;
89 };89 };
90 90
91+export type AppointmentStatus = "pending" | "approved" | "rejected" | "cancelled";
92+
93+export type AppointmentSlot = {
94+ id: string;
95+ teacher: PersonRef;
96+ starts_at: number; // unix ms UTC
97+ ends_at: number; // unix ms UTC, half-open
98+ note: string | null;
99+ series: string | null; // null = one-off; shared id across a weekly series
100+ created_at: number;
101+};
102+
103+export type Appointment = {
104+ id: string;
105+ slot: string;
106+ teacher: PersonRef | null; // null only if slot vanished
107+ requester: PersonRef;
108+ status: AppointmentStatus;
109+ reason: string;
110+ starts_at: number | null; // effective window (proposal if accepted, else slot's)
111+ ends_at: number | null;
112+ proposed_starts_at: number | null;
113+ proposed_ends_at: number | null;
114+ proposed_by: PersonRef | null;
115+ decided_by: PersonRef | null; // null while pending
116+ cancelled_by: PersonRef | null; // set only when status === "cancelled"
117+ cancel_reason: string | null; // optional reason, null when none given
118+ reject_reason: string | null; // optional reason when status === "rejected" (rejecter is decided_by)
119+ created_at: number;
120+};
121+
122+export const APPOINTMENT_LIMITS = {
123+ noteMaxLen: 500, // MAX_APPOINTMENT_NOTE_LEN, empty allowed
124+ reasonMaxLen: 1000, // MAX_APPOINTMENT_REASON_LEN, non-blank required
125+ maxSlotOccurrences: 52, // MAX_SLOT_OCCURRENCES for repeat_weekly
126+} as const;
127+
91 export type Course = {128 export type Course = {
92 id: string;129 id: string;
93 creator: PersonRef;130 creator: PersonRef;
src/components/appointments/book-appointment-form.tsxadded+82 -0
@@ -0,0 +1,82 @@
1+import { createSignal } from "solid-js";
2+import { APPOINTMENT_LIMITS, formatApiError, type AppointmentSlot } from "@/api/client";
3+import { Button } from "@/components/ui/button";
4+import { Label } from "@/components/ui/label";
5+import { Textarea } from "@/components/ui/textarea";
6+import { formatDateTime } from "@/lib/format";
7+import { personLabel } from "@/lib/person";
8+import { usePreferences, useT } from "@/stores/preferences-context";
9+
10+export function BookAppointmentForm(props: {
11+ slot: AppointmentSlot;
12+ onSubmit: (reason: string) => Promise<void>;
13+ onCancel?: () => void;
14+}) {
15+ const t = useT();
16+ const { locale } = usePreferences();
17+ const [reason, setReason] = createSignal("");
18+ const [error, setError] = createSignal("");
19+ const [pending, setPending] = createSignal(false);
20+
21+ const handleSubmit = async (e: SubmitEvent) => {
22+ e.preventDefault();
23+ const value = reason().trim();
24+ if (!value) {
25+ setError(t("appointments.reasonRequired"));
26+ return;
27+ }
28+ if (value.length > APPOINTMENT_LIMITS.reasonMaxLen) {
29+ setError(t("form.descriptionMax"));
30+ return;
31+ }
32+ setError("");
33+ setPending(true);
34+ try {
35+ await props.onSubmit(value);
36+ } catch (err) {
37+ setError(formatApiError(err));
38+ } finally {
39+ setPending(false);
40+ }
41+ };
42+
43+ return (
44+ <form class="space-y-4" onSubmit={handleSubmit}>
45+ <div class="space-y-1.5 rounded-2xl border border-sky-500/15 bg-sky-500/3 p-4 text-sm">
46+ <p>
47+ <span class="text-muted-foreground">{t("appointments.teacher")}:</span>{" "}
48+ <span class="font-medium">{personLabel(props.slot.teacher)}</span>
49+ </p>
50+ <p class="mono text-xs text-muted-foreground">
51+ {formatDateTime(props.slot.starts_at, locale())} β€” {formatDateTime(props.slot.ends_at, locale())}
52+ </p>
53+ </div>
54+
55+ <div class="space-y-1.5 rounded-2xl border border-violet-500/15 bg-violet-500/3 p-4">
56+ <Label for="book-reason">{t("appointments.reason")}</Label>
57+ <Textarea
58+ id="book-reason"
59+ class="min-h-28"
60+ value={reason()}
61+ maxlength={APPOINTMENT_LIMITS.reasonMaxLen}
62+ rows={4}
63+ required
64+ placeholder={t("appointments.reasonPlaceholder")}
65+ onInput={(e) => setReason(e.currentTarget.value)}
66+ />
67+ </div>
68+
69+ {error() && <p class="text-sm text-destructive">{error()}</p>}
70+ <div class="sticky bottom-0 -mx-5 flex flex-wrap items-center gap-2 border-t border-border bg-background px-5 pb-6 pt-4 sm:-mx-6 sm:px-6 sm:pb-6">
71+ <Button type="submit" class="h-10 flex-1 sm:flex-none" disabled={pending()}>
72+ {t("appointments.book")}
73+ </Button>
74+ {props.onCancel && (
75+ <Button type="button" variant="outline" class="h-10 flex-1 sm:flex-none" onClick={props.onCancel}>
76+ {t("common.cancel")}
77+ </Button>
78+ )}
79+ </div>
80+ </form>
81+ );
82+}
src/components/appointments/publish-slots-form.tsxadded+163 -0
@@ -0,0 +1,163 @@
1+import { createSignal, Show } from "solid-js";
2+import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client";
3+import { Button } from "@/components/ui/button";
4+import { DatePicker } from "@/components/ui/date-picker";
5+import { Input } from "@/components/ui/input";
6+import { Label } from "@/components/ui/label";
7+import { Textarea } from "@/components/ui/textarea";
8+import { createNow } from "@/lib/create-now";
9+import { dateInputToEndOfDayMs, dateTimeInputToMs } from "@/lib/datetime-input";
10+import { useT } from "@/stores/preferences-context";
11+
12+export type PublishSlotsValues = {
13+ starts_at: number;
14+ ends_at: number;
15+ note: string | null;
16+ repeat_weekly: boolean;
17+ until: number | null;
18+};
19+
20+export function PublishSlotsForm(props: {
21+ onSubmit: (values: PublishSlotsValues) => Promise<void>;
22+ onCancel?: () => void;
23+}) {
24+ const t = useT();
25+ const now = createNow();
26+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
27+ const [startsDate, setStartsDate] = createSignal("");
28+ const [startsTime, setStartsTime] = createSignal("");
29+ const [endsDate, setEndsDate] = createSignal("");
30+ const [endsTime, setEndsTime] = createSignal("");
31+ const [note, setNote] = createSignal("");
32+ const [repeatWeekly, setRepeatWeekly] = createSignal(false);
33+ const [untilDate, setUntilDate] = createSignal("");
34+ const [error, setError] = createSignal("");
35+ const [pending, setPending] = createSignal(false);
36+
37+ const validate = (starts: number | null, ends: number | null, until: number | null): string | null => {
38+ if (starts == null || ends == null) return t("form.timeOrder");
39+ if (ends < starts) return t("form.timeOrder");
40+ const grace = now() - 60_000;
41+ if (starts < grace || ends < grace) return t("form.timePast");
42+ if (repeatWeekly()) {
43+ if (until == null) return t("appointments.untilRequired");
44+ if (until < grace) return t("form.timePast");
45+ const occurrences = Math.floor((until - starts) / WEEK_MS) + 1;
46+ if (occurrences > APPOINTMENT_LIMITS.maxSlotOccurrences) {
47+ return t("appointments.tooManyOccurrences", { count: occurrences, max: APPOINTMENT_LIMITS.maxSlotOccurrences });
48+ }
49+ }
50+ if (note().length > APPOINTMENT_LIMITS.noteMaxLen) return t("form.descriptionMax");
51+ return null;
52+ };
53+
54+ const handleSubmit = async (e: SubmitEvent) => {
55+ e.preventDefault();
56+ const starts_at = dateTimeInputToMs(startsDate(), startsTime());
57+ const ends_at = dateTimeInputToMs(endsDate(), endsTime());
58+ const until = repeatWeekly() ? dateInputToEndOfDayMs(untilDate()) : null;
59+ const v = validate(starts_at, ends_at, until);
60+ if (v) {
61+ setError(v);
62+ return;
63+ }
64+ setError("");
65+ setPending(true);
66+ try {
67+ await props.onSubmit({
68+ starts_at: starts_at!,
69+ ends_at: ends_at!,
70+ note: note().trim() ? note().trim() : null,
71+ repeat_weekly: repeatWeekly(),
72+ until,
73+ });
74+ } catch (err) {
75+ setError(formatApiError(err));
76+ } finally {
77+ setPending(false);
78+ }
79+ };
80+
81+ return (
82+ <form class="space-y-4" onSubmit={handleSubmit}>
83+ <div class="grid gap-3 rounded-2xl border border-amber-500/15 bg-amber-500/3 p-4">
84+ <div class="space-y-1.5">
85+ <Label for="slot-starts">{t("appointments.starts")}</Label>
86+ <div class="grid grid-cols-2 gap-2">
87+ <DatePicker id="slot-starts" class="h-11" placeholder={t("form.datePlaceholder")} value={startsDate()} onChange={setStartsDate} />
88+ <Input
89+ id="slot-starts-time"
90+ class="h-11 font-mono placeholder:text-muted-foreground/45"
91+ inputMode="numeric"
92+ placeholder="09:00"
93+ pattern="[0-2][0-9]:[0-5][0-9]"
94+ value={startsTime()}
95+ aria-label={t("appointments.starts")}
96+ onInput={(e) => setStartsTime(e.currentTarget.value)}
97+ />
98+ </div>
99+ </div>
100+ <div class="space-y-1.5">
101+ <Label for="slot-ends">{t("appointments.ends")}</Label>
102+ <div class="grid grid-cols-2 gap-2">
103+ <DatePicker id="slot-ends" class="h-11" placeholder={t("form.datePlaceholder")} value={endsDate()} onChange={setEndsDate} />
104+ <Input
105+ id="slot-ends-time"
106+ class="h-11 font-mono placeholder:text-muted-foreground/45"
107+ inputMode="numeric"
108+ placeholder="10:00"
109+ pattern="[0-2][0-9]:[0-5][0-9]"
110+ value={endsTime()}
111+ aria-label={t("appointments.ends")}
112+ onInput={(e) => setEndsTime(e.currentTarget.value)}
113+ />
114+ </div>
115+ </div>
116+ </div>
117+
118+ <div class="space-y-1.5 rounded-2xl border border-sky-500/15 bg-sky-500/3 p-4">
119+ <Label for="slot-note">{t("appointments.note")}</Label>
120+ <Textarea
121+ id="slot-note"
122+ class="min-h-20"
123+ value={note()}
124+ maxlength={APPOINTMENT_LIMITS.noteMaxLen}
125+ rows={2}
126+ placeholder={t("appointments.notePlaceholder")}
127+ onInput={(e) => setNote(e.currentTarget.value)}
128+ />
129+ </div>
130+
131+ <div class="space-y-3 rounded-2xl border border-violet-500/15 bg-violet-500/3 p-4">
132+ <label class="flex items-center gap-2 text-sm font-medium">
133+ <input
134+ type="checkbox"
135+ class="h-4 w-4 rounded border-border"
136+ checked={repeatWeekly()}
137+ onChange={(e) => setRepeatWeekly(e.currentTarget.checked)}
138+ />
139+ <span>{t("appointments.repeatWeekly")}</span>
140+ </label>
141+ <p class="text-xs text-muted-foreground">{t("appointments.repeatWeeklyHelp")}</p>
142+ <Show when={repeatWeekly()}>
143+ <div class="space-y-1.5 pt-1">
144+ <Label for="slot-until">{t("appointments.until")}</Label>
145+ <DatePicker id="slot-until" class="h-11" placeholder={t("form.datePlaceholder")} value={untilDate()} onChange={setUntilDate} />
146+ </div>
147+ </Show>
148+ </div>
149+
150+ {error() && <p class="text-sm text-destructive">{error()}</p>}
151+ <div class="sticky bottom-0 -mx-5 flex flex-wrap items-center gap-2 border-t border-border bg-background px-5 pb-6 pt-4 sm:-mx-6 sm:px-6 sm:pb-6">
152+ <Button type="submit" class="h-10 flex-1 sm:flex-none" disabled={pending()}>
153+ {t("appointments.publish")}
154+ </Button>
155+ {props.onCancel && (
156+ <Button type="button" variant="outline" class="h-10 flex-1 sm:flex-none" onClick={props.onCancel}>
157+ {t("common.cancel")}
158+ </Button>
159+ )}
160+ </div>
161+ </form>
162+ );
163+}
src/components/appointments/reschedule-form.tsxadded+99 -0
@@ -0,0 +1,99 @@
1+import { createSignal } from "solid-js";
2+import { formatApiError, type Appointment } from "@/api/client";
3+import { Button } from "@/components/ui/button";
4+import { DatePicker } from "@/components/ui/date-picker";
5+import { Input } from "@/components/ui/input";
6+import { Label } from "@/components/ui/label";
7+import { createNow } from "@/lib/create-now";
8+import { dateInputFromMs, dateTimeInputToMs, timeInputFromMs } from "@/lib/datetime-input";
9+import { useT } from "@/stores/preferences-context";
10+
11+export function RescheduleForm(props: {
12+ appointment: Appointment;
13+ onSubmit: (values: { starts_at: number; ends_at: number }) => Promise<void>;
14+ onCancel?: () => void;
15+}) {
16+ const t = useT();
17+ const now = createNow();
18+ const [startsDate, setStartsDate] = createSignal(dateInputFromMs(props.appointment.starts_at));
19+ const [startsTime, setStartsTime] = createSignal(timeInputFromMs(props.appointment.starts_at));
20+ const [endsDate, setEndsDate] = createSignal(dateInputFromMs(props.appointment.ends_at));
21+ const [endsTime, setEndsTime] = createSignal(timeInputFromMs(props.appointment.ends_at));
22+ const [error, setError] = createSignal("");
23+ const [pending, setPending] = createSignal(false);
24+
25+ const handleSubmit = async (e: SubmitEvent) => {
26+ e.preventDefault();
27+ const starts_at = dateTimeInputToMs(startsDate(), startsTime());
28+ const ends_at = dateTimeInputToMs(endsDate(), endsTime());
29+ if (starts_at == null || ends_at == null || ends_at < starts_at) {
30+ setError(t("form.timeOrder"));
31+ return;
32+ }
33+ const grace = now() - 60_000;
34+ if (starts_at < grace || ends_at < grace) {
35+ setError(t("form.timePast"));
36+ return;
37+ }
38+ setError("");
39+ setPending(true);
40+ try {
41+ await props.onSubmit({ starts_at, ends_at });
42+ } catch (err) {
43+ setError(formatApiError(err));
44+ } finally {
45+ setPending(false);
46+ }
47+ };
48+
49+ return (
50+ <form class="space-y-4" onSubmit={handleSubmit}>
51+ <div class="grid gap-3 rounded-2xl border border-amber-500/15 bg-amber-500/3 p-4">
52+ <div class="space-y-1.5">
53+ <Label for="resched-starts">{t("appointments.starts")}</Label>
54+ <div class="grid grid-cols-2 gap-2">
55+ <DatePicker id="resched-starts" class="h-11" placeholder={t("form.datePlaceholder")} value={startsDate()} onChange={setStartsDate} />
56+ <Input
57+ id="resched-starts-time"
58+ class="h-11 font-mono placeholder:text-muted-foreground/45"
59+ inputMode="numeric"
60+ placeholder="09:00"
61+ pattern="[0-2][0-9]:[0-5][0-9]"
62+ value={startsTime()}
63+ aria-label={t("appointments.starts")}
64+ onInput={(e) => setStartsTime(e.currentTarget.value)}
65+ />
66+ </div>
67+ </div>
68+ <div class="space-y-1.5">
69+ <Label for="resched-ends">{t("appointments.ends")}</Label>
70+ <div class="grid grid-cols-2 gap-2">
71+ <DatePicker id="resched-ends" class="h-11" placeholder={t("form.datePlaceholder")} value={endsDate()} onChange={setEndsDate} />
72+ <Input
73+ id="resched-ends-time"
74+ class="h-11 font-mono placeholder:text-muted-foreground/45"
75+ inputMode="numeric"
76+ placeholder="10:00"
77+ pattern="[0-2][0-9]:[0-5][0-9]"
78+ value={endsTime()}
79+ aria-label={t("appointments.ends")}
80+ onInput={(e) => setEndsTime(e.currentTarget.value)}
81+ />
82+ </div>
83+ </div>
84+ </div>
85+
86+ {error() && <p class="text-sm text-destructive">{error()}</p>}
87+ <div class="sticky bottom-0 -mx-5 flex flex-wrap items-center gap-2 border-t border-border bg-background px-5 pb-6 pt-4 sm:-mx-6 sm:px-6 sm:pb-6">
88+ <Button type="submit" class="h-10 flex-1 sm:flex-none" disabled={pending()}>
89+ {t("appointments.reschedule")}
90+ </Button>
91+ {props.onCancel && (
92+ <Button type="button" variant="outline" class="h-10 flex-1 sm:flex-none" onClick={props.onCancel}>
93+ {t("common.cancel")}
94+ </Button>
95+ )}
96+ </div>
97+ </form>
98+ );
99+}
src/components/layout/nav-items.tsmodified+3 -1
@@ -58,6 +58,7 @@ const NAV_GROUPS: NavGroup[] = [
58 { to: "/exams", labelKey: "nav.exams", Icon: IconExam },58 { to: "/exams", labelKey: "nav.exams", Icon: IconExam },
59 { to: "/events", labelKey: "nav.events", Icon: IconCalendar },59 { to: "/events", labelKey: "nav.events", Icon: IconCalendar },
60 { to: "/calendar", labelKey: "nav.calendar", Icon: IconCalendarDays },60 { to: "/calendar", labelKey: "nav.calendar", Icon: IconCalendarDays },
61+ { to: "/appointments", labelKey: "nav.appointments", Icon: IconClock },
61 { to: "/marks", labelKey: "nav.marks", Icon: IconChart, exactRole: "student" },62 { to: "/marks", labelKey: "nav.marks", Icon: IconChart, exactRole: "student" },
62 { to: "/attendance", labelKey: "nav.attendance", Icon: IconClipboardCheck, exactRole: "student" },63 { to: "/attendance", labelKey: "nav.attendance", Icon: IconClipboardCheck, exactRole: "student" },
63 { to: "/pomodoro", labelKey: "nav.pomodoro", Icon: IconClock, exactRole: "student" },64 { to: "/pomodoro", labelKey: "nav.pomodoro", Icon: IconClock, exactRole: "student" },
@@ -137,11 +138,12 @@ const PARENT_GROUP: NavGroup = {
137 exactRole: "parent",138 exactRole: "parent",
138 items: [139 items: [
139 { to: "/students", labelKey: "nav.myStudents", Icon: IconUsers, exactRole: "parent" },140 { to: "/students", labelKey: "nav.myStudents", Icon: IconUsers, exactRole: "parent" },
141+ { to: "/appointments", labelKey: "nav.appointments", Icon: IconClock },
140 ],142 ],
141 };143 };
142 144
143 function itemVisible(item: NavItem, role: Role | undefined) {145 function itemVisible(item: NavItem, role: Role | undefined) {
144- if (role === "parent") return item.to === "/students";146+ if (role === "parent") return item.to === "/students" || item.to === "/appointments";
145 if (item.exactRole) return hasExactRole(role, item.exactRole);147 if (item.exactRole) return hasExactRole(role, item.exactRole);
146 if (item.minRole || item.maxRole) return roleInRange(role, item.minRole, item.maxRole);148 if (item.minRole || item.maxRole) return roleInRange(role, item.minRole, item.maxRole);
147 return true;149 return true;
src/components/layout/right-nav.tsxmodified+141 -37
@@ -2,8 +2,10 @@ import { For, Show, Suspense, createEffect, createMemo, createResource, createSi
2 import { useLocation, useNavigate } from "@tanstack/solid-router";2 import { useLocation, useNavigate } from "@tanstack/solid-router";
3 import { getEvents } from "@/api/events";3 import { getEvents } from "@/api/events";
4 import { getExams } from "@/api/exams";4 import { getExams } from "@/api/exams";
5+import { getAppointments } from "@/api/appointments";
5 import { getMessages, patchMessageById } from "@/api/messages";6 import { getMessages, patchMessageById } from "@/api/messages";
6-import type { Event, Exam, Message } from "@/api/client";7+import type { Appointment, Event, Exam, Message } from "@/api/client";
8+import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status";
7 import { Badge } from "@/components/ui/badge";9 import { Badge } from "@/components/ui/badge";
8 import { Button } from "@/components/ui/button";10 import { Button } from "@/components/ui/button";
9 import { PageSpinner } from "@/components/ui/page-spinner";11 import { PageSpinner } from "@/components/ui/page-spinner";
@@ -22,7 +24,10 @@ import { personLabel } from "@/lib/person";
22 import { usePreferences, useT } from "@/stores/preferences-context";24 import { usePreferences, useT } from "@/stores/preferences-context";
23 25
24 type ActiveTab = "messages" | "calendar" | null;26 type ActiveTab = "messages" | "calendar" | null;
25-type CalendarItemRef = { type: "event"; data: Event } | { type: "exam"; data: Exam };27+type CalendarItemRef =
28+ | { type: "event"; data: Event }
29+ | { type: "exam"; data: Exam }
30+ | { type: "appointment"; data: Appointment };
26 31
27 const PAGE_SIZE = 5;32 const PAGE_SIZE = 5;
28 33
@@ -44,7 +49,7 @@ export function RightNav() {
44 49
45 // Calendar drawer state50 // Calendar drawer state
46 const [calPage, setCalPage] = createSignal(0);51 const [calPage, setCalPage] = createSignal(0);
47- const [calFilter, setCalFilter] = createSignal<"all" | "events" | "exams">("all");52+ const [calFilter, setCalFilter] = createSignal<"all" | "events" | "exams" | "appointments">("all");
48 const [selectedCalItem, setSelectedCalItem] = createSignal<CalendarItemRef | null>(null);53 const [selectedCalItem, setSelectedCalItem] = createSignal<CalendarItemRef | null>(null);
49 54
50 // Fetch inbox messages55 // Fetch inbox messages
@@ -82,12 +87,24 @@ export function RightNav() {
82 { initialValue: [] }87 { initialValue: [] }
83 );88 );
84 89
90+ const [appointmentsRes, { refetch: refetchAppointments }] = createResource(
91+ async () => {
92+ try {
93+ return (await getAppointments({ limit: 100 })).items;
94+ } catch {
95+ return [];
96+ }
97+ },
98+ { initialValue: [] }
99+ );
100+
85 // Revalidate every source so an item deleted on another page stops showing101 // Revalidate every source so an item deleted on another page stops showing
86 // in the drawer/badge: on the periodic clock tick and whenever a drawer opens.102 // in the drawer/badge: on the periodic clock tick and whenever a drawer opens.
87 const refreshAll = () => {103 const refreshAll = () => {
88 void refetchMessages();104 void refetchMessages();
89 void refetchEvents();105 void refetchEvents();
90 void refetchExams();106 void refetchExams();
107+ void refetchAppointments();
91 };108 };
92 109
93 // Computed message data110 // Computed message data
@@ -138,6 +155,12 @@ export function RightNav() {
138 return examsRes.latest.filter((e: Exam) => !e.draft && notEnded(e.starts_at, e.ends_at));155 return examsRes.latest.filter((e: Exam) => !e.draft && notEnded(e.starts_at, e.ends_at));
139 });156 });
140 157
158+ const activeAppointments = createMemo(() => {
159+ return appointmentsRes.latest.filter(
160+ (a: Appointment) => (a.status === "pending" || a.status === "approved") && notEnded(a.starts_at, a.ends_at)
161+ );
162+ });
163+
141 const hasTodayEvents = createMemo(() => activeEvents().length > 0);164 const hasTodayEvents = createMemo(() => activeEvents().length > 0);
142 const hasTodayExams = createMemo(() => activeExams().length > 0);165 const hasTodayExams = createMemo(() => activeExams().length > 0);
143 166
@@ -156,6 +179,12 @@ export function RightNav() {
156 }179 }
157 }180 }
158 181
182+ if (calFilter() === "all" || calFilter() === "appointments") {
183+ for (const ap of activeAppointments()) {
184+ items.push({ type: "appointment", data: ap });
185+ }
186+ }
187+
159 // Sort chronologically by start date188 // Sort chronologically by start date
160 return items.sort((a, b) => {189 return items.sort((a, b) => {
161 const timeA = a.data.starts_at ? new Date(a.data.starts_at).getTime() : 0;190 const timeA = a.data.starts_at ? new Date(a.data.starts_at).getTime() : 0;
@@ -596,6 +625,18 @@ export function RightNav() {
596 >625 >
597 {t("calendar.exams")} ({activeExams().length})626 {t("calendar.exams")} ({activeExams().length})
598 </button>627 </button>
628+ <button
629+ type="button"
630+ onClick={() => { setCalFilter("appointments"); setCalPage(0); }}
631+ class={cn(
632+ "rounded-lg px-2.5 py-1 text-[11px] font-medium transition-colors border",
633+ calFilter() === "appointments"
634+ ? "bg-violet-500 text-white font-semibold border-violet-500"
635+ : "text-violet-600 dark:text-violet-400 border-violet-500/30 hover:bg-violet-500/10"
636+ )}
637+ >
638+ {t("calendar.appointments")} ({activeAppointments().length})
639+ </button>
599 </div>640 </div>
600 641
601 <Show642 <Show
@@ -611,7 +652,11 @@ export function RightNav() {
611 <For each={paginatedCalItems()}>652 <For each={paginatedCalItems()}>
612 {(item) => {653 {(item) => {
613 const isEvent = item.type === "event";654 const isEvent = item.type === "event";
614- const ev = item.data;655+ const isAppt = item.type === "appointment";
656+ const title = item.type === "appointment"
657+ ? ((item.data.teacher?.display_name ?? item.data.teacher?.username)
658+ ?? item.data.requester.display_name ?? item.data.requester.username)
659+ : item.data.title;
615 return (660 return (
616 <div661 <div
617 onClick={() => setSelectedCalItem(item)}662 onClick={() => setSelectedCalItem(item)}
@@ -619,7 +664,9 @@ export function RightNav() {
619 "group flex cursor-pointer items-start justify-between gap-2.5 rounded-xl border p-3 shadow-2xs transition-all hover:shadow-md",664 "group flex cursor-pointer items-start justify-between gap-2.5 rounded-xl border p-3 shadow-2xs transition-all hover:shadow-md",
620 isEvent665 isEvent
621 ? "border-emerald-500/30 bg-emerald-500/2 hover:border-emerald-500/60 hover:bg-emerald-500/5"666 ? "border-emerald-500/30 bg-emerald-500/2 hover:border-emerald-500/60 hover:bg-emerald-500/5"
622- : "border-rose-500/30 bg-rose-500/2 hover:border-rose-500/60 hover:bg-rose-500/5"667+ : isAppt
668+ ? "border-violet-500/30 bg-violet-500/2 hover:border-violet-500/60 hover:bg-violet-500/5"
669+ : "border-rose-500/30 bg-rose-500/2 hover:border-rose-500/60 hover:bg-rose-500/5"
623 )}670 )}
624 >671 >
625 <div class="min-w-0 space-y-1">672 <div class="min-w-0 space-y-1">
@@ -628,16 +675,23 @@ export function RightNav() {
628 "truncate text-xs font-semibold",675 "truncate text-xs font-semibold",
629 isEvent676 isEvent
630 ? "text-emerald-700 dark:text-emerald-300 group-hover:text-emerald-600"677 ? "text-emerald-700 dark:text-emerald-300 group-hover:text-emerald-600"
631- : "text-rose-700 dark:text-rose-300 group-hover:text-rose-600"678+ : isAppt
679+ ? "text-violet-700 dark:text-violet-300 group-hover:text-violet-600"
680+ : "text-rose-700 dark:text-rose-300 group-hover:text-rose-600"
632 )}681 )}
633 >682 >
634- {ev.title}683+ {title}
635 </p>684 </p>
685+ <Show when={item.type === "appointment" && item.data.reason}>
686+ <p class="truncate text-[11px] text-muted-foreground">
687+ {item.type === "appointment" ? item.data.reason : ""}
688+ </p>
689+ </Show>
636 <div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">690 <div class="flex items-center gap-1.5 text-[11px] text-muted-foreground">
637 <IconClock class="h-3 w-3 shrink-0" />691 <IconClock class="h-3 w-3 shrink-0" />
638 <span>692 <span>
639- {ev.starts_at693+ {item.data.starts_at
640- ? new Date(ev.starts_at).toLocaleDateString(694+ ? new Date(item.data.starts_at).toLocaleDateString(
641 locale() === "tr" ? "tr-TR" : "en-US",695 locale() === "tr" ? "tr-TR" : "en-US",
642 { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }696 { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }
643 )697 )
@@ -646,17 +700,30 @@ export function RightNav() {
646 </div>700 </div>
647 </div>701 </div>
648 702
649- <Badge703+ <Show
650- variant="outline"704+ when={isAppt}
651- class={cn(705+ fallback={
652- "shrink-0 text-[9px] font-semibold px-2 py-0.5",706+ <Badge
653- isEvent707+ variant="outline"
654- ? "border-emerald-500/40 text-emerald-700 dark:text-emerald-300 bg-emerald-500/10"708+ class={cn(
655- : "border-rose-500/40 text-rose-700 dark:text-rose-300 bg-rose-500/10"709+ "shrink-0 text-[9px] font-semibold px-2 py-0.5",
656- )}710+ isEvent
711+ ? "border-emerald-500/40 text-emerald-700 dark:text-emerald-300 bg-emerald-500/10"
712+ : "border-rose-500/40 text-rose-700 dark:text-rose-300 bg-rose-500/10"
713+ )}
714+ >
715+ {isEvent ? t("calendar.events") : t("calendar.exams")}
716+ </Badge>
717+ }
657 >718 >
658- {isEvent ? t("calendar.events") : t("calendar.exams")}719+ <Badge
659- </Badge>720+ variant="outline"
721+ class={cn("shrink-0 gap-1 text-[9px] font-semibold px-2 py-0.5", appointmentStatusClass((item.data as Appointment).status))}
722+ >
723+ <span class={cn("h-1.5 w-1.5 rounded-full", appointmentStatusDotClass((item.data as Appointment).status))} />
724+ {t(appointmentStatusLabelKey((item.data as Appointment).status))}
725+ </Badge>
726+ </Show>
660 </div>727 </div>
661 );728 );
662 }}729 }}
@@ -677,7 +744,14 @@ export function RightNav() {
677 >744 >
678 {(item) => {745 {(item) => {
679 const isEvent = item().type === "event";746 const isEvent = item().type === "event";
680- const data = item().data;747+ const isAppt = item().type === "appointment";
748+ const cur = item();
749+ const appt = () => (cur.type === "appointment" ? cur.data : null);
750+ const title = () => {
751+ const a = appt();
752+ if (a) return (a.teacher?.display_name ?? a.teacher?.username) ?? a.requester.display_name ?? a.requester.username;
753+ return (cur.data as Event | Exam).title;
754+ };
681 return (755 return (
682 <div class="space-y-4 animate-in fade-in-50">756 <div class="space-y-4 animate-in fade-in-50">
683 <div757 <div
@@ -685,33 +759,52 @@ export function RightNav() {
685 "rounded-xl border p-4 space-y-3",759 "rounded-xl border p-4 space-y-3",
686 isEvent760 isEvent
687 ? "border-emerald-500/30 bg-emerald-500/3"761 ? "border-emerald-500/30 bg-emerald-500/3"
688- : "border-rose-500/30 bg-rose-500/3"762+ : isAppt
763+ ? "border-violet-500/30 bg-violet-500/3"
764+ : "border-rose-500/30 bg-rose-500/3"
689 )}765 )}
690 >766 >
691 <div class="flex items-center justify-between">767 <div class="flex items-center justify-between">
692- <Badge768+ <Show
693- variant="outline"769+ when={appt()}
694- class={cn(770+ fallback={
695- "text-xs font-semibold px-2.5 py-0.5",771+ <Badge
696- isEvent772+ variant="outline"
697- ? "border-emerald-500/50 text-emerald-700 dark:text-emerald-300 bg-emerald-500/10"773+ class={cn(
698- : "border-rose-500/50 text-rose-700 dark:text-rose-300 bg-rose-500/10"774+ "text-xs font-semibold px-2.5 py-0.5",
699- )}775+ isEvent
776+ ? "border-emerald-500/50 text-emerald-700 dark:text-emerald-300 bg-emerald-500/10"
777+ : "border-rose-500/50 text-rose-700 dark:text-rose-300 bg-rose-500/10"
778+ )}
779+ >
780+ {isEvent ? t("calendar.events") : t("calendar.exams")}
781+ </Badge>
782+ }
700 >783 >
701- {isEvent ? t("calendar.events") : t("calendar.exams")}784+ {(a) => (
702- </Badge>785+ <>
786+ <Badge variant="outline" class="text-xs font-semibold px-2.5 py-0.5 border-violet-500/50 text-violet-700 dark:text-violet-300 bg-violet-500/10">
787+ {t("calendar.appointments")}
788+ </Badge>
789+ <Badge variant="outline" class={cn("gap-1 text-xs font-semibold px-2.5 py-0.5", appointmentStatusClass(a().status))}>
790+ <span class={cn("h-1.5 w-1.5 rounded-full", appointmentStatusDotClass(a().status))} />
791+ {t(appointmentStatusLabelKey(a().status))}
792+ </Badge>
793+ </>
794+ )}
795+ </Show>
703 </div>796 </div>
704 797
705 <h3 class="text-base font-bold text-foreground tracking-tight">798 <h3 class="text-base font-bold text-foreground tracking-tight">
706- {data.title}799+ {title()}
707 </h3>800 </h3>
708 801
709 <div class="space-y-2 text-xs text-muted-foreground border-t border-border/40 pt-2.5">802 <div class="space-y-2 text-xs text-muted-foreground border-t border-border/40 pt-2.5">
710 <div class="flex items-center gap-2">803 <div class="flex items-center gap-2">
711 <IconClock class="h-4 w-4 text-primary shrink-0" />804 <IconClock class="h-4 w-4 text-primary shrink-0" />
712 <span>805 <span>
713- {data.starts_at806+ {cur.data.starts_at
714- ? new Date(data.starts_at).toLocaleString(807+ ? new Date(cur.data.starts_at).toLocaleString(
715 locale() === "tr" ? "tr-TR" : "en-US",808 locale() === "tr" ? "tr-TR" : "en-US",
716 { dateStyle: "full", timeStyle: "short" }809 { dateStyle: "full", timeStyle: "short" }
717 )810 )
@@ -719,10 +812,21 @@ export function RightNav() {
719 </span>812 </span>
720 </div>813 </div>
721 814
722- <Show when={"description" in data && data.description}>815+ <Show when={appt()}>
816+ {(a) => (
817+ <Show when={a().reason}>
818+ <div class="pt-2 border-t border-border/30 text-foreground">
819+ <p class="text-xs font-medium text-muted-foreground mb-1">{t("appointments.reason")}</p>
820+ <p class="text-xs leading-relaxed whitespace-pre-wrap">{a().reason}</p>
821+ </div>
822+ </Show>
823+ )}
824+ </Show>
825+
826+ <Show when={!isAppt && "description" in cur.data && cur.data.description}>
723 <div class="pt-2 border-t border-border/30 text-foreground">827 <div class="pt-2 border-t border-border/30 text-foreground">
724 <p class="text-xs font-medium text-muted-foreground mb-1">AΓ§Δ±klama / Detay:</p>828 <p class="text-xs font-medium text-muted-foreground mb-1">AΓ§Δ±klama / Detay:</p>
725- <p class="text-xs leading-relaxed whitespace-pre-wrap">{String(data.description)}</p>829+ <p class="text-xs leading-relaxed whitespace-pre-wrap">{String((cur.data as Event).description)}</p>
726 </div>830 </div>
727 </Show>831 </Show>
728 </div>832 </div>
@@ -733,7 +837,7 @@ export function RightNav() {
733 variant="secondary"837 variant="secondary"
734 size="sm"838 size="sm"
735 class="h-8 rounded-lg gap-1.5 text-xs font-medium"839 class="h-8 rounded-lg gap-1.5 text-xs font-medium"
736- onClick={() => goTo(isEvent ? `/events/${data.id}` : `/exams/${data.id}`)}840+ onClick={() => goTo(isAppt ? "/appointments" : isEvent ? `/events/${cur.data.id}` : `/exams/${cur.data.id}`)}
737 >841 >
738 <span>Detay SayfasΔ±na Git</span>842 <span>Detay SayfasΔ±na Git</span>
739 <IconExternalLink class="h-3.5 w-3.5" />843 <IconExternalLink class="h-3.5 w-3.5" />
src/components/ui/confirm-dialog.tsxmodified+38 -5
@@ -1,4 +1,4 @@
1-import { type JSX, createSignal, Show } from "solid-js";1+import { type JSX, createEffect, createSignal, Show } from "solid-js";
2 import {2 import {
3 AlertDialog,3 AlertDialog,
4 AlertDialogBody,4 AlertDialogBody,
@@ -10,6 +10,8 @@ import {
10 AlertDialogTitle,10 AlertDialogTitle,
11 } from "@/components/ui/alert-dialog";11 } from "@/components/ui/alert-dialog";
12 import { Button } from "@/components/ui/button";12 import { Button } from "@/components/ui/button";
13+import { Label } from "@/components/ui/label";
14+import { Textarea } from "@/components/ui/textarea";
13 import { IconAlert, IconTrash } from "@/components/ui/icons";15 import { IconAlert, IconTrash } from "@/components/ui/icons";
14 import { useT } from "@/stores/preferences-context";16 import { useT } from "@/stores/preferences-context";
15 import { cn } from "@/lib/cn";17 import { cn } from "@/lib/cn";
@@ -23,19 +25,29 @@ export type ConfirmDialogProps = {
23 confirmLabel?: string;25 confirmLabel?: string;
24 cancelLabel?: string;26 cancelLabel?: string;
25 variant?: "default" | "destructive";27 variant?: "default" | "destructive";
26- onConfirm: () => void | Promise<void>;28+ /** Header glyph. Defaults to trash (destructive) / alert (default). */
29+ icon?: JSX.Element;
30+ /** When set, renders an optional free-text field; its value is passed to onConfirm. */
31+ prompt?: { label: string; placeholder?: string; maxLength?: number };
32+ onConfirm: (prompt?: string) => void | Promise<void>;
27 };33 };
28 34
29 export function ConfirmDialog(props: ConfirmDialogProps) {35 export function ConfirmDialog(props: ConfirmDialogProps) {
30 const t = useT();36 const t = useT();
31 const [pending, setPending] = createSignal(false);37 const [pending, setPending] = createSignal(false);
38+ const [promptValue, setPromptValue] = createSignal("");
32 const destructive = () => props.variant === "destructive";39 const destructive = () => props.variant === "destructive";
33 40
41+ // Reset the field each time the dialog opens so a prior entry never leaks over.
42+ createEffect(() => {
43+ if (props.open) setPromptValue("");
44+ });
45+
34 const run = async () => {46 const run = async () => {
35 if (pending()) return;47 if (pending()) return;
36 setPending(true);48 setPending(true);
37 try {49 try {
38- await props.onConfirm();50+ await props.onConfirm(props.prompt ? (promptValue().trim() || undefined) : undefined);
39 props.onOpenChange(false);51 props.onOpenChange(false);
40 } finally {52 } finally {
41 setPending(false);53 setPending(false);
@@ -52,8 +64,12 @@ export function ConfirmDialog(props: ConfirmDialogProps) {
52 destructive() ? "border-destructive/20 bg-destructive/10 text-destructive" : "border-primary/20 bg-primary/10 text-primary",64 destructive() ? "border-destructive/20 bg-destructive/10 text-destructive" : "border-primary/20 bg-primary/10 text-primary",
53 )}65 )}
54 >66 >
55- <Show when={destructive()} fallback={<IconAlert class="h-4 w-4" />}>67+ <Show when={props.icon} fallback={
56- <IconTrash class="h-4 w-4" />68+ <Show when={destructive()} fallback={<IconAlert class="h-4 w-4" />}>
69+ <IconTrash class="h-4 w-4" />
70+ </Show>
71+ }>
72+ {props.icon}
57 </Show>73 </Show>
58 </span>74 </span>
59 <div class="min-w-0 space-y-1">75 <div class="min-w-0 space-y-1">
@@ -69,6 +85,23 @@ export function ConfirmDialog(props: ConfirmDialogProps) {
69 <div class="rounded-md border border-border bg-muted/40 px-3 py-3 text-sm leading-relaxed">85 <div class="rounded-md border border-border bg-muted/40 px-3 py-3 text-sm leading-relaxed">
70 {props.summary}86 {props.summary}
71 </div>87 </div>
88+ <Show when={props.prompt}>
89+ {(prompt) => (
90+ <div class="mt-3 space-y-1.5">
91+ <Label for="confirm-prompt">{prompt().label}</Label>
92+ <Textarea
93+ id="confirm-prompt"
94+ class="min-h-20"
95+ rows={2}
96+ maxlength={prompt().maxLength}
97+ placeholder={prompt().placeholder}
98+ value={promptValue()}
99+ disabled={pending()}
100+ onInput={(e) => setPromptValue(e.currentTarget.value)}
101+ />
102+ </div>
103+ )}
104+ </Show>
72 </AlertDialogBody>105 </AlertDialogBody>
73 106
74 <AlertDialogFooter>107 <AlertDialogFooter>
src/components/ui/dialog.tsxmodified+8 -6
@@ -9,11 +9,12 @@ export const DialogTrigger = DialogPrimitive.Trigger;
9 export const DialogClose = DialogPrimitive.CloseButton;9 export const DialogClose = DialogPrimitive.CloseButton;
10 10
11 export function DialogContent<T extends ValidComponent = "div">(11 export function DialogContent<T extends ValidComponent = "div">(
12- props: ComponentProps<typeof DialogPrimitive.Content<T>>,12+ props: ComponentProps<typeof DialogPrimitive.Content<T>> & { dismissable?: boolean },
13 ) {13 ) {
14- const [local, rest] = splitProps(props as ComponentProps<typeof DialogPrimitive.Content>, [14+ const [local, rest] = splitProps(props as ComponentProps<typeof DialogPrimitive.Content> & { dismissable?: boolean }, [
15 "class",15 "class",
16 "children",16 "children",
17+ "dismissable",
17 ]);18 ]);
18 return (19 return (
19 <DialogPrimitive.Portal>20 <DialogPrimitive.Portal>
@@ -25,10 +26,11 @@ export function DialogContent<T extends ValidComponent = "div">(
25 "pointer-events-auto relative flex max-h-[min(90vh,48rem)] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-black/8 bg-popover/95 text-popover-foreground shadow-apple outline-hidden backdrop-blur-xl animate-fade-up dark:border-white/12 sm:rounded-3xl",26 "pointer-events-auto relative flex max-h-[min(90vh,48rem)] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-black/8 bg-popover/95 text-popover-foreground shadow-apple outline-hidden backdrop-blur-xl animate-fade-up dark:border-white/12 sm:rounded-3xl",
26 local.class,27 local.class,
27 )}28 )}
28- // ponytail: close only via X β€” outside/ESC races with clickable cards underneath29+ // Default: close only via X β€” outside/ESC races with clickable cards underneath.
29- onPointerDownOutside={(e) => e.preventDefault()}30+ // Opt into backdrop/ESC dismissal per-dialog with `dismissable`.
30- onInteractOutside={(e) => e.preventDefault()}31+ onPointerDownOutside={local.dismissable ? undefined : (e) => e.preventDefault()}
31- onEscapeKeyDown={(e) => e.preventDefault()}32+ onInteractOutside={local.dismissable ? undefined : (e) => e.preventDefault()}
33+ onEscapeKeyDown={local.dismissable ? undefined : (e) => e.preventDefault()}
32 {...rest}34 {...rest}
33 >35 >
34 <DialogPrimitive.CloseButton36 <DialogPrimitive.CloseButton
src/i18n/messages.tsmodified+202 -1
@@ -814,7 +814,74 @@ export type MessageKey =
814 | "calendar.today"814 | "calendar.today"
815 | "calendar.noEvents"815 | "calendar.noEvents"
816 | "calendar.events"816 | "calendar.events"
817- | "calendar.exams";817+ | "calendar.exams"
818+ | "calendar.appointments"
819+ | "nav.appointments"
820+ | "appointments.title"
821+ | "appointments.subtitle"
822+ | "appointments.empty"
823+ | "appointments.mySlots"
824+ | "appointments.availableSlots"
825+ | "appointments.requests"
826+ | "appointments.myBookings"
827+ | "appointments.publish"
828+ | "appointments.book"
829+ | "appointments.approve"
830+ | "appointments.reject"
831+ | "appointments.cancel"
832+ | "appointments.reschedule"
833+ | "appointments.acceptReschedule"
834+ | "appointments.declineReschedule"
835+ | "appointments.deleteSlot"
836+ | "appointments.deleteSeries"
837+ | "appointments.note"
838+ | "appointments.reason"
839+ | "appointments.repeatWeekly"
840+ | "appointments.until"
841+ | "appointments.starts"
842+ | "appointments.ends"
843+ | "appointments.teacher"
844+ | "appointments.student"
845+ | "appointments.proposedTime"
846+ | "appointments.newTime"
847+ | "appointments.status.pending"
848+ | "appointments.status.approved"
849+ | "appointments.status.rejected"
850+ | "appointments.status.cancelled"
851+ | "appointments.confirmCancel"
852+ | "appointments.confirmDeleteSlot"
853+ | "appointments.confirmDeleteSeries"
854+ | "appointments.rescheduleProposed"
855+ | "appointments.slotTaken"
856+ | "appointments.noSlots"
857+ | "appointments.series"
858+ | "appointments.time"
859+ | "appointments.status"
860+ | "appointments.publishSubtitle"
861+ | "appointments.bookSubtitle"
862+ | "appointments.rescheduleSubtitle"
863+ | "appointments.reasonPlaceholder"
864+ | "appointments.notePlaceholder"
865+ | "appointments.noRequests"
866+ | "appointments.noBookings"
867+ | "appointments.repeatWeeklyHelp"
868+ | "appointments.untilRequired"
869+ | "appointments.tooManyOccurrences"
870+ | "appointments.cancelTitle"
871+ | "appointments.cancelAction"
872+ | "appointments.cancelReasonLabel"
873+ | "appointments.cancelReasonPlaceholder"
874+ | "appointments.cancelledBy"
875+ | "appointments.details"
876+ | "appointments.cancelReason"
877+ | "appointments.rejectTitle"
878+ | "appointments.rejectAction"
879+ | "appointments.confirmReject"
880+ | "appointments.rejectReasonLabel"
881+ | "appointments.rejectReasonPlaceholder"
882+ | "appointments.rejectReason"
883+ | "appointments.rejectedBy"
884+ | "appointments.reasonRequired";
818 885
819 type Dict = Record<MessageKey, string>;886 type Dict = Record<MessageKey, string>;
820 887
@@ -1161,6 +1228,73 @@ const en: Dict = {
1161 "calendar.noEvents": "No events or exams on this day.",1228 "calendar.noEvents": "No events or exams on this day.",
1162 "calendar.events": "Events",1229 "calendar.events": "Events",
1163 "calendar.exams": "Exams",1230 "calendar.exams": "Exams",
1231+ "calendar.appointments": "Appointments",
1232+ "nav.appointments": "Appointments",
1233+ "appointments.title": "Appointments",
1234+ "appointments.subtitle": "Book a meeting with a teacher, or publish times you are available.",
1235+ "appointments.empty": "No appointments yet.",
1236+ "appointments.mySlots": "My available times",
1237+ "appointments.availableSlots": "Available times",
1238+ "appointments.requests": "Booking requests",
1239+ "appointments.myBookings": "My bookings",
1240+ "appointments.publish": "Publish times",
1241+ "appointments.book": "Book",
1242+ "appointments.approve": "Approve",
1243+ "appointments.reject": "Reject",
1244+ "appointments.cancel": "Cancel",
1245+ "appointments.reschedule": "Propose new time",
1246+ "appointments.acceptReschedule": "Accept new time",
1247+ "appointments.declineReschedule": "Decline new time",
1248+ "appointments.deleteSlot": "Delete time",
1249+ "appointments.deleteSeries": "Delete series",
1250+ "appointments.note": "Note",
1251+ "appointments.reason": "Reason",
1252+ "appointments.repeatWeekly": "Repeat weekly",
1253+ "appointments.until": "Repeat until",
1254+ "appointments.starts": "Start",
1255+ "appointments.ends": "End",
1256+ "appointments.teacher": "Teacher",
1257+ "appointments.student": "Requested by",
1258+ "appointments.proposedTime": "Proposed time",
1259+ "appointments.newTime": "New time",
1260+ "appointments.status.pending": "Pending",
1261+ "appointments.status.approved": "Approved",
1262+ "appointments.status.rejected": "Rejected",
1263+ "appointments.status.cancelled": "Cancelled",
1264+ "appointments.confirmCancel": "Cancel this appointment? This cannot be undone.",
1265+ "appointments.confirmDeleteSlot": "Delete this available time? Any pending request for it will be dropped.",
1266+ "appointments.confirmDeleteSeries": "Delete the whole weekly series? All of its times will be removed.",
1267+ "appointments.rescheduleProposed": "A new time has been proposed and is waiting for the requester to accept.",
1268+ "appointments.slotTaken": "This time was just taken by someone else. Please pick another.",
1269+ "appointments.noSlots": "No available times right now.",
1270+ "appointments.series": "Series",
1271+ "appointments.time": "Time",
1272+ "appointments.status": "Status",
1273+ "appointments.publishSubtitle": "Offer a time window students can book. Repeat it weekly if you like.",
1274+ "appointments.bookSubtitle": "Tell the teacher why you would like to meet.",
1275+ "appointments.rescheduleSubtitle": "Propose a different time; the requester can accept or decline it.",
1276+ "appointments.reasonPlaceholder": "What would you like to talk about?",
1277+ "appointments.notePlaceholder": "Optional note for students (e.g. topic, location).",
1278+ "appointments.noRequests": "No booking requests.",
1279+ "appointments.noBookings": "You have no bookings yet.",
1280+ "appointments.repeatWeeklyHelp": "Creates the same time every week until the chosen date (max 52 times).",
1281+ "appointments.untilRequired": "Pick a date to repeat until.",
1282+ "appointments.tooManyOccurrences": "This range would create {count} weekly slots; the limit is {max}. Choose an earlier end date.",
1283+ "appointments.cancelTitle": "Cancel appointment?",
1284+ "appointments.cancelAction": "Yes, cancel",
1285+ "appointments.cancelReasonLabel": "Reason (optional)",
1286+ "appointments.cancelReasonPlaceholder": "Why are you cancelling?",
1287+ "appointments.cancelledBy": "Cancelled by",
1288+ "appointments.details": "Details",
1289+ "appointments.cancelReason": "Cancellation reason",
1290+ "appointments.rejectTitle": "Reject booking?",
1291+ "appointments.rejectAction": "Reject",
1292+ "appointments.confirmReject": "Reject this booking request? The slot frees up for others.",
1293+ "appointments.rejectReasonLabel": "Reason (optional)",
1294+ "appointments.rejectReasonPlaceholder": "Why are you rejecting?",
1295+ "appointments.rejectReason": "Rejection reason",
1296+ "appointments.rejectedBy": "Rejected by",
1297+ "appointments.reasonRequired": "Please give a reason for the meeting.",
1164 "events.clearStart": "Will clear start time",1298 "events.clearStart": "Will clear start time",
1165 "events.clearEnd": "Will clear end time",1299 "events.clearEnd": "Will clear end time",
1166 "events.upcoming": "Upcoming",1300 "events.upcoming": "Upcoming",
@@ -1991,6 +2125,73 @@ const tr: Dict = {
1991 "calendar.noEvents": "Bu gΓΌnde etkinlik veya sΔ±nav yok.",2125 "calendar.noEvents": "Bu gΓΌnde etkinlik veya sΔ±nav yok.",
1992 "calendar.events": "Etkinlikler",2126 "calendar.events": "Etkinlikler",
1993 "calendar.exams": "SΔ±navlar",2127 "calendar.exams": "SΔ±navlar",
2128+ "calendar.appointments": "Randevular",
2129+ "nav.appointments": "Randevular",
2130+ "appointments.title": "Randevular",
2131+ "appointments.subtitle": "Bir âğretmenle gârüşme ayarlayın ya da uygun olduğunuz saatleri yayımlayın.",
2132+ "appointments.empty": "HenΓΌz randevu yok.",
2133+ "appointments.mySlots": "Uygun saatlerim",
2134+ "appointments.availableSlots": "Uygun saatler",
2135+ "appointments.requests": "Randevu talepleri",
2136+ "appointments.myBookings": "RandevularΔ±m",
2137+ "appointments.publish": "Saat yayΔ±mla",
2138+ "appointments.book": "Randevu al",
2139+ "appointments.approve": "Onayla",
2140+ "appointments.reject": "Reddet",
2141+ "appointments.cancel": "Δ°ptal et",
2142+ "appointments.reschedule": "Yeni saat ΓΆner",
2143+ "appointments.acceptReschedule": "Yeni saati kabul et",
2144+ "appointments.declineReschedule": "Yeni saati reddet",
2145+ "appointments.deleteSlot": "Saati sil",
2146+ "appointments.deleteSeries": "Seriyi sil",
2147+ "appointments.note": "Not",
2148+ "appointments.reason": "Sebep",
2149+ "appointments.repeatWeekly": "HaftalΔ±k tekrarla",
2150+ "appointments.until": "Şu tarihe kadar tekrarla",
2151+ "appointments.starts": "Başlangıç",
2152+ "appointments.ends": "Bitiş",
2153+ "appointments.teacher": "Γ–ΔŸretmen",
2154+ "appointments.student": "Talep eden",
2155+ "appointments.proposedTime": "Γ–nerilen saat",
2156+ "appointments.newTime": "Yeni saat",
2157+ "appointments.status.pending": "Bekliyor",
2158+ "appointments.status.approved": "OnaylandΔ±",
2159+ "appointments.status.rejected": "Reddedildi",
2160+ "appointments.status.cancelled": "Δ°ptal edildi",
2161+ "appointments.confirmCancel": "Bu randevu iptal edilsin mi? Bu işlem geri alınamaz.",
2162+ "appointments.confirmDeleteSlot": "Bu uygun saat silinsin mi? Bekleyen talepleri de düşecektir.",
2163+ "appointments.confirmDeleteSeries": "TΓΌm haftalΔ±k seri silinsin mi? Serinin bΓΌtΓΌn saatleri kaldΔ±rΔ±lacak.",
2164+ "appointments.rescheduleProposed": "Yeni bir saat ΓΆnerildi ve talep edenin kabul etmesi bekleniyor.",
2165+ "appointments.slotTaken": "Bu saat az ânce başka biri tarafından alındı. Lütfen başka bir saat seçin.",
2166+ "appointments.noSlots": "Şu anda uygun saat yok.",
2167+ "appointments.series": "Seri",
2168+ "appointments.time": "Saat",
2169+ "appointments.status": "Durum",
2170+ "appointments.publishSubtitle": "Γ–ΔŸrencilerin alabileceği bir saat aralığı sunun. Δ°sterseniz haftalΔ±k tekrarlayΔ±n.",
2171+ "appointments.bookSubtitle": "Γ–ΔŸretmene neden gΓΆrüşmek istediğinizi belirtin.",
2172+ "appointments.rescheduleSubtitle": "FarklΔ± bir saat ΓΆnerin; talep eden bunu kabul edebilir ya da reddedebilir.",
2173+ "appointments.reasonPlaceholder": "Ne hakkında konuşmak istiyorsunuz?",
2174+ "appointments.notePlaceholder": "Γ–ΔŸrenciler iΓ§in isteğe bağlΔ± not (ΓΆr. konu, yer).",
2175+ "appointments.noRequests": "Randevu talebi yok.",
2176+ "appointments.noBookings": "HenΓΌz randevunuz yok.",
2177+ "appointments.repeatWeeklyHelp": "Seçilen tarihe kadar her hafta aynı saati oluşturur (en fazla 52 kez).",
2178+ "appointments.untilRequired": "Tekrarlanacak son tarihi seΓ§in.",
2179+ "appointments.tooManyOccurrences": "Bu aralık {count} haftalık saat oluşturur; sınır {max}. Daha yakın bir bitiş tarihi seçin.",
2180+ "appointments.cancelTitle": "Randevu iptal edilsin mi?",
2181+ "appointments.cancelAction": "Evet, iptal et",
2182+ "appointments.cancelReasonLabel": "Neden (isteğe bağlı)",
2183+ "appointments.cancelReasonPlaceholder": "Neden iptal ediyorsunuz?",
2184+ "appointments.cancelledBy": "Δ°ptal eden",
2185+ "appointments.details": "Detaylar",
2186+ "appointments.cancelReason": "Δ°ptal nedeni",
2187+ "appointments.rejectTitle": "Randevu talebi reddedilsin mi?",
2188+ "appointments.rejectAction": "Reddet",
2189+ "appointments.confirmReject": "Bu randevu talebi reddedilsin mi? Saat başkalarına açılır.",
2190+ "appointments.rejectReasonLabel": "Neden (isteğe bağlı)",
2191+ "appointments.rejectReasonPlaceholder": "Neden reddediyorsunuz?",
2192+ "appointments.rejectReason": "Ret nedeni",
2193+ "appointments.rejectedBy": "Reddeden",
2194+ "appointments.reasonRequired": "Lütfen gârüşme için bir sebep belirtin.",
1994 "events.clearStart": "Başlangıç saati temizlenecek",2195 "events.clearStart": "Başlangıç saati temizlenecek",
1995 "events.clearEnd": "Bitiş saati temizlenecek",2196 "events.clearEnd": "Bitiş saati temizlenecek",
1996 "events.upcoming": "Yaklaşan",2197 "events.upcoming": "Yaklaşan",
src/lib/appointment-status.test.tsadded+22 -0
@@ -0,0 +1,22 @@
1+import type { AppointmentStatus } from "@/api/client";
2+import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "./appointment-status";
3+
4+const STATUSES: AppointmentStatus[] = ["pending", "approved", "rejected", "cancelled"];
5+
6+it("maps each status to a non-empty class and dot class", () => {
7+ for (const status of STATUSES) {
8+ expect(appointmentStatusClass(status).length).toBeGreaterThan(0);
9+ expect(appointmentStatusDotClass(status).length).toBeGreaterThan(0);
10+ }
11+});
12+
13+it("gives each status a distinct label key", () => {
14+ const keys = STATUSES.map(appointmentStatusLabelKey);
15+ expect(new Set(keys).size).toBe(STATUSES.length);
16+ expect(keys).toEqual([
17+ "appointments.status.pending",
18+ "appointments.status.approved",
19+ "appointments.status.rejected",
20+ "appointments.status.cancelled",
21+ ]);
22+});
src/lib/appointment-status.tsadded+21 -0
@@ -0,0 +1,21 @@
1+/** Shared semantic colors for appointment status chips, mirroring schedule-status. */
2+import type { AppointmentStatus } from "@/api/client";
3+import type { MessageKey } from "@/i18n/messages";
4+
5+export function appointmentStatusClass(status: AppointmentStatus | string): string {
6+ if (status === "pending") return "border-warning/30 bg-warning/10 text-warning";
7+ if (status === "approved") return "border-success/30 bg-success/10 text-success";
8+ if (status === "rejected") return "border-destructive/30 bg-destructive/10 text-destructive";
9+ return "border-muted bg-muted/50 text-muted-foreground";
10+}
11+
12+export function appointmentStatusDotClass(status: AppointmentStatus | string): string {
13+ if (status === "pending") return "bg-warning";
14+ if (status === "approved") return "bg-success";
15+ if (status === "rejected") return "bg-destructive";
16+ return "bg-muted-foreground";
17+}
18+
19+export function appointmentStatusLabelKey(status: AppointmentStatus): MessageKey {
20+ return `appointments.status.${status}` as MessageKey;
21+}
src/lib/datetime-input.test.tsadded+18 -0
@@ -0,0 +1,18 @@
1+import { dateInputToEndOfDayMs, dateTimeInputToMs } from "./datetime-input";
2+
3+it("parses a valid date + time to the matching local ms", () => {
4+ const ms = dateTimeInputToMs("15/03/2027", "09:30");
5+ expect(ms).toBe(new Date(2027, 2, 15, 9, 30, 0, 0).getTime());
6+});
7+
8+it("rejects malformed or overflowing input", () => {
9+ expect(dateTimeInputToMs("15/13/2027", "09:30")).toBeNull();
10+ expect(dateTimeInputToMs("32/03/2027", "09:30")).toBeNull();
11+ expect(dateTimeInputToMs("15/03/2027", "9:30")).toBeNull();
12+ expect(dateTimeInputToMs("", "")).toBeNull();
13+});
14+
15+it("maps a repeat-until date to end of day", () => {
16+ expect(dateInputToEndOfDayMs("15/03/2027")).toBe(new Date(2027, 2, 15, 23, 59, 0, 0).getTime());
17+ expect(dateInputToEndOfDayMs("bad")).toBeNull();
18+});
src/lib/datetime-input.tsadded+44 -0
@@ -0,0 +1,44 @@
1+/** dd/mm/yyyy + HH:mm form-input <-> unix-ms helpers, matching event-form's local pattern. */
2+
3+export function dateInputFromMs(ms: number | null | undefined): string {
4+ if (ms == null) return "";
5+ const d = new Date(ms);
6+ const pad = (n: number) => String(n).padStart(2, "0");
7+ return `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()}`;
8+}
9+
10+export function timeInputFromMs(ms: number | null | undefined): string {
11+ if (ms == null) return "";
12+ const d = new Date(ms);
13+ const pad = (n: number) => String(n).padStart(2, "0");
14+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
15+}
16+
17+export function dateTimeInputToMs(date: string, time: string): number | null {
18+ const dateMatch = date.trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
19+ const timeMatch = time.trim().match(/^(\d{2}):(\d{2})$/);
20+ if (!dateMatch || !timeMatch) return null;
21+ const [, dayRaw, monthRaw, yearRaw] = dateMatch;
22+ const [, hourRaw, minuteRaw] = timeMatch;
23+ const day = Number(dayRaw);
24+ const month = Number(monthRaw);
25+ const year = Number(yearRaw);
26+ const hour = Number(hourRaw);
27+ const minute = Number(minuteRaw);
28+ const d = new Date(year, month - 1, day, hour, minute, 0, 0);
29+ if (d.getFullYear() !== year || d.getMonth() !== month - 1 || d.getDate() !== day || d.getHours() !== hour || d.getMinutes() !== minute) return null;
30+ return d.getTime();
31+}
32+
33+/** dd/mm/yyyy at end-of-day, for a "repeat until" date with no time input. */
34+export function dateInputToEndOfDayMs(date: string): number | null {
35+ const dateMatch = date.trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
36+ if (!dateMatch) return null;
37+ const [, dayRaw, monthRaw, yearRaw] = dateMatch;
38+ const day = Number(dayRaw);
39+ const month = Number(monthRaw);
40+ const year = Number(yearRaw);
41+ const d = new Date(year, month - 1, day, 23, 59, 0, 0);
42+ if (d.getFullYear() !== year || d.getMonth() !== month - 1 || d.getDate() !== day) return null;
43+ return d.getTime();
44+}
src/pages/appointments-page.tsxadded+533 -0
@@ -0,0 +1,533 @@
1+import { Show, createMemo, createResource, createSignal, onCleanup } from "solid-js";
2+import type { ColumnDef } from "@tanstack/solid-table";
3+import {
4+ deleteSlotById,
5+ deleteSlotSeries,
6+ getAppointments,
7+ getSlots,
8+ patchAcceptReschedule,
9+ patchApproveAppointment,
10+ patchCancelAppointment,
11+ patchDeclineReschedule,
12+ patchRejectAppointment,
13+ patchRescheduleAppointment,
14+ postAppointment,
15+ postSlots,
16+} from "@/api/appointments";
17+import { APPOINTMENT_LIMITS, formatApiError } from "@/api/client";
18+import type { Appointment, AppointmentSlot, AppointmentStatus } from "@/api/client";
19+import type { MessageKey } from "@/i18n/messages";
20+import { BookAppointmentForm } from "@/components/appointments/book-appointment-form";
21+import { PublishSlotsForm } from "@/components/appointments/publish-slots-form";
22+import { RescheduleForm } from "@/components/appointments/reschedule-form";
23+import { RouteGuard } from "@/components/layout/route-guard";
24+import { Alert } from "@/components/ui/alert";
25+import { Badge } from "@/components/ui/badge";
26+import { Button } from "@/components/ui/button";
27+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
28+import { DataTable, DataTableSkeleton } from "@/components/ui/data-table";
29+import { Dialog, DialogBody, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
30+import { IconCheck, IconEye, IconPlus, IconRefresh, IconTrash, IconX } from "@/components/ui/icons";
31+import { SidePanel } from "@/components/ui/side-panel";
32+import { TableRowActions } from "@/components/ui/table-row-actions";
33+import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status";
34+import { cn } from "@/lib/cn";
35+import { createFlash } from "@/lib/flash";
36+import { createNow } from "@/lib/create-now";
37+import { formatDateTime } from "@/lib/format";
38+import { personLabel } from "@/lib/person";
39+import { hasMinRole } from "@/lib/roles";
40+import { useAuth } from "@/stores/auth-context";
41+import { usePreferences, useT } from "@/stores/preferences-context";
42+
43+const PAGE_SIZE = 10;
44+const isLive = (status: AppointmentStatus) => status === "pending" || status === "approved";
45+
46+export default function AppointmentsPage() {
47+ return (
48+ <RouteGuard>
49+ <AppointmentsContent />
50+ </RouteGuard>
51+ );
52+}
53+
54+function AppointmentsContent() {
55+ const auth = useAuth();
56+ const t = useT();
57+ const { locale } = usePreferences();
58+ const now = createNow();
59+ const [error, setError] = createSignal("");
60+ const [, setFlash] = createFlash();
61+ const [showPublish, setShowPublish] = createSignal(false);
62+ const [bookSlot, setBookSlot] = createSignal<AppointmentSlot | null>(null);
63+ const [reschedAppt, setReschedAppt] = createSignal<Appointment | null>(null);
64+ const [detailAppt, setDetailAppt] = createSignal<Appointment | null>(null);
65+ const [confirm, setConfirm] = createSignal<{ summary: string; run: (reason?: string) => Promise<unknown>; title?: string; confirmLabel?: string; icon?: import("solid-js").JSX.Element; prompt?: { label: string; placeholder?: string; maxLength?: number } } | null>(null);
66+
67+ const me = () => auth.user();
68+ const isStaff = () => hasMinRole(me()?.role, "teacher");
69+ const isManager = () => hasMinRole(me()?.role, "manager");
70+
71+ const [slots, { refetch: refetchSlots }] = createResource(async () => (await getSlots({ limit: 100 })).items);
72+ const [appts, { refetch: refetchAppts }] = createResource(async () => (await getAppointments({ limit: 100 })).items);
73+
74+ const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]);
75+ const loaded = () => slots.latest !== undefined && appts.latest !== undefined;
76+
77+ // Poll so statuses stay in sync when the other party acts (approve, book,
78+ // cancel…). Reads use `.latest`, so a refetch never re-suspends/blanks the tables.
79+ const poll = setInterval(() => void refetchAll(), 30_000);
80+ onCleanup(() => clearInterval(poll));
81+ const act = async (fn: () => Promise<unknown>, successKey?: MessageKey) => {
82+ setError("");
83+ try {
84+ await fn();
85+ await refetchAll();
86+ if (successKey) setFlash(t(successKey));
87+ } catch (err) {
88+ setError(formatApiError(err));
89+ }
90+ };
91+ const askConfirm = (summary: string, run: (reason?: string) => Promise<unknown>, opts?: { title?: string; confirmLabel?: string; icon?: import("solid-js").JSX.Element; prompt?: { label: string; placeholder?: string; maxLength?: number } }) =>
92+ setConfirm({ summary, run, ...opts });
93+ // withReason: the cancel path collects an optional reason; decline records none.
94+ const askCancel = (run: (reason?: string) => Promise<unknown>, withReason = true) =>
95+ askConfirm(t("appointments.confirmCancel"), run, {
96+ title: t("appointments.cancelTitle"),
97+ confirmLabel: t("appointments.cancelAction"),
98+ icon: <IconX class="h-4 w-4" />,
99+ prompt: withReason
100+ ? { label: t("appointments.cancelReasonLabel"), placeholder: t("appointments.cancelReasonPlaceholder"), maxLength: APPOINTMENT_LIMITS.reasonMaxLen }
101+ : undefined,
102+ });
103+ const askReject = (id: string) =>
104+ askConfirm(t("appointments.confirmReject"), (reason) => patchRejectAppointment(id, reason ? { reason } : undefined), {
105+ title: t("appointments.rejectTitle"),
106+ confirmLabel: t("appointments.rejectAction"),
107+ icon: <IconX class="h-4 w-4" />,
108+ prompt: { label: t("appointments.rejectReasonLabel"), placeholder: t("appointments.rejectReasonPlaceholder"), maxLength: APPOINTMENT_LIMITS.reasonMaxLen },
109+ });
110+
111+ const timeOnly = (ms: number | null) =>
112+ ms == null ? "β€”" : new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-US", { timeStyle: "short" }).format(new Date(ms));
113+ const sameDay = (a: number | null, b: number | null) =>
114+ a != null && b != null && new Date(a).toDateString() === new Date(b).toDateString();
115+ // Same-day windows collapse the repeated date: "Jul 31, 2026, 3:07 – 7:30 PM".
116+ const timeWindow = (starts: number | null, ends: number | null) =>
117+ sameDay(starts, ends)
118+ ? `${formatDateTime(starts, locale())} – ${timeOnly(ends)}`
119+ : `${formatDateTime(starts, locale())} β€” ${formatDateTime(ends, locale())}`;
120+ const statusBadge = (status: AppointmentStatus) => (
121+ <Badge variant="outline" class={cn("w-28 justify-center rounded-full", appointmentStatusClass(status))}>
122+ <span class={cn("mr-1.5 h-1.5 w-1.5 rounded-full", appointmentStatusDotClass(status))} />
123+ {t(appointmentStatusLabelKey(status))}
124+ </Badge>
125+ );
126+ const hasProposal = (a: Appointment) => a.proposed_starts_at != null;
127+ // Cancelled/rejected appointments carry a record (who + optional reason) shown in the details dialog.
128+ const hasRecord = (a: Appointment) => a.status === "cancelled" || a.status === "rejected";
129+ const detailAction = (a: Appointment) =>
130+ hasRecord(a)
131+ ? [{ label: t("appointments.details"), icon: <IconEye class="h-4 w-4" />, onSelect: () => setDetailAppt(a) }]
132+ : [];
133+ // The details dialog surfaces cancelled-by/cancel-reason or (for rejected) decided-by/reject-reason.
134+ const recordActor = (a: Appointment) => (a.status === "rejected" ? a.decided_by : a.cancelled_by);
135+ const recordActorLabel = (a: Appointment) => (a.status === "rejected" ? t("appointments.rejectedBy") : t("appointments.cancelledBy"));
136+ const recordReason = (a: Appointment) => (a.status === "rejected" ? a.reject_reason : a.cancel_reason);
137+ const recordReasonLabel = (a: Appointment) => (a.status === "rejected" ? t("appointments.rejectReason") : t("appointments.cancelReason"));
138+
139+ // --- staff: my published slots ---
140+ const mySlots = () => {
141+ const list = slots.latest ?? [];
142+ if (isManager()) return list;
143+ const uid = me()?.id;
144+ return list.filter((s) => s.teacher.id === uid);
145+ };
146+ const slotBooking = (slotId: string) => (appts.latest ?? []).find((a) => a.slot === slotId && isLive(a.status));
147+
148+ const slotColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [
149+ {
150+ id: "time",
151+ header: t("appointments.time"),
152+ meta: { headerClass: "w-64", cellClass: "mono text-xs text-muted-foreground align-top whitespace-normal break-words pr-4" },
153+ cell: (cell) => timeWindow(cell.row.original.starts_at, cell.row.original.ends_at),
154+ },
155+ {
156+ id: "note",
157+ header: t("appointments.note"),
158+ cell: (cell) => <span class="truncate">{cell.row.original.note || "β€”"}</span>,
159+ },
160+ {
161+ id: "series",
162+ header: t("appointments.series"),
163+ meta: { headerClass: "text-center", cellClass: "text-center" },
164+ cell: (cell) => (cell.row.original.series ? <Badge variant="outline" class="rounded-full"><IconRefresh class="mr-1 h-3 w-3" />{t("appointments.repeatWeekly")}</Badge> : <span class="text-muted-foreground">β€”</span>),
165+ },
166+ {
167+ id: "status",
168+ header: t("appointments.status"),
169+ meta: { headerClass: "text-center", cellClass: "text-center" },
170+ cell: (cell) => {
171+ const booking = slotBooking(cell.row.original.id);
172+ return booking ? statusBadge(booking.status) : <span class="text-xs text-muted-foreground">{t("appointments.availableSlots")}</span>;
173+ },
174+ },
175+ {
176+ id: "actions",
177+ header: t("common.actions"),
178+ meta: { headerClass: "text-center", cellClass: "w-28 min-w-[7rem] text-center whitespace-nowrap" },
179+ cell: (cell) => {
180+ const slot = cell.row.original;
181+ const actions = [{
182+ label: t("appointments.deleteSlot"),
183+ icon: <IconTrash class="h-4 w-4" />,
184+ destructive: true,
185+ onSelect: () => askConfirm(t("appointments.confirmDeleteSlot"), () => deleteSlotById(slot.id)),
186+ }];
187+ if (slot.series) {
188+ actions.push({
189+ label: t("appointments.deleteSeries"),
190+ icon: <IconTrash class="h-4 w-4" />,
191+ destructive: true,
192+ onSelect: () => askConfirm(t("appointments.confirmDeleteSeries"), () => deleteSlotSeries(slot.series!)),
193+ });
194+ }
195+ return <TableRowActions label={t("common.actions")} actions={actions} />;
196+ },
197+ },
198+ ]);
199+
200+ // --- staff: booking requests for my slots ---
201+ const requests = () => {
202+ const list = appts.latest ?? [];
203+ if (isManager()) return list;
204+ const uid = me()?.id;
205+ return list.filter((a) => a.teacher?.id === uid);
206+ };
207+
208+ const requestColumns = createMemo<ColumnDef<Appointment>[]>(() => [
209+ {
210+ id: "student",
211+ header: t("appointments.student"),
212+ cell: (cell) => <span class="font-medium">{personLabel(cell.row.original.requester)}</span>,
213+ },
214+ {
215+ id: "reason",
216+ header: t("appointments.reason"),
217+ cell: (cell) => <span class="truncate text-sm text-muted-foreground">{cell.row.original.reason || "β€”"}</span>,
218+ },
219+ {
220+ id: "time",
221+ header: t("appointments.time"),
222+ meta: { headerClass: "w-64", cellClass: "mono text-xs text-muted-foreground align-top whitespace-normal break-words pr-4" },
223+ cell: (cell) => (
224+ <div>
225+ <div>{timeWindow(cell.row.original.starts_at, cell.row.original.ends_at)}</div>
226+ <Show when={hasProposal(cell.row.original) && cell.row.original.status === "pending"}>
227+ <div class="text-info">{t("appointments.rescheduleProposed")}</div>
228+ </Show>
229+ </div>
230+ ),
231+ },
232+ {
233+ id: "status",
234+ header: t("appointments.status"),
235+ meta: { headerClass: "text-center", cellClass: "text-center" },
236+ cell: (cell) => statusBadge(cell.row.original.status),
237+ },
238+ {
239+ id: "actions",
240+ header: t("common.actions"),
241+ meta: { headerClass: "text-center", cellClass: "w-28 min-w-[7rem] text-center whitespace-nowrap" },
242+ cell: (cell) => {
243+ const a = cell.row.original;
244+ const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];
245+ if (a.status === "pending" && !hasProposal(a)) {
246+ actions.push({ label: t("appointments.approve"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchApproveAppointment(a.id), "appointments.status.approved") });
247+ actions.push({ label: t("appointments.reject"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askReject(a.id) });
248+ }
249+ if (isLive(a.status) && !hasProposal(a)) {
250+ actions.push({ label: t("appointments.reschedule"), icon: <IconRefresh class="h-4 w-4" />, onSelect: () => setReschedAppt(a) });
251+ }
252+ if (isLive(a.status)) {
253+ actions.push({ label: t("appointments.cancel"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) });
254+ }
255+ actions.push(...detailAction(a));
256+ return <Show when={actions.length > 0} fallback={<span class="text-muted-foreground">β€”</span>}><TableRowActions label={t("common.actions")} actions={actions} /></Show>;
257+ },
258+ },
259+ ]);
260+
261+ // --- booker: available slots ---
262+ const myLiveSlotIds = () => new Set((appts.latest ?? []).filter((a) => a.requester.id === me()?.id && isLive(a.status)).map((a) => a.slot));
263+ const availableSlots = () => {
264+ const taken = myLiveSlotIds();
265+ return (slots.latest ?? []).filter((s) => s.ends_at > now() && !taken.has(s.id));
266+ };
267+
268+ const availableColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [
269+ {
270+ id: "teacher",
271+ header: t("appointments.teacher"),
272+ cell: (cell) => <span class="font-medium">{personLabel(cell.row.original.teacher)}</span>,
273+ },
274+ {
275+ id: "time",
276+ header: t("appointments.time"),
277+ meta: { headerClass: "w-64", cellClass: "mono text-xs text-muted-foreground align-top whitespace-normal break-words pr-4" },
278+ cell: (cell) => timeWindow(cell.row.original.starts_at, cell.row.original.ends_at),
279+ },
280+ {
281+ id: "note",
282+ header: t("appointments.note"),
283+ cell: (cell) => <span class="truncate text-sm text-muted-foreground">{cell.row.original.note || "β€”"}</span>,
284+ },
285+ {
286+ id: "actions",
287+ header: t("common.actions"),
288+ meta: { headerClass: "text-center", cellClass: "w-28 min-w-[7rem] text-center whitespace-nowrap" },
289+ cell: (cell) => (
290+ <Button type="button" size="sm" variant="outline" class="rounded-lg" onClick={() => setBookSlot(cell.row.original)}>
291+ <IconPlus class="h-4 w-4" />
292+ {t("appointments.book")}
293+ </Button>
294+ ),
295+ },
296+ ]);
297+
298+ // --- booker: my bookings ---
299+ const myBookings = () => (appts.latest ?? []).filter((a) => a.requester.id === me()?.id);
300+
301+ const bookingColumns = createMemo<ColumnDef<Appointment>[]>(() => [
302+ {
303+ id: "teacher",
304+ header: t("appointments.teacher"),
305+ cell: (cell) => <span class="font-medium">{personLabel(cell.row.original.teacher)}</span>,
306+ },
307+ {
308+ id: "time",
309+ header: t("appointments.time"),
310+ meta: { headerClass: "w-64", cellClass: "mono text-xs text-muted-foreground align-top whitespace-normal break-words pr-4" },
311+ cell: (cell) => (
312+ <div>
313+ <div>{timeWindow(cell.row.original.starts_at, cell.row.original.ends_at)}</div>
314+ <Show when={hasProposal(cell.row.original) && cell.row.original.status === "pending"}>
315+ <div class="text-info">{t("appointments.proposedTime")}: {timeWindow(cell.row.original.proposed_starts_at, cell.row.original.proposed_ends_at)}</div>
316+ </Show>
317+ </div>
318+ ),
319+ },
320+ {
321+ id: "status",
322+ header: t("appointments.status"),
323+ meta: { headerClass: "text-center", cellClass: "text-center" },
324+ cell: (cell) => statusBadge(cell.row.original.status),
325+ },
326+ {
327+ id: "actions",
328+ header: t("common.actions"),
329+ meta: { headerClass: "text-center", cellClass: "w-28 min-w-[7rem] text-center whitespace-nowrap" },
330+ cell: (cell) => {
331+ const a = cell.row.original;
332+ const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];
333+ if (a.status === "pending" && hasProposal(a)) {
334+ actions.push({ label: t("appointments.acceptReschedule"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchAcceptReschedule(a.id), "appointments.status.approved") });
335+ actions.push({ label: t("appointments.declineReschedule"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel(() => patchDeclineReschedule(a.id), false) });
336+ } else if (isLive(a.status)) {
337+ actions.push({ label: t("appointments.cancel"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) });
338+ }
339+ actions.push(...detailAction(a));
340+ return <Show when={actions.length > 0} fallback={<span class="text-muted-foreground">β€”</span>}><TableRowActions label={t("common.actions")} actions={actions} /></Show>;
341+ },
342+ },
343+ ]);
344+
345+ return (
346+ <div class="space-y-6">
347+ <SidePanel open={showPublish()} onOpenChange={setShowPublish} title={t("appointments.publish")} description={t("appointments.publishSubtitle")}>
348+ <PublishSlotsForm
349+ onCancel={() => setShowPublish(false)}
350+ onSubmit={async (values) => {
351+ setError("");
352+ try {
353+ await postSlots(values);
354+ setShowPublish(false);
355+ await refetchAll();
356+ setFlash(t("common.created"));
357+ } catch (err) {
358+ setError(formatApiError(err));
359+ throw err;
360+ }
361+ }}
362+ />
363+ </SidePanel>
364+
365+ <SidePanel open={bookSlot() != null} onOpenChange={(o) => !o && setBookSlot(null)} title={t("appointments.book")} description={t("appointments.bookSubtitle")}>
366+ <Show when={bookSlot()}>
367+ {(slot) => (
368+ <BookAppointmentForm
369+ slot={slot()}
370+ onCancel={() => setBookSlot(null)}
371+ onSubmit={async (reason) => {
372+ setError("");
373+ try {
374+ await postAppointment({ slot: slot().id, reason });
375+ setBookSlot(null);
376+ await refetchAll();
377+ setFlash(t("common.created"));
378+ } catch (err) {
379+ setError(formatApiError(err));
380+ throw err;
381+ }
382+ }}
383+ />
384+ )}
385+ </Show>
386+ </SidePanel>
387+
388+ <SidePanel open={reschedAppt() != null} onOpenChange={(o) => !o && setReschedAppt(null)} title={t("appointments.reschedule")} description={t("appointments.rescheduleSubtitle")}>
389+ <Show when={reschedAppt()}>
390+ {(appt) => (
391+ <RescheduleForm
392+ appointment={appt()}
393+ onCancel={() => setReschedAppt(null)}
394+ onSubmit={async (values) => {
395+ setError("");
396+ try {
397+ await patchRescheduleAppointment(appt().id, values);
398+ setReschedAppt(null);
399+ await refetchAll();
400+ setFlash(t("appointments.rescheduleProposed"));
401+ } catch (err) {
402+ setError(formatApiError(err));
403+ throw err;
404+ }
405+ }}
406+ />
407+ )}
408+ </Show>
409+ </SidePanel>
410+
411+ <Show when={error() && !showPublish() && bookSlot() == null && reschedAppt() == null}>
412+ <Alert variant="destructive">{error()}</Alert>
413+ </Show>
414+
415+ <Show when={isStaff()} fallback={
416+ <>
417+ <section class="data-shell space-y-4 border-sky-500/15 bg-sky-500/2.5 p-4">
418+ <Show when={loaded()} fallback={<DataTableSkeleton columns={4} rows={6} />}>
419+ <Show when={slots.error}><Alert variant="destructive">{formatApiError(slots.error)}</Alert></Show>
420+ <DataTable
421+ title={t("appointments.availableSlots")}
422+ description={t("appointments.subtitle")}
423+ columns={availableColumns()}
424+ data={availableSlots()}
425+ tableClass="table-fixed min-w-[52rem]"
426+ enablePagination
427+ pageSize={PAGE_SIZE}
428+ empty={t("appointments.noSlots")}
429+ />
430+ </Show>
431+ </section>
432+ <section class="data-shell space-y-4 border-violet-500/15 bg-violet-500/2.5 p-4">
433+ <Show when={loaded()} fallback={<DataTableSkeleton columns={4} rows={6} />}>
434+ <Show when={appts.error}><Alert variant="destructive">{formatApiError(appts.error)}</Alert></Show>
435+ <DataTable
436+ title={t("appointments.myBookings")}
437+ columns={bookingColumns()}
438+ data={myBookings()}
439+ tableClass="table-fixed min-w-[52rem]"
440+ enablePagination
441+ pageSize={PAGE_SIZE}
442+ empty={t("appointments.noBookings")}
443+ />
444+ </Show>
445+ </section>
446+ </>
447+ }>
448+ <section class="data-shell space-y-4 border-sky-500/15 bg-sky-500/2.5 p-4">
449+ <Show when={loaded()} fallback={<DataTableSkeleton columns={5} rows={6} />}>
450+ <Show when={slots.error}><Alert variant="destructive">{formatApiError(slots.error)}</Alert></Show>
451+ <DataTable
452+ title={t("appointments.mySlots")}
453+ description={t("appointments.subtitle")}
454+ actions={
455+ <Button type="button" size="sm" class="min-w-30" onClick={() => setShowPublish(true)}>
456+ <IconPlus class="h-4 w-4" />
457+ {t("appointments.publish")}
458+ </Button>
459+ }
460+ columns={slotColumns()}
461+ data={mySlots()}
462+ tableClass="table-fixed min-w-[52rem]"
463+ enablePagination
464+ pageSize={PAGE_SIZE}
465+ empty={t("appointments.noSlots")}
466+ />
467+ </Show>
468+ </section>
469+ <section class="data-shell space-y-4 border-violet-500/15 bg-violet-500/2.5 p-4">
470+ <Show when={loaded()} fallback={<DataTableSkeleton columns={5} rows={6} />}>
471+ <Show when={appts.error}><Alert variant="destructive">{formatApiError(appts.error)}</Alert></Show>
472+ <DataTable
473+ title={t("appointments.requests")}
474+ columns={requestColumns()}
475+ data={requests()}
476+ tableClass="table-fixed min-w-[52rem]"
477+ enablePagination
478+ pageSize={PAGE_SIZE}
479+ empty={t("appointments.noRequests")}
480+ />
481+ </Show>
482+ </section>
483+ </Show>
484+
485+ <Dialog open={detailAppt() != null} onOpenChange={(o) => !o && setDetailAppt(null)}>
486+ <DialogContent class="max-w-md" dismissable>
487+ <DialogHeader>
488+ <DialogTitle>{t("appointments.details")}</DialogTitle>
489+ </DialogHeader>
490+ <Show when={detailAppt()}>
491+ {(a) => (
492+ <DialogBody class="space-y-3 text-sm">
493+ <div class="flex items-center justify-between gap-3">
494+ <span class="text-muted-foreground">{t("appointments.status")}</span>
495+ {statusBadge(a().status)}
496+ </div>
497+ <div class="flex items-center justify-between gap-3">
498+ <span class="text-muted-foreground">{t("appointments.time")}</span>
499+ <span class="mono text-xs">{timeWindow(a().starts_at, a().ends_at)}</span>
500+ </div>
501+ <Show when={recordActor(a())}>
502+ <div class="flex items-center justify-between gap-3">
503+ <span class="text-muted-foreground">{recordActorLabel(a())}</span>
504+ <span class="font-medium">{personLabel(recordActor(a()))}</span>
505+ </div>
506+ </Show>
507+ <div class="space-y-1">
508+ <p class="text-muted-foreground">{recordReasonLabel(a())}</p>
509+ <p class="rounded-md border border-border bg-muted/40 px-3 py-2 leading-relaxed">{recordReason(a()) || "β€”"}</p>
510+ </div>
511+ </DialogBody>
512+ )}
513+ </Show>
514+ </DialogContent>
515+ </Dialog>
516+
517+ <ConfirmDialog
518+ open={confirm() != null}
519+ onOpenChange={(o) => !o && setConfirm(null)}
520+ variant="destructive"
521+ title={confirm()?.title ?? t("confirm.deleteTitle")}
522+ confirmLabel={confirm()?.confirmLabel}
523+ icon={confirm()?.icon}
524+ prompt={confirm()?.prompt}
525+ summary={confirm()?.summary ?? ""}
526+ onConfirm={async (reason) => {
527+ const c = confirm();
528+ if (c) await act(() => c.run(reason));
529+ }}
530+ />
531+ </div>
532+ );
533+}
src/pages/calendar-page.tsxmodified+54 -10
@@ -1,7 +1,9 @@
1 import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js";1 import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js";
2 import { getEvents } from "@/api/events";2 import { getEvents } from "@/api/events";
3 import { getExams } from "@/api/exams";3 import { getExams } from "@/api/exams";
4-import type { Event, Exam } from "@/api/client";4+import { getAppointments } from "@/api/appointments";
5+import type { Appointment, Event, Exam } from "@/api/client";
6+import { appointmentStatusClass, appointmentStatusDotClass, appointmentStatusLabelKey } from "@/lib/appointment-status";
5 import { RouteGuard } from "@/components/layout/route-guard";7 import { RouteGuard } from "@/components/layout/route-guard";
6 import { Badge } from "@/components/ui/badge";8 import { Badge } from "@/components/ui/badge";
7 import { Button } from "@/components/ui/button";9 import { Button } from "@/components/ui/button";
@@ -39,6 +41,7 @@ function CalendarContent() {
39 41
40 const [events] = createResource(async () => (await getEvents({ limit: 100 })).items, { initialValue: [] });42 const [events] = createResource(async () => (await getEvents({ limit: 100 })).items, { initialValue: [] });
41 const [exams] = createResource(async () => (await getExams({ limit: 100 })).items, { initialValue: [] });43 const [exams] = createResource(async () => (await getExams({ limit: 100 })).items, { initialValue: [] });
44+ const [appointments] = createResource(async () => (await getAppointments({ limit: 100 })).items, { initialValue: [] });
42 45
43 const monthLabel = () => {46 const monthLabel = () => {
44 const names = locale() === "tr" ? MONTH_NAMES_TR : MONTH_NAMES;47 const names = locale() === "tr" ? MONTH_NAMES_TR : MONTH_NAMES;
@@ -56,18 +59,22 @@ function CalendarContent() {
56 });59 });
57 60
58 const itemsByDay = createMemo(() => {61 const itemsByDay = createMemo(() => {
59- const map = new Map<string, { events: Event[]; exams: Exam[] }>();62+ const map = new Map<string, { events: Event[]; exams: Exam[]; appointments: Appointment[] }>();
63+ const bucket = (k: string) => {
64+ if (!map.has(k)) map.set(k, { events: [], exams: [], appointments: [] });
65+ return map.get(k)!;
66+ };
60 for (const e of events()) {67 for (const e of events()) {
61 if (!e.starts_at) continue;68 if (!e.starts_at) continue;
62- const k = dateKey(new Date(e.starts_at));69+ bucket(dateKey(new Date(e.starts_at))).events.push(e);
63- if (!map.has(k)) map.set(k, { events: [], exams: [] });
64- map.get(k)!.events.push(e);
65 }70 }
66 for (const e of exams()) {71 for (const e of exams()) {
67 if (!e.starts_at || e.draft) continue;72 if (!e.starts_at || e.draft) continue;
68- const k = dateKey(new Date(e.starts_at));73+ bucket(dateKey(new Date(e.starts_at))).exams.push(e);
69- if (!map.has(k)) map.set(k, { events: [], exams: [] });74+ }
70- map.get(k)!.exams.push(e);75+ for (const a of appointments()) {
76+ if (!a.starts_at || (a.status !== "pending" && a.status !== "approved")) continue;
77+ bucket(dateKey(new Date(a.starts_at))).appointments.push(a);
71 }78 }
72 return map;79 return map;
73 });80 });
@@ -77,7 +84,7 @@ function CalendarContent() {
77 const [y, m, d] = selected().split("-").map(Number);84 const [y, m, d] = selected().split("-").map(Number);
78 return new Date(y, m, d);85 return new Date(y, m, d);
79 };86 };
80- const selectedItems = () => itemsByDay().get(selectedKey()) ?? { events: [], exams: [] };87+ const selectedItems = () => itemsByDay().get(selectedKey()) ?? { events: [], exams: [], appointments: [] };
81 const isToday = (day: number) => {88 const isToday = (day: number) => {
82 const n = nowDate();89 const n = nowDate();
83 return n.getFullYear() === viewYear() && n.getMonth() === viewMonth() && n.getDate() === day;90 return n.getFullYear() === viewYear() && n.getMonth() === viewMonth() && n.getDate() === day;
@@ -186,6 +193,17 @@ function CalendarContent() {
186 </span>193 </span>
187 )}194 )}
188 </Show>195 </Show>
196+ <Show when={dayItems().appointments[0]}>
197+ {(appt) => (
198+ <span class="inline-flex min-w-0 items-center gap-1 rounded bg-violet-100 px-1 py-0.5 text-[9px] font-medium leading-none text-violet-700 dark:border dark:border-violet-800/50 dark:bg-violet-950/60 dark:text-violet-300">
199+ <span class="h-1.5 w-1.5 shrink-0 rounded-full bg-violet-500" />
200+ <span class="truncate">{appt().requester.display_name ?? appt().requester.username}</span>
201+ <Show when={dayItems().appointments.length > 1}>
202+ <span class="shrink-0 opacity-70">+{dayItems().appointments.length - 1}</span>
203+ </Show>
204+ </span>
205+ )}
206+ </Show>
189 </div>207 </div>
190 )}208 )}
191 </Show>209 </Show>
@@ -203,7 +221,7 @@ function CalendarContent() {
203 </h3>221 </h3>
204 222
205 <div class="mt-2 space-y-2.5">223 <div class="mt-2 space-y-2.5">
206- <Show when={selectedItems().events.length === 0 && selectedItems().exams.length === 0}>224+ <Show when={selectedItems().events.length === 0 && selectedItems().exams.length === 0 && selectedItems().appointments.length === 0}>
207 <p class="text-xs text-muted-foreground">{t("calendar.noEvents")}</p>225 <p class="text-xs text-muted-foreground">{t("calendar.noEvents")}</p>
208 </Show>226 </Show>
209 227
@@ -252,6 +270,32 @@ function CalendarContent() {
252 </For>270 </For>
253 </div>271 </div>
254 </Show>272 </Show>
273+
274+ <Show when={selectedItems().appointments.length > 0}>
275+ <div class="space-y-2">
276+ <p class="text-[10px] font-semibold uppercase tracking-wider text-violet-500">{t("calendar.appointments")}</p>
277+ <For each={selectedItems().appointments}>
278+ {(appt) => (
279+ <a
280+ href="/appointments"
281+ class="group flex items-start justify-between gap-2 rounded-lg border border-violet-500/40 bg-card p-2.5 shadow-xs transition-all hover:border-violet-500/70 hover:shadow-md dark:border-violet-500/30 dark:hover:border-violet-500/70"
282+ >
283+ <div class="min-w-0">
284+ <p class="truncate text-xs font-semibold group-hover:text-violet-500">{appt.requester.display_name ?? appt.requester.username}</p>
285+ <p class="mt-0.5 text-[11px] text-muted-foreground">
286+ {appt.starts_at ? new Date(appt.starts_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" }) : ""}
287+ {appt.ends_at ? ` β€” ${new Date(appt.ends_at).toLocaleTimeString(locale() === "tr" ? "tr-TR" : "en-US", { hour: "2-digit", minute: "2-digit" })}` : ""}
288+ </p>
289+ </div>
290+ <Badge variant="outline" class={cn("shrink-0 gap-1 text-[10px]", appointmentStatusClass(appt.status))}>
291+ <span class={cn("h-1.5 w-1.5 rounded-full", appointmentStatusDotClass(appt.status))} />
292+ {t(appointmentStatusLabelKey(appt.status))}
293+ </Badge>
294+ </a>
295+ )}
296+ </For>
297+ </div>
298+ </Show>
255 </div>299 </div>
256 </div>300 </div>
257 </div>301 </div>
src/routes/router.tsxmodified+8 -0
@@ -52,6 +52,7 @@ const MyStudentsPage = lazyRoute(() => import("@/pages/my-students-page"));
52 const QuestionsPage = lazyRoute(() => import("@/pages/questions-page"));52 const QuestionsPage = lazyRoute(() => import("@/pages/questions-page"));
53 const QuestionDetailPage = lazyRoute(() => import("@/pages/question-detail-page"));53 const QuestionDetailPage = lazyRoute(() => import("@/pages/question-detail-page"));
54 const CalendarPage = lazyRoute(() => import("@/pages/calendar-page"));54 const CalendarPage = lazyRoute(() => import("@/pages/calendar-page"));
55+const AppointmentsPage = lazyRoute(() => import("@/pages/appointments-page"));
55 56
56 function RootComponent() {57 function RootComponent() {
57 return (58 return (
@@ -275,6 +276,12 @@ const calendarRoute = createRoute({
275 component: CalendarPage,276 component: CalendarPage,
276 });277 });
277 278
279+const appointmentsRoute = createRoute({
280+ getParentRoute: () => rootRoute,
281+ path: "/appointments",
282+ component: AppointmentsPage,
283+});
284+
278 const routeTree = rootRoute.addChildren([285 const routeTree = rootRoute.addChildren([
279 indexRoute,286 indexRoute,
280 loginRoute,287 loginRoute,
@@ -309,6 +316,7 @@ const routeTree = rootRoute.addChildren([
309 questionsRoute,316 questionsRoute,
310 questionDetailRoute,317 questionDetailRoute,
311 calendarRoute,318 calendarRoute,
319+ appointmentsRoute,
312 ]);320 ]);
313 321
314 function RouterPending() {322 function RouterPending() {