From 7992c8ffa0c7de59de9ed8e62767c6fa5532d6fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Burak=20Boduro=C4=9Flu?= <80620802+burakboduroglu@users.noreply.github.com> Date: Thu, 16 Jul 2026 09:28:53 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=E2=9C=A8=20note=20attachments=20and=20?= =?UTF-8?q?side-panel=20notebook=20flow=20-=20add=20note=20file=20upload/d?= =?UTF-8?q?ownload=20API=20wiring=20and=20settings=20limits=20-=20show=20n?= =?UTF-8?q?ote=20file=20controls=20in=20create=20and=20read=20flows=20-=20?= =?UTF-8?q?move=20notebook=20create,=20edit,=20and=20read=20views=20from?= =?UTF-8?q?=20dialog=20to=20side=20panel=20-=20fix=20dialog=20close=20butt?= =?UTF-8?q?on=20through=20the=20Kobalte=20close=20primitive=20-=20update?= =?UTF-8?q?=20docs=20and=20copy=20for=20note=20attachment=20behavior?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 15 +-- docs/frontend-next-steps.md | 14 +- src/api/client.ts | 31 +++++ src/api/deleteNoteFileById.ts | 5 + src/api/getNoteFileUrl.ts | 3 + src/api/getNoteFiles.ts | 8 ++ src/api/patchSettings.ts | 1 + src/api/postNoteFile.ts | 8 ++ src/api/types.ts | 8 ++ src/components/notes/note-card.tsx | 111 ++++++++------- src/components/notes/note-files-panel.tsx | 141 ++++++++++++++++++++ src/components/notes/note-form.tsx | 112 +++++++++++++++- src/components/notes/note-list.tsx | 56 +++++--- src/components/notes/note-reader-dialog.tsx | 30 ----- src/components/notes/note-reader-panel.tsx | 50 +++++++ src/components/ui/dialog.tsx | 19 ++- src/i18n/messages.ts | 30 +++++ src/pages/notes-page.tsx | 14 +- src/pages/settings-page.tsx | 38 +++++- 19 files changed, 552 insertions(+), 142 deletions(-) create mode 100644 src/api/deleteNoteFileById.ts create mode 100644 src/api/getNoteFileUrl.ts create mode 100644 src/api/getNoteFiles.ts create mode 100644 src/api/postNoteFile.ts create mode 100644 src/components/notes/note-files-panel.tsx delete mode 100644 src/components/notes/note-reader-dialog.tsx create mode 100644 src/components/notes/note-reader-panel.tsx diff --git a/README.md b/README.md index b605307..9fa6e50 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Dashboard and table summaries must use the same role scope as the related page. | `/login`, `/register` | Guests | Authentication | | `/` | Authenticated | Role-scoped, observation-only dashboard | | `/profile` | Authenticated | Edit personal info (name, email, phone, birth date) | -| `/notes` | Student+ | Personal notebook CRUD with paper-style read dialogs; file attachments are the next frontend integration | +| `/notes` | Student+ | Personal notebook CRUD with paper-style read dialogs and file attachments | | `/events`, `/events/:id` | Student+ | Event list & detail with search, time filters, and lazy attendance roster | | `/exams` | Student+ | Exam table with role-scoped course filtering | | `/exams/:id` | Student+ | Exam detail, questions, grading, statistics (teacher+) | @@ -79,7 +79,7 @@ Dashboard and table summaries must use the same role scope as the related page. - **Course sessions**: right-panel session creation and paginated roll call panels - **Schedule validation**: event, exam, and lesson-session forms use `GET /time` for server-clock-aware past-date warnings before submit - **Notebook**: notes render as paper-style cards, open in a paper-style read dialog, and keep create/edit/delete in dialogs with three-dot card actions -- **Note files**: backend supports per-note file upload/list/download/delete; frontend integration will use native `FormData`, no upload dependency +- **Note files**: per-note upload/list/download/delete through native `FormData`, with school-configured file-size warnings from settings - **Events and courses**: events keep card rendering with toolbar search and upcoming/past filters; courses use table search plus term/unassigned filters - **Attendance UI**: localized status labels with explanatory detail text and semantic colors - **Role-scoped dashboard**: read-only summaries and KPIs by current role @@ -97,16 +97,7 @@ Dashboard and table summaries must use the same role scope as the related page. - Disclosure sections either defer hidden content for request savings or preserve mounted content when local state should not reset. - Event detail attendance roster is teacher-only and lazy-loaded when its disclosure opens. -## Upcoming Note File Integration - -The backend now supports note attachments: `POST /notes/{id}/files` with multipart field `file`, `GET /notes/{id}/files`, raw download by file id, and delete by file id. The frontend implementation should stay minimal: - -- Add `NoteFile` and `max_file_bytes` to API types/settings. -- Add one API file per request: list, upload, delete, and a download URL helper. -- Use native `FormData`; do not set `Content-Type` manually for multipart. -- Mount a small attachments panel in the note reader dialog only after a note exists. -- Read `settings.max_file_bytes` for a client-side size warning; backend remains authoritative for `413` and the 10-file cap. -- Skip list-card attachment counts and file previews until there is a real product need. +- Note attachments live in the note reader dialog. Upload uses native `FormData`; downloads are same-origin links to `/api/notes/{id}/files/{file_id}`. Backend remains authoritative for the 10-file cap and payload validation. ## Docs diff --git a/docs/frontend-next-steps.md b/docs/frontend-next-steps.md index aec50cd..09a3488 100644 --- a/docs/frontend-next-steps.md +++ b/docs/frontend-next-steps.md @@ -18,7 +18,7 @@ validation, and list filtering cleanup. - Settings requests are cached and refreshed after settings patches. - Sidebar icons use local SVG wrappers to avoid large icon package module graphs. - Notes use a paper-style notebook card layout, a paper-style read dialog, and dialog-based create/edit/delete flows. -- Backend note attachments are available but not yet wired in the frontend. Planned frontend scope is reader-dialog attachments only, using native `FormData` and backend-enforced caps. +- Note attachments are wired in the reader dialog with native `FormData`, same-origin download links, and settings-based file-size warnings. Backend remains authoritative for the 10-file cap and upload validation. - List endpoints return `{ items, total, limit, offset }`. API helpers under `src/api/` accept optional `limit`/`offset` via `Page`. - Events keep card rendering with shared toolbar search and all/upcoming/past filters. - Event, exam, and lesson-session schedule forms use `GET /time` for server-clock-aware past-date warnings before submit. @@ -54,17 +54,6 @@ validation, and list filtering cleanup. ## Active Backlog -### Note File Attachments - -| Item | Plan | -|---|---| -| API types | Add `NoteFile` and `SchoolSettings.max_file_bytes` | -| API helpers | Add list/upload/delete helpers plus a download URL helper; keep one file per request | -| Upload transport | Use native `FormData` with the multipart field named `file`; do not route multipart through JSON `client()` | -| UI | Add a compact `NoteFilesPanel` inside the note reader dialog; no card-level file counts | -| Limits | Read `settings.max_file_bytes` for client warning; backend remains authoritative for 10-file cap and `413` | -| Deferred | No previews, no drag-drop dependency, no draft-upload queue before note creation | - ### Recently fixed (this batch) | Item | Fix | @@ -75,6 +64,7 @@ validation, and list filtering cleanup. | Manager work log | `/management/staff-work` + get/patch/delete work APIs | | Work route guard | `beforeLoad` teacher+ on `/work` | | BE student-only gates (enroll/sit/grade/roll call) | Localized error strings for the new 400/403 messages; student-marks lookup picker filters `role=student`; exam-detail own-result gates on `isStudent()` | +| Note file attachments | Reader-dialog attachments panel with list/upload/download/delete; settings exposes `max_file_bytes` | ### Incomplete Product Features diff --git a/src/api/client.ts b/src/api/client.ts index 3ac3d75..b5770eb 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -171,6 +171,37 @@ export async function client(path: string, options: RequestOptions = {}): Pro return data as T; } +export async function formClient(path: string, body: FormData, signal?: AbortSignal): Promise { + const res = await fetch(`${API_PREFIX}${path}`, { + method: "POST", + body, + credentials: "same-origin", + signal, + }); + + const text = await res.text(); + let data: unknown = null; + if (text) { + try { + data = JSON.parse(text); + } catch { + data = { error: text }; + } + } + + if (!res.ok) { + const message = + data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string" + ? (data as { error: string }).error + : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string" + ? (data as { message: string }).message + : res.statusText || "Request failed"; + throw new ApiError(res.status, message); + } + + return data as T; +} + export function formatApiErrorMessage(message: string, locale: Locale = currentLocale()): string { const normalized = normalizeApiMessage(message); const known = API_ERROR_MESSAGES[normalized]?.[locale]; diff --git a/src/api/deleteNoteFileById.ts b/src/api/deleteNoteFileById.ts new file mode 100644 index 0000000..3a8d8c1 --- /dev/null +++ b/src/api/deleteNoteFileById.ts @@ -0,0 +1,5 @@ +import { client } from "./client"; + +export function deleteNoteFileById(noteId: string, fileId: string): Promise { + return client(`/notes/${noteId}/files/${fileId}`, { method: "DELETE" }); +} diff --git a/src/api/getNoteFileUrl.ts b/src/api/getNoteFileUrl.ts new file mode 100644 index 0000000..2ec3793 --- /dev/null +++ b/src/api/getNoteFileUrl.ts @@ -0,0 +1,3 @@ +export function getNoteFileUrl(noteId: string, fileId: string): string { + return `/api/notes/${encodeURIComponent(noteId)}/files/${encodeURIComponent(fileId)}`; +} diff --git a/src/api/getNoteFiles.ts b/src/api/getNoteFiles.ts new file mode 100644 index 0000000..2a76ab3 --- /dev/null +++ b/src/api/getNoteFiles.ts @@ -0,0 +1,8 @@ +import { client } from "./client"; +import { normalizePage, pageQuery, type Page, type PageParams } from "./page"; +import type { NoteFile } from "./types"; + +export async function getNoteFiles(noteId: string, params?: PageParams, signal?: AbortSignal): Promise> { + const data = await client(`/notes/${noteId}/files${pageQuery(params)}`, { signal }); + return normalizePage(data); +} diff --git a/src/api/patchSettings.ts b/src/api/patchSettings.ts index f9c205e..426b79b 100644 --- a/src/api/patchSettings.ts +++ b/src/api/patchSettings.ts @@ -6,6 +6,7 @@ export type PatchSettingsBody = { exam_kinds?: ExamKindSetting[]; attendance_statuses?: string[]; grade_bands?: GradeBand[]; + max_file_bytes?: number; }; export function patchSettings(body: PatchSettingsBody): Promise { diff --git a/src/api/postNoteFile.ts b/src/api/postNoteFile.ts new file mode 100644 index 0000000..00ab4a9 --- /dev/null +++ b/src/api/postNoteFile.ts @@ -0,0 +1,8 @@ +import { formClient } from "./client"; +import type { NoteFile } from "./types"; + +export function postNoteFile(noteId: string, file: File, signal?: AbortSignal): Promise { + const body = new FormData(); + body.append("file", file); + return formClient(`/notes/${noteId}/files`, body, signal); +} diff --git a/src/api/types.ts b/src/api/types.ts index 62d18bb..9696ea2 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -40,6 +40,13 @@ export type Note = { content: string; }; +export type NoteFile = { + id: string; + name: string; + content_type: string; + size: number; +}; + export type Event = { id: string; creator: string; @@ -297,6 +304,7 @@ export type SchoolSettings = { exam_kinds: ExamKindSetting[]; attendance_statuses: string[]; grade_bands: GradeBand[]; + max_file_bytes: number; }; export const EXAM_KINDS: KnownExamKind[] = [ diff --git a/src/components/notes/note-card.tsx b/src/components/notes/note-card.tsx index b5f0fe1..695feb9 100644 --- a/src/components/notes/note-card.tsx +++ b/src/components/notes/note-card.tsx @@ -2,80 +2,77 @@ import { createSignal } from "solid-js"; import { formatApiError } from "@/api/client"; import type { Note } from "@/api/types"; import { NoteForm } from "@/components/notes/note-form"; -import { NoteReaderDialog } from "@/components/notes/note-reader-dialog"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; -import { FormDialog } from "@/components/ui/form-dialog"; import { IconEdit, IconTrash } from "@/components/ui/icons"; +import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { useT } from "@/stores/preferences-context"; export function NoteCard(props: { note: Note; + onOpen: (note: Note) => void; onUpdate: (id: string, values: { title: string; content: string }) => Promise; onDelete: (id: string) => Promise; }) { const t = useT(); - const [reading, setReading] = createSignal(false); const [editing, setEditing] = createSignal(false); const [error, setError] = createSignal(""); const [deleteOpen, setDeleteOpen] = createSignal(false); return ( -
setReading(true)} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") setReading(true); - }} - > -
-

