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
@@ -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>
);
}