Merge pull request #25 from fedyna-k/PMPR-22

Pmpr 22
This commit is contained in:
Kevin FEDYNA
2025-01-21 16:11:56 +01:00
committed by GitHub
12 changed files with 129 additions and 31 deletions
@@ -0,0 +1,67 @@
import { useEffect, useState } from "preact/hooks";
interface Student {
id: number;
firstName: string;
lastName: string;
email: string;
promotion: string;
}
export default function ConsultStudents() {
const [students, setStudents] = useState<Student[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchStudents = async () => {
try {
const response = await fetch("/mobility/api/insert_students");
if (!response.ok) {
throw new Error(`Error fetching students: ${response.statusText}`);
}
const data: Student[] = await response.json();
setStudents(data);
} catch (err) {
console.error("Error fetching students:", err);
setError("Failed to load students. Please try again later.");
}
};
fetchStudents();
}, []);
return (
<section>
<h2>Consult Students</h2>
{error && <p className="error">{error}</p>}
{students.length === 0 ? (
<p>No students found.</p>
) : (
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Promotion</th>
</tr>
</thead>
<tbody>
{students.map((student) => (
<tr key={student.id}>
<td>{student.id}</td>
<td>{student.firstName}</td>
<td>{student.lastName}</td>
<td>{student.email}</td>
<td>{student.promotion}</td>
</tr>
))}
</tbody>
</table>
)}
</section>
);
}
@@ -11,6 +11,7 @@ export default function UploadStudents() {
if (input.files && input.files.length > 0) {
fileData.value = input.files[0];
statusMessage.value = "File selected: " + input.files[0].name;
console.log("File selected:", input.files[0].name);
} else {
fileData.value = null;
statusMessage.value = "No file selected";
@@ -18,8 +19,10 @@ export default function UploadStudents() {
};
const confirmUpload = async () => {
console.log("Confirm Upload");
if (!fileData.value) {
statusMessage.value = "Please select a file before confirming upload.";
console.error("Error: No file selected.");
return;
}
@@ -34,11 +37,13 @@ export default function UploadStudents() {
for (const sheetName of workbook.SheetNames) {
const sheet = workbook.Sheets[sheetName];
const data = XLSX.utils.sheet_to_json(sheet, {
header: ["Nom", "Prénom", "Mail"],
header: ["Nom", "Prénom", "Mail"],
range: 1, // Ignorer les en-têtes
});
const response = await fetch("/api/insert_students", {
console.log(`Data from sheet ${sheetName}:`, data);
const response = await fetch("/mobility/api/insert_students", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ promoName: sheetName, data }),
+31 -25
View File
@@ -1,14 +1,13 @@
import { Handlers } from "$fresh/server.ts";
import { Database } from "@db/sqlite";
import { Database } from "@db/sqlite";
export const handler: Handlers = {
async GET(_request, context) {
try {
// Ouvre ou crée la base de données SQLite
const db = new Database("databases/data/mobility.db");
// Crée la table si elle n'existe pas
db.execute(`
db.prepare(
`
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
firstName TEXT NOT NULL,
@@ -16,19 +15,16 @@ export const handler: Handlers = {
email TEXT NOT NULL,
promotion TEXT NOT NULL
);
`);
`
).run();
// Récupère toutes les données
const students = [];
for (const [id, firstName, lastName, email, promotion] of db.query(
const rows = db.prepare(
"SELECT id, firstName, lastName, email, promotion FROM students"
)) {
students.push({ id, firstName, lastName, email, promotion });
}
).all();
db.close();
return new Response(JSON.stringify(students), {
return new Response(JSON.stringify(rows), {
status: 200,
headers: { "Content-Type": "application/json" },
});
@@ -39,15 +35,24 @@ export const handler: Handlers = {
},
async POST(request) {
console.log("API /mobility/api/insert_students called");
try {
const body = await request.json();
const { data, promoName } = body;
// Ouvre ou crée la base de données SQLite
console.log("Received data:", { promoName, data });
if (!promoName || !Array.isArray(data)) {
throw new Error("Invalid request body");
}
const db = new Database("databases/data/mobility.db");
// Crée la table si elle n'existe pas
db.execute(`
console.log("Database opened successfully");
db.prepare(
`
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
firstName TEXT NOT NULL,
@@ -55,20 +60,21 @@ export const handler: Handlers = {
email TEXT NOT NULL,
promotion TEXT NOT NULL
);
`);
`
).run();
console.log("Table ensured successfully");
const insertQuery = db.prepare(
"INSERT INTO students (firstName, lastName, email, promotion) VALUES (?, ?, ?, ?)"
);
// Prépare et insère les données
const insertQuery =
"INSERT INTO students (firstName, lastName, email, promotion) VALUES (?, ?, ?, ?)";
for (const student of data) {
db.query(insertQuery, [
student.firstName,
student.lastName,
student.email,
promoName,
]);
console.log("Inserting student:", student);
insertQuery.run(student.Nom, student["Prénom"], student.Mail, promoName);
}
console.log("All students inserted successfully");
db.close();
return new Response("Students inserted successfully", { status: 201 });
+4 -3
View File
@@ -1,7 +1,7 @@
import { RouteConfig } from "$fresh/server.ts";
import UploadStudents from "../(_components)/UploadStudents.tsx";
//import ConsultStudents from "../(_components)/ConsultStudents.tsx";
//import EditStudents from "../(_components)/EditStudents.tsx";
import UploadStudents from "../(_islands)/UploadStudents.tsx";
import ConsultStudents from "../(_islands)/ConsultStudents.tsx";
//import EditStudents from "../(_islands)/EditStudents.tsx";
export const config: RouteConfig = {
skipAppWrapper: false,
@@ -14,6 +14,7 @@ export default function Students() {
<h1>Manage Promotions</h1>
<UploadStudents />
<hr />
<ConsultStudents />
</section>
);
}