forge
Explore
Log in

Don't you dare go Hollow

🔗 align frontend with backend delta dd4f66d..f12af3a (phase 1)

Browse files at this commit

45cbc34535ea911e428d2e0d9215a42547290a0aBurak BoduroğluParent: 1290f39
  • fix
    • 🔗 align frontend with backend delta dd4f66d..f12af3a (phase 1)
Show full message
fix: 🔗 align frontend with backend delta dd4f66d..f12af3a (phase 1)
- appointments: reschedule/accept now sends the pinned proposal window
  {proposed_starts_at, proposed_ends_at}; guards null proposals and the
  api test asserts the body
- types: Enrollment gains source (the class that pumped the row, or null);
  Limits.course gains max_class_{name_len,grade_len,members,courses,bytes}
- settings: block new meal-slot names containing / \ ? # % (grandfather
  already-saved names); backend 409s still surface via formatApiError
- meals: canteen balance/ledger reads are manager+ now — hide those
  sections and skip the fetch for plain teachers (self/parent/manager keep)
- exams: self-review degrades to a friendly banner instead of erroring
  when the caller's latest sitting is still in progress (409)
src/api/__tests__/appointments/appointments.test.tsmodified+3 -1
@@ -168,12 +168,14 @@ describe("appointments API", () => {
168 const mockAppt = { id: "a1" };168 const mockAppt = { id: "a1" };
169 mockFetchSuccess(mockAppt);169 mockFetchSuccess(mockAppt);
170 170
171- const result = await patchAcceptReschedule("a1");171+ const body = { proposed_starts_at: 1000, proposed_ends_at: 2000 };
172+ const result = await patchAcceptReschedule("a1", body);
172 expect(result).toEqual(mockAppt);173 expect(result).toEqual(mockAppt);
173 174
174 const [url, init] = lastFetchCall();175 const [url, init] = lastFetchCall();
175 expect(url).toBe("/api/appointments/a1/reschedule/accept");176 expect(url).toBe("/api/appointments/a1/reschedule/accept");
176 expect(init?.method).toBe("PATCH");177 expect(init?.method).toBe("PATCH");
178+ expect(init?.body).toBe(JSON.stringify(body));
177 });179 });
178 180
179 it("patchDeclineReschedule calls /appointments/:id/reschedule/decline", async () => {181 it("patchDeclineReschedule calls /appointments/:id/reschedule/decline", async () => {
src/api/appointments/patchAcceptReschedule.tsmodified+6 -2
@@ -1,6 +1,10 @@
1 import { client } from "../client";1 import { client } from "../client";
2 import type { Appointment } from "../client";2 import type { Appointment } from "../client";
3 3
4-export function patchAcceptReschedule(id: string): Promise<Appointment> {4+// The backend pins which proposal is being accepted: the caller echoes the
5- return client<Appointment>(`/appointments/${id}/reschedule/accept`, { method: "PATCH" });5+// proposed window it read, and a superseded proposal returns 409.
6+export type AcceptRescheduleBody = { proposed_starts_at: number; proposed_ends_at: number };
7+
8+export function patchAcceptReschedule(id: string, body: AcceptRescheduleBody): Promise<Appointment> {
9+ return client<Appointment>(`/appointments/${id}/reschedule/accept`, { method: "PATCH", body });
6 }10 }
src/api/client/types.tsmodified+9 -0
@@ -159,6 +159,10 @@ export type Enrollment = {
159 course: string;159 course: string;
160 user: PersonRef;160 user: PersonRef;
161 enrolled_by: PersonRef;161 enrolled_by: PersonRef;
162+ // The class (ClassGroup id) that pumped this enrollment, or null for a
163+ // hand-placed row. A row with a source is swept when that class drops the
164+ // student or detaches the course; a null row is permanent.
165+ source: string | null;
162 };166 };
163 167
164 export type CourseSession = {168 export type CourseSession = {
@@ -492,6 +496,11 @@ export type Limits = {
492 max_subject_description_len: number;496 max_subject_description_len: number;
493 max_session_topic_len: number;497 max_session_topic_len: number;
494 max_term_name_len: number;498 max_term_name_len: number;
499+ max_class_name_len: number;
500+ max_class_grade_len: number;
501+ max_class_members: number;
502+ max_class_courses: number;
503+ max_class_bytes: number;
495 };504 };
496 exam: {505 exam: {
497 max_title_len: number;506 max_title_len: number;
src/components/exams/answer-sheet-view.tsxmodified+16 -2
@@ -22,6 +22,11 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
22 // /review routes (no userId in path). Everything below is identical either way.22 // /review routes (no userId in path). Everything below is identical either way.
23 const mode = () => props.mode ?? "grader";23 const mode = () => props.mode ?? "grader";
24 24
25+ // Self-review reads 409 while the caller's latest sitting is still in
26+ // progress — a retake must submit before it can read the answer key. We
27+ // degrade to a friendly banner instead of erroring the panel.
28+ const [reviewInProgress, setReviewInProgress] = createSignal(false);
29+
25 // Which sitting the grader is viewing. null = the latest (grade-of-record), the default.30 // Which sitting the grader is viewing. null = the latest (grade-of-record), the default.
26 const [selectedSeq, setSelectedSeq] = createSignal<number | null>(null);31 const [selectedSeq, setSelectedSeq] = createSignal<number | null>(null);
27 // Switch sittings inside a transition so the current sheet stays on screen32 // Switch sittings inside a transition so the current sheet stays on screen
@@ -34,10 +39,15 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
34 const [attempts] = createResource(39 const [attempts] = createResource(
35 () => [props.examId, props.userId] as const,40 () => [props.examId, props.userId] as const,
36 async ([examId, userId]) => {41 async ([examId, userId]) => {
42+ if (mode() === "self") setReviewInProgress(false);
37 try {43 try {
38 return mode() === "self" ? await getExamReviewAttempts(examId) : await getStudentAttempts(examId, userId);44 return mode() === "self" ? await getExamReviewAttempts(examId) : await getStudentAttempts(examId, userId);
39 } catch (err) {45 } catch (err) {
40 if (err instanceof ApiError && err.status === 404) return [] as number[];46 if (err instanceof ApiError && err.status === 404) return [] as number[];
47+ if (mode() === "self" && err instanceof ApiError && err.status === 409) {
48+ setReviewInProgress(true);
49+ return [] as number[];
50+ }
41 throw err;51 throw err;
42 }52 }
43 },53 },
@@ -94,7 +104,8 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
94 : await getStudentAttemptAnswers(examId, userId, seq);104 : await getStudentAttemptAnswers(examId, userId, seq);
95 }105 }
96 } catch (err) {106 } catch (err) {
97- if (err instanceof ApiError && err.status === 404) {107+ if (err instanceof ApiError && (err.status === 404 || (mode() === "self" && err.status === 409))) {
108+ if (mode() === "self" && err instanceof ApiError && err.status === 409) setReviewInProgress(true);
98 sheet = {109 sheet = {
99 exam: examId,110 exam: examId,
100 user: { id: userId, username: userId, display_name: null },111 user: { id: userId, username: userId, display_name: null },
@@ -136,6 +147,9 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
136 // unmount and its portalled menu would flash unpositioned (top-left) on147 // unmount and its portalled menu would flash unpositioned (top-left) on
137 // every select. Only the answer sheet suspends.148 // every select. Only the answer sheet suspends.
138 <div class="space-y-4">149 <div class="space-y-4">
150+ <Show when={reviewInProgress()}>
151+ <p class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-sm text-muted-foreground">{t("exams.reviewInProgress")}</p>
152+ </Show>
139 <Show when={(attempts() ?? []).length > 1}>153 <Show when={(attempts() ?? []).length > 1}>
140 <div class="flex flex-col gap-1.5">154 <div class="flex flex-col gap-1.5">
141 <span class="text-xs font-medium text-muted-foreground">{t("exams.previousAttempts")}</span>155 <span class="text-xs font-medium text-muted-foreground">{t("exams.previousAttempts")}</span>
@@ -148,7 +162,7 @@ export function AnswerSheetView(props: { examId: string; userId: string; mode?:
148 </div>162 </div>
149 </Show>163 </Show>
150 <Suspense fallback={<PageSpinner />}>164 <Suspense fallback={<PageSpinner />}>
151- <Show when={data()}>165+ <Show when={!reviewInProgress() && data()}>
152 {(d) => (166 {(d) => (
153 <div class={cn("space-y-4 transition-opacity", switching() && "opacity-60")}>167 <div class={cn("space-y-4 transition-opacity", switching() && "opacity-60")}>
154 <Show when={!isLatest()}>168 <Show when={!isLatest()}>
src/i18n/messages.tsmodified+6 -0
@@ -816,6 +816,7 @@ export type MessageKey =
816 | "exams.attemptN"816 | "exams.attemptN"
817 | "exams.currentAttempt"817 | "exams.currentAttempt"
818 | "exams.pastAttemptReadOnly"818 | "exams.pastAttemptReadOnly"
819+ | "exams.reviewInProgress"
819 | "exams.uploadAnswerImage"820 | "exams.uploadAnswerImage"
820 | "exams.playDrawing"821 | "exams.playDrawing"
821 | "exams.showImage"822 | "exams.showImage"
@@ -870,6 +871,7 @@ export type MessageKey =
870 | "settings.maxFileSize"871 | "settings.maxFileSize"
871 | "settings.maxFileSizeHelp"872 | "settings.maxFileSizeHelp"
872 | "settings.maxFileSizeInvalid"873 | "settings.maxFileSizeInvalid"
874+ | "settings.mealSlotNameInvalid"
873 | "settings.aiPolicy"875 | "settings.aiPolicy"
874 | "settings.aiPolicyHelp"876 | "settings.aiPolicyHelp"
875 | "settings.chatHistory"877 | "settings.chatHistory"
@@ -2123,6 +2125,7 @@ const en: Dict = {
2123 "exams.attemptN": "Attempt {n}",2125 "exams.attemptN": "Attempt {n}",
2124 "exams.currentAttempt": "current",2126 "exams.currentAttempt": "current",
2125 "exams.pastAttemptReadOnly": "Viewing a previous attempt — read-only. Grading applies to the current attempt.",2127 "exams.pastAttemptReadOnly": "Viewing a previous attempt — read-only. Grading applies to the current attempt.",
2128+ "exams.reviewInProgress": "Submit your current attempt before you can review it.",
2126 "exams.uploadAnswerImage": "Upload image",2129 "exams.uploadAnswerImage": "Upload image",
2127 "exams.playDrawing": "Play drawing",2130 "exams.playDrawing": "Play drawing",
2128 "exams.showImage": "Show image",2131 "exams.showImage": "Show image",
@@ -2177,6 +2180,7 @@ const en: Dict = {
2177 "settings.maxFileSize": "Max note file size",2180 "settings.maxFileSize": "Max note file size",
2178 "settings.maxFileSizeHelp": "Per-file upload cap for note attachments, in MiB. Backend accepts 0.001-25 MiB.",2181 "settings.maxFileSizeHelp": "Per-file upload cap for note attachments, in MiB. Backend accepts 0.001-25 MiB.",
2179 "settings.maxFileSizeInvalid": "Enter a valid file size.",2182 "settings.maxFileSizeInvalid": "Enter a valid file size.",
2183+ "settings.mealSlotNameInvalid": "A meal slot name can't contain / \\ ? # or %.",
2180 "settings.aiPolicy": "AI policy",2184 "settings.aiPolicy": "AI policy",
2181 "settings.aiPolicyHelp": "Limits for conversation context, threads, and message length.",2185 "settings.aiPolicyHelp": "Limits for conversation context, threads, and message length.",
2182 "settings.chatHistory": "History turns",2186 "settings.chatHistory": "History turns",
@@ -3356,6 +3360,7 @@ const tr: Dict = {
3356 "exams.attemptN": "{n}. deneme",3360 "exams.attemptN": "{n}. deneme",
3357 "exams.currentAttempt": "güncel",3361 "exams.currentAttempt": "güncel",
3358 "exams.pastAttemptReadOnly": "Önceki bir deneme görüntüleniyor — salt okunur. Puanlama güncel denemeye uygulanır.",3362 "exams.pastAttemptReadOnly": "Önceki bir deneme görüntüleniyor — salt okunur. Puanlama güncel denemeye uygulanır.",
3363+ "exams.reviewInProgress": "İncelemek için önce mevcut denemeni gönder.",
3359 "exams.uploadAnswerImage": "Görsel yükle",3364 "exams.uploadAnswerImage": "Görsel yükle",
3360 "exams.playDrawing": "Çizimi oynat",3365 "exams.playDrawing": "Çizimi oynat",
3361 "exams.showImage": "Görseli göster",3366 "exams.showImage": "Görseli göster",
@@ -3410,6 +3415,7 @@ const tr: Dict = {
3410 "settings.maxFileSize": "Not dosyası boyut sınırı",3415 "settings.maxFileSize": "Not dosyası boyut sınırı",
3411 "settings.maxFileSizeHelp": "Not ekleri için dosya başına yükleme sınırı, MiB cinsinden. Backend 0.001-25 MiB kabul eder.",3416 "settings.maxFileSizeHelp": "Not ekleri için dosya başına yükleme sınırı, MiB cinsinden. Backend 0.001-25 MiB kabul eder.",
3412 "settings.maxFileSizeInvalid": "Geçerli bir dosya boyutu gir.",3417 "settings.maxFileSizeInvalid": "Geçerli bir dosya boyutu gir.",
3418+ "settings.mealSlotNameInvalid": "Öğün adı / \\ ? # veya % içeremez.",
3413 "settings.aiPolicy": "Yapay zekâ politikası",3419 "settings.aiPolicy": "Yapay zekâ politikası",
3414 "settings.aiPolicyHelp": "Konuşma bağlamı, konu sayısı ve mesaj uzunluğu sınırları.",3420 "settings.aiPolicyHelp": "Konuşma bağlamı, konu sayısı ve mesaj uzunluğu sınırları.",
3415 "settings.chatHistory": "Geçmiş turu",3421 "settings.chatHistory": "Geçmiş turu",
src/pages/appointments-page.tsxmodified+1 -1
@@ -355,7 +355,7 @@ function AppointmentsContent() {
355 const a = cell.row.original;355 const a = cell.row.original;
356 const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];356 const actions = [] as { label: string; icon: import("solid-js").JSX.Element; destructive?: boolean; onSelect: () => void }[];
357 for (const action of appointmentActions(a, "requester", now())) {357 for (const action of appointmentActions(a, "requester", now())) {
358- if (action === "acceptReschedule") actions.push({ label: t("appointments.acceptReschedule"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchAcceptReschedule(a.id), "appointments.status.approved") });358+ if (action === "acceptReschedule" && a.proposed_starts_at != null && a.proposed_ends_at != null) actions.push({ label: t("appointments.acceptReschedule"), icon: <IconCheck class="h-4 w-4" />, onSelect: () => void act(() => patchAcceptReschedule(a.id, { proposed_starts_at: a.proposed_starts_at!, proposed_ends_at: a.proposed_ends_at! }), "appointments.status.approved") });
359 if (action === "declineReschedule") actions.push({ label: t("appointments.declineReschedule"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel(() => patchDeclineReschedule(a.id), false) });359 if (action === "declineReschedule") actions.push({ label: t("appointments.declineReschedule"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel(() => patchDeclineReschedule(a.id), false) });
360 if (action === "cancel") actions.push({ label: t("appointments.cancel"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) });360 if (action === "cancel") actions.push({ label: t("appointments.cancel"), icon: <IconX class="h-4 w-4" />, destructive: true, onSelect: () => askCancel((reason) => patchCancelAppointment(a.id, reason ? { reason } : undefined)) });
361 }361 }
src/pages/meal-detail-page.tsxmodified+7 -4
@@ -68,6 +68,9 @@ function MealDetailContent() {
68 const isParent = () => role() === "parent";68 const isParent = () => role() === "parent";
69 const canServe = () => hasMinRole(role(), "teacher");69 const canServe = () => hasMinRole(role(), "teacher");
70 const canManage = () => hasMinRole(role(), "manager");70 const canManage = () => hasMinRole(role(), "manager");
71+ // Canteen balance/ledger are family-money reads: self, a parent of the
72+ // student, or manager+. Teachers are no longer allowed (backend 403s).
73+ const canReadMoney = () => isStudent() || isParent() || canManage();
71 const isAdmin = () => role() === "admin";74 const isAdmin = () => role() === "admin";
72 const moneyLocale = () => locale() === "tr" ? "tr-TR" : "en-US";75 const moneyLocale = () => locale() === "tr" ? "tr-TR" : "en-US";
73 76
@@ -99,10 +102,10 @@ function MealDetailContent() {
99 async (userId) => userId === auth.user()!.id ? getMyDietaryProfile() : getDietaryProfileByUserId(userId),102 async (userId) => userId === auth.user()!.id ? getMyDietaryProfile() : getDietaryProfileByUserId(userId),
100 );103 );
101 const [balance, { refetch: refetchBalance }] = createResource(104 const [balance, { refetch: refetchBalance }] = createResource(
102- targetId,105+ () => canReadMoney() ? targetId() : null,
103 async (userId) => userId === auth.user()!.id ? getMyMealBalance() : getMealBalanceByUserId(userId),106 async (userId) => userId === auth.user()!.id ? getMyMealBalance() : getMealBalanceByUserId(userId),
104 );107 );
105- const [ledger, { refetch: refetchLedger }] = createResource(targetId, (userId) => getMealLedgerByUserId(userId, { limit: 20 }));108+ const [ledger, { refetch: refetchLedger }] = createResource(() => canReadMoney() ? targetId() : null, (userId) => getMealLedgerByUserId(userId, { limit: 20 }));
106 const [attendance] = createResource(targetId, (userId) => getMealAttendanceByUserId(userId, { limit: 20 }));109 const [attendance] = createResource(targetId, (userId) => getMealAttendanceByUserId(userId, { limit: 20 }));
107 // The backend does not expose a teacher-visible service-roster endpoint.110 // The backend does not expose a teacher-visible service-roster endpoint.
108 // Teachers can still see and amend recorded service; managers additionally111 // Teachers can still see and amend recorded service; managers additionally
@@ -231,9 +234,9 @@ function MealDetailContent() {
231 <TabsContent value="account" class="space-y-4">234 <TabsContent value="account" class="space-y-4">
232 <div class="grid gap-4 lg:grid-cols-2">235 <div class="grid gap-4 lg:grid-cols-2">
233 <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>236 <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>
234- <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>237+ <Show when={canReadMoney()}><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></Show>
235 </div>238 </div>
236- <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>239+ <Show when={canReadMoney()}><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></Show>
237 <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>240 <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>
238 </TabsContent>241 </TabsContent>
239 242
src/pages/settings-page.tsxmodified+12 -0
@@ -111,6 +111,18 @@ function SettingsContent() {
111 setError(t("settings.maxFileSizeInvalid"));111 setError(t("settings.maxFileSizeInvalid"));
112 return;112 return;
113 }113 }
114+ // A meal-slot name becomes a URL path segment on the backend, so these
115+ // characters are rejected there — but a name already on the saved list is
116+ // grandfathered in, so only newly-typed names are blocked client-side.
117+ const savedSlotNames = new Set((baseline()?.meal_slots ?? []).map((slot) => slot.name));
118+ const badSlot = mealSlots().find((slot) => {
119+ const name = slot.name.trim();
120+ return name !== "" && /[/\\?#%]/.test(name) && !savedSlotNames.has(name);
121+ });
122+ if (badSlot) {
123+ setError(t("settings.mealSlotNameInvalid"));
124+ return;
125+ }
114 setPending(true);126 setPending(true);
115 try {127 try {
116 const before = baseline();128 const before = baseline();