refactor: add migration, seed permissions, update permissions API

feat(notes): add XLSX import island and admin route

feat(upload): add drag‑and‑drop upload, template download, UI tweaks
This commit is contained in:
2026-04-27 17:08:58 +02:00
parent 733259e317
commit d3de5c29e7
14 changed files with 467 additions and 119 deletions
@@ -171,21 +171,19 @@ export default function AdminRoles() {
<label
key={p.id}
class={`perm-toggle-card${active ? " active" : ""}`}
onClick={() => togglePerm(p.id)}
>
<div class="perm-toggle-label">
<span class="perm-toggle-id">{p.id}</span>
<span class="perm-toggle-nom">{p.nom}</span>
</div>
<label class="toggle-switch">
<span class="toggle-switch">
<input
type="checkbox"
checked={active}
onChange={() => togglePerm(p.id)}
onClick={(e) => e.stopPropagation()}
/>
<span class="toggle-slider" />
</label>
</span>
</label>
);
})}
+9 -15
View File
@@ -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<null, AuthenticatedState> = {
GET(_request, _context): Response {
return new Response(JSON.stringify(PERMISSIONS), {
async GET(
_request: Request,
_context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const result = await db.select().from(permissions);
return new Response(JSON.stringify(result), {
headers: { "content-type": "application/json" },
});
},
@@ -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<File | null>(null);
const dragging = useSignal(false);
const uploading = useSignal(false);
const error = useSignal<string | null>(null);
const success = useSignal<string | null>(null);
const inputRef = useRef<HTMLInputElement>(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 (
<div>
<input
ref={inputRef}
type="file"
accept=".xlsx,.xls"
style="display:none"
onChange={onInputChange}
/>
<div
class={`drop-zone${dragging.value ? " dragging" : ""}`}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onClick={() => inputRef.current?.click()}
>
<span class="drop-zone-icon"></span>
{file.value
? <span class="drop-zone-file">{file.value.name}</span>
: (
<>
<span class="drop-zone-text">Glisser le fichier .xlsx ici</span>
<span class="drop-zone-hint">ou cliquer pour parcourir</span>
</>
)}
</div>
{error.value && <p class="state-error">{error.value}</p>}
{success.value && (
<p style="font-size:0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.75rem">
{success.value}
</p>
)}
<div class="upload-actions">
<button
type="button"
class="btn btn-primary"
onClick={doImport}
disabled={!file.value || uploading.value}
>
{uploading.value ? "…" : "⊕ Importer"}
</button>
<button
type="button"
class="btn btn-secondary"
onClick={downloadTemplate}
>
Télécharger Modèle
</button>
</div>
<p class="upload-format">
Format : <strong>numEtud</strong> | <strong>idModule</strong> |{" "}
<strong>note</strong>
</p>
</div>
);
}
+2 -1
View File
@@ -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",
};
@@ -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<State>,
) {
return (
<div class="page-content">
<h2 class="page-title">Importer des Notes</h2>
<p
class="upload-format"
style="margin-bottom: 1.25rem"
>
POST /notes/api/notes
</p>
<ImportNotes />
</div>
);
}
export const config = getPartialsConfig();
export default makePartials(ImportNotesPage);
@@ -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<string>,
fileData: Signal<File | null>,
): (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<File | null>(null);
const dragging = useSignal(false);
const uploading = useSignal(false);
const error = useSignal<string | null>(null);
const success = useSignal<string | null>(null);
const inputRef = useRef<HTMLInputElement>(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<string>,
fileData: Signal<File | null>,
): () => 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<FileReader>) => {
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<string>("");
const fileData = useSignal<File | null>(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 (
<>
<input type="file" accept=".xlsx, .xls" onChange={handleFileChange} />
<button type="button" onClick={confirmUpload}>Confirm Upload</button>
<p>{statusMessage.value}</p>
</>
<div>
<input
ref={inputRef}
type="file"
accept=".xlsx,.xls"
style="display:none"
onChange={onInputChange}
/>
<div
class={`drop-zone${dragging.value ? " dragging" : ""}`}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onClick={() => inputRef.current?.click()}
>
<span class="drop-zone-icon"></span>
{file.value
? <span class="drop-zone-file">{file.value.name}</span>
: (
<>
<span class="drop-zone-text">Glisser le fichier .xlsx ici</span>
<span class="drop-zone-hint">ou cliquer pour parcourir</span>
</>
)}
</div>
{error.value && <p class="state-error">{error.value}</p>}
{success.value && (
<p style="font-size:0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.75rem">
{success.value}
</p>
)}
<div class="upload-actions">
<button
type="button"
class="btn btn-primary"
onClick={doImport}
disabled={!file.value || uploading.value}
>
{uploading.value ? "…" : "⊕ Importer"}
</button>
<button
type="button"
class="btn btn-secondary"
onClick={downloadTemplate}
>
Télécharger Modèle
</button>
</div>
<p class="upload-format">
Format : <strong>promo</strong> (nom de la feuille) |{" "}
<strong>numEtud</strong> | <strong>nom</strong> |{" "}
<strong>prénom</strong>
</p>
</div>
);
}
@@ -9,10 +9,16 @@ import { State } from "$root/defaults/interfaces.ts";
// deno-lint-ignore require-await
async function Students(_request: Request, _context: FreshContext<State>) {
return (
<>
<h2>Upload Students</h2>
<div class="page-content">
<h2 class="page-title">Importer des Élèves</h2>
<p
class="upload-format"
style="margin-bottom: 1.25rem"
>
POST /students/api/students/import-csv
</p>
<UploadStudents />
</>
</div>
);
}