diff --git a/compose.test.yml b/compose.test.yml index 37b8e04..89a1142 100644 --- a/compose.test.yml +++ b/compose.test.yml @@ -7,9 +7,6 @@ services: POSTGRES_USER: postgres POSTGRES_DB: polympr_test volumes: - # Init script strips drizzle-kit markers and applies migrations on first start - - ./databases/docker-init.sh:/docker-entrypoint-initdb.d/01-migrate.sh:ro - - ./databases/migrations:/migrations:ro - db_data_test:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] @@ -17,6 +14,23 @@ services: timeout: 5s retries: 10 + migrate: + image: node:alpine + working_dir: /app + restart: "no" + volumes: + - .:/app + command: node_modules/.bin/drizzle-kit migrate + environment: + POSTGRES_HOST: db + POSTGRES_PORT: "5432" + POSTGRES_USER: postgres + POSTGRES_PASS: testpass + POSTGRES_DB: polympr_test + depends_on: + db: + condition: service_healthy + app: image: denoland/deno:alpine working_dir: /app @@ -34,8 +48,8 @@ services: POSTGRES_DB: polympr_test LOCAL: "true" depends_on: - db: - condition: service_healthy + migrate: + condition: service_completed_successfully volumes: db_data_test: diff --git a/databases/migrations/0001_seed_permissions.sql b/databases/migrations/0001_seed_permissions.sql new file mode 100644 index 0000000..6ea1572 --- /dev/null +++ b/databases/migrations/0001_seed_permissions.sql @@ -0,0 +1,10 @@ +--> statement-breakpoint +INSERT INTO "permissions" ("id", "nom") VALUES + ('note_read', 'Consulter les notes des étudiants'), + ('note_write', 'Saisir et modifier les notes'), + ('student_read', 'Consulter la liste des étudiants'), + ('student_write','Gérer les étudiants (ajout, modification, suppression)'), + ('module_read', 'Consulter les modules et enseignements'), + ('module_write', 'Gérer les modules et enseignements'), + ('user_read', 'Consulter les utilisateurs et leurs rôles'), + ('user_write', 'Gérer les utilisateurs et leurs rôles'); diff --git a/databases/migrations/0002_update_permission_names.sql b/databases/migrations/0002_update_permission_names.sql new file mode 100644 index 0000000..4e1b1d0 --- /dev/null +++ b/databases/migrations/0002_update_permission_names.sql @@ -0,0 +1,13 @@ +-- Update permission names to French +-- This migration inserts or updates the permission labels used by the API. +--> statement-breakpoint +INSERT INTO "permissions" ("id", "nom") VALUES + ('note_read', 'Consulter les notes des étudiants'), + ('note_write', 'Saisir et modifier les notes'), + ('student_read', 'Consulter la liste des étudiants'), + ('student_write','Gérer les étudiants (ajout, modification, suppression)'), + ('module_read', 'Consulter les modules et enseignements'), + ('module_write', 'Gérer les modules et enseignements'), + ('user_read', 'Consulter les utilisateurs et leurs rôles'), + ('user_write', 'Gérer les utilisateurs et leurs rôles') +ON CONFLICT ("id") DO UPDATE SET "nom" = EXCLUDED."nom"; diff --git a/databases/migrations/meta/_journal.json b/databases/migrations/meta/_journal.json index ad99452..e4f070f 100644 --- a/databases/migrations/meta/_journal.json +++ b/databases/migrations/meta/_journal.json @@ -8,6 +8,20 @@ "when": 1777155028708, "tag": "0000_square_jetstream", "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1777155028709, + "tag": "0001_seed_permissions", + "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1777155028710, + "tag": "0002_update_permission_names", + "breakpoints": true } ] } diff --git a/fresh.gen.ts b/fresh.gen.ts index a4a95f9..f19d57b 100644 --- a/fresh.gen.ts +++ b/fresh.gen.ts @@ -36,6 +36,7 @@ import * as $_apps_notes_api_ues from "./routes/(apps)/notes/api/ues.ts"; import * as $_apps_notes_api_ues_idUE_ from "./routes/(apps)/notes/api/ues/[idUE].ts"; import * as $_apps_notes_index from "./routes/(apps)/notes/index.tsx"; import * as $_apps_notes_partials_admin_courses from "./routes/(apps)/notes/partials/(admin)/courses.tsx"; +import * as $_apps_notes_partials_admin_import from "./routes/(apps)/notes/partials/(admin)/import.tsx"; import * as $_apps_notes_partials_admin_ues from "./routes/(apps)/notes/partials/(admin)/ues.tsx"; import * as $_apps_notes_partials_index from "./routes/(apps)/notes/partials/index.tsx"; import * as $_apps_notes_partials_notes from "./routes/(apps)/notes/partials/notes.tsx"; @@ -72,6 +73,7 @@ import * as $_apps_mobility_islands_EditMobility from "./routes/(apps)/mobility/ import * as $_apps_mobility_islands_ImportFile from "./routes/(apps)/mobility/(_islands)/ImportFile.tsx"; import * as $_apps_notes_islands_AdminConsultNotes from "./routes/(apps)/notes/(_islands)/AdminConsultNotes.tsx"; import * as $_apps_notes_islands_AdminUEs from "./routes/(apps)/notes/(_islands)/AdminUEs.tsx"; +import * as $_apps_notes_islands_ImportNotes from "./routes/(apps)/notes/(_islands)/ImportNotes.tsx"; import * as $_apps_notes_islands_NotesView from "./routes/(apps)/notes/(_islands)/NotesView.tsx"; import * as $_apps_students_islands_AdminPromotions from "./routes/(apps)/students/(_islands)/AdminPromotions.tsx"; import * as $_apps_students_islands_ConsultStudents from "./routes/(apps)/students/(_islands)/ConsultStudents.tsx"; @@ -129,6 +131,8 @@ const manifest = { "./routes/(apps)/notes/index.tsx": $_apps_notes_index, "./routes/(apps)/notes/partials/(admin)/courses.tsx": $_apps_notes_partials_admin_courses, + "./routes/(apps)/notes/partials/(admin)/import.tsx": + $_apps_notes_partials_admin_import, "./routes/(apps)/notes/partials/(admin)/ues.tsx": $_apps_notes_partials_admin_ues, "./routes/(apps)/notes/partials/index.tsx": $_apps_notes_partials_index, @@ -187,6 +191,8 @@ const manifest = { $_apps_notes_islands_AdminConsultNotes, "./routes/(apps)/notes/(_islands)/AdminUEs.tsx": $_apps_notes_islands_AdminUEs, + "./routes/(apps)/notes/(_islands)/ImportNotes.tsx": + $_apps_notes_islands_ImportNotes, "./routes/(apps)/notes/(_islands)/NotesView.tsx": $_apps_notes_islands_NotesView, "./routes/(apps)/students/(_islands)/AdminPromotions.tsx": diff --git a/routes/(apps)/admin/(_islands)/AdminRoles.tsx b/routes/(apps)/admin/(_islands)/AdminRoles.tsx index 448e334..b29b616 100644 --- a/routes/(apps)/admin/(_islands)/AdminRoles.tsx +++ b/routes/(apps)/admin/(_islands)/AdminRoles.tsx @@ -171,21 +171,19 @@ export default function AdminRoles() { ); })} diff --git a/routes/(apps)/admin/api/permissions.ts b/routes/(apps)/admin/api/permissions.ts index 1175eb0..61bf4ed 100644 --- a/routes/(apps)/admin/api/permissions.ts +++ b/routes/(apps)/admin/api/permissions.ts @@ -1,21 +1,15 @@ -import { Handlers } from "$fresh/server.ts"; +import { FreshContext, Handlers } from "$fresh/server.ts"; +import { db } from "$root/databases/db.ts"; +import { permissions } from "$root/databases/schema.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts"; -const PERMISSIONS = [ - { id: "student_read", nom: "Consulter les élèves" }, - { id: "student_write", nom: "Gérer les élèves" }, - { id: "note_read", nom: "Consulter les notes" }, - { id: "note_write", nom: "Gérer les notes" }, - { id: "module_read", nom: "Consulter les modules" }, - { id: "module_write", nom: "Gérer les modules" }, - { id: "user_read", nom: "Consulter les utilisateurs" }, - { id: "user_write", nom: "Gérer les utilisateurs" }, - { id: "role_write", nom: "Gérer les rôles" }, -] as const; - export const handler: Handlers = { - GET(_request, _context): Response { - return new Response(JSON.stringify(PERMISSIONS), { + async GET( + _request: Request, + _context: FreshContext, + ): Promise { + const result = await db.select().from(permissions); + return new Response(JSON.stringify(result), { headers: { "content-type": "application/json" }, }); }, diff --git a/routes/(apps)/notes/(_islands)/ImportNotes.tsx b/routes/(apps)/notes/(_islands)/ImportNotes.tsx new file mode 100644 index 0000000..e738057 --- /dev/null +++ b/routes/(apps)/notes/(_islands)/ImportNotes.tsx @@ -0,0 +1,153 @@ +// @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts" +import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs"; +import { useRef } from "preact/hooks"; +import { useSignal } from "@preact/signals"; + +export default function ImportNotes() { + const file = useSignal(null); + const dragging = useSignal(false); + const uploading = useSignal(false); + const error = useSignal(null); + const success = useSignal(null); + const inputRef = useRef(null); + + function pickFile(f: File) { + if (!f.name.match(/\.xlsx?$/i)) { + error.value = "Fichier invalide — format attendu : .xlsx"; + return; + } + file.value = f; + error.value = null; + success.value = null; + } + + function onDragOver(e: DragEvent) { + e.preventDefault(); + dragging.value = true; + } + + function onDragLeave() { + dragging.value = false; + } + + function onDrop(e: DragEvent) { + e.preventDefault(); + dragging.value = false; + const f = e.dataTransfer?.files?.[0]; + if (f) pickFile(f); + } + + function onInputChange(e: Event) { + const f = (e.target as HTMLInputElement).files?.[0]; + if (f) pickFile(f); + } + + async function doImport() { + if (!file.value) return; + uploading.value = true; + error.value = null; + success.value = null; + + try { + const arrayBuffer = await file.value.arrayBuffer(); + const workbook = XLSX.read(arrayBuffer, { type: "array" }); + let imported = 0; + let failed = 0; + + for (const sheetName of workbook.SheetNames) { + const sheet = workbook.Sheets[sheetName]; + const rows = XLSX.utils.sheet_to_json<{ + numEtud: number; + idModule: string; + note: number; + }>(sheet, { header: ["numEtud", "idModule", "note"], range: 1 }); + + for (const row of rows) { + const res = await fetch("/notes/api/notes", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(row), + }); + if (res.ok) imported++; + else failed++; + } + } + + success.value = + `Import terminé — ${imported} ajouté${imported !== 1 ? "s" : ""}${ + failed > 0 ? `, ${failed} erreur${failed !== 1 ? "s" : ""}` : "" + }`; + } catch { + error.value = "Erreur lors de la lecture du fichier."; + } finally { + uploading.value = false; + } + } + + function downloadTemplate() { + const wb = XLSX.utils.book_new(); + const ws = XLSX.utils.aoa_to_sheet([["numEtud", "idModule", "note"]]); + XLSX.utils.book_append_sheet(wb, ws, "Notes"); + XLSX.writeFile(wb, "modele_notes.xlsx"); + } + + return ( +
+ + +
inputRef.current?.click()} + > + + {file.value + ? {file.value.name} + : ( + <> + Glisser le fichier .xlsx ici + ou cliquer pour parcourir + + )} +
+ + {error.value &&

{error.value}

} + {success.value && ( +

+ {success.value} +

+ )} + +
+ + +
+ +

