Adding table promotion (consult not working yet)

This commit is contained in:
Clayzxr
2025-01-21 16:31:08 +01:00
parent 642d59dcab
commit db6669901b
3 changed files with 133 additions and 52 deletions
@@ -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<Student[]>([]);
const [promotions, setPromotions] = useState<Promotion[]>([]);
const [studentsByPromotion, setStudentsByPromotion] = useState<Record<number, Student[]>>({});
const [error, setError] = useState<string | null>(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<number, Student[]> = {};
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 (
<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>
{promotions.length === 0 ? (
<p>No promotions found.</p>
) : (
promotions.map((promo) => (
<div key={promo.id}>
<h3>Promotion: {promo.name}</h3>
{studentsByPromotion[promo.id]?.length ? (
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{studentsByPromotion[promo.id].map((student) => (
<tr key={student.id}>
<td>{student.id}</td>
<td>{student.firstName}</td>
<td>{student.lastName}</td>
<td>{student.email}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No students in this promotion.</p>
)}
</div>
))
)}
</section>
);
+36 -17
View File
@@ -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");
+31
View File
@@ -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 });
}
},
};