Working DB with table promotions
This commit is contained in:
@@ -11,57 +11,39 @@ interface Student {
|
|||||||
lastName: string;
|
lastName: string;
|
||||||
email: string;
|
email: string;
|
||||||
promotionId: number;
|
promotionId: number;
|
||||||
|
promotionName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function ConsultStudents() {
|
export default function ConsultStudents() {
|
||||||
const [promotions, setPromotions] = useState<Promotion[]>([]);
|
const [data, setData] = useState<{ promotions: Promotion[]; students: Student[] } | null>(null);
|
||||||
const [studentsByPromotion, setStudentsByPromotion] = useState<Record<number, Student[]>>({});
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchPromotionsAndStudents = async () => {
|
const fetchData = async () => {
|
||||||
try {
|
try {
|
||||||
const promoResponse = await fetch("/mobility/api/promotions");
|
const response = await fetch("/mobility/api/insert_students");
|
||||||
if (!promoResponse.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`Error fetching promotions: ${promoResponse.statusText}`);
|
throw new Error(`Error fetching data: ${response.statusText}`);
|
||||||
}
|
}
|
||||||
const promos: Promotion[] = await promoResponse.json();
|
|
||||||
setPromotions(promos);
|
|
||||||
|
|
||||||
const studentsResponse = await fetch("/mobility/api/insert_students");
|
const result = await response.json();
|
||||||
if (!studentsResponse.ok) {
|
setData(result);
|
||||||
throw new Error(`Error fetching students: ${studentsResponse.statusText}`);
|
|
||||||
}
|
|
||||||
const students: Student[] = await studentsResponse.json();
|
|
||||||
|
|
||||||
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) {
|
} catch (err) {
|
||||||
console.error("Error fetching promotions or students:", err);
|
console.error("Error fetching data:", err);
|
||||||
setError("Failed to load data. Please try again later.");
|
setError("Failed to load data. Please try again later.");
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchPromotionsAndStudents();
|
fetchData();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
<h2>Consult Students</h2>
|
<h2>Consult Students</h2>
|
||||||
{error && <p className="error">{error}</p>}
|
{error && <p className="error">{error}</p>}
|
||||||
{promotions.length === 0 ? (
|
{data?.promotions.map((promo) => (
|
||||||
<p>No promotions found.</p>
|
|
||||||
) : (
|
|
||||||
promotions.map((promo) => (
|
|
||||||
<div key={promo.id}>
|
<div key={promo.id}>
|
||||||
<h3>Promotion: {promo.name}</h3>
|
<h3>Promotion: {promo.name}</h3>
|
||||||
{studentsByPromotion[promo.id]?.length ? (
|
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -72,7 +54,9 @@ export default function ConsultStudents() {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{studentsByPromotion[promo.id].map((student) => (
|
{data.students
|
||||||
|
.filter((student) => student.promotionId === promo.id)
|
||||||
|
.map((student) => (
|
||||||
<tr key={student.id}>
|
<tr key={student.id}>
|
||||||
<td>{student.id}</td>
|
<td>{student.id}</td>
|
||||||
<td>{student.firstName}</td>
|
<td>{student.firstName}</td>
|
||||||
@@ -82,12 +66,8 @@ export default function ConsultStudents() {
|
|||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
) : (
|
|
||||||
<p>No students in this promotion.</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
))
|
))}
|
||||||
)}
|
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,18 +11,15 @@ export default function UploadStudents() {
|
|||||||
if (input.files && input.files.length > 0) {
|
if (input.files && input.files.length > 0) {
|
||||||
fileData.value = input.files[0];
|
fileData.value = input.files[0];
|
||||||
statusMessage.value = "File selected: " + input.files[0].name;
|
statusMessage.value = "File selected: " + input.files[0].name;
|
||||||
console.log("File selected:", input.files[0].name);
|
|
||||||
} else {
|
} else {
|
||||||
fileData.value = null;
|
fileData.value = null;
|
||||||
statusMessage.value = "No file selected";
|
statusMessage.value = "No file selected";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const confirmUpload = () => {
|
const confirmUpload = async () => {
|
||||||
console.log("Confirm Upload");
|
|
||||||
if (!fileData.value) {
|
if (!fileData.value) {
|
||||||
statusMessage.value = "Please select a file before confirming upload.";
|
statusMessage.value = "Please select a file before confirming upload.";
|
||||||
console.error("Error: No file selected.");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,7 +27,6 @@ export default function UploadStudents() {
|
|||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
|
|
||||||
reader.onload = async (e) => {
|
reader.onload = async (e) => {
|
||||||
try {
|
|
||||||
const arrayBuffer = e.target?.result as ArrayBuffer;
|
const arrayBuffer = e.target?.result as ArrayBuffer;
|
||||||
const workbook = XLSX.read(arrayBuffer, { type: "array" });
|
const workbook = XLSX.read(arrayBuffer, { type: "array" });
|
||||||
|
|
||||||
@@ -41,8 +37,6 @@ export default function UploadStudents() {
|
|||||||
range: 1, // Ignorer les en-têtes
|
range: 1, // Ignorer les en-têtes
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`Data from sheet ${sheetName}:`, data);
|
|
||||||
|
|
||||||
const response = await fetch("/mobility/api/insert_students", {
|
const response = await fetch("/mobility/api/insert_students", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -50,22 +44,14 @@ export default function UploadStudents() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(
|
throw new Error(`Failed to insert data for promotion ${sheetName}`);
|
||||||
`Failed to insert data for promotion ${sheetName}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
statusMessage.value = "Data uploaded and inserted successfully!";
|
statusMessage.value = "Data uploaded and inserted successfully!";
|
||||||
} catch (error) {
|
|
||||||
console.error("Error processing the file:", error);
|
|
||||||
statusMessage.value =
|
|
||||||
"Error processing the file. Please check its format.";
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
reader.onerror = (e) => {
|
reader.onerror = () => {
|
||||||
console.error("FileReader error:", e);
|
|
||||||
statusMessage.value = "Error reading the file.";
|
statusMessage.value = "Error reading the file.";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -2,58 +2,10 @@ import { Handlers } from "$fresh/server.ts";
|
|||||||
import { Database } from "@db/sqlite";
|
import { Database } from "@db/sqlite";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
async GET(_request, context) {
|
async GET() {
|
||||||
try {
|
try {
|
||||||
const db = new Database("databases/data/mobility.db");
|
const db = new Database("databases/data/mobility.db");
|
||||||
|
|
||||||
db.prepare(
|
|
||||||
`
|
|
||||||
CREATE TABLE IF NOT EXISTS students (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
firstName TEXT NOT NULL,
|
|
||||||
lastName TEXT NOT NULL,
|
|
||||||
email TEXT NOT NULL,
|
|
||||||
promotionId INTEGER NOT NULL,
|
|
||||||
FOREIGN KEY (promotionId) REFERENCES promotions (id)
|
|
||||||
);
|
|
||||||
`
|
|
||||||
).run();
|
|
||||||
|
|
||||||
const rows = db
|
|
||||||
.prepare(
|
|
||||||
"SELECT students.id, firstName, lastName, email, promotionId FROM students"
|
|
||||||
)
|
|
||||||
.all();
|
|
||||||
|
|
||||||
db.close();
|
|
||||||
|
|
||||||
return new Response(JSON.stringify(rows), {
|
|
||||||
status: 200,
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching students:", error);
|
|
||||||
return new Response("Failed to fetch students", { status: 500 });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
async POST(request) {
|
|
||||||
console.log("API /mobility/api/insert_students called");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const body = await request.json();
|
|
||||||
const { data, promoName } = body;
|
|
||||||
|
|
||||||
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");
|
|
||||||
|
|
||||||
console.log("Database opened successfully");
|
|
||||||
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`
|
`
|
||||||
CREATE TABLE IF NOT EXISTS promotions (
|
CREATE TABLE IF NOT EXISTS promotions (
|
||||||
@@ -76,9 +28,48 @@ export const handler: Handlers = {
|
|||||||
`
|
`
|
||||||
).run();
|
).run();
|
||||||
|
|
||||||
console.log("Tables ensured successfully");
|
const promotions = db.prepare("SELECT id, name FROM promotions").all();
|
||||||
|
|
||||||
|
const students = db
|
||||||
|
.prepare(
|
||||||
|
`
|
||||||
|
SELECT students.id, firstName, lastName, email, promotionId, promotions.name AS promotionName
|
||||||
|
FROM students
|
||||||
|
JOIN promotions ON students.promotionId = promotions.id
|
||||||
|
`
|
||||||
|
)
|
||||||
|
.all();
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ promotions, students }),
|
||||||
|
{
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching data:", error);
|
||||||
|
return new Response("Failed to fetch data", { status: 500 });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async POST(request) {
|
||||||
|
console.log("API /mobility/api/insert_students called");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = await request.json();
|
||||||
|
const { data, promoName } = body;
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
// Insérer ou récupérer l'ID de la promotion
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
"INSERT OR IGNORE INTO promotions (name) VALUES (?)"
|
"INSERT OR IGNORE INTO promotions (name) VALUES (?)"
|
||||||
).run(promoName);
|
).run(promoName);
|
||||||
@@ -99,13 +90,13 @@ export const handler: Handlers = {
|
|||||||
insertQuery.run(student.Nom, student["Prénom"], student.Mail, promoId);
|
insertQuery.run(student.Nom, student["Prénom"], student.Mail, promoId);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("All students inserted successfully");
|
|
||||||
db.close();
|
db.close();
|
||||||
|
|
||||||
return new Response("Students inserted successfully", { status: 201 });
|
console.log("All data inserted successfully");
|
||||||
|
return new Response("Data inserted successfully", { status: 201 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error inserting students:", error);
|
console.error("Error inserting data:", error);
|
||||||
return new Response("Failed to insert students", { status: 500 });
|
return new Response("Failed to insert data", { status: 500 });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
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 });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
Reference in New Issue
Block a user