diff --git a/src/components/meals/meal-menu-card.tsx b/src/components/meals/meal-menu-card.tsx new file mode 100644 index 0000000..f8798af --- /dev/null +++ b/src/components/meals/meal-menu-card.tsx @@ -0,0 +1,33 @@ +import { For, Show } from "solid-js"; +import { Link } from "@tanstack/solid-router"; +import type { MealMenu } from "@/api/client"; +import { Badge } from "@/components/ui/badge"; +import { IconAlert, IconUtensils } from "@/components/ui/icons"; +import { formatTry } from "@/lib/meals"; + +export function MealMenuCard(props: { menu: MealMenu; locale: string; labels: { dishes: string; capacity: string; conflict: string } }) { + const total = () => props.menu.dishes.reduce((sum, dish) => sum + dish.price_minor, 0); + const conflicts = () => [...new Set(props.menu.dishes.flatMap((dish) => dish.conflicts))]; + + return ( + +
+
+ +

{props.menu.slot}

+
+ {formatTry(total(), props.locale)} +
+
{(dish) => {dish.name}}
+ 0}> +
+ {props.labels.conflict}: {conflicts().join(", ")} +
+
+
+ {props.menu.dishes.length} {props.labels.dishes} + {props.labels.capacity}: {props.menu.capacity ?? "∞"} +
+ + ); +} diff --git a/src/components/ui/icons.tsx b/src/components/ui/icons.tsx index 1f522af..c4406d3 100644 --- a/src/components/ui/icons.tsx +++ b/src/components/ui/icons.tsx @@ -642,6 +642,18 @@ export function IconBriefcase(props: IconProps) { ); } +export function IconUtensils(props: IconProps) { + return ( + + + + + + + + ); +} + export function IconSearch(props: IconProps) { return ( @@ -725,4 +737,3 @@ export function IconBell(props: IconProps) { ); } - diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index 5ea19f8..e7ae9c5 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -284,7 +284,7 @@ export type MessageKey = | "dashboard.workloadSplit" | "dashboard.workloadSplitDesc" | "dashboard.deadlines" - | "dashboard.classSizes" + | "dashboard.courseCapacities" | "dashboard.courseAverages" | "dashboard.chartEmpty" | "dashboard.chartEmptyHint" @@ -308,18 +308,15 @@ export type MessageKey = | "dashboard.attend.excused" | "dashboard.welcomeBack" | "dashboard.welcomeHint" - | "dashboard.refresh" - | "dashboard.col.priority" - | "dashboard.priority.high" - | "dashboard.priority.medium" + | "dashboard.teachingResources" + | "dashboard.teachingResourcesDesc" + | "dashboard.questionBankDesc" + | "dashboard.questionPoolDesc" | "dashboard.quickReview.title" | "dashboard.quickReview.subtitle" | "dashboard.quickReview.placeholder" | "dashboard.quickReview.practice" | "dashboard.quickReview.startQuiz" - | "dashboard.questionHubDesc" - | "dashboard.questionHubPlaceholder" - | "dashboard.askQuestion" | "notes.title" | "notes.subtitle" | "notes.new" @@ -693,6 +690,7 @@ export type MessageKey = | "courses.title" | "courses.listTitle" | "courses.subtitle" + | "courses.pageSubtitle" | "courses.create" | "courses.empty" | "courses.enrolled" @@ -1020,6 +1018,7 @@ export type MessageKey = | "calendar.appointments" | "nav.appointments" | "appointments.title" + | "appointments.calendar" | "appointments.subtitle" | "appointments.empty" | "appointments.mySlots" @@ -1371,7 +1370,7 @@ const en: Dict = { "dashboard.workloadSplit": "Workload split", "dashboard.workloadSplitDesc": "Courses, exams, events, and more.", "dashboard.deadlines": "Upcoming deadlines", - "dashboard.classSizes": "Class sizes", + "dashboard.courseCapacities": "Course capacities", "dashboard.courseAverages": "Course averages", "dashboard.chartEmpty": "No records found", "dashboard.chartEmptyHint": "Not enough data to display yet.", @@ -1395,18 +1394,15 @@ const en: Dict = { "dashboard.attend.excused": "Excused", "dashboard.welcomeBack": "Welcome back, {name}!", "dashboard.welcomeHint": "Here's what needs your attention today.", - "dashboard.refresh": "Refresh data", - "dashboard.col.priority": "Priority", - "dashboard.priority.high": "High", - "dashboard.priority.medium": "Medium", + "dashboard.teachingResources": "Teaching resources", + "dashboard.teachingResourcesDesc": "Review reusable material and student questions.", + "dashboard.questionBankDesc": "Build and reuse question templates for exams.", + "dashboard.questionPoolDesc": "Review questions submitted by students.", "dashboard.quickReview.title": "Quick review", "dashboard.quickReview.subtitle": "Sharpen your knowledge in 2 minutes!", "dashboard.quickReview.placeholder": "Choose a topic to review…", "dashboard.quickReview.practice": "Practice", "dashboard.quickReview.startQuiz": "Start quiz", - "dashboard.questionHubDesc": "Browse the question bank or ask a question.", - "dashboard.questionHubPlaceholder": "Search the question bank…", - "dashboard.askQuestion": "Ask a question", "notes.title": "Notebook", "notes.subtitle": "Private scratchpad for class ideas and reminders.", "notes.new": "New note", @@ -1497,6 +1493,7 @@ const en: Dict = { "calendar.appointments": "Appointments", "nav.appointments": "Appointments", "appointments.title": "Appointments", + "appointments.calendar": "Appointment calendar", "appointments.subtitle": "Book a meeting with a teacher, or publish times you are available.", "appointments.empty": "No appointments yet.", "appointments.mySlots": "My available times", @@ -1865,6 +1862,7 @@ const en: Dict = { "courses.title": "Education", "courses.listTitle": "{item} records", "courses.subtitle": "Manage {item}, enrollment, and exams here.", + "courses.pageSubtitle": "Classes, study groups, and clubs in one place.", "courses.create": "New education item", "courses.empty": "No {item} yet.", "courses.enrolled": "Enrolled", @@ -2277,7 +2275,7 @@ const tr: Dict = { "common.approve": "Onayla", "common.reject": "Reddet", "common.actions": "İşlemler", - "common.columns": "Kolonlar", + "common.columns": "Sütunlar", "common.moreFilters": "Daha fazla filtre", "common.lessFilters": "Daha az filtre", "common.search": "Ara", @@ -2470,7 +2468,7 @@ const tr: Dict = { "dashboard.workloadSplit": "İş yükü dağılımı", "dashboard.workloadSplitDesc": "Dersler, sınavlar, etkinlikler ve dahası.", "dashboard.deadlines": "Yaklaşan son tarihler", - "dashboard.classSizes": "Sınıf mevcutları", + "dashboard.courseCapacities": "Eğitim kapasiteleri", "dashboard.courseAverages": "Ders ortalamaları", "dashboard.chartEmpty": "Kayıt bulunamadı", "dashboard.chartEmptyHint": "Gösterilecek yeterli veri yok.", @@ -2494,18 +2492,15 @@ const tr: Dict = { "dashboard.attend.excused": "İzinli", "dashboard.welcomeBack": "Tekrar hoş geldin, {name}!", "dashboard.welcomeHint": "Bugün dikkat etmen gerekenler burada.", - "dashboard.refresh": "Verileri yenile", - "dashboard.col.priority": "Öncelik", - "dashboard.priority.high": "Yüksek", - "dashboard.priority.medium": "Orta", + "dashboard.teachingResources": "Öğretim kaynakları", + "dashboard.teachingResourcesDesc": "Yeniden kullanılabilir içerikleri ve öğrenci sorularını incele.", + "dashboard.questionBankDesc": "Sınavlar için soru şablonları oluştur ve yeniden kullan.", + "dashboard.questionPoolDesc": "Öğrencilerin gönderdiği soruları incele.", "dashboard.quickReview.title": "Hızlı tekrar", "dashboard.quickReview.subtitle": "2 dakikada bilgini tazele!", "dashboard.quickReview.placeholder": "Tekrar için konu seç…", "dashboard.quickReview.practice": "Alıştır", "dashboard.quickReview.startQuiz": "Teste başla", - "dashboard.questionHubDesc": "Soru havuzuna göz at ya da soru sor.", - "dashboard.questionHubPlaceholder": "Soru havuzunda ara…", - "dashboard.askQuestion": "Soru sor", "notes.title": "Defter", "notes.subtitle": "Ders fikirleri ve hatırlatmalar için özel defter.", "notes.new": "Yeni not", @@ -2596,6 +2591,7 @@ const tr: Dict = { "calendar.appointments": "Randevular", "nav.appointments": "Randevular", "appointments.title": "Randevular", + "appointments.calendar": "Randevu takvimi", "appointments.subtitle": "Bir öğretmenle görüşme ayarlayın ya da uygun olduğunuz saatleri yayımlayın.", "appointments.empty": "Henüz randevu yok.", "appointments.mySlots": "Uygun saatlerim", @@ -2964,6 +2960,7 @@ const tr: Dict = { "courses.title": "Eğitim", "courses.listTitle": "{item} kayıtları", "courses.subtitle": "{item}, kayıtlar ve sınavlar burada.", + "courses.pageSubtitle": "Dersler, etütler ve kulüpler tek yerde.", "courses.create": "Yeni eğitim kaydı", "courses.empty": "Henüz {item} yok.", "courses.enrolled": "Kayıtlı", diff --git a/src/lib/meals.test.ts b/src/lib/meals.test.ts new file mode 100644 index 0000000..2425e2a --- /dev/null +++ b/src/lib/meals.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; +import type { SchoolSettings } from "@/api/client"; +import { dirtySettingsPatch, formatTry, mealCutoffAt, minuteToUtcTime, nextCourseWork, utcTimeToMinute } from "./meals"; + +describe("meal helpers", () => { + it("formats minor units as TRY", () => { + expect(formatTry(4550, "tr-TR")).toContain("45,50"); + }); + + it("converts UTC minute values", () => { + expect(minuteToUtcTime(540)).toBe("09:00"); + expect(utcTimeToMinute("23:59")).toBe(1439); + expect(utcTimeToMinute("24:00")).toBeNull(); + }); + + it("calculates the booking cutoff in UTC", () => { + expect(mealCutoffAt("2026-07-28", { name: "lunch", serving_minute: 720 }, 120)) + .toBe(Date.parse("2026-07-28T10:00:00Z")); + }); + + it("selects nearest course work", () => { + expect(nextCourseWork( + "c1", + [{ course: "c1", title: "Exam", starts_at: 30 } as never], + [{ course: "c1", title: "Homework", due_at: 20 } as never], + )?.title).toBe("Homework"); + }); + + it("builds a field-only settings patch", () => { + const before = { + exam_kinds: [], attendance_statuses: [], grade_bands: [], max_file_bytes: 1, + chatbot_history_turns: 1, max_chatbot_threads: 1, max_chatbot_message_len: 100, + meal_slots: [], dietary_tags: [], meal_cancel_cutoff_minutes: null, + } satisfies SchoolSettings; + expect(dirtySettingsPatch(before, { ...before, max_chatbot_threads: 2 })).toEqual({ max_chatbot_threads: 2 }); + }); +}); diff --git a/src/lib/meals.ts b/src/lib/meals.ts new file mode 100644 index 0000000..551472f --- /dev/null +++ b/src/lib/meals.ts @@ -0,0 +1,50 @@ +import type { Exam, Homework, MealSlot, SchoolSettings } from "@/api/client"; +import type { PatchSettingsBody } from "@/api/settings"; + +export function formatTry(minor: number, locale: string): string { + return new Intl.NumberFormat(locale, { style: "currency", currency: "TRY" }).format(minor / 100); +} + +export function minuteToUtcTime(minute: number | null): string { + if (minute == null) return ""; + return `${String(Math.floor(minute / 60)).padStart(2, "0")}:${String(minute % 60).padStart(2, "0")}`; +} + +export function utcTimeToMinute(value: string): number | null { + const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value); + return match ? Number(match[1]) * 60 + Number(match[2]) : null; +} + +export function mealCutoffAt(date: string, slot: MealSlot | undefined, minutes: number | null): number | null { + if (minutes == null) return null; + const servingMinute = slot?.serving_minute ?? 0; + return Date.parse(`${date}T00:00:00Z`) + servingMinute * 60_000 - minutes * 60_000; +} + +export function nextCourseWork(courseId: string, exams: Exam[], homework: Homework[]) { + return [ + ...exams.filter((item) => item.course === courseId).map((item) => ({ kind: "exam" as const, title: item.title, at: item.starts_at ?? item.ends_at })), + ...homework.filter((item) => item.course === courseId).map((item) => ({ kind: "homework" as const, title: item.title, at: item.due_at })), + ] + .filter((item): item is { kind: "exam" | "homework"; title: string; at: number } => item.at != null) + .sort((a, b) => a.at - b.at)[0] ?? null; +} + +export function dirtySettingsPatch(before: SchoolSettings, after: SchoolSettings): PatchSettingsBody { + const patch: PatchSettingsBody = {}; + for (const key of [ + "exam_kinds", + "attendance_statuses", + "grade_bands", + "max_file_bytes", + "chatbot_history_turns", + "max_chatbot_threads", + "max_chatbot_message_len", + "meal_slots", + "dietary_tags", + "meal_cancel_cutoff_minutes", + ] as const) { + if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) patch[key] = after[key] as never; + } + return patch; +} diff --git a/src/pages/meal-detail-page.tsx b/src/pages/meal-detail-page.tsx new file mode 100644 index 0000000..2b8938e --- /dev/null +++ b/src/pages/meal-detail-page.tsx @@ -0,0 +1,275 @@ +import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal } from "solid-js"; +import { Link, useLocation, useNavigate, useParams } from "@tanstack/solid-router"; +import { getLimits } from "@/api/limits"; +import { + deleteMealBookingById, + deleteMealDishById, + deleteMealMenuById, + getDietaryProfileByUserId, + getMealAttendanceByUserId, + getMealBalanceByUserId, + getMealLedgerByUserId, + getMealMenuBookings, + getMealMenuById, + getMealServiceRoster, + getMyDietaryProfile, + getMyMealBalance, + getMyMealBookings, + patchDietaryProfileByUserId, + patchMealDishById, + patchMealMenuById, + postMealAttendance, + postMealBooking, + postMealCredit, + postMealDish, +} from "@/api/meals"; +import { getMyStudents } from "@/api/parents"; +import { getSettings } from "@/api/settings"; +import { getTime } from "@/api/time"; +import { formatApiError, type MealDish } from "@/api/client"; +import { PageHeader } from "@/components/layout/page-header"; +import { RouteGuard } from "@/components/layout/route-guard"; +import { Alert } from "@/components/ui/alert"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { EmptyState } from "@/components/ui/empty-state"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconAlert, IconChevronLeft, IconEdit, IconPlus, IconTrash } from "@/components/ui/icons"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { Select } from "@/components/ui/select"; +import { SidePanel } from "@/components/ui/side-panel"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Textarea } from "@/components/ui/textarea"; +import { UserSearchSelect } from "@/components/users/user-search-select"; +import { formatDateTime } from "@/lib/format"; +import { formatTry, mealCutoffAt } from "@/lib/meals"; +import { personLabel } from "@/lib/person"; +import { hasMinRole } from "@/lib/roles"; +import { useAuth } from "@/stores/auth-context"; +import { usePreferences, useT } from "@/stores/preferences-context"; + +export default function MealDetailPage() { + return ; +} + +function MealDetailContent() { + const auth = useAuth(); + const t = useT(); + const { locale } = usePreferences(); + const navigate = useNavigate(); + const location = useLocation(); + const params = useParams({ from: "/meals/$id" }); + const id = createMemo(() => { location(); return params().id; }); + const role = () => auth.user()!.role; + const isStudent = () => role() === "student"; + const isParent = () => role() === "parent"; + const canServe = () => hasMinRole(role(), "teacher"); + const canManage = () => hasMinRole(role(), "manager"); + const isAdmin = () => role() === "admin"; + const moneyLocale = () => locale() === "tr" ? "tr-TR" : "en-US"; + + const [menu, { refetch: refetchMenu }] = createResource(id, (menuId) => getMealMenuById(menuId)); + const [settings] = createResource(() => getSettings()); + const [limits, { refetch: refetchLimits }] = createResource(() => getLimits()); + const [serverTime] = createResource(() => getTime().catch(() => ({ now: Date.now() }))); + const [children] = createResource(() => isParent() ? getMyStudents({ limit: 100 }) : null); + const [selectedStudent, setSelectedStudent] = createSignal(""); + const [lookupStudent, setLookupStudent] = createSignal(""); + const [tab, setTab] = createSignal("menu"); + const [error, setError] = createSignal(""); + const [success, setSuccess] = createSignal(""); + const [pending, setPending] = createSignal(false); + const [cancelOpen, setCancelOpen] = createSignal(false); + const [deleteMenuOpen, setDeleteMenuOpen] = createSignal(false); + const [deleteDish, setDeleteDish] = createSignal(null); + + createEffect(() => { + if (isParent() && !selectedStudent() && children()?.items[0]) setSelectedStudent(children()!.items[0].id); + }); + const targetId = () => isStudent() ? auth.user()!.id : isParent() ? selectedStudent() : lookupStudent(); + const canBook = () => (isStudent() || isParent()) && !!targetId(); + + const [bookings, { refetch: refetchBookings }] = createResource(() => canBook(), async (enabled) => enabled ? getMyMealBookings({ limit: 100 }) : null); + const activeBooking = createMemo(() => bookings()?.items.find((booking) => booking.menu_id === id() && booking.student.id === targetId() && booking.status === "booked") ?? null); + const [profile, { refetch: refetchProfile }] = createResource( + targetId, + async (userId) => userId === auth.user()!.id ? getMyDietaryProfile() : getDietaryProfileByUserId(userId), + ); + const [balance, { refetch: refetchBalance }] = createResource( + targetId, + async (userId) => userId === auth.user()!.id ? getMyMealBalance() : getMealBalanceByUserId(userId), + ); + const [ledger, { refetch: refetchLedger }] = createResource(targetId, (userId) => getMealLedgerByUserId(userId, { limit: 20 })); + const [attendance] = createResource(targetId, (userId) => getMealAttendanceByUserId(userId, { limit: 20 })); + const [service, { refetch: refetchService }] = createResource( + () => canServe() ? id() : null, + (menuId) => getMealServiceRoster(menuId, { limit: 100 }), + ); + const [audit] = createResource( + () => canManage() ? id() : null, + (menuId) => getMealMenuBookings(menuId, { limit: 100 }), + ); + + const total = () => menu()?.dishes.reduce((sum, dish) => sum + dish.price_minor, 0) ?? 0; + const conflicts = () => [...new Set(menu()?.dishes.flatMap((dish) => dish.conflicts) ?? [])]; + const slot = () => settings()?.meal_slots.find((item) => item.name === menu()?.slot); + const cutoff = () => menu() ? mealCutoffAt(menu()!.date, slot(), settings()?.meal_cancel_cutoff_minutes ?? null) : null; + const cutoffClosed = () => cutoff() != null && (serverTime()?.now ?? Date.now()) >= cutoff()!; + + const [capacity, setCapacity] = createSignal(""); + const [showMenuEdit, setShowMenuEdit] = createSignal(false); + const [showDishForm, setShowDishForm] = createSignal(false); + const [editingDish, setEditingDish] = createSignal(null); + const [dishName, setDishName] = createSignal(""); + const [dishDescription, setDishDescription] = createSignal(""); + const [dishPrice, setDishPrice] = createSignal(""); + const [dishTags, setDishTags] = createSignal([]); + const [profileTags, setProfileTags] = createSignal([]); + const [profileNote, setProfileNote] = createSignal(""); + const [creditAmount, setCreditAmount] = createSignal(""); + const [creditMethod, setCreditMethod] = createSignal(""); + const [creditNote, setCreditNote] = createSignal(""); + const [walkIn, setWalkIn] = createSignal(""); + + createEffect(() => { + if (profile()) { setProfileTags([...profile()!.tags]); setProfileNote(profile()!.note ?? ""); } + }); + const run = async (work: () => Promise, message = t("common.saved")) => { + setPending(true); setError(""); setSuccess(""); + try { await work(); setSuccess(message); } + catch (err) { setError(formatApiError(err)); } + finally { setPending(false); } + }; + const openDish = (dish?: MealDish) => { + setEditingDish(dish ?? null); + setDishName(dish?.name ?? ""); setDishDescription(dish?.description ?? ""); + setDishPrice(dish ? String(dish.price_minor / 100) : ""); setDishTags(dish?.tags ?? []); + setShowDishForm(true); + }; + const toggleTag = (tag: string, selected: string[], set: (value: string[]) => void) => + set(selected.includes(tag) ? selected.filter((item) => item !== tag) : [...selected, tag]); + + return ( + }> + }> void refetchMenu()} />}> + {(current) => ( +
+
} + /> + void refetchLimits()} /> + {error()} + {success()} + +
+

{t("meals.total")}

{formatTry(total(), moneyLocale())}

+

{t("meals.capacity")}

{current().capacity ?? "∞"}

+

{t("meals.cutoff")}

{cutoff() == null ? t("meals.noCutoff") : formatDateTime(cutoff(), locale())}

+

{t("meals.bookingStatus")}

{cutoffClosed() ? t("meals.closed") : t("meals.open")}

+
+ + 0}> + {t("meals.conflict")}: {conflicts().join(", ")} + + + +
+
+ + + + {t("meals.menu")} + {t("meals.myAccount")} + {t("meals.service")} + {t("meals.manage")} + + + +
+ {(dish) => ( +
+

{dish.name}

{formatTry(dish.price_minor, moneyLocale())}
+

{dish.description || "—"}

+
{(tag) => {dish.conflicts.includes(tag) ? `⚠ ${tag}` : tag}}
+
+
+ )}
+
+ + +
+

{activeBooking() ? t("meals.booked") : t("meals.notBooked")}

{cutoffClosed() ? t("meals.cutoffPassed") : t("meals.bookingHelp")}

+ void run(async () => { await postMealBooking(id(), isParent() ? targetId() : undefined); await Promise.all([refetchBookings(), refetchBalance(), refetchLedger()]); }, t("meals.booked"))}>{t("meals.book")}}> +
+
+
+ + +
+

{t("meals.dietaryProfile")}

{(tag) => ⚠ {tag}}

{profile()?.note || t("meals.noDietaryNotes")}

+

{t("meals.balance")}

{formatTry(balance()?.balance_minor ?? 0, moneyLocale())}

+
+

{t("meals.ledger")}

{(line) =>

{t(`meals.ledger.${line.kind}` as never)}

{line.note || line.method || "—"} · {formatDateTime(line.created_at, locale())}

{line.kind === "charge" ? "−" : "+"}{formatTry(line.amount_minor, moneyLocale())}
}

{t("meals.noLedger")}

+

{t("meals.attendance")}

{(row) =>
{row.status}{formatDateTime(row.marked_at, locale())}
}
+
+ + +
+

{t("meals.walkIn")}

+
+
+ void refetchService()} /> +
+ {(entry) =>

{personLabel(entry.student)}

{entry.booking ? t("meals.booked") : t("meals.walkIn")} · {entry.attendance?.status ?? t("meals.notMarked")}

}
+
+
+ + +
+
+

{t("meals.studentRecord")}

+ + +
+
{(tag) => }
+