forge
Explore
Log in

Don't you dare go Hollow

🍽️ add meal management

Browse files at this commit

4307fb0ba8a19e6ddb2b931b54b16addeead589bBurak BoduroğluParent: 4e531e5
  • feat
    • 🍽️ add meal management
Show full message
feat(meals): 🍽️ add meal management

- add role-aware menus, bookings, service, and balance flows

- expose meal and AI policy settings with server limits

- add English and Turkish interface copy
src/components/meals/meal-menu-card.tsxadded+33 -0
@@ -0,0 +1,33 @@
1+import { For, Show } from "solid-js";
2+import { Link } from "@tanstack/solid-router";
3+import type { MealMenu } from "@/api/client";
4+import { Badge } from "@/components/ui/badge";
5+import { IconAlert, IconUtensils } from "@/components/ui/icons";
6+import { formatTry } from "@/lib/meals";
7+
8+export function MealMenuCard(props: { menu: MealMenu; locale: string; labels: { dishes: string; capacity: string; conflict: string } }) {
9+ const total = () => props.menu.dishes.reduce((sum, dish) => sum + dish.price_minor, 0);
10+ const conflicts = () => [...new Set(props.menu.dishes.flatMap((dish) => dish.conflicts))];
11+
12+ return (
13+ <Link to="/meals/$id" params={{ id: props.menu.id }} class="group flex min-h-56 flex-col rounded-2xl border border-border/70 bg-card p-4 shadow-2xs transition hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
14+ <div class="flex items-start justify-between gap-3">
15+ <div class="flex min-w-0 items-center gap-3">
16+ <span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border bg-muted/40"><IconUtensils class="h-5 w-5" /></span>
17+ <div><h2 class="font-display font-semibold">{props.menu.slot}</h2><time class="mono text-xs text-muted-foreground" datetime={props.menu.date}>{props.menu.date}</time></div>
18+ </div>
19+ <span class="font-semibold tabular-nums">{formatTry(total(), props.locale)}</span>
20+ </div>
21+ <div class="mt-4 flex flex-wrap gap-1.5"><For each={props.menu.dishes}>{(dish) => <Badge variant="outline">{dish.name}</Badge>}</For></div>
22+ <Show when={conflicts().length > 0}>
23+ <div class="mt-3 flex items-start gap-2 rounded-xl border border-amber-500/40 bg-amber-500/10 p-2 text-xs text-amber-800 dark:text-amber-200">
24+ <IconAlert class="mt-0.5 h-4 w-4" /><span>{props.labels.conflict}: {conflicts().join(", ")}</span>
25+ </div>
26+ </Show>
27+ <div class="mt-auto flex justify-between border-t border-border/60 pt-3 text-xs text-muted-foreground">
28+ <span>{props.menu.dishes.length} {props.labels.dishes}</span>
29+ <span>{props.labels.capacity}: <span class="mono">{props.menu.capacity ?? "∞"}</span></span>
30+ </div>
31+ </Link>
32+ );
33+}
src/components/ui/icons.tsxmodified+12 -1
@@ -642,6 +642,18 @@ export function IconBriefcase(props: IconProps) {
642 );642 );
643 }643 }
644 644
645+export function IconUtensils(props: IconProps) {
646+ return (
647+ <Svg {...props}>
648+ <path d="M3 2v7a3 3 0 0 0 3 3V2" />
649+ <path d="M3 6h3" />
650+ <path d="M6 12v10" />
651+ <path d="M17 2v20" />
652+ <path d="M17 2c3 2 4 5 4 8h-4" />
653+ </Svg>
654+ );
655+}
656+
645 export function IconSearch(props: IconProps) {657 export function IconSearch(props: IconProps) {
646 return (658 return (
647 <Svg {...props}>659 <Svg {...props}>
@@ -725,4 +737,3 @@ export function IconBell(props: IconProps) {
725 </Svg>737 </Svg>
726 );738 );
727 }739 }
728-
src/i18n/messages.tsmodified+22 -25
@@ -284,7 +284,7 @@ export type MessageKey =
284 | "dashboard.workloadSplit"284 | "dashboard.workloadSplit"
285 | "dashboard.workloadSplitDesc"285 | "dashboard.workloadSplitDesc"
286 | "dashboard.deadlines"286 | "dashboard.deadlines"
287- | "dashboard.classSizes"287+ | "dashboard.courseCapacities"
288 | "dashboard.courseAverages"288 | "dashboard.courseAverages"
289 | "dashboard.chartEmpty"289 | "dashboard.chartEmpty"
290 | "dashboard.chartEmptyHint"290 | "dashboard.chartEmptyHint"
@@ -308,18 +308,15 @@ export type MessageKey =
308 | "dashboard.attend.excused"308 | "dashboard.attend.excused"
309 | "dashboard.welcomeBack"309 | "dashboard.welcomeBack"
310 | "dashboard.welcomeHint"310 | "dashboard.welcomeHint"
311- | "dashboard.refresh"311+ | "dashboard.teachingResources"
312- | "dashboard.col.priority"312+ | "dashboard.teachingResourcesDesc"
313- | "dashboard.priority.high"313+ | "dashboard.questionBankDesc"
314- | "dashboard.priority.medium"314+ | "dashboard.questionPoolDesc"
315 | "dashboard.quickReview.title"315 | "dashboard.quickReview.title"
316 | "dashboard.quickReview.subtitle"316 | "dashboard.quickReview.subtitle"
317 | "dashboard.quickReview.placeholder"317 | "dashboard.quickReview.placeholder"
318 | "dashboard.quickReview.practice"318 | "dashboard.quickReview.practice"
319 | "dashboard.quickReview.startQuiz"319 | "dashboard.quickReview.startQuiz"
320- | "dashboard.questionHubDesc"
321- | "dashboard.questionHubPlaceholder"
322- | "dashboard.askQuestion"
323 | "notes.title"320 | "notes.title"
324 | "notes.subtitle"321 | "notes.subtitle"
325 | "notes.new"322 | "notes.new"
@@ -693,6 +690,7 @@ export type MessageKey =
693 | "courses.title"690 | "courses.title"
694 | "courses.listTitle"691 | "courses.listTitle"
695 | "courses.subtitle"692 | "courses.subtitle"
693+ | "courses.pageSubtitle"
696 | "courses.create"694 | "courses.create"
697 | "courses.empty"695 | "courses.empty"
698 | "courses.enrolled"696 | "courses.enrolled"
@@ -1020,6 +1018,7 @@ export type MessageKey =
1020 | "calendar.appointments"1018 | "calendar.appointments"
1021 | "nav.appointments"1019 | "nav.appointments"
1022 | "appointments.title"1020 | "appointments.title"
1021+ | "appointments.calendar"
1023 | "appointments.subtitle"1022 | "appointments.subtitle"
1024 | "appointments.empty"1023 | "appointments.empty"
1025 | "appointments.mySlots"1024 | "appointments.mySlots"
@@ -1371,7 +1370,7 @@ const en: Dict = {
1371 "dashboard.workloadSplit": "Workload split",1370 "dashboard.workloadSplit": "Workload split",
1372 "dashboard.workloadSplitDesc": "Courses, exams, events, and more.",1371 "dashboard.workloadSplitDesc": "Courses, exams, events, and more.",
1373 "dashboard.deadlines": "Upcoming deadlines",1372 "dashboard.deadlines": "Upcoming deadlines",
1374- "dashboard.classSizes": "Class sizes",1373+ "dashboard.courseCapacities": "Course capacities",
1375 "dashboard.courseAverages": "Course averages",1374 "dashboard.courseAverages": "Course averages",
1376 "dashboard.chartEmpty": "No records found",1375 "dashboard.chartEmpty": "No records found",
1377 "dashboard.chartEmptyHint": "Not enough data to display yet.",1376 "dashboard.chartEmptyHint": "Not enough data to display yet.",
@@ -1395,18 +1394,15 @@ const en: Dict = {
1395 "dashboard.attend.excused": "Excused",1394 "dashboard.attend.excused": "Excused",
1396 "dashboard.welcomeBack": "Welcome back, {name}!",1395 "dashboard.welcomeBack": "Welcome back, {name}!",
1397 "dashboard.welcomeHint": "Here's what needs your attention today.",1396 "dashboard.welcomeHint": "Here's what needs your attention today.",
1398- "dashboard.refresh": "Refresh data",1397+ "dashboard.teachingResources": "Teaching resources",
1399- "dashboard.col.priority": "Priority",1398+ "dashboard.teachingResourcesDesc": "Review reusable material and student questions.",
1400- "dashboard.priority.high": "High",1399+ "dashboard.questionBankDesc": "Build and reuse question templates for exams.",
1401- "dashboard.priority.medium": "Medium",1400+ "dashboard.questionPoolDesc": "Review questions submitted by students.",
1402 "dashboard.quickReview.title": "Quick review",1401 "dashboard.quickReview.title": "Quick review",
1403 "dashboard.quickReview.subtitle": "Sharpen your knowledge in 2 minutes!",1402 "dashboard.quickReview.subtitle": "Sharpen your knowledge in 2 minutes!",
1404 "dashboard.quickReview.placeholder": "Choose a topic to review…",1403 "dashboard.quickReview.placeholder": "Choose a topic to review…",
1405 "dashboard.quickReview.practice": "Practice",1404 "dashboard.quickReview.practice": "Practice",
1406 "dashboard.quickReview.startQuiz": "Start quiz",1405 "dashboard.quickReview.startQuiz": "Start quiz",
1407- "dashboard.questionHubDesc": "Browse the question bank or ask a question.",
1408- "dashboard.questionHubPlaceholder": "Search the question bank…",
1409- "dashboard.askQuestion": "Ask a question",
1410 "notes.title": "Notebook",1406 "notes.title": "Notebook",
1411 "notes.subtitle": "Private scratchpad for class ideas and reminders.",1407 "notes.subtitle": "Private scratchpad for class ideas and reminders.",
1412 "notes.new": "New note",1408 "notes.new": "New note",
@@ -1497,6 +1493,7 @@ const en: Dict = {
1497 "calendar.appointments": "Appointments",1493 "calendar.appointments": "Appointments",
1498 "nav.appointments": "Appointments",1494 "nav.appointments": "Appointments",
1499 "appointments.title": "Appointments",1495 "appointments.title": "Appointments",
1496+ "appointments.calendar": "Appointment calendar",
1500 "appointments.subtitle": "Book a meeting with a teacher, or publish times you are available.",1497 "appointments.subtitle": "Book a meeting with a teacher, or publish times you are available.",
1501 "appointments.empty": "No appointments yet.",1498 "appointments.empty": "No appointments yet.",
1502 "appointments.mySlots": "My available times",1499 "appointments.mySlots": "My available times",
@@ -1865,6 +1862,7 @@ const en: Dict = {
1865 "courses.title": "Education",1862 "courses.title": "Education",
1866 "courses.listTitle": "{item} records",1863 "courses.listTitle": "{item} records",
1867 "courses.subtitle": "Manage {item}, enrollment, and exams here.",1864 "courses.subtitle": "Manage {item}, enrollment, and exams here.",
1865+ "courses.pageSubtitle": "Classes, study groups, and clubs in one place.",
1868 "courses.create": "New education item",1866 "courses.create": "New education item",
1869 "courses.empty": "No {item} yet.",1867 "courses.empty": "No {item} yet.",
1870 "courses.enrolled": "Enrolled",1868 "courses.enrolled": "Enrolled",
@@ -2277,7 +2275,7 @@ const tr: Dict = {
2277 "common.approve": "Onayla",2275 "common.approve": "Onayla",
2278 "common.reject": "Reddet",2276 "common.reject": "Reddet",
2279 "common.actions": "İşlemler",2277 "common.actions": "İşlemler",
2280- "common.columns": "Kolonlar",2278+ "common.columns": "Sütunlar",
2281 "common.moreFilters": "Daha fazla filtre",2279 "common.moreFilters": "Daha fazla filtre",
2282 "common.lessFilters": "Daha az filtre",2280 "common.lessFilters": "Daha az filtre",
2283 "common.search": "Ara",2281 "common.search": "Ara",
@@ -2470,7 +2468,7 @@ const tr: Dict = {
2470 "dashboard.workloadSplit": "İş yükü dağılımı",2468 "dashboard.workloadSplit": "İş yükü dağılımı",
2471 "dashboard.workloadSplitDesc": "Dersler, sınavlar, etkinlikler ve dahası.",2469 "dashboard.workloadSplitDesc": "Dersler, sınavlar, etkinlikler ve dahası.",
2472 "dashboard.deadlines": "Yaklaşan son tarihler",2470 "dashboard.deadlines": "Yaklaşan son tarihler",
2473- "dashboard.classSizes": "Sınıf mevcutları",2471+ "dashboard.courseCapacities": "Eğitim kapasiteleri",
2474 "dashboard.courseAverages": "Ders ortalamaları",2472 "dashboard.courseAverages": "Ders ortalamaları",
2475 "dashboard.chartEmpty": "Kayıt bulunamadı",2473 "dashboard.chartEmpty": "Kayıt bulunamadı",
2476 "dashboard.chartEmptyHint": "Gösterilecek yeterli veri yok.",2474 "dashboard.chartEmptyHint": "Gösterilecek yeterli veri yok.",
@@ -2494,18 +2492,15 @@ const tr: Dict = {
2494 "dashboard.attend.excused": "İzinli",2492 "dashboard.attend.excused": "İzinli",
2495 "dashboard.welcomeBack": "Tekrar hoş geldin, {name}!",2493 "dashboard.welcomeBack": "Tekrar hoş geldin, {name}!",
2496 "dashboard.welcomeHint": "Bugün dikkat etmen gerekenler burada.",2494 "dashboard.welcomeHint": "Bugün dikkat etmen gerekenler burada.",
2497- "dashboard.refresh": "Verileri yenile",2495+ "dashboard.teachingResources": "Öğretim kaynakları",
2498- "dashboard.col.priority": "Öncelik",2496+ "dashboard.teachingResourcesDesc": "Yeniden kullanılabilir içerikleri ve öğrenci sorularını incele.",
2499- "dashboard.priority.high": "Yüksek",2497+ "dashboard.questionBankDesc": "Sınavlar için soru şablonları oluştur ve yeniden kullan.",
2500- "dashboard.priority.medium": "Orta",2498+ "dashboard.questionPoolDesc": "Öğrencilerin gönderdiği soruları incele.",
2501 "dashboard.quickReview.title": "Hızlı tekrar",2499 "dashboard.quickReview.title": "Hızlı tekrar",
2502 "dashboard.quickReview.subtitle": "2 dakikada bilgini tazele!",2500 "dashboard.quickReview.subtitle": "2 dakikada bilgini tazele!",
2503 "dashboard.quickReview.placeholder": "Tekrar için konu seç…",2501 "dashboard.quickReview.placeholder": "Tekrar için konu seç…",
2504 "dashboard.quickReview.practice": "Alıştır",2502 "dashboard.quickReview.practice": "Alıştır",
2505 "dashboard.quickReview.startQuiz": "Teste başla",2503 "dashboard.quickReview.startQuiz": "Teste başla",
2506- "dashboard.questionHubDesc": "Soru havuzuna göz at ya da soru sor.",
2507- "dashboard.questionHubPlaceholder": "Soru havuzunda ara…",
2508- "dashboard.askQuestion": "Soru sor",
2509 "notes.title": "Defter",2504 "notes.title": "Defter",
2510 "notes.subtitle": "Ders fikirleri ve hatırlatmalar için özel defter.",2505 "notes.subtitle": "Ders fikirleri ve hatırlatmalar için özel defter.",
2511 "notes.new": "Yeni not",2506 "notes.new": "Yeni not",
@@ -2596,6 +2591,7 @@ const tr: Dict = {
2596 "calendar.appointments": "Randevular",2591 "calendar.appointments": "Randevular",
2597 "nav.appointments": "Randevular",2592 "nav.appointments": "Randevular",
2598 "appointments.title": "Randevular",2593 "appointments.title": "Randevular",
2594+ "appointments.calendar": "Randevu takvimi",
2599 "appointments.subtitle": "Bir öğretmenle görüşme ayarlayın ya da uygun olduğunuz saatleri yayımlayın.",2595 "appointments.subtitle": "Bir öğretmenle görüşme ayarlayın ya da uygun olduğunuz saatleri yayımlayın.",
2600 "appointments.empty": "Henüz randevu yok.",2596 "appointments.empty": "Henüz randevu yok.",
2601 "appointments.mySlots": "Uygun saatlerim",2597 "appointments.mySlots": "Uygun saatlerim",
@@ -2964,6 +2960,7 @@ const tr: Dict = {
2964 "courses.title": "Eğitim",2960 "courses.title": "Eğitim",
2965 "courses.listTitle": "{item} kayıtları",2961 "courses.listTitle": "{item} kayıtları",
2966 "courses.subtitle": "{item}, kayıtlar ve sınavlar burada.",2962 "courses.subtitle": "{item}, kayıtlar ve sınavlar burada.",
2963+ "courses.pageSubtitle": "Dersler, etütler ve kulüpler tek yerde.",
2967 "courses.create": "Yeni eğitim kaydı",2964 "courses.create": "Yeni eğitim kaydı",
2968 "courses.empty": "Henüz {item} yok.",2965 "courses.empty": "Henüz {item} yok.",
2969 "courses.enrolled": "Kayıtlı",2966 "courses.enrolled": "Kayıtlı",
src/lib/meals.test.tsadded+37 -0
@@ -0,0 +1,37 @@
1+import { describe, expect, it } from "vitest";
2+import type { SchoolSettings } from "@/api/client";
3+import { dirtySettingsPatch, formatTry, mealCutoffAt, minuteToUtcTime, nextCourseWork, utcTimeToMinute } from "./meals";
4+
5+describe("meal helpers", () => {
6+ it("formats minor units as TRY", () => {
7+ expect(formatTry(4550, "tr-TR")).toContain("45,50");
8+ });
9+
10+ it("converts UTC minute values", () => {
11+ expect(minuteToUtcTime(540)).toBe("09:00");
12+ expect(utcTimeToMinute("23:59")).toBe(1439);
13+ expect(utcTimeToMinute("24:00")).toBeNull();
14+ });
15+
16+ it("calculates the booking cutoff in UTC", () => {
17+ expect(mealCutoffAt("2026-07-28", { name: "lunch", serving_minute: 720 }, 120))
18+ .toBe(Date.parse("2026-07-28T10:00:00Z"));
19+ });
20+
21+ it("selects nearest course work", () => {
22+ expect(nextCourseWork(
23+ "c1",
24+ [{ course: "c1", title: "Exam", starts_at: 30 } as never],
25+ [{ course: "c1", title: "Homework", due_at: 20 } as never],
26+ )?.title).toBe("Homework");
27+ });
28+
29+ it("builds a field-only settings patch", () => {
30+ const before = {
31+ exam_kinds: [], attendance_statuses: [], grade_bands: [], max_file_bytes: 1,
32+ chatbot_history_turns: 1, max_chatbot_threads: 1, max_chatbot_message_len: 100,
33+ meal_slots: [], dietary_tags: [], meal_cancel_cutoff_minutes: null,
34+ } satisfies SchoolSettings;
35+ expect(dirtySettingsPatch(before, { ...before, max_chatbot_threads: 2 })).toEqual({ max_chatbot_threads: 2 });
36+ });
37+});
src/lib/meals.tsadded+50 -0
@@ -0,0 +1,50 @@
1+import type { Exam, Homework, MealSlot, SchoolSettings } from "@/api/client";
2+import type { PatchSettingsBody } from "@/api/settings";
3+
4+export function formatTry(minor: number, locale: string): string {
5+ return new Intl.NumberFormat(locale, { style: "currency", currency: "TRY" }).format(minor / 100);
6+}
7+
8+export function minuteToUtcTime(minute: number | null): string {
9+ if (minute == null) return "";
10+ return `${String(Math.floor(minute / 60)).padStart(2, "0")}:${String(minute % 60).padStart(2, "0")}`;
11+}
12+
13+export function utcTimeToMinute(value: string): number | null {
14+ const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value);
15+ return match ? Number(match[1]) * 60 + Number(match[2]) : null;
16+}
17+
18+export function mealCutoffAt(date: string, slot: MealSlot | undefined, minutes: number | null): number | null {
19+ if (minutes == null) return null;
20+ const servingMinute = slot?.serving_minute ?? 0;
21+ return Date.parse(`${date}T00:00:00Z`) + servingMinute * 60_000 - minutes * 60_000;
22+}
23+
24+export function nextCourseWork(courseId: string, exams: Exam[], homework: Homework[]) {
25+ return [
26+ ...exams.filter((item) => item.course === courseId).map((item) => ({ kind: "exam" as const, title: item.title, at: item.starts_at ?? item.ends_at })),
27+ ...homework.filter((item) => item.course === courseId).map((item) => ({ kind: "homework" as const, title: item.title, at: item.due_at })),
28+ ]
29+ .filter((item): item is { kind: "exam" | "homework"; title: string; at: number } => item.at != null)
30+ .sort((a, b) => a.at - b.at)[0] ?? null;
31+}
32+
33+export function dirtySettingsPatch(before: SchoolSettings, after: SchoolSettings): PatchSettingsBody {
34+ const patch: PatchSettingsBody = {};
35+ for (const key of [
36+ "exam_kinds",
37+ "attendance_statuses",
38+ "grade_bands",
39+ "max_file_bytes",
40+ "chatbot_history_turns",
41+ "max_chatbot_threads",
42+ "max_chatbot_message_len",
43+ "meal_slots",
44+ "dietary_tags",
45+ "meal_cancel_cutoff_minutes",
46+ ] as const) {
47+ if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) patch[key] = after[key] as never;
48+ }
49+ return patch;
50+}
src/pages/meal-detail-page.tsxadded+275 -0
@@ -0,0 +1,275 @@
1+import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js";
2+import { Link, useLocation, useNavigate, useParams } from "@tanstack/solid-router";
3+import { getLimits } from "@/api/limits";
4+import {
5+ deleteMealBookingById,
6+ deleteMealDishById,
7+ deleteMealMenuById,
8+ getDietaryProfileByUserId,
9+ getMealAttendanceByUserId,
10+ getMealBalanceByUserId,
11+ getMealLedgerByUserId,
12+ getMealMenuBookings,
13+ getMealMenuById,
14+ getMealServiceRoster,
15+ getMyDietaryProfile,
16+ getMyMealBalance,
17+ getMyMealBookings,
18+ patchDietaryProfileByUserId,
19+ patchMealDishById,
20+ patchMealMenuById,
21+ postMealAttendance,
22+ postMealBooking,
23+ postMealCredit,
24+ postMealDish,
25+} from "@/api/meals";
26+import { getMyStudents } from "@/api/parents";
27+import { getSettings } from "@/api/settings";
28+import { getTime } from "@/api/time";
29+import { formatApiError, type MealDish } from "@/api/client";
30+import { PageHeader } from "@/components/layout/page-header";
31+import { RouteGuard } from "@/components/layout/route-guard";
32+import { Alert } from "@/components/ui/alert";
33+import { Badge } from "@/components/ui/badge";
34+import { Button } from "@/components/ui/button";
35+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
36+import { EmptyState } from "@/components/ui/empty-state";
37+import { ErrorAlert } from "@/components/ui/error-alert";
38+import { IconAlert, IconChevronLeft, IconEdit, IconPlus, IconTrash } from "@/components/ui/icons";
39+import { Input } from "@/components/ui/input";
40+import { Label } from "@/components/ui/label";
41+import { PageSpinner } from "@/components/ui/page-spinner";
42+import { Select } from "@/components/ui/select";
43+import { SidePanel } from "@/components/ui/side-panel";
44+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
45+import { Textarea } from "@/components/ui/textarea";
46+import { UserSearchSelect } from "@/components/users/user-search-select";
47+import { formatDateTime } from "@/lib/format";
48+import { formatTry, mealCutoffAt } from "@/lib/meals";
49+import { personLabel } from "@/lib/person";
50+import { hasMinRole } from "@/lib/roles";
51+import { useAuth } from "@/stores/auth-context";
52+import { usePreferences, useT } from "@/stores/preferences-context";
53+
54+export default function MealDetailPage() {
55+ return <RouteGuard><MealDetailContent /></RouteGuard>;
56+}
57+
58+function MealDetailContent() {
59+ const auth = useAuth();
60+ const t = useT();
61+ const { locale } = usePreferences();
62+ const navigate = useNavigate();
63+ const location = useLocation();
64+ const params = useParams({ from: "/meals/$id" });
65+ const id = createMemo(() => { location(); return params().id; });
66+ const role = () => auth.user()!.role;
67+ const isStudent = () => role() === "student";
68+ const isParent = () => role() === "parent";
69+ const canServe = () => hasMinRole(role(), "teacher");
70+ const canManage = () => hasMinRole(role(), "manager");
71+ const isAdmin = () => role() === "admin";
72+ const moneyLocale = () => locale() === "tr" ? "tr-TR" : "en-US";
73+
74+ const [menu, { refetch: refetchMenu }] = createResource(id, (menuId) => getMealMenuById(menuId));
75+ const [settings] = createResource(() => getSettings());
76+ const [limits, { refetch: refetchLimits }] = createResource(() => getLimits());
77+ const [serverTime] = createResource(() => getTime().catch(() => ({ now: Date.now() })));
78+ const [children] = createResource(() => isParent() ? getMyStudents({ limit: 100 }) : null);
79+ const [selectedStudent, setSelectedStudent] = createSignal("");
80+ const [lookupStudent, setLookupStudent] = createSignal("");
81+ const [tab, setTab] = createSignal("menu");
82+ const [error, setError] = createSignal("");
83+ const [success, setSuccess] = createSignal("");
84+ const [pending, setPending] = createSignal(false);
85+ const [cancelOpen, setCancelOpen] = createSignal(false);
86+ const [deleteMenuOpen, setDeleteMenuOpen] = createSignal(false);
87+ const [deleteDish, setDeleteDish] = createSignal<MealDish | null>(null);
88+
89+ createEffect(() => {
90+ if (isParent() && !selectedStudent() && children()?.items[0]) setSelectedStudent(children()!.items[0].id);
91+ });
92+ const targetId = () => isStudent() ? auth.user()!.id : isParent() ? selectedStudent() : lookupStudent();
93+ const canBook = () => (isStudent() || isParent()) && !!targetId();
94+
95+ const [bookings, { refetch: refetchBookings }] = createResource(() => canBook(), async (enabled) => enabled ? getMyMealBookings({ limit: 100 }) : null);
96+ const activeBooking = createMemo(() => bookings()?.items.find((booking) => booking.menu_id === id() && booking.student.id === targetId() && booking.status === "booked") ?? null);
97+ const [profile, { refetch: refetchProfile }] = createResource(
98+ targetId,
99+ async (userId) => userId === auth.user()!.id ? getMyDietaryProfile() : getDietaryProfileByUserId(userId),
100+ );
101+ const [balance, { refetch: refetchBalance }] = createResource(
102+ targetId,
103+ async (userId) => userId === auth.user()!.id ? getMyMealBalance() : getMealBalanceByUserId(userId),
104+ );
105+ const [ledger, { refetch: refetchLedger }] = createResource(targetId, (userId) => getMealLedgerByUserId(userId, { limit: 20 }));
106+ const [attendance] = createResource(targetId, (userId) => getMealAttendanceByUserId(userId, { limit: 20 }));
107+ const [service, { refetch: refetchService }] = createResource(
108+ () => canServe() ? id() : null,
109+ (menuId) => getMealServiceRoster(menuId, { limit: 100 }),
110+ );
111+ const [audit] = createResource(
112+ () => canManage() ? id() : null,
113+ (menuId) => getMealMenuBookings(menuId, { limit: 100 }),
114+ );
115+
116+ const total = () => menu()?.dishes.reduce((sum, dish) => sum + dish.price_minor, 0) ?? 0;
117+ const conflicts = () => [...new Set(menu()?.dishes.flatMap((dish) => dish.conflicts) ?? [])];
118+ const slot = () => settings()?.meal_slots.find((item) => item.name === menu()?.slot);
119+ const cutoff = () => menu() ? mealCutoffAt(menu()!.date, slot(), settings()?.meal_cancel_cutoff_minutes ?? null) : null;
120+ const cutoffClosed = () => cutoff() != null && (serverTime()?.now ?? Date.now()) >= cutoff()!;
121+
122+ const [capacity, setCapacity] = createSignal("");
123+ const [showMenuEdit, setShowMenuEdit] = createSignal(false);
124+ const [showDishForm, setShowDishForm] = createSignal(false);
125+ const [editingDish, setEditingDish] = createSignal<MealDish | null>(null);
126+ const [dishName, setDishName] = createSignal("");
127+ const [dishDescription, setDishDescription] = createSignal("");
128+ const [dishPrice, setDishPrice] = createSignal("");
129+ const [dishTags, setDishTags] = createSignal<string[]>([]);
130+ const [profileTags, setProfileTags] = createSignal<string[]>([]);
131+ const [profileNote, setProfileNote] = createSignal("");
132+ const [creditAmount, setCreditAmount] = createSignal("");
133+ const [creditMethod, setCreditMethod] = createSignal("");
134+ const [creditNote, setCreditNote] = createSignal("");
135+ const [walkIn, setWalkIn] = createSignal("");
136+
137+ createEffect(() => {
138+ if (profile()) { setProfileTags([...profile()!.tags]); setProfileNote(profile()!.note ?? ""); }
139+ });
140+ const run = async (work: () => Promise<void>, message = t("common.saved")) => {
141+ setPending(true); setError(""); setSuccess("");
142+ try { await work(); setSuccess(message); }
143+ catch (err) { setError(formatApiError(err)); }
144+ finally { setPending(false); }
145+ };
146+ const openDish = (dish?: MealDish) => {
147+ setEditingDish(dish ?? null);
148+ setDishName(dish?.name ?? ""); setDishDescription(dish?.description ?? "");
149+ setDishPrice(dish ? String(dish.price_minor / 100) : ""); setDishTags(dish?.tags ?? []);
150+ setShowDishForm(true);
151+ };
152+ const toggleTag = (tag: string, selected: string[], set: (value: string[]) => void) =>
153+ set(selected.includes(tag) ? selected.filter((item) => item !== tag) : [...selected, tag]);
154+
155+ return (
156+ <Suspense fallback={<PageSpinner />}>
157+ <Show when={menu()?.id === id() ? menu() : undefined} fallback={<Show when={menu.error} fallback={<PageSpinner />}><ErrorAlert message={formatApiError(menu.error)} onRetry={() => void refetchMenu()} /></Show>}>
158+ {(current) => (
159+ <div class="space-y-5">
160+ <PageHeader
161+ accent="violet"
162+ eyebrow={`${current().date} · ${current().slot}`}
163+ title={t("meals.menu")}
164+ description={t("meals.detailHelp")}
165+ actions={<div class="detail-action-group"><Link to="/meals"><Button variant="ghost" size="sm"><IconChevronLeft class="h-4 w-4" />{t("common.back")}</Button></Link><Show when={canManage()}><Button variant="outline" size="sm" onClick={() => { setCapacity(current().capacity == null ? "" : String(current().capacity)); setShowMenuEdit(true); }}><IconEdit class="h-4 w-4" />{t("common.edit")}</Button><Button variant="destructive" size="sm" onClick={() => setDeleteMenuOpen(true)}><IconTrash class="h-4 w-4" />{t("common.delete")}</Button></Show></div>}
166+ />
167+ <Show when={limits.error}><ErrorAlert message={formatApiError(limits.error)} onRetry={() => void refetchLimits()} /></Show>
168+ <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show>
169+ <Show when={success()}><Alert variant="success">{success()}</Alert></Show>
170+
171+ <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
172+ <div class="detail-metric-card"><p class="text-xs uppercase text-muted-foreground">{t("meals.total")}</p><p class="mt-1 font-semibold">{formatTry(total(), moneyLocale())}</p></div>
173+ <div class="detail-metric-card"><p class="text-xs uppercase text-muted-foreground">{t("meals.capacity")}</p><p class="mono mt-1 font-semibold">{current().capacity ?? "∞"}</p></div>
174+ <div class="detail-metric-card"><p class="text-xs uppercase text-muted-foreground">{t("meals.cutoff")}</p><p class="mt-1 font-semibold">{cutoff() == null ? t("meals.noCutoff") : formatDateTime(cutoff(), locale())}</p></div>
175+ <div class="detail-metric-card"><p class="text-xs uppercase text-muted-foreground">{t("meals.bookingStatus")}</p><p class="mt-1 font-semibold">{cutoffClosed() ? t("meals.closed") : t("meals.open")}</p></div>
176+ </div>
177+
178+ <Show when={conflicts().length > 0}>
179+ <Alert class="border-amber-500/40 bg-amber-500/10 text-amber-800 dark:text-amber-200"><span class="flex gap-2"><IconAlert class="mt-0.5 h-4 w-4 shrink-0" /><span>{t("meals.conflict")}: {conflicts().join(", ")}</span></span></Alert>
180+ </Show>
181+
182+ <Show when={isParent()}>
183+ <div class="data-shell max-w-md p-4"><Label for="meal-child">{t("meals.child")}</Label><Select id="meal-child" value={selectedStudent()} onChange={(e) => setSelectedStudent(e.currentTarget.value)}><For each={children()?.items ?? []}>{(child) => <option value={child.id}>{personLabel(child)}</option>}</For></Select></div>
184+ </Show>
185+
186+ <Tabs value={tab()} onChange={setTab}>
187+ <TabsList>
188+ <TabsTrigger value="menu">{t("meals.menu")}</TabsTrigger>
189+ <Show when={canBook()}><TabsTrigger value="account">{t("meals.myAccount")}</TabsTrigger></Show>
190+ <Show when={canServe()}><TabsTrigger value="service">{t("meals.service")}</TabsTrigger></Show>
191+ <Show when={canManage()}><TabsTrigger value="manage">{t("meals.manage")}</TabsTrigger></Show>
192+ </TabsList>
193+
194+ <TabsContent value="menu" class="space-y-4">
195+ <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
196+ <For each={current().dishes}>{(dish) => (
197+ <article class="rounded-2xl border border-border/70 bg-card p-4">
198+ <div class="flex justify-between gap-3"><h2 class="font-semibold">{dish.name}</h2><span class="font-semibold">{formatTry(dish.price_minor, moneyLocale())}</span></div>
199+ <p class="mt-2 text-sm text-muted-foreground">{dish.description || "—"}</p>
200+ <div class="mt-3 flex flex-wrap gap-1"><For each={dish.tags}>{(tag) => <Badge variant="outline" class={dish.conflicts.includes(tag) ? "border-amber-500/40 bg-amber-500/10 text-amber-800 dark:text-amber-200" : ""}>{dish.conflicts.includes(tag) ? `⚠ ${tag}` : tag}</Badge>}</For></div>
201+ <Show when={canManage()}><div class="mt-3 flex gap-2 border-t pt-3"><Button variant="outline" size="sm" onClick={() => openDish(dish)}>{t("common.edit")}</Button><Button variant="ghost" size="sm" class="text-destructive" onClick={() => setDeleteDish(dish)}>{t("common.delete")}</Button></div></Show>
202+ </article>
203+ )}</For>
204+ </div>
205+ <Show when={current().dishes.length === 0}><EmptyState title={t("meals.noDishes")} /></Show>
206+ <Show when={canBook()}>
207+ <div class="data-shell flex flex-wrap items-center justify-between gap-3 p-4">
208+ <div><p class="font-semibold">{activeBooking() ? t("meals.booked") : t("meals.notBooked")}</p><p class="text-sm text-muted-foreground">{cutoffClosed() ? t("meals.cutoffPassed") : t("meals.bookingHelp")}</p></div>
209+ <Show when={activeBooking()} fallback={<Button disabled={pending() || cutoffClosed()} onClick={() => void run(async () => { await postMealBooking(id(), isParent() ? targetId() : undefined); await Promise.all([refetchBookings(), refetchBalance(), refetchLedger()]); }, t("meals.booked"))}>{t("meals.book")}</Button>}><Button variant="destructive" disabled={pending() || cutoffClosed()} onClick={() => setCancelOpen(true)}>{t("meals.cancelBooking")}</Button></Show>
210+ </div>
211+ </Show>
212+ </TabsContent>
213+
214+ <TabsContent value="account" class="space-y-4">
215+ <div class="grid gap-4 lg:grid-cols-2">
216+ <section class="data-shell p-4"><h2 class="font-semibold">{t("meals.dietaryProfile")}</h2><div class="mt-3 flex flex-wrap gap-1.5"><For each={profile()?.tags ?? []}>{(tag) => <Badge variant="outline" class="border-amber-500/40 bg-amber-500/10 text-amber-800 dark:text-amber-200">⚠ {tag}</Badge>}</For></div><p class="mt-3 text-sm text-muted-foreground">{profile()?.note || t("meals.noDietaryNotes")}</p></section>
217+ <section class="data-shell p-4"><h2 class="font-semibold">{t("meals.balance")}</h2><p class="mt-3 text-2xl font-semibold tabular-nums">{formatTry(balance()?.balance_minor ?? 0, moneyLocale())}</p></section>
218+ </div>
219+ <section class="data-shell p-4"><h2 class="font-semibold">{t("meals.ledger")}</h2><div class="mt-3 divide-y divide-border/60"><For each={ledger()?.items ?? []}>{(line) => <div class="flex justify-between gap-3 py-3 text-sm"><div><p class="font-medium">{t(`meals.ledger.${line.kind}` as never)}</p><p class="text-xs text-muted-foreground">{line.note || line.method || "—"} · {formatDateTime(line.created_at, locale())}</p></div><span class="font-semibold tabular-nums">{line.kind === "charge" ? "−" : "+"}{formatTry(line.amount_minor, moneyLocale())}</span></div>}</For></div><Show when={(ledger()?.items.length ?? 0) === 0}><p class="mt-3 text-sm text-muted-foreground">{t("meals.noLedger")}</p></Show></section>
220+ <section class="data-shell p-4"><h2 class="font-semibold">{t("meals.attendance")}</h2><div class="mt-3 divide-y divide-border/60"><For each={attendance()?.items ?? []}>{(row) => <div class="flex justify-between gap-3 py-3 text-sm"><span>{row.status}</span><span class="text-muted-foreground">{formatDateTime(row.marked_at, locale())}</span></div>}</For></div></section>
221+ </TabsContent>
222+
223+ <TabsContent value="service" class="space-y-4">
224+ <div class="data-shell p-4">
225+ <h2 class="font-semibold">{t("meals.walkIn")}</h2>
226+ <div class="mt-3 flex flex-col gap-2 sm:flex-row sm:items-end"><div class="min-w-0 flex-1"><UserSearchSelect id="meal-walkin" value={walkIn()} onChange={setWalkIn} placeholder={t("form.selectStudent")} /></div><Button disabled={!walkIn() || pending()} onClick={() => void run(async () => { await postMealAttendance(id(), walkIn(), "served"); setWalkIn(""); await refetchService(); })}>{t("meals.served")}</Button></div>
227+ </div>
228+ <Show when={service.error}><ErrorAlert message={formatApiError(service.error)} onRetry={() => void refetchService()} /></Show>
229+ <div class="space-y-2">
230+ <For each={service()?.items ?? []}>{(entry) => <div class="data-shell flex flex-wrap items-center justify-between gap-3 p-3"><div><p class="font-medium">{personLabel(entry.student)}</p><p class="text-xs text-muted-foreground">{entry.booking ? t("meals.booked") : t("meals.walkIn")} · {entry.attendance?.status ?? t("meals.notMarked")}</p></div><div class="flex gap-2"><Button size="sm" variant={entry.attendance?.status === "served" ? "default" : "outline"} onClick={() => void run(async () => { await postMealAttendance(id(), entry.student.id, "served"); await refetchService(); })}>{t("meals.served")}</Button><Button size="sm" variant={entry.attendance?.status === "missed" ? "destructive" : "outline"} onClick={() => void run(async () => { await postMealAttendance(id(), entry.student.id, "missed"); await refetchService(); })}>{t("meals.missed")}</Button></div></div>}</For>
231+ </div>
232+ </TabsContent>
233+
234+ <TabsContent value="manage" class="space-y-5">
235+ <div class="flex justify-end"><Button size="sm" onClick={() => openDish()}><IconPlus class="h-4 w-4" />{t("meals.addDish")}</Button></div>
236+ <section class="data-shell space-y-4 p-4">
237+ <h2 class="font-semibold">{t("meals.studentRecord")}</h2>
238+ <UserSearchSelect id="meal-record-user" role="student" value={lookupStudent()} onChange={setLookupStudent} label={t("meals.student")} />
239+ <Show when={lookupStudent()}>
240+ <div class="space-y-3">
241+ <div class="flex flex-wrap gap-2"><For each={settings()?.dietary_tags ?? []}>{(tag) => <label class="flex items-center gap-2 rounded-lg border px-3 py-2 text-sm"><input type="checkbox" checked={profileTags().includes(tag)} onChange={() => toggleTag(tag, profileTags(), setProfileTags)} />{tag}</label>}</For></div>
242+ <Textarea maxlength={limits()?.meal.max_dietary_note_len} value={profileNote()} placeholder={t("meals.dietaryNote")} onInput={(e) => setProfileNote(e.currentTarget.value)} />
243+ <Button disabled={pending()} onClick={() => void run(async () => { await patchDietaryProfileByUserId(lookupStudent(), { tags: profileTags(), note: profileNote().trim() || null }); await refetchProfile(); })}>{t("common.save")}</Button>
244+ </div>
245+ </Show>
246+ </section>
247+ <section class="data-shell p-4"><h2 class="font-semibold">{t("meals.bookingAudit")}</h2><div class="mt-3 divide-y divide-border/60"><For each={audit()?.items ?? []}>{(booking) => <div class="flex justify-between gap-3 py-3 text-sm"><span>{personLabel(booking.student)}</span><Badge variant={booking.status === "booked" ? "default" : "secondary"}>{booking.status}</Badge></div>}</For></div></section>
248+ <Show when={isAdmin()}>
249+ <section class="data-shell space-y-3 p-4"><h2 class="font-semibold">{t("meals.recordCredit")}</h2><p class="text-sm text-muted-foreground">{t("meals.creditAppendOnly")}</p><Input type="number" min={0.01} step={0.01} value={creditAmount()} placeholder={t("meals.amountTry")} onInput={(e) => setCreditAmount(e.currentTarget.value)} /><Input maxlength={limits()?.meal.max_ledger_method_len} value={creditMethod()} placeholder={t("meals.method")} onInput={(e) => setCreditMethod(e.currentTarget.value)} /><Textarea maxlength={limits()?.meal.max_ledger_note_len} value={creditNote()} placeholder={t("meals.note")} onInput={(e) => setCreditNote(e.currentTarget.value)} /><Button disabled={!lookupStudent() || pending()} onClick={() => void run(async () => { await postMealCredit({ student_id: lookupStudent(), amount_minor: Math.round(Number(creditAmount()) * 100), method: creditMethod().trim() || undefined, note: creditNote().trim() || undefined }); setCreditAmount(""); setCreditMethod(""); setCreditNote(""); await Promise.all([refetchBalance(), refetchLedger()]); }, t("meals.creditRecorded"))}>{t("meals.recordCredit")}</Button></section>
250+ </Show>
251+ </TabsContent>
252+ </Tabs>
253+
254+ <ConfirmDialog open={cancelOpen()} onOpenChange={setCancelOpen} title={t("meals.cancelBooking")} variant="destructive" summary={t("meals.cancelSummary")} onConfirm={() => run(async () => { const booking = activeBooking(); if (!booking) return; await deleteMealBookingById(booking.id); await Promise.all([refetchBookings(), refetchBalance(), refetchLedger()]); }, t("meals.cancelled"))} />
255+ <ConfirmDialog open={deleteMenuOpen()} onOpenChange={setDeleteMenuOpen} title={t("meals.deleteMenu")} variant="destructive" summary={`${current().date} · ${current().slot}`} onConfirm={() => run(async () => { await deleteMealMenuById(id()); void navigate({ to: "/meals" }); }, t("common.deleted"))} />
256+ <ConfirmDialog open={deleteDish() !== null} onOpenChange={(open) => !open && setDeleteDish(null)} title={t("meals.deleteDish")} variant="destructive" summary={deleteDish()?.name ?? ""} onConfirm={() => run(async () => { if (!deleteDish()) return; await deleteMealDishById(deleteDish()!.id); setDeleteDish(null); await refetchMenu(); }, t("common.deleted"))} />
257+
258+ <SidePanel open={showMenuEdit()} onOpenChange={setShowMenuEdit} title={t("meals.editMenu")} description={`${current().date} · ${current().slot}`}>
259+ <form class="space-y-4" onSubmit={(e) => { e.preventDefault(); void run(async () => { await patchMealMenuById(id(), { capacity: capacity() ? Number(capacity()) : null }); setShowMenuEdit(false); await refetchMenu(); }); }}><div class="space-y-1.5"><Label for="menu-capacity">{t("meals.capacity")}</Label><Input id="menu-capacity" type="number" min={0} max={limits()?.meal.max_menu_capacity} value={capacity()} onInput={(e) => setCapacity(e.currentTarget.value)} /></div><Button type="submit" disabled={pending()}>{t("common.save")}</Button></form>
260+ </SidePanel>
261+ <SidePanel open={showDishForm()} onOpenChange={setShowDishForm} title={editingDish() ? t("meals.editDish") : t("meals.addDish")} description={`${current().date} · ${current().slot}`}>
262+ <form class="space-y-4" onSubmit={(e) => { e.preventDefault(); void run(async () => { const body = { name: dishName().trim(), description: dishDescription().trim() || null, price_minor: Math.round(Number(dishPrice()) * 100), tags: dishTags() }; if (editingDish()) await patchMealDishById(editingDish()!.id, body); else await postMealDish(id(), body); setShowDishForm(false); await refetchMenu(); }); }}>
263+ <div class="space-y-1.5"><Label for="dish-name">{t("meals.dishName")}</Label><Input id="dish-name" required maxlength={limits()?.meal.max_dish_name_len} value={dishName()} onInput={(e) => setDishName(e.currentTarget.value)} /></div>
264+ <div class="space-y-1.5"><Label for="dish-description">{t("form.description")}</Label><Textarea id="dish-description" maxlength={limits()?.meal.max_dish_description_len} value={dishDescription()} onInput={(e) => setDishDescription(e.currentTarget.value)} /></div>
265+ <div class="space-y-1.5"><Label for="dish-price">{t("meals.priceTry")}</Label><Input id="dish-price" required type="number" min={0} step={0.01} value={dishPrice()} onInput={(e) => setDishPrice(e.currentTarget.value)} /></div>
266+ <div class="flex flex-wrap gap-2"><For each={settings()?.dietary_tags ?? []}>{(tag) => <label class="flex items-center gap-2 rounded-lg border px-3 py-2 text-sm"><input type="checkbox" checked={dishTags().includes(tag)} onChange={() => toggleTag(tag, dishTags(), setDishTags)} />{tag}</label>}</For></div>
267+ <Button type="submit" disabled={pending()}>{t("common.save")}</Button>
268+ </form>
269+ </SidePanel>
270+ </div>
271+ )}
272+ </Show>
273+ </Suspense>
274+ );
275+}
src/pages/meals-page.tsxadded+98 -0
@@ -0,0 +1,98 @@
1+import { For, Show, Suspense, createMemo, createResource, createSignal } from "solid-js";
2+import { getLimits } from "@/api/limits";
3+import { getMealMenus, postMealMenu } from "@/api/meals";
4+import { getSettings } from "@/api/settings";
5+import { formatApiError } from "@/api/client";
6+import { MealMenuCard } from "@/components/meals/meal-menu-card";
7+import { PageHeader } from "@/components/layout/page-header";
8+import { RouteGuard } from "@/components/layout/route-guard";
9+import { Alert } from "@/components/ui/alert";
10+import { Button } from "@/components/ui/button";
11+import { EmptyState } from "@/components/ui/empty-state";
12+import { ErrorAlert } from "@/components/ui/error-alert";
13+import { IconPlus } from "@/components/ui/icons";
14+import { Input } from "@/components/ui/input";
15+import { Label } from "@/components/ui/label";
16+import { PageSpinner } from "@/components/ui/page-spinner";
17+import { PaginationControls } from "@/components/ui/pagination-controls";
18+import { Select } from "@/components/ui/select";
19+import { SidePanel } from "@/components/ui/side-panel";
20+import { createFlash } from "@/lib/flash";
21+import { hasMinRole } from "@/lib/roles";
22+import { useAuth } from "@/stores/auth-context";
23+import { usePreferences, useT } from "@/stores/preferences-context";
24+
25+const PAGE_SIZE = 12;
26+const today = () => new Date().toISOString().slice(0, 10);
27+
28+export default function MealsPage() {
29+ return <RouteGuard><MealsContent /></RouteGuard>;
30+}
31+
32+function MealsContent() {
33+ const auth = useAuth();
34+ const t = useT();
35+ const { locale } = usePreferences();
36+ const canManage = () => hasMinRole(auth.user()?.role, "manager");
37+ const [page, setPage] = createSignal(0);
38+ const [from, setFrom] = createSignal(today());
39+ const [slot, setSlot] = createSignal("all");
40+ const [showCreate, setShowCreate] = createSignal(false);
41+ const [date, setDate] = createSignal(today());
42+ const [newSlot, setNewSlot] = createSignal("");
43+ const [capacity, setCapacity] = createSignal("");
44+ const [pending, setPending] = createSignal(false);
45+ const [error, setError] = createSignal("");
46+ const [flash, setFlash] = createFlash();
47+ const [settings] = createResource(() => getSettings());
48+ const [limits, { refetch: refetchLimits }] = createResource(() => canManage() ? getLimits() : null);
49+ const [menus, { refetch }] = createResource(
50+ () => [from(), page()] as const,
51+ async ([start, index]) => getMealMenus({ from: start || undefined, limit: PAGE_SIZE, offset: index * PAGE_SIZE }),
52+ );
53+ const visible = createMemo(() => slot() === "all" ? menus()?.items ?? [] : (menus()?.items ?? []).filter((menu) => menu.slot === slot()));
54+ const totalPages = createMemo(() => Math.max(1, Math.ceil((menus()?.total ?? 0) / PAGE_SIZE)));
55+
56+ const publish = async (event: SubmitEvent) => {
57+ event.preventDefault();
58+ setPending(true); setError("");
59+ try {
60+ await postMealMenu({ date: date(), slot: newSlot(), capacity: capacity() ? Number(capacity()) : null });
61+ setShowCreate(false); setCapacity(""); await refetch(); setFlash(t("common.created"));
62+ } catch (err) {
63+ setError(formatApiError(err));
64+ } finally {
65+ setPending(false);
66+ }
67+ };
68+
69+ return (
70+ <div class="space-y-5">
71+ <PageHeader accent="violet" eyebrow={t("nav.group.classes")} title={t("meals.title")} description={t("meals.subtitle")} actions={<Show when={canManage()}><Button size="sm" class="min-w-30 rounded-lg" onClick={() => { setNewSlot(settings()?.meal_slots[0]?.name ?? ""); setShowCreate(true); }}><IconPlus class="h-4 w-4" />{t("meals.publish")}</Button></Show>} />
72+ <SidePanel open={showCreate()} onOpenChange={setShowCreate} title={t("meals.publish")} description={t("meals.publishHelp")}>
73+ <form class="space-y-4" onSubmit={publish}>
74+ <Show when={limits.error}><ErrorAlert message={formatApiError(limits.error)} onRetry={() => void refetchLimits()} /></Show>
75+ <div class="space-y-1.5"><Label for="meal-date">{t("meals.date")}</Label><Input id="meal-date" type="date" required value={date()} onInput={(e) => setDate(e.currentTarget.value)} /></div>
76+ <div class="space-y-1.5"><Label for="meal-slot">{t("meals.slot")}</Label><Select id="meal-slot" required value={newSlot()} onChange={(e) => setNewSlot(e.currentTarget.value)}><For each={settings()?.meal_slots ?? []}>{(item) => <option value={item.name}>{item.name}</option>}</For></Select></div>
77+ <div class="space-y-1.5"><Label for="meal-capacity">{t("meals.capacity")}</Label><Input id="meal-capacity" type="number" min={0} max={limits()?.meal.max_menu_capacity} value={capacity()} onInput={(e) => setCapacity(e.currentTarget.value)} /></div>
78+ <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show>
79+ <div class="flex gap-2 border-t pt-4"><Button type="submit" disabled={pending()}>{t("common.create")}</Button><Button type="button" variant="outline" onClick={() => setShowCreate(false)}>{t("common.cancel")}</Button></div>
80+ </form>
81+ </SidePanel>
82+ <Show when={flash()}><Alert variant="success">{flash()}</Alert></Show>
83+ <section class="data-shell space-y-4 p-4">
84+ <div class="grid gap-3 sm:grid-cols-2">
85+ <div class="space-y-1.5"><Label for="menus-from">{t("meals.from")}</Label><Input id="menus-from" type="date" value={from()} onInput={(e) => { setFrom(e.currentTarget.value); setPage(0); }} /></div>
86+ <div class="space-y-1.5"><Label for="menus-slot">{t("meals.slot")}</Label><Select id="menus-slot" value={slot()} onChange={(e) => setSlot(e.currentTarget.value)}><option value="all">{t("common.all")}</option><For each={settings()?.meal_slots ?? []}>{(item) => <option value={item.name}>{item.name}</option>}</For></Select></div>
87+ </div>
88+ <Suspense fallback={<PageSpinner />}>
89+ <Show when={menus.error}><ErrorAlert message={formatApiError(menus.error)} onRetry={() => void refetch()} /></Show>
90+ <Show when={visible().length > 0} fallback={<EmptyState title={t("meals.empty")} />}>
91+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"><For each={visible()}>{(menu) => <MealMenuCard menu={menu} locale={locale() === "tr" ? "tr-TR" : "en-US"} labels={{ dishes: t("meals.dishes"), capacity: t("meals.capacity"), conflict: t("meals.conflict") }} />}</For></div>
92+ <PaginationControls page={page()} totalPages={totalPages()} onPageChange={setPage} />
93+ </Show>
94+ </Suspense>
95+ </section>
96+ </div>
97+ );
98+}
src/pages/settings-page.tsxmodified+99 -25
@@ -1,7 +1,8 @@
1 import { For, Show, Suspense, createEffect, createResource, createSignal } from "solid-js";1 import { For, Show, Suspense, createEffect, createResource, createSignal } from "solid-js";
2 import { getSettings } from "@/api/settings";2 import { getSettings } from "@/api/settings";
3 import { patchSettings } from "@/api/settings";3 import { patchSettings } from "@/api/settings";
4-import type { ExamKindSetting, GradeBand } from "@/api/client";4+import { getLimits } from "@/api/limits";
5+import type { ExamKindSetting, GradeBand, MealSlot, SchoolSettings } from "@/api/client";
5 import { formatApiError } from "@/api/client";6 import { formatApiError } from "@/api/client";
6 import { RouteGuard } from "@/components/layout/route-guard";7 import { RouteGuard } from "@/components/layout/route-guard";
7 import { PageHeader } from "@/components/layout/page-header";8 import { PageHeader } from "@/components/layout/page-header";
@@ -11,9 +12,11 @@ import { Button } from "@/components/ui/button";
11 import { ErrorAlert } from "@/components/ui/error-alert";12 import { ErrorAlert } from "@/components/ui/error-alert";
12 import { IconPlus, IconTrash } from "@/components/ui/icons";13 import { IconPlus, IconTrash } from "@/components/ui/icons";
13 import { Input } from "@/components/ui/input";14 import { Input } from "@/components/ui/input";
15+import { Label } from "@/components/ui/label";
14 import { PageSpinner } from "@/components/ui/page-spinner";16 import { PageSpinner } from "@/components/ui/page-spinner";
15 import { getAttendanceStatusMeta } from "@/lib/attendance-status";17 import { getAttendanceStatusMeta } from "@/lib/attendance-status";
16 import { cn } from "@/lib/cn";18 import { cn } from "@/lib/cn";
19+import { dirtySettingsPatch, minuteToUtcTime, utcTimeToMinute } from "@/lib/meals";
17 import { useT } from "@/stores/preferences-context";20 import { useT } from "@/stores/preferences-context";
18 21
19 const CORE_ATTENDANCE = new Set(["present", "absent", "late", "excused"]);22 const CORE_ATTENDANCE = new Set(["present", "absent", "late", "excused"]);
@@ -45,18 +48,30 @@ function SettingsContent() {
45 const [attendanceStatuses, setAttendanceStatuses] = createSignal<string[]>([]);48 const [attendanceStatuses, setAttendanceStatuses] = createSignal<string[]>([]);
46 const [gradeBands, setGradeBands] = createSignal<GradeBand[]>([]);49 const [gradeBands, setGradeBands] = createSignal<GradeBand[]>([]);
47 const [maxFileMiB, setMaxFileMiB] = createSignal("5");50 const [maxFileMiB, setMaxFileMiB] = createSignal("5");
51+ const [chatbotHistoryTurns, setChatbotHistoryTurns] = createSignal("10");
52+ const [maxChatbotThreads, setMaxChatbotThreads] = createSignal("50");
53+ const [maxChatbotMessageLen, setMaxChatbotMessageLen] = createSignal("4000");
54+ const [mealSlots, setMealSlots] = createSignal<MealSlot[]>([]);
55+ const [dietaryTags, setDietaryTags] = createSignal<string[]>([]);
56+ const [mealCutoff, setMealCutoff] = createSignal("");
48 const [error, setError] = createSignal("");57 const [error, setError] = createSignal("");
49 const [saved, setSaved] = createSignal(false);58 const [saved, setSaved] = createSignal(false);
50 const [pending, setPending] = createSignal(false);59 const [pending, setPending] = createSignal(false);
51- const [baseline, setBaseline] = createSignal("");60+ const [baseline, setBaseline] = createSignal<SchoolSettings | null>(null);
61+ const [limits, { refetch: refetchLimits }] = createResource(() => getLimits());
52 let savedTimer: number | undefined;62 let savedTimer: number | undefined;
53 63
54- const snapshot = () =>64+ const snapshot = (): SchoolSettings => ({
55- JSON.stringify({
56 exam_kinds: examKinds(),65 exam_kinds: examKinds(),
57 attendance_statuses: attendanceStatuses(),66 attendance_statuses: attendanceStatuses(),
58 grade_bands: gradeBands(),67 grade_bands: gradeBands(),
59 max_file_bytes: Math.round(Number(maxFileMiB()) * BYTES_PER_MIB),68 max_file_bytes: Math.round(Number(maxFileMiB()) * BYTES_PER_MIB),
69+ chatbot_history_turns: Number(chatbotHistoryTurns()),
70+ max_chatbot_threads: Number(maxChatbotThreads()),
71+ max_chatbot_message_len: Number(maxChatbotMessageLen()),
72+ meal_slots: mealSlots(),
73+ dietary_tags: dietaryTags(),
74+ meal_cancel_cutoff_minutes: mealCutoff() === "" ? null : Number(mealCutoff()),
60 });75 });
61 76
62 createEffect(() => {77 createEffect(() => {
@@ -67,17 +82,16 @@ function SettingsContent() {
67 setAttendanceStatuses([...next.attendance_statuses]);82 setAttendanceStatuses([...next.attendance_statuses]);
68 setGradeBands(next.grade_bands.map((item) => ({ ...item })));83 setGradeBands(next.grade_bands.map((item) => ({ ...item })));
69 setMaxFileMiB(String(Math.round((fileBytes / BYTES_PER_MIB) * 10) / 10));84 setMaxFileMiB(String(Math.round((fileBytes / BYTES_PER_MIB) * 10) / 10));
70- setBaseline(85+ setChatbotHistoryTurns(String(next.chatbot_history_turns));
71- JSON.stringify({86+ setMaxChatbotThreads(String(next.max_chatbot_threads));
72- exam_kinds: next.exam_kinds,87+ setMaxChatbotMessageLen(String(next.max_chatbot_message_len));
73- attendance_statuses: next.attendance_statuses,88+ setMealSlots(next.meal_slots.map((slot) => ({ ...slot })));
74- grade_bands: next.grade_bands,89+ setDietaryTags([...next.dietary_tags]);
75- max_file_bytes: fileBytes,90+ setMealCutoff(next.meal_cancel_cutoff_minutes == null ? "" : String(next.meal_cancel_cutoff_minutes));
76- }),91+ setBaseline({ ...next, max_file_bytes: fileBytes });
77- );
78 });92 });
79 93
80- const dirty = () => baseline() !== "" && snapshot() !== baseline();94+ const dirty = () => baseline() !== null && JSON.stringify(snapshot()) !== JSON.stringify(baseline());
81 95
82 createEffect(() => {96 createEffect(() => {
83 if (dirty() && saved()) setSaved(false);97 if (dirty() && saved()) setSaved(false);
@@ -93,21 +107,20 @@ function SettingsContent() {
93 }107 }
94 setPending(true);108 setPending(true);
95 try {109 try {
96- const next = await patchSettings({110+ const before = baseline();
111+ if (!before) return;
112+ const current = {
113+ ...snapshot(),
97 exam_kinds: examKinds().map((item) => ({ name: item.name.trim(), weight: Number(item.weight) })),114 exam_kinds: examKinds().map((item) => ({ name: item.name.trim(), weight: Number(item.weight) })),
98 attendance_statuses: attendanceStatuses().map((status) => status.trim()),115 attendance_statuses: attendanceStatuses().map((status) => status.trim()),
99 grade_bands: gradeBands().map((band) => ({ min: Number(band.min), label: band.label.trim() })),116 grade_bands: gradeBands().map((band) => ({ min: Number(band.min), label: band.label.trim() })),
100 max_file_bytes: maxFileBytes,117 max_file_bytes: maxFileBytes,
101- });118+ meal_slots: mealSlots().map((slot) => ({ ...slot, name: slot.name.trim() })),
119+ dietary_tags: dietaryTags().map((tag) => tag.trim()),
120+ };
121+ const next = await patchSettings(dirtySettingsPatch(before, current));
102 mutate(next);122 mutate(next);
103- setBaseline(123+ setBaseline(next);
104- JSON.stringify({
105- exam_kinds: next.exam_kinds,
106- attendance_statuses: next.attendance_statuses,
107- grade_bands: next.grade_bands,
108- max_file_bytes: next.max_file_bytes,
109- }),
110- );
111 setSaved(true);124 setSaved(true);
112 if (savedTimer) window.clearTimeout(savedTimer);125 if (savedTimer) window.clearTimeout(savedTimer);
113 savedTimer = window.setTimeout(() => setSaved(false), 3000);126 savedTimer = window.setTimeout(() => setSaved(false), 3000);
@@ -152,6 +165,9 @@ function SettingsContent() {
152 <Show when={error()}>165 <Show when={error()}>
153 <Alert variant="destructive">{error()}</Alert>166 <Alert variant="destructive">{error()}</Alert>
154 </Show>167 </Show>
168+ <Show when={limits.error}>
169+ <ErrorAlert message={formatApiError(limits.error)} onRetry={() => void refetchLimits()} />
170+ </Show>
155 171
156 <Suspense fallback={<PageSpinner />}>172 <Suspense fallback={<PageSpinner />}>
157 <Show when={settings.error}>173 <Show when={settings.error}>
@@ -175,8 +191,8 @@ function SettingsContent() {
175 aria-label={t("settings.maxFileSize")}191 aria-label={t("settings.maxFileSize")}
176 class="h-10 rounded-md text-right font-mono"192 class="h-10 rounded-md text-right font-mono"
177 type="number"193 type="number"
178- min={0.001}194+ min={(limits()?.file.min_max_file_bytes ?? 1024) / BYTES_PER_MIB}
179- max={25}195+ max={(limits()?.file.max_max_file_bytes ?? 25 * BYTES_PER_MIB) / BYTES_PER_MIB}
180 step={0.1}196 step={0.1}
181 value={maxFileMiB()}197 value={maxFileMiB()}
182 onInput={(event) => setMaxFileMiB(event.currentTarget.value)}198 onInput={(event) => setMaxFileMiB(event.currentTarget.value)}
@@ -184,6 +200,64 @@ function SettingsContent() {
184 </div>200 </div>
185 </section>201 </section>
186 202
203+ <div class="grid gap-4 xl:grid-cols-2">
204+ <section class="data-shell space-y-4 p-4">
205+ <div>
206+ <h2 class="font-display text-base font-semibold">{t("settings.aiPolicy")}</h2>
207+ <p class="mt-1 text-sm text-muted-foreground">{t("settings.aiPolicyHelp")}</p>
208+ </div>
209+ <div class="grid gap-3 sm:grid-cols-3">
210+ <div class="space-y-1.5">
211+ <Label for="chat-history">{t("settings.chatHistory")}</Label>
212+ <Input id="chat-history" type="number" min={limits()?.chatbot.min_history_turns} max={limits()?.chatbot.max_history_turns} value={chatbotHistoryTurns()} onInput={(e) => setChatbotHistoryTurns(e.currentTarget.value)} />
213+ </div>
214+ <div class="space-y-1.5">
215+ <Label for="chat-threads">{t("settings.chatThreads")}</Label>
216+ <Input id="chat-threads" type="number" min={limits()?.chatbot.min_max_threads} max={limits()?.chatbot.max_max_threads} value={maxChatbotThreads()} onInput={(e) => setMaxChatbotThreads(e.currentTarget.value)} />
217+ </div>
218+ <div class="space-y-1.5">
219+ <Label for="chat-message">{t("settings.chatMessage")}</Label>
220+ <Input id="chat-message" type="number" min={limits()?.chatbot.min_max_message_len} max={limits()?.chatbot.max_max_message_len} value={maxChatbotMessageLen()} onInput={(e) => setMaxChatbotMessageLen(e.currentTarget.value)} />
221+ </div>
222+ </div>
223+ </section>
224+
225+ <section class="data-shell space-y-4 p-4">
226+ <div>
227+ <h2 class="font-display text-base font-semibold">{t("settings.foodPolicy")}</h2>
228+ <p class="mt-1 text-sm text-muted-foreground">{t("settings.foodPolicyHelp")}</p>
229+ </div>
230+ <div class="space-y-1.5">
231+ <Label for="meal-cutoff">{t("settings.mealCutoff")}</Label>
232+ <Input id="meal-cutoff" type="number" min={0} max={limits()?.meal.max_cancel_cutoff_minutes} value={mealCutoff()} placeholder={t("settings.noCutoff")} onInput={(e) => setMealCutoff(e.currentTarget.value)} />
233+ </div>
234+ <div class="space-y-2">
235+ <For each={mealSlots()}>
236+ {(slot, index) => (
237+ <div class="grid grid-cols-[minmax(0,1fr)_8rem_2.25rem] gap-2">
238+ <Input aria-label={t("settings.mealSlot")} maxlength={limits()?.settings.max_item_len} value={slot.name} onInput={(e) => setMealSlots((rows) => rows.map((row, i) => i === index() ? { ...row, name: e.currentTarget.value } : row))} />
239+ <Input aria-label={t("settings.servingTimeUtc")} type="time" value={minuteToUtcTime(slot.serving_minute)} onInput={(e) => setMealSlots((rows) => rows.map((row, i) => i === index() ? { ...row, serving_minute: utcTimeToMinute(e.currentTarget.value) } : row))} />
240+ <Button type="button" variant="ghost" size="icon" aria-label={t("common.delete")} onClick={() => setMealSlots((rows) => rows.filter((_, i) => i !== index()))}><IconTrash class="h-4 w-4" /></Button>
241+ </div>
242+ )}
243+ </For>
244+ <Button type="button" variant="outline" size="sm" onClick={() => setMealSlots((rows) => [...rows, { name: "", serving_minute: null }])}><IconPlus class="h-4 w-4" />{t("settings.addMealSlot")}</Button>
245+ </div>
246+ <div class="space-y-2">
247+ <Label>{t("settings.dietaryTags")}</Label>
248+ <For each={dietaryTags()}>
249+ {(tag, index) => (
250+ <div class="flex gap-2">
251+ <Input aria-label={t("settings.dietaryTags")} maxlength={limits()?.settings.max_item_len} value={tag} onInput={(e) => setDietaryTags((rows) => rows.map((row, i) => i === index() ? e.currentTarget.value : row))} />
252+ <Button type="button" variant="ghost" size="icon" aria-label={t("common.delete")} onClick={() => setDietaryTags((rows) => rows.filter((_, i) => i !== index()))}><IconTrash class="h-4 w-4" /></Button>
253+ </div>
254+ )}
255+ </For>
256+ <Button type="button" variant="outline" size="sm" onClick={() => setDietaryTags((rows) => [...rows, ""])}><IconPlus class="h-4 w-4" />{t("settings.addDietaryTag")}</Button>
257+ </div>
258+ </section>
259+ </div>
260+
187 <div class="grid gap-4 xl:grid-cols-3">261 <div class="grid gap-4 xl:grid-cols-3">
188 <section class="data-shell flex flex-col overflow-hidden">262 <section class="data-shell flex flex-col overflow-hidden">
189 <header class="border-b border-border/70 px-4 py-3">263 <header class="border-b border-border/70 px-4 py-3">