From db6669901b15f0191902004ecb740ea7362c3ff6 Mon Sep 17 00:00:00 2001 From: Clayzxr Date: Tue, 21 Jan 2025 16:31:08 +0100 Subject: [PATCH] Adding table promotion (consult not working yet) --- .../mobility/(_islands)/ConsultStudents.tsx | 101 ++++++++++++------ routes/(apps)/mobility/api/insert_students.ts | 53 ++++++--- routes/(apps)/mobility/api/promo.ts | 31 ++++++ 3 files changed, 133 insertions(+), 52 deletions(-) create mode 100644 routes/(apps)/mobility/api/promo.ts diff --git a/routes/(apps)/mobility/(_islands)/ConsultStudents.tsx b/routes/(apps)/mobility/(_islands)/ConsultStudents.tsx index 4ca3459..8513a6b 100644 --- a/routes/(apps)/mobility/(_islands)/ConsultStudents.tsx +++ b/routes/(apps)/mobility/(_islands)/ConsultStudents.tsx @@ -1,64 +1,95 @@ import { useEffect, useState } from "preact/hooks"; +interface Promotion { + id: number; + name: string; +} + interface Student { id: number; firstName: string; lastName: string; email: string; - promotion: string; + promotionId: number; } export default function ConsultStudents() { - const [students, setStudents] = useState([]); + const [promotions, setPromotions] = useState([]); + const [studentsByPromotion, setStudentsByPromotion] = useState>({}); const [error, setError] = useState(null); useEffect(() => { - const fetchStudents = async () => { + const fetchPromotionsAndStudents = async () => { try { - const response = await fetch("/mobility/api/insert_students"); - - if (!response.ok) { - throw new Error(`Error fetching students: ${response.statusText}`); + // Récupérer toutes les promotions + const promoResponse = await fetch("/mobility/api/promotions"); + if (!promoResponse.ok) { + throw new Error(`Error fetching promotions: ${promoResponse.statusText}`); } + const promos: Promotion[] = await promoResponse.json(); + setPromotions(promos); - const data: Student[] = await response.json(); - setStudents(data); + // Récupérer les étudiants + const studentsResponse = await fetch("/mobility/api/insert_students"); + if (!studentsResponse.ok) { + throw new Error(`Error fetching students: ${studentsResponse.statusText}`); + } + const students: Student[] = await studentsResponse.json(); + + // Grouper les étudiants par promotionId + const grouped: Record = {}; + for (const student of students) { + if (!grouped[student.promotionId]) { + grouped[student.promotionId] = []; + } + grouped[student.promotionId].push(student); + } + setStudentsByPromotion(grouped); } catch (err) { - console.error("Error fetching students:", err); - setError("Failed to load students. Please try again later."); + console.error("Error fetching promotions or students:", err); + setError("Failed to load data. Please try again later."); } }; - fetchStudents(); + fetchPromotionsAndStudents(); }, []); return (

Consult Students

{error &&

{error}

} - {students.length === 0 ?

No students found.

: ( - - - - - - - - - - - - {students.map((student) => ( - - - - - - - - ))} - -
IDFirst NameLast NameEmailPromotion
{student.id}{student.firstName}{student.lastName}{student.email}{student.promotion}
+ {promotions.length === 0 ? ( +

No promotions found.

+ ) : ( + promotions.map((promo) => ( +
+

Promotion: {promo.name}

+ {studentsByPromotion[promo.id]?.length ? ( + + + + + + + + + + + {studentsByPromotion[promo.id].map((student) => ( + + + + + + + ))} + +
IDFirst NameLast NameEmail
{student.id}{student.firstName}{student.lastName}{student.email}
+ ) : ( +

No students in this promotion.

+ )} +
+ )) )}
); diff --git a/routes/(apps)/mobility/api/insert_students.ts b/routes/(apps)/mobility/api/insert_students.ts index e8af2fe..6fac691 100644 --- a/routes/(apps)/mobility/api/insert_students.ts +++ b/routes/(apps)/mobility/api/insert_students.ts @@ -2,8 +2,7 @@ import { Handlers } from "$fresh/server.ts"; import { Database } from "@db/sqlite"; export const handler: Handlers = { - // deno-lint-ignore require-await - async GET(_request, _context) { + async GET(_request, context) { try { const db = new Database("databases/data/mobility.db"); @@ -14,14 +13,17 @@ export const handler: Handlers = { firstName TEXT NOT NULL, lastName TEXT NOT NULL, email TEXT NOT NULL, - promotion TEXT NOT NULL + promotionId INTEGER NOT NULL, + FOREIGN KEY (promotionId) REFERENCES promotions (id) ); - `, + ` ).run(); - const rows = db.prepare( - "SELECT id, firstName, lastName, email, promotion FROM students", - ).all(); + const rows = db + .prepare( + "SELECT students.id, firstName, lastName, email, promotionId FROM students" + ) + .all(); db.close(); @@ -52,6 +54,15 @@ export const handler: Handlers = { console.log("Database opened successfully"); + db.prepare( + ` + CREATE TABLE IF NOT EXISTS promotions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE NOT NULL + ); + ` + ).run(); + db.prepare( ` CREATE TABLE IF NOT EXISTS students ( @@ -59,25 +70,33 @@ export const handler: Handlers = { firstName TEXT NOT NULL, lastName TEXT NOT NULL, email TEXT NOT NULL, - promotion TEXT NOT NULL + promotionId INTEGER NOT NULL, + FOREIGN KEY (promotionId) REFERENCES promotions (id) ); - `, + ` ).run(); - console.log("Table ensured successfully"); + console.log("Tables ensured successfully"); + + // Insérer ou récupérer l'ID de la promotion + db.prepare( + "INSERT OR IGNORE INTO promotions (name) VALUES (?)" + ).run(promoName); + + const promoIdRow = db + .prepare("SELECT id FROM promotions WHERE name = ?") + .get(promoName); + const promoId = promoIdRow.id; + + console.log(`Promotion ID for "${promoName}":`, promoId); const insertQuery = db.prepare( - "INSERT INTO students (firstName, lastName, email, promotion) VALUES (?, ?, ?, ?)", + "INSERT INTO students (firstName, lastName, email, promotionId) VALUES (?, ?, ?, ?)" ); for (const student of data) { console.log("Inserting student:", student); - insertQuery.run( - student.Nom, - student["Prénom"], - student.Mail, - promoName, - ); + insertQuery.run(student.Nom, student["Prénom"], student.Mail, promoId); } console.log("All students inserted successfully"); diff --git a/routes/(apps)/mobility/api/promo.ts b/routes/(apps)/mobility/api/promo.ts new file mode 100644 index 0000000..288524b --- /dev/null +++ b/routes/(apps)/mobility/api/promo.ts @@ -0,0 +1,31 @@ +import { Handlers } from "$fresh/server.ts"; +import { Database } from "@db/sqlite"; + +export const handler: Handlers = { + async GET() { + try { + const db = new Database("databases/data/mobility.db"); + + db.prepare( + ` + CREATE TABLE IF NOT EXISTS promotions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE NOT NULL + ); + ` + ).run(); + + const promotions = db.prepare("SELECT id, name FROM promotions").all(); + + db.close(); + + return new Response(JSON.stringify(promotions), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } catch (error) { + console.error("Error fetching promotions:", error); + return new Response("Failed to fetch promotions", { status: 500 }); + } + }, +};