{props.note.title}

-
event.stopPropagation()}> - , - onSelect: () => setEditing(true), - }, - { - label: t("common.delete"), - icon: , - destructive: true, - onSelect: () => setDeleteOpen(true), - }, - ]} - /> + <> +
props.onOpen(props.note)} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + props.onOpen(props.note); + } + }} + > +
+

{props.note.title}

+
event.stopPropagation()}> + , + onSelect: () => setEditing(true), + }, + { + label: t("common.delete"), + icon: , + destructive: true, + onSelect: () => setDeleteOpen(true), + }, + ]} + /> +
-
-
-

- {props.note.content || t("notes.noContent")} -

- {error() &&

{error()}

} -
- - +
+

+ {props.note.content || t("notes.noContent")} +

+ {error() &&

{error()}

} +
+
- - setEditing(false)} - onSubmit={async (values) => { - await props.onUpdate(props.note.id, values); - setEditing(false); - }} - /> - + + setEditing(false)} + onSubmit={async (values) => { + await props.onUpdate(props.note.id, values); + setEditing(false); + }} + /> + - + ); } diff --git a/src/components/notes/note-files-panel.tsx b/src/components/notes/note-files-panel.tsx new file mode 100644 index 0000000..2fcb6b5 --- /dev/null +++ b/src/components/notes/note-files-panel.tsx @@ -0,0 +1,141 @@ +import { For, Show, Suspense, createResource, createSignal } from "solid-js"; +import { deleteNoteFileById } from "@/api/deleteNoteFileById"; +import { getNoteFileUrl } from "@/api/getNoteFileUrl"; +import { getNoteFiles } from "@/api/getNoteFiles"; +import { getSettings } from "@/api/getSettings"; +import { postNoteFile } from "@/api/postNoteFile"; +import { ApiError, formatApiError } from "@/api/client"; +import type { NoteFile } from "@/api/types"; +import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { IconPlus, IconTrash } from "@/components/ui/icons"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { useT } from "@/stores/preferences-context"; + +const MAX_NOTE_FILES = 10; + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +export function NoteFilesPanel(props: { noteId: string; active: boolean }) { + let input: HTMLInputElement | undefined; + const t = useT(); + const [error, setError] = createSignal(""); + const [pending, setPending] = createSignal(false); + const [deleteTarget, setDeleteTarget] = createSignal(null); + const [files, { refetch }] = createResource( + () => (props.active ? props.noteId : null), + async (noteId) => { + if (!noteId) return [] as NoteFile[]; + // ponytail: empty on 404 so missing BE file API doesn't kill the reader dialog + try { + return (await getNoteFiles(noteId, { limit: MAX_NOTE_FILES })).items; + } catch (err) { + if (err instanceof ApiError && (err.status === 404 || err.status === 501)) return []; + throw err; + } + }, + ); + const [settings] = createResource(async () => { + try { + return await getSettings(); + } catch { + return null; + } + }); + const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024; + const atLimit = () => (files() ?? []).length >= MAX_NOTE_FILES; + + const upload = async (file: File | undefined) => { + if (!file) return; + setError(""); + if (file.size > maxFileBytes()) { + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); + return; + } + setPending(true); + try { + await postNoteFile(props.noteId, file); + await refetch(); + if (input) input.value = ""; + } catch (err) { + setError(formatApiError(err)); + } finally { + setPending(false); + } + }; + + return ( +
+
+
+

{t("notes.files")}

+

{t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })}

+
+ { + input = el; + }} + type="file" + class="hidden" + disabled={pending() || atLimit()} + onChange={(event) => void upload(event.currentTarget.files?.[0])} + /> + +
+ + {error() &&

{error()}

} + +

{t("notes.fileLimit")}

+
+ + +

{formatApiError(files.error)}

+
+ + }> + 0} + fallback={

{t("notes.noFiles")}

} + > +
    + + {(file) => ( +
  • + + {file.name} + + {formatBytes(file.size)} + +
  • + )} +
    +
+
+
+ + !open && setDeleteTarget(null)} + title={t("confirm.deleteTitle")} + variant="destructive" + summary={t("confirm.deleteNoteFile", { title: deleteTarget()?.name ?? "" })} + onConfirm={async () => { + const target = deleteTarget(); + if (!target) return; + await deleteNoteFileById(props.noteId, target.id); + setDeleteTarget(null); + await refetch(); + }} + /> +
+ ); +} diff --git a/src/components/notes/note-form.tsx b/src/components/notes/note-form.tsx index cb83811..b428161 100644 --- a/src/components/notes/note-form.tsx +++ b/src/components/notes/note-form.tsx @@ -1,8 +1,10 @@ -import { createSignal } from "solid-js"; +import { For, Show, createResource, createSignal } from "solid-js"; import { formatApiError } from "@/api/client"; +import { getSettings } from "@/api/getSettings"; import type { Note } from "@/api/types"; import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; +import { IconPlus, IconTrash } from "@/components/ui/icons"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; @@ -11,22 +13,44 @@ import { useT } from "@/stores/preferences-context"; export type NoteFormValues = { title: string; content: string; + files: File[]; }; +const MAX_NOTE_FILES = 10; + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + export function NoteForm(props: { initial?: Partial; submitLabel?: string; + /** Stage files on create (uploaded by parent after note exists). */ + enableFiles?: boolean; onSubmit: (values: NoteFormValues) => Promise; onCancel?: () => void; }) { const t = useT(); + let fileInput: HTMLInputElement | undefined; const isUpdate = () => !!props.initial?.id; const [title, setTitle] = createSignal(props.initial?.title ?? ""); const [content, setContent] = createSignal(props.initial?.content ?? ""); + const [files, setFiles] = createSignal([]); const [error, setError] = createSignal(""); const [pending, setPending] = createSignal(false); const [confirmOpen, setConfirmOpen] = createSignal(false); const [pendingValues, setPendingValues] = createSignal(null); + const [settings] = createResource(async () => { + try { + return await getSettings(); + } catch { + return null; + } + }); + const maxFileBytes = () => settings()?.max_file_bytes ?? 5 * 1024 * 1024; + const showFiles = () => !!props.enableFiles && !isUpdate(); const validate = (): string | null => { const value = title().trim(); @@ -36,6 +60,21 @@ export function NoteForm(props: { return null; }; + const addFile = (file: File | undefined) => { + if (!file) return; + setError(""); + if (file.size > maxFileBytes()) { + setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); + return; + } + if (files().length >= MAX_NOTE_FILES) { + setError(t("notes.fileLimit")); + return; + } + setFiles((prev) => [...prev, file]); + if (fileInput) fileInput.value = ""; + }; + const save = async (values: NoteFormValues) => { setError(""); setPending(true); @@ -44,6 +83,7 @@ export function NoteForm(props: { if (!isUpdate()) { setTitle(""); setContent(""); + setFiles([]); } } catch (err) { setError(formatApiError(err)); @@ -59,7 +99,7 @@ export function NoteForm(props: { setError(v); return; } - const values = { title: title().trim(), content: content() }; + const values: NoteFormValues = { title: title().trim(), content: content(), files: files() }; if (isUpdate()) { setPendingValues(values); setConfirmOpen(true); @@ -93,7 +133,73 @@ export function NoteForm(props: { onInput={(e) => setContent(e.currentTarget.value)} /> - {error() &&

{error()}

} + + +
+
+
+

{t("notes.files")}

+

+ {t("notes.filesHelp", { size: formatBytes(maxFileBytes()) })} +

+
+ { + fileInput = el; + }} + type="file" + class="hidden" + disabled={pending() || files().length >= MAX_NOTE_FILES} + onChange={(event) => addFile(event.currentTarget.files?.[0])} + /> + +
+ 0} + fallback={ +

+ {t("notes.noFiles")} +

+ } + > +
    + + {(file, index) => ( +
  • + {file.name} + {formatBytes(file.size)} + +
  • + )} +
    +
+
+
+
+ + {error() && ( +

+ {error()} +

+ )}
{props.onCancel && (