+ Format : numEtud | idModule |{" "} + note +

+
+ ); +} diff --git a/routes/(apps)/notes/(_props)/props.ts b/routes/(apps)/notes/(_props)/props.ts index fb7f11b..2f5be17 100644 --- a/routes/(apps)/notes/(_props)/props.ts +++ b/routes/(apps)/notes/(_props)/props.ts @@ -8,8 +8,9 @@ const properties: AppProperties = { notes: "Mes notes", courses: "Consulter", ues: "UEs", + import: "Import xlsx", }, - adminOnly: ["courses", "ues"], + adminOnly: ["courses", "ues", "import"], hint: "Student grading management", }; diff --git a/routes/(apps)/notes/partials/(admin)/import.tsx b/routes/(apps)/notes/partials/(admin)/import.tsx new file mode 100644 index 0000000..4a92c3d --- /dev/null +++ b/routes/(apps)/notes/partials/(admin)/import.tsx @@ -0,0 +1,29 @@ +import { + getPartialsConfig, + makePartials, +} from "$root/defaults/makePartials.tsx"; +import { FreshContext } from "$fresh/server.ts"; +import { State } from "$root/defaults/interfaces.ts"; +import ImportNotes from "../../(_islands)/ImportNotes.tsx"; + +// deno-lint-ignore require-await +async function ImportNotesPage( + _request: Request, + _context: FreshContext, +) { + return ( +
+

Importer des Notes

+

+ POST /notes/api/notes +

+ +
+ ); +} + +export const config = getPartialsConfig(); +export default makePartials(ImportNotesPage); diff --git a/routes/(apps)/students/(_islands)/UploadStudents.tsx b/routes/(apps)/students/(_islands)/UploadStudents.tsx index 6e21876..df6f592 100644 --- a/routes/(apps)/students/(_islands)/UploadStudents.tsx +++ b/routes/(apps)/students/(_islands)/UploadStudents.tsx @@ -1,111 +1,154 @@ // @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts" import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs"; -import { Signal, useSignal } from "@preact/signals"; +import { useRef } from "preact/hooks"; +import { useSignal } from "@preact/signals"; -/** - * Create a new handler for file change that displays - * messages in statusMessage and gets file data in fileData. - * @param statusMessage The status message signal. - * @param fileData The file data signal. - * @returns The file change handler. - */ -function getFileChangeHandler( - statusMessage: Signal, - fileData: Signal, -): (event: Event) => void { - /** - * Handle file change. - * @param event The file change event. - */ - return (event: Event) => { - const input = event.target as HTMLInputElement; - if (input.files && input.files.length > 0) { - fileData.value = input.files[0]; - statusMessage.value = `File selected: ${input.files[0].name}`; - } else { - fileData.value = null; - statusMessage.value = "No file selected"; - } - }; -} +export default function UploadStudents() { + const file = useSignal(null); + const dragging = useSignal(false); + const uploading = useSignal(false); + const error = useSignal(null); + const success = useSignal(null); + const inputRef = useRef(null); -/** - * Create a new handler that sends data file to server. - * @param statusMessage The status message signal. - * @param fileData The file data signal. - * @returns The file confirmation handler. - */ -function getUploadConfirmationFunction( - statusMessage: Signal, - fileData: Signal, -): () => void { - /** - * Add students to database. - * @returns Confirm upload of students. - */ - return () => { - if (!fileData.value) { - statusMessage.value = "Please select a file before confirming upload."; + function pickFile(f: File) { + if (!f.name.match(/\.xlsx?$/i)) { + error.value = "Fichier invalide — format attendu : .xlsx"; return; } + file.value = f; + error.value = null; + success.value = null; + } - const reader = new FileReader(); + function onDragOver(e: DragEvent) { + e.preventDefault(); + dragging.value = true; + } - /** - * Send all data to the server. - * @param event The finished progress event. - */ - reader.onload = async (event: ProgressEvent) => { - const arrayBuffer = event.target!.result as ArrayBuffer; + function onDragLeave() { + dragging.value = false; + } + + function onDrop(e: DragEvent) { + e.preventDefault(); + dragging.value = false; + const f = e.dataTransfer?.files?.[0]; + if (f) pickFile(f); + } + + function onInputChange(e: Event) { + const f = (e.target as HTMLInputElement).files?.[0]; + if (f) pickFile(f); + } + + async function doImport() { + if (!file.value) return; + uploading.value = true; + error.value = null; + success.value = null; + + try { + const arrayBuffer = await file.value.arrayBuffer(); const workbook = XLSX.read(arrayBuffer, { type: "array" }); - let allOK = true; + let imported = 0; + let failed = 0; for (const sheetName of workbook.SheetNames) { const sheet = workbook.Sheets[sheetName]; - const data = XLSX.utils.sheet_to_json(sheet, { - header: ["userId", "lastName", "firstName", "mail"], - range: 1, - }); + const rows = XLSX.utils.sheet_to_json<{ + numEtud: number; + nom: string; + prenom: string; + }>(sheet, { header: ["numEtud", "nom", "prenom"], range: 1 }); - const response = await fetch("/students/api/students", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ promoName: sheetName, data }), - }); - - if (!response.ok) { - allOK = false; + for (const row of rows) { + const res = await fetch("/students/api/students", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ...row, idPromo: sheetName }), + }); + if (res.ok) imported++; + else failed++; } } - statusMessage.value = allOK - ? "Failed to insert all data." - : "Data uploaded and inserted successfully!"; - }; + success.value = + `Import terminé — ${imported} ajouté${imported !== 1 ? "s" : ""}${ + failed > 0 ? `, ${failed} erreur${failed !== 1 ? "s" : ""}` : "" + }`; + } catch { + error.value = "Erreur lors de la lecture du fichier."; + } finally { + uploading.value = false; + } + } - /** - * Display error message if any. - */ - reader.onerror = () => { - statusMessage.value = "Error reading the file."; - }; - - reader.readAsArrayBuffer(fileData.value); - }; -} - -export default function UploadStudents() { - const statusMessage = useSignal(""); - const fileData = useSignal(null); - - const handleFileChange = getFileChangeHandler(statusMessage, fileData); - const confirmUpload = getUploadConfirmationFunction(statusMessage, fileData); + function downloadTemplate() { + const wb = XLSX.utils.book_new(); + const ws = XLSX.utils.aoa_to_sheet([["numEtud", "nom", "prenom"]]); + XLSX.utils.book_append_sheet(wb, ws, "4A22"); + XLSX.writeFile(wb, "modele_etudiants.xlsx"); + } return ( - <> - - -

{statusMessage.value}

- +
+ + +
inputRef.current?.click()} + > + + {file.value + ? {file.value.name} + : ( + <> + Glisser le fichier .xlsx ici + ou cliquer pour parcourir + + )} +
+ + {error.value &&

{error.value}

} + {success.value && ( +

+ {success.value} +

+ )} + +
+ + +
+ +

+ Format : promo (nom de la feuille) |{" "} + numEtud | nom |{" "} + prénom +

+
); } diff --git a/routes/(apps)/students/partials/(admin)/upload.tsx b/routes/(apps)/students/partials/(admin)/upload.tsx index 2f36f6d..cdb94fd 100644 --- a/routes/(apps)/students/partials/(admin)/upload.tsx +++ b/routes/(apps)/students/partials/(admin)/upload.tsx @@ -9,10 +9,16 @@ import { State } from "$root/defaults/interfaces.ts"; // deno-lint-ignore require-await async function Students(_request: Request, _context: FreshContext) { return ( - <> -

Upload Students

+
+

Importer des Élèves

+

+ POST /students/api/students/import-csv +

- +
); } diff --git a/static/styles/main.css b/static/styles/main.css index ce2282a..9fbd74e 100644 --- a/static/styles/main.css +++ b/static/styles/main.css @@ -29,6 +29,10 @@ font-family: var(--font-family-text); } +html { + font-size: 130%; /* scale up from browser default 16px → ~20.8px */ +} + html, body { margin: 0; padding: 0; diff --git a/static/styles/ui.css b/static/styles/ui.css index 12132eb..88d3080 100644 --- a/static/styles/ui.css +++ b/static/styles/ui.css @@ -6,7 +6,6 @@ .page-content { padding: 1.5rem; - max-width: 960px; } .page-title { @@ -783,6 +782,70 @@ text-decoration: underline; } +/* ------------------------------------------------------- + File drop zone (import pages) +------------------------------------------------------- */ + +.drop-zone { + border: 2px dashed + light-dark(var(--light-foreground-dimmer), var(--dark-foreground-dimmer)); + border-radius: 6px; + background: light-dark(white, #141228); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.6rem; + padding: 3rem 2rem; + cursor: pointer; + transition: border-color 150ms, background 150ms; + margin-bottom: 1.25rem; + text-align: center; +} + +.drop-zone:hover, +.drop-zone.dragging { + border-color: light-dark(var(--light-accent-color), var(--dark-accent-color)); + background: light-dark(#f0fff4, #0a1a10); +} + +.drop-zone-icon { + font-size: 2.4rem; + line-height: 1; + opacity: 0.8; +} + +.drop-zone-text { + font-size: 0.88rem; + font-weight: var(--font-weight-bold); +} + +.drop-zone-hint { + font-size: 0.75rem; + font-family: monospace; + color: light-dark(var(--light-foreground-dim), var(--dark-foreground-dim)); +} + +.drop-zone-file { + font-size: 0.78rem; + font-family: monospace; + color: light-dark(var(--light-accent-color), var(--dark-accent-color)); + font-weight: var(--font-weight-bold); +} + +.upload-actions { + display: flex; + gap: 0.75rem; + align-items: center; + margin-bottom: 0.75rem; +} + +.upload-format { + font-size: 0.72rem; + font-family: monospace; + color: light-dark(var(--light-foreground-dim), var(--dark-foreground-dim)); +} + /* Info note box */ .info-note { padding: 0.75rem 1rem;