Moved all student management tools into student app for global uses (working)

This commit is contained in:
Clayzxr
2025-01-21 17:29:59 +01:00
parent c04505e95d
commit b5fedbb425
12 changed files with 79 additions and 65 deletions
@@ -0,0 +1,73 @@
import { useEffect, useState } from "preact/hooks";
interface Promotion {
id: number;
name: string;
}
interface Student {
id: number;
firstName: string;
lastName: string;
email: string;
promotionId: number;
promotionName: string;
}
export default function ConsultStudents() {
const [data, setData] = useState<{ promotions: Promotion[]; students: Student[] } | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch("/students/api/insert_students");
if (!response.ok) {
throw new Error(`Error fetching data: ${response.statusText}`);
}
const result = await response.json();
setData(result);
} catch (err) {
console.error("Error fetching data:", err);
setError("Failed to load data. Please try again later.");
}
};
fetchData();
}, []);
return (
<section>
<h2>Consult Students</h2>
{error && <p className="error">{error}</p>}
{data?.promotions.map((promo) => (
<div key={promo.id}>
<h3>Promotion: {promo.name}</h3>
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{data.students
.filter((student) => student.promotionId === 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>
</div>
))}
</section>
);
}
@@ -0,0 +1,73 @@
// @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 { useSignal } from "@preact/signals";
export default function UploadStudents() {
const statusMessage = useSignal<string>("");
const fileData = useSignal<File | null>(null);
const handleFileChange = (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";
}
};
const confirmUpload = async () => {
if (!fileData.value) {
statusMessage.value = "Please select a file before confirming upload.";
return;
}
try {
const reader = new FileReader();
reader.onload = async (e) => {
const arrayBuffer = e.target?.result as ArrayBuffer;
const workbook = XLSX.read(arrayBuffer, { type: "array" });
for (const sheetName of workbook.SheetNames) {
const sheet = workbook.Sheets[sheetName];
const data = XLSX.utils.sheet_to_json(sheet, {
header: ["Nom", "Prénom", "Mail"],
range: 1, // Ignorer les en-têtes
});
const response = await fetch("/students/api/insert_students", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ promoName: sheetName, data }),
});
if (!response.ok) {
throw new Error(`Failed to insert data for promotion ${sheetName}`);
}
}
statusMessage.value = "Data uploaded and inserted successfully!";
};
reader.onerror = () => {
statusMessage.value = "Error reading the file.";
};
reader.readAsArrayBuffer(fileData.value);
} catch (error) {
console.error("Error uploading file:", error);
statusMessage.value = "An unexpected error occurred during upload.";
}
};
return (
<div>
<h2>Upload Students</h2>
<input type="file" accept=".xlsx, .xls" onChange={handleFileChange} />
<button onClick={confirmUpload}>Confirm Upload</button>
<p>{statusMessage.value}</p>
</div>
);
}
+4 -2
View File
@@ -5,10 +5,12 @@ const properties: AppProperties = {
icon: "badge",
pages: {
index: "Homepage",
overview: "Students overview",
upload: "Upload students",
consult: "Consult students"
},
adminOnly: ["upload"],
hint: "See student information",
adminOnly: ["upload", "consult"],
hint: "Create students promotion and see informations",
};
export default properties;
-22
View File
@@ -1,22 +0,0 @@
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
async POST(request, context) {
if (request.headers.get("content-type") != "application/json") {
return new Response(null, {
status: 400,
});
}
const responseBody = {
requestBody: await request.json(),
context,
};
return new Response(JSON.stringify(responseBody), {
headers: {
"content-type": "application/json",
},
});
},
};
@@ -0,0 +1,102 @@
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();
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 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");
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, promotionId) VALUES (?, ?, ?, ?)"
);
for (const student of data) {
console.log("Inserting student:", student);
insertQuery.run(student.Nom, student["Prénom"], student.Mail, promoId);
}
db.close();
console.log("All data inserted successfully");
return new Response("Data inserted successfully", { status: 201 });
} catch (error) {
console.error("Error inserting data:", error);
return new Response("Failed to insert data", { status: 500 });
}
},
};
@@ -0,0 +1,17 @@
import ConsultStudents from "$root/routes/(apps)/students/(_islands)/ConsultStudents.tsx";
import { getPartialsConfig, makePartials } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/routes/_middleware.ts";
//import EditStudents from "../(_islands)/EditStudents.tsx";
async function Students(_request: Request, _context: FreshContext<State>) {
return (
<>
<h1>Manage Promotions</h1>
<ConsultStudents />
</>
);
}
export const config = getPartialsConfig();
export default makePartials(Students);
@@ -0,0 +1,17 @@
import UploadStudents from "$root/routes/(apps)/students/(_islands)/UploadStudents.tsx";
import { getPartialsConfig, makePartials } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/routes/_middleware.ts";
//import EditStudents from "../(_islands)/EditStudents.tsx";
async function Students(_request: Request, _context: FreshContext<State>) {
return (
<>
<h1>Manage Promotions</h1>
<UploadStudents />
</>
);
}
export const config = getPartialsConfig();
export default makePartials(Students);
@@ -0,0 +1,17 @@
import { Partial } from "$fresh/runtime.ts";
import { RouteConfig } from "$fresh/server.ts";
type ModulesProps = Record<string | number | symbol, never>;
export const config: RouteConfig = {
skipAppWrapper: true,
skipInheritedLayouts: true,
};
export default function Modules(_props: ModulesProps) {
return (
<Partial name="body">
<a href="students" f-partial={"notes/partials"}>students</a>
</Partial>
);
}