feat : fix a lot of stuff
Check Deno code / Check Deno code (pull_request) Failing after 8s
Tests / Unit tests (pull_request) Successful in 13s
Tests / Integration tests (pull_request) Failing after 1m0s

This commit is contained in:
2026-04-30 13:49:47 +02:00
parent 04be659d6b
commit df3957741d
50 changed files with 2664 additions and 437 deletions
@@ -0,0 +1,3 @@
ALTER TABLE "notes" ADD COLUMN "noteSession2" double precision;
--> statement-breakpoint
ALTER TABLE "ajustements" ADD COLUMN "malus" integer NOT NULL DEFAULT 0;
+7
View File
@@ -22,6 +22,13 @@
"when": 1777155028710, "when": 1777155028710,
"tag": "0002_update_permission_names", "tag": "0002_update_permission_names",
"breakpoints": true "breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1777155028711,
"tag": "0003_add_session2_and_malus",
"breakpoints": true
} }
] ]
} }
+2
View File
@@ -75,6 +75,7 @@ export const notes = pgTable("notes", {
numEtud: integer("numEtud").notNull().references(() => students.numEtud), numEtud: integer("numEtud").notNull().references(() => students.numEtud),
idModule: text("idModule").notNull().references(() => modules.id), idModule: text("idModule").notNull().references(() => modules.id),
note: doublePrecision("note").notNull(), note: doublePrecision("note").notNull(),
noteSession2: doublePrecision("noteSession2"),
}, (t) => ({ }, (t) => ({
pk: primaryKey({ columns: [t.numEtud, t.idModule] }), pk: primaryKey({ columns: [t.numEtud, t.idModule] }),
})); }));
@@ -83,6 +84,7 @@ export const ajustements = pgTable("ajustements", {
numEtud: integer("numEtud").notNull().references(() => students.numEtud), numEtud: integer("numEtud").notNull().references(() => students.numEtud),
idUE: integer("idUE").notNull().references(() => ues.id), idUE: integer("idUE").notNull().references(() => ues.id),
valeur: doublePrecision("valeur").notNull(), valeur: doublePrecision("valeur").notNull(),
malus: integer("malus").notNull().default(0),
}, (t) => ({ }, (t) => ({
pk: primaryKey({ columns: [t.numEtud, t.idUE] }), pk: primaryKey({ columns: [t.numEtud, t.idUE] }),
})); }));
+102
View File
@@ -0,0 +1,102 @@
import { useState } from "preact/hooks";
export type ImportResult = {
added: number;
modified: number;
ignored: number;
errors: number;
details: ImportDetail[];
};
export type ImportDetail = {
type: "change" | "error";
message: string;
};
type Props = {
result: ImportResult;
onClose: () => void;
};
export default function ImportResultPopup({ result, onClose }: Props) {
const [showDetails, setShowDetails] = useState(false);
const hasErrors = result.errors > 0;
const changes = result.details.filter((d) => d.type === "change");
const errors = result.details.filter((d) => d.type === "error");
return (
<div class="import-popup-overlay" onClick={onClose}>
<div class="import-popup" onClick={(e) => e.stopPropagation()}>
<div class="import-popup-header">
<h3 class="import-popup-title">Resultats de l'import</h3>
<span
class={`import-popup-badge ${
hasErrors ? "badge-error" : "badge-success"
}`}
>
{hasErrors ? "Erreur" : "Succes"}
</span>
</div>
<div class="import-popup-stats">
<div class="import-stat-row">
<span class="import-stat-label">Ajoutes</span>
<span class="import-stat-value stat-added">
{result.added} note{result.added !== 1 ? "s" : ""}
</span>
</div>
<div class="import-stat-row">
<span class="import-stat-label">Modifies</span>
<span class="import-stat-value stat-modified">
{result.modified} note{result.modified !== 1 ? "s" : ""}
</span>
</div>
<div class="import-stat-row">
<span class="import-stat-label">Ignores</span>
<span class="import-stat-value stat-ignored">
{result.ignored} note{result.ignored !== 1 ? "s" : ""}
</span>
</div>
<div class="import-stat-row">
<span class="import-stat-label">Erreurs</span>
<span class="import-stat-value stat-errors">
{result.errors} note{result.errors !== 1 ? "s" : ""}
</span>
</div>
</div>
<div class="import-popup-actions">
{result.details.length > 0 && (
<button
type="button"
class="btn btn-secondary"
onClick={() => setShowDetails(!showDetails)}
>
Details {showDetails ? "\u25B3" : "\u25BD"}
</button>
)}
<button
type="button"
class="btn btn-primary"
onClick={onClose}
>
Ok
</button>
</div>
{showDetails && result.details.length > 0 && (
<div class="import-popup-details">
{changes.length > 0 &&
changes.map((d, i) => (
<p key={`c-${i}`} class="import-detail-change">{d.message}</p>
))}
{errors.length > 0 &&
errors.map((d, i) => (
<p key={`e-${i}`} class="import-detail-error">{d.message}</p>
))}
</div>
)}
</div>
</div>
);
}
+26 -21
View File
@@ -12,15 +12,22 @@ import * as $_apps_admin_api_modules_idModule_ from "./routes/(apps)/admin/api/m
import * as $_apps_admin_api_permissions from "./routes/(apps)/admin/api/permissions.ts"; import * as $_apps_admin_api_permissions from "./routes/(apps)/admin/api/permissions.ts";
import * as $_apps_admin_api_roles from "./routes/(apps)/admin/api/roles.ts"; import * as $_apps_admin_api_roles from "./routes/(apps)/admin/api/roles.ts";
import * as $_apps_admin_api_roles_idRole_ from "./routes/(apps)/admin/api/roles/[idRole].ts"; import * as $_apps_admin_api_roles_idRole_ from "./routes/(apps)/admin/api/roles/[idRole].ts";
import * as $_apps_admin_api_ue_modules from "./routes/(apps)/admin/api/ue-modules.ts";
import * as $_apps_admin_api_ue_modules_idModule_idUE_idPromo_ from "./routes/(apps)/admin/api/ue-modules/[idModule]/[idUE]/[idPromo].ts";
import * as $_apps_admin_api_ues from "./routes/(apps)/admin/api/ues.ts";
import * as $_apps_admin_api_ues_idUE_ from "./routes/(apps)/admin/api/ues/[idUE].ts";
import * as $_apps_admin_api_users from "./routes/(apps)/admin/api/users.ts"; import * as $_apps_admin_api_users from "./routes/(apps)/admin/api/users.ts";
import * as $_apps_admin_api_users_id_ from "./routes/(apps)/admin/api/users/[id].ts"; import * as $_apps_admin_api_users_id_ from "./routes/(apps)/admin/api/users/[id].ts";
import * as $_apps_admin_index from "./routes/(apps)/admin/index.tsx"; import * as $_apps_admin_index from "./routes/(apps)/admin/index.tsx";
import * as $_apps_admin_modules_idModule_ from "./routes/(apps)/admin/modules/[idModule].tsx"; import * as $_apps_admin_modules_idModule_ from "./routes/(apps)/admin/modules/[idModule].tsx";
import * as $_apps_admin_partials_enseignements from "./routes/(apps)/admin/partials/enseignements.tsx"; import * as $_apps_admin_partials_enseignements from "./routes/(apps)/admin/partials/enseignements.tsx";
import * as $_apps_admin_partials_import_maquette from "./routes/(apps)/admin/partials/import-maquette.tsx";
import * as $_apps_admin_partials_index from "./routes/(apps)/admin/partials/index.tsx"; import * as $_apps_admin_partials_index from "./routes/(apps)/admin/partials/index.tsx";
import * as $_apps_admin_partials_modules from "./routes/(apps)/admin/partials/modules.tsx"; import * as $_apps_admin_partials_modules from "./routes/(apps)/admin/partials/modules.tsx";
import * as $_apps_admin_partials_permissions from "./routes/(apps)/admin/partials/permissions.tsx"; import * as $_apps_admin_partials_permissions from "./routes/(apps)/admin/partials/permissions.tsx";
import * as $_apps_admin_partials_promotions from "./routes/(apps)/admin/partials/promotions.tsx";
import * as $_apps_admin_partials_roles from "./routes/(apps)/admin/partials/roles.tsx"; import * as $_apps_admin_partials_roles from "./routes/(apps)/admin/partials/roles.tsx";
import * as $_apps_admin_partials_ues from "./routes/(apps)/admin/partials/ues.tsx";
import * as $_apps_admin_partials_users from "./routes/(apps)/admin/partials/users.tsx"; import * as $_apps_admin_partials_users from "./routes/(apps)/admin/partials/users.tsx";
import * as $_apps_admin_users_id_ from "./routes/(apps)/admin/users/[id].tsx"; import * as $_apps_admin_users_id_ from "./routes/(apps)/admin/users/[id].tsx";
import * as $_apps_mobility_api_insert_mobility from "./routes/(apps)/mobility/api/insert_mobility.ts"; import * as $_apps_mobility_api_insert_mobility from "./routes/(apps)/mobility/api/insert_mobility.ts";
@@ -33,15 +40,10 @@ import * as $_apps_notes_api_ajustements_numEtud_idUE_ from "./routes/(apps)/not
import * as $_apps_notes_api_notes from "./routes/(apps)/notes/api/notes.ts"; import * as $_apps_notes_api_notes from "./routes/(apps)/notes/api/notes.ts";
import * as $_apps_notes_api_notes_numEtud_idModule_ from "./routes/(apps)/notes/api/notes/[numEtud]/[idModule].ts"; import * as $_apps_notes_api_notes_numEtud_idModule_ from "./routes/(apps)/notes/api/notes/[numEtud]/[idModule].ts";
import * as $_apps_notes_api_notes_import_xlsx from "./routes/(apps)/notes/api/notes/import-xlsx.ts"; import * as $_apps_notes_api_notes_import_xlsx from "./routes/(apps)/notes/api/notes/import-xlsx.ts";
import * as $_apps_notes_api_ue_modules from "./routes/(apps)/notes/api/ue-modules.ts";
import * as $_apps_notes_api_ue_modules_idModule_idUE_idPromo_ from "./routes/(apps)/notes/api/ue-modules/[idModule]/[idUE]/[idPromo].ts";
import * as $_apps_notes_api_ues from "./routes/(apps)/notes/api/ues.ts";
import * as $_apps_notes_api_ues_idUE_ from "./routes/(apps)/notes/api/ues/[idUE].ts";
import * as $_apps_notes_edition_numEtud_ from "./routes/(apps)/notes/edition/[numEtud].tsx"; import * as $_apps_notes_edition_numEtud_ from "./routes/(apps)/notes/edition/[numEtud].tsx";
import * as $_apps_notes_index from "./routes/(apps)/notes/index.tsx"; import * as $_apps_notes_index from "./routes/(apps)/notes/index.tsx";
import * as $_apps_notes_partials_admin_courses from "./routes/(apps)/notes/partials/(admin)/courses.tsx"; import * as $_apps_notes_partials_admin_courses from "./routes/(apps)/notes/partials/(admin)/courses.tsx";
import * as $_apps_notes_partials_admin_import from "./routes/(apps)/notes/partials/(admin)/import.tsx"; import * as $_apps_notes_partials_admin_import from "./routes/(apps)/notes/partials/(admin)/import.tsx";
import * as $_apps_notes_partials_admin_ues from "./routes/(apps)/notes/partials/(admin)/ues.tsx";
import * as $_apps_notes_partials_index from "./routes/(apps)/notes/partials/index.tsx"; import * as $_apps_notes_partials_index from "./routes/(apps)/notes/partials/index.tsx";
import * as $_apps_notes_partials_notes from "./routes/(apps)/notes/partials/notes.tsx"; import * as $_apps_notes_partials_notes from "./routes/(apps)/notes/partials/notes.tsx";
import * as $_apps_notes_recap_numEtud_ from "./routes/(apps)/notes/recap/[numEtud].tsx"; import * as $_apps_notes_recap_numEtud_ from "./routes/(apps)/notes/recap/[numEtud].tsx";
@@ -53,7 +55,6 @@ import * as $_apps_students_api_students_import_csv from "./routes/(apps)/studen
import * as $_apps_students_edit_numEtud_ from "./routes/(apps)/students/edit/[numEtud].tsx"; import * as $_apps_students_edit_numEtud_ from "./routes/(apps)/students/edit/[numEtud].tsx";
import * as $_apps_students_index from "./routes/(apps)/students/index.tsx"; import * as $_apps_students_index from "./routes/(apps)/students/index.tsx";
import * as $_apps_students_partials_admin_consult from "./routes/(apps)/students/partials/(admin)/consult.tsx"; import * as $_apps_students_partials_admin_consult from "./routes/(apps)/students/partials/(admin)/consult.tsx";
import * as $_apps_students_partials_admin_promotions from "./routes/(apps)/students/partials/(admin)/promotions.tsx";
import * as $_apps_students_partials_admin_upload from "./routes/(apps)/students/partials/(admin)/upload.tsx"; import * as $_apps_students_partials_admin_upload from "./routes/(apps)/students/partials/(admin)/upload.tsx";
import * as $_apps_students_partials_index from "./routes/(apps)/students/partials/index.tsx"; import * as $_apps_students_partials_index from "./routes/(apps)/students/partials/index.tsx";
import * as $_apps_students_types_d from "./routes/(apps)/students/types.d.ts"; import * as $_apps_students_types_d from "./routes/(apps)/students/types.d.ts";
@@ -71,19 +72,20 @@ import * as $_islands_Navbar from "./routes/(_islands)/Navbar.tsx";
import * as $_apps_admin_islands_AdminEnseignements from "./routes/(apps)/admin/(_islands)/AdminEnseignements.tsx"; import * as $_apps_admin_islands_AdminEnseignements from "./routes/(apps)/admin/(_islands)/AdminEnseignements.tsx";
import * as $_apps_admin_islands_AdminModules from "./routes/(apps)/admin/(_islands)/AdminModules.tsx"; import * as $_apps_admin_islands_AdminModules from "./routes/(apps)/admin/(_islands)/AdminModules.tsx";
import * as $_apps_admin_islands_AdminPermissions from "./routes/(apps)/admin/(_islands)/AdminPermissions.tsx"; import * as $_apps_admin_islands_AdminPermissions from "./routes/(apps)/admin/(_islands)/AdminPermissions.tsx";
import * as $_apps_admin_islands_AdminPromotions from "./routes/(apps)/admin/(_islands)/AdminPromotions.tsx";
import * as $_apps_admin_islands_AdminRoles from "./routes/(apps)/admin/(_islands)/AdminRoles.tsx"; import * as $_apps_admin_islands_AdminRoles from "./routes/(apps)/admin/(_islands)/AdminRoles.tsx";
import * as $_apps_admin_islands_AdminUEs from "./routes/(apps)/admin/(_islands)/AdminUEs.tsx";
import * as $_apps_admin_islands_AdminUsers from "./routes/(apps)/admin/(_islands)/AdminUsers.tsx"; import * as $_apps_admin_islands_AdminUsers from "./routes/(apps)/admin/(_islands)/AdminUsers.tsx";
import * as $_apps_admin_islands_EditModule from "./routes/(apps)/admin/(_islands)/EditModule.tsx"; import * as $_apps_admin_islands_EditModule from "./routes/(apps)/admin/(_islands)/EditModule.tsx";
import * as $_apps_admin_islands_EditUser from "./routes/(apps)/admin/(_islands)/EditUser.tsx"; import * as $_apps_admin_islands_EditUser from "./routes/(apps)/admin/(_islands)/EditUser.tsx";
import * as $_apps_admin_islands_ImportMaquette from "./routes/(apps)/admin/(_islands)/ImportMaquette.tsx";
import * as $_apps_mobility_islands_ConsultMobility from "./routes/(apps)/mobility/(_islands)/ConsultMobility.tsx"; import * as $_apps_mobility_islands_ConsultMobility from "./routes/(apps)/mobility/(_islands)/ConsultMobility.tsx";
import * as $_apps_mobility_islands_EditMobility from "./routes/(apps)/mobility/(_islands)/EditMobility.tsx"; import * as $_apps_mobility_islands_EditMobility from "./routes/(apps)/mobility/(_islands)/EditMobility.tsx";
import * as $_apps_mobility_islands_ImportFile from "./routes/(apps)/mobility/(_islands)/ImportFile.tsx"; import * as $_apps_mobility_islands_ImportFile from "./routes/(apps)/mobility/(_islands)/ImportFile.tsx";
import * as $_apps_notes_islands_AdminConsultNotes from "./routes/(apps)/notes/(_islands)/AdminConsultNotes.tsx"; import * as $_apps_notes_islands_AdminConsultNotes from "./routes/(apps)/notes/(_islands)/AdminConsultNotes.tsx";
import * as $_apps_notes_islands_AdminUEs from "./routes/(apps)/notes/(_islands)/AdminUEs.tsx";
import * as $_apps_notes_islands_ImportNotes from "./routes/(apps)/notes/(_islands)/ImportNotes.tsx"; import * as $_apps_notes_islands_ImportNotes from "./routes/(apps)/notes/(_islands)/ImportNotes.tsx";
import * as $_apps_notes_islands_NoteRecap from "./routes/(apps)/notes/(_islands)/NoteRecap.tsx"; import * as $_apps_notes_islands_NoteRecap from "./routes/(apps)/notes/(_islands)/NoteRecap.tsx";
import * as $_apps_notes_islands_NotesView from "./routes/(apps)/notes/(_islands)/NotesView.tsx"; import * as $_apps_notes_islands_NotesView from "./routes/(apps)/notes/(_islands)/NotesView.tsx";
import * as $_apps_students_islands_AdminPromotions from "./routes/(apps)/students/(_islands)/AdminPromotions.tsx";
import * as $_apps_students_islands_ConsultStudents from "./routes/(apps)/students/(_islands)/ConsultStudents.tsx"; import * as $_apps_students_islands_ConsultStudents from "./routes/(apps)/students/(_islands)/ConsultStudents.tsx";
import * as $_apps_students_islands_EditStudents from "./routes/(apps)/students/(_islands)/EditStudents.tsx"; import * as $_apps_students_islands_EditStudents from "./routes/(apps)/students/(_islands)/EditStudents.tsx";
import * as $_apps_students_islands_UploadStudents from "./routes/(apps)/students/(_islands)/UploadStudents.tsx"; import * as $_apps_students_islands_UploadStudents from "./routes/(apps)/students/(_islands)/UploadStudents.tsx";
@@ -105,6 +107,11 @@ const manifest = {
"./routes/(apps)/admin/api/roles.ts": $_apps_admin_api_roles, "./routes/(apps)/admin/api/roles.ts": $_apps_admin_api_roles,
"./routes/(apps)/admin/api/roles/[idRole].ts": "./routes/(apps)/admin/api/roles/[idRole].ts":
$_apps_admin_api_roles_idRole_, $_apps_admin_api_roles_idRole_,
"./routes/(apps)/admin/api/ue-modules.ts": $_apps_admin_api_ue_modules,
"./routes/(apps)/admin/api/ue-modules/[idModule]/[idUE]/[idPromo].ts":
$_apps_admin_api_ue_modules_idModule_idUE_idPromo_,
"./routes/(apps)/admin/api/ues.ts": $_apps_admin_api_ues,
"./routes/(apps)/admin/api/ues/[idUE].ts": $_apps_admin_api_ues_idUE_,
"./routes/(apps)/admin/api/users.ts": $_apps_admin_api_users, "./routes/(apps)/admin/api/users.ts": $_apps_admin_api_users,
"./routes/(apps)/admin/api/users/[id].ts": $_apps_admin_api_users_id_, "./routes/(apps)/admin/api/users/[id].ts": $_apps_admin_api_users_id_,
"./routes/(apps)/admin/index.tsx": $_apps_admin_index, "./routes/(apps)/admin/index.tsx": $_apps_admin_index,
@@ -112,11 +119,16 @@ const manifest = {
$_apps_admin_modules_idModule_, $_apps_admin_modules_idModule_,
"./routes/(apps)/admin/partials/enseignements.tsx": "./routes/(apps)/admin/partials/enseignements.tsx":
$_apps_admin_partials_enseignements, $_apps_admin_partials_enseignements,
"./routes/(apps)/admin/partials/import-maquette.tsx":
$_apps_admin_partials_import_maquette,
"./routes/(apps)/admin/partials/index.tsx": $_apps_admin_partials_index, "./routes/(apps)/admin/partials/index.tsx": $_apps_admin_partials_index,
"./routes/(apps)/admin/partials/modules.tsx": $_apps_admin_partials_modules, "./routes/(apps)/admin/partials/modules.tsx": $_apps_admin_partials_modules,
"./routes/(apps)/admin/partials/permissions.tsx": "./routes/(apps)/admin/partials/permissions.tsx":
$_apps_admin_partials_permissions, $_apps_admin_partials_permissions,
"./routes/(apps)/admin/partials/promotions.tsx":
$_apps_admin_partials_promotions,
"./routes/(apps)/admin/partials/roles.tsx": $_apps_admin_partials_roles, "./routes/(apps)/admin/partials/roles.tsx": $_apps_admin_partials_roles,
"./routes/(apps)/admin/partials/ues.tsx": $_apps_admin_partials_ues,
"./routes/(apps)/admin/partials/users.tsx": $_apps_admin_partials_users, "./routes/(apps)/admin/partials/users.tsx": $_apps_admin_partials_users,
"./routes/(apps)/admin/users/[id].tsx": $_apps_admin_users_id_, "./routes/(apps)/admin/users/[id].tsx": $_apps_admin_users_id_,
"./routes/(apps)/mobility/api/insert_mobility.ts": "./routes/(apps)/mobility/api/insert_mobility.ts":
@@ -136,11 +148,6 @@ const manifest = {
$_apps_notes_api_notes_numEtud_idModule_, $_apps_notes_api_notes_numEtud_idModule_,
"./routes/(apps)/notes/api/notes/import-xlsx.ts": "./routes/(apps)/notes/api/notes/import-xlsx.ts":
$_apps_notes_api_notes_import_xlsx, $_apps_notes_api_notes_import_xlsx,
"./routes/(apps)/notes/api/ue-modules.ts": $_apps_notes_api_ue_modules,
"./routes/(apps)/notes/api/ue-modules/[idModule]/[idUE]/[idPromo].ts":
$_apps_notes_api_ue_modules_idModule_idUE_idPromo_,
"./routes/(apps)/notes/api/ues.ts": $_apps_notes_api_ues,
"./routes/(apps)/notes/api/ues/[idUE].ts": $_apps_notes_api_ues_idUE_,
"./routes/(apps)/notes/edition/[numEtud].tsx": "./routes/(apps)/notes/edition/[numEtud].tsx":
$_apps_notes_edition_numEtud_, $_apps_notes_edition_numEtud_,
"./routes/(apps)/notes/index.tsx": $_apps_notes_index, "./routes/(apps)/notes/index.tsx": $_apps_notes_index,
@@ -148,8 +155,6 @@ const manifest = {
$_apps_notes_partials_admin_courses, $_apps_notes_partials_admin_courses,
"./routes/(apps)/notes/partials/(admin)/import.tsx": "./routes/(apps)/notes/partials/(admin)/import.tsx":
$_apps_notes_partials_admin_import, $_apps_notes_partials_admin_import,
"./routes/(apps)/notes/partials/(admin)/ues.tsx":
$_apps_notes_partials_admin_ues,
"./routes/(apps)/notes/partials/index.tsx": $_apps_notes_partials_index, "./routes/(apps)/notes/partials/index.tsx": $_apps_notes_partials_index,
"./routes/(apps)/notes/partials/notes.tsx": $_apps_notes_partials_notes, "./routes/(apps)/notes/partials/notes.tsx": $_apps_notes_partials_notes,
"./routes/(apps)/notes/recap/[numEtud].tsx": $_apps_notes_recap_numEtud_, "./routes/(apps)/notes/recap/[numEtud].tsx": $_apps_notes_recap_numEtud_,
@@ -167,8 +172,6 @@ const manifest = {
"./routes/(apps)/students/index.tsx": $_apps_students_index, "./routes/(apps)/students/index.tsx": $_apps_students_index,
"./routes/(apps)/students/partials/(admin)/consult.tsx": "./routes/(apps)/students/partials/(admin)/consult.tsx":
$_apps_students_partials_admin_consult, $_apps_students_partials_admin_consult,
"./routes/(apps)/students/partials/(admin)/promotions.tsx":
$_apps_students_partials_admin_promotions,
"./routes/(apps)/students/partials/(admin)/upload.tsx": "./routes/(apps)/students/partials/(admin)/upload.tsx":
$_apps_students_partials_admin_upload, $_apps_students_partials_admin_upload,
"./routes/(apps)/students/partials/index.tsx": "./routes/(apps)/students/partials/index.tsx":
@@ -193,14 +196,20 @@ const manifest = {
$_apps_admin_islands_AdminModules, $_apps_admin_islands_AdminModules,
"./routes/(apps)/admin/(_islands)/AdminPermissions.tsx": "./routes/(apps)/admin/(_islands)/AdminPermissions.tsx":
$_apps_admin_islands_AdminPermissions, $_apps_admin_islands_AdminPermissions,
"./routes/(apps)/admin/(_islands)/AdminPromotions.tsx":
$_apps_admin_islands_AdminPromotions,
"./routes/(apps)/admin/(_islands)/AdminRoles.tsx": "./routes/(apps)/admin/(_islands)/AdminRoles.tsx":
$_apps_admin_islands_AdminRoles, $_apps_admin_islands_AdminRoles,
"./routes/(apps)/admin/(_islands)/AdminUEs.tsx":
$_apps_admin_islands_AdminUEs,
"./routes/(apps)/admin/(_islands)/AdminUsers.tsx": "./routes/(apps)/admin/(_islands)/AdminUsers.tsx":
$_apps_admin_islands_AdminUsers, $_apps_admin_islands_AdminUsers,
"./routes/(apps)/admin/(_islands)/EditModule.tsx": "./routes/(apps)/admin/(_islands)/EditModule.tsx":
$_apps_admin_islands_EditModule, $_apps_admin_islands_EditModule,
"./routes/(apps)/admin/(_islands)/EditUser.tsx": "./routes/(apps)/admin/(_islands)/EditUser.tsx":
$_apps_admin_islands_EditUser, $_apps_admin_islands_EditUser,
"./routes/(apps)/admin/(_islands)/ImportMaquette.tsx":
$_apps_admin_islands_ImportMaquette,
"./routes/(apps)/mobility/(_islands)/ConsultMobility.tsx": "./routes/(apps)/mobility/(_islands)/ConsultMobility.tsx":
$_apps_mobility_islands_ConsultMobility, $_apps_mobility_islands_ConsultMobility,
"./routes/(apps)/mobility/(_islands)/EditMobility.tsx": "./routes/(apps)/mobility/(_islands)/EditMobility.tsx":
@@ -209,16 +218,12 @@ const manifest = {
$_apps_mobility_islands_ImportFile, $_apps_mobility_islands_ImportFile,
"./routes/(apps)/notes/(_islands)/AdminConsultNotes.tsx": "./routes/(apps)/notes/(_islands)/AdminConsultNotes.tsx":
$_apps_notes_islands_AdminConsultNotes, $_apps_notes_islands_AdminConsultNotes,
"./routes/(apps)/notes/(_islands)/AdminUEs.tsx":
$_apps_notes_islands_AdminUEs,
"./routes/(apps)/notes/(_islands)/ImportNotes.tsx": "./routes/(apps)/notes/(_islands)/ImportNotes.tsx":
$_apps_notes_islands_ImportNotes, $_apps_notes_islands_ImportNotes,
"./routes/(apps)/notes/(_islands)/NoteRecap.tsx": "./routes/(apps)/notes/(_islands)/NoteRecap.tsx":
$_apps_notes_islands_NoteRecap, $_apps_notes_islands_NoteRecap,
"./routes/(apps)/notes/(_islands)/NotesView.tsx": "./routes/(apps)/notes/(_islands)/NotesView.tsx":
$_apps_notes_islands_NotesView, $_apps_notes_islands_NotesView,
"./routes/(apps)/students/(_islands)/AdminPromotions.tsx":
$_apps_students_islands_AdminPromotions,
"./routes/(apps)/students/(_islands)/ConsultStudents.tsx": "./routes/(apps)/students/(_islands)/ConsultStudents.tsx":
$_apps_students_islands_ConsultStudents, $_apps_students_islands_ConsultStudents,
"./routes/(apps)/students/(_islands)/EditStudents.tsx": "./routes/(apps)/students/(_islands)/EditStudents.tsx":
+7 -3
View File
@@ -21,16 +21,20 @@ export const handler: MiddlewareHandler<AuthenticatedState>[] = [
`./${currentApp}/(_props)/props.ts` `./${currentApp}/(_props)/props.ts`
)).default; )).default;
context.state.availablePages = properties.pages; context.state.availablePages = { ...properties.pages };
const isStudent = const isStudent =
context.state.session.eduPersonPrimaryAffiliation == "student" && context.state.session.eduPersonPrimaryAffiliation === "student";
Deno.env.get("LOCAL") != "true"; const isLocal = Deno.env.get("LOCAL") === "true";
if (isStudent) { if (isStudent) {
// Students only see studentOnly pages (+ non-restricted pages)
properties.adminOnly.forEach((page) => properties.adminOnly.forEach((page) =>
delete context.state.availablePages[page] delete context.state.availablePages[page]
); );
} else if (isLocal) {
// In local mode, employees see all pages (admin + student)
} else { } else {
// In prod, employees don't see studentOnly pages
properties.studentOnly?.forEach((page) => properties.studentOnly?.forEach((page) =>
delete context.state.availablePages[page] delete context.state.availablePages[page]
); );
@@ -74,13 +74,26 @@ export default function AdminPromotions() {
} }
async function deletePromo(id: string) { async function deletePromo(id: string) {
if (!confirm(`Supprimer la promotion ${id} ?`)) return; if (studentCount(id) > 0) {
setError(
`Impossible de supprimer ${id} : des étudiants y sont encore assignés. Réassignez-les d'abord.`,
);
return;
}
if (
!confirm(`Supprimer la promotion ${id} et toutes ses données liées ?`)
) {
return;
}
try { try {
const res = await fetch( const res = await fetch(
`/students/api/promotions/${encodeURIComponent(id)}`, `/students/api/promotions/${encodeURIComponent(id)}`,
{ method: "DELETE" }, { method: "DELETE" },
); );
if (!res.ok) throw new Error("Suppression échouée"); if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Suppression échouée");
}
await load(); await load();
} catch (e) { } catch (e) {
setError(e instanceof Error ? e.message : "Erreur"); setError(e instanceof Error ? e.message : "Erreur");
@@ -218,6 +231,10 @@ export default function AdminPromotions() {
<button <button
type="button" type="button"
class="btn btn-sm btn-danger" class="btn btn-sm btn-danger"
disabled={count > 0}
title={count > 0
? "Réassignez les étudiants avant de supprimer"
: "Supprimer la promotion"}
onClick={() => deletePromo(p.id)} onClick={() => deletePromo(p.id)}
> >
<svg <svg
@@ -19,6 +19,7 @@ export default function AdminUEs() {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [selectedUe, setSelectedUe] = useState<UE | null>(null); const [selectedUe, setSelectedUe] = useState<UE | null>(null);
const [filterPromo, setFilterPromo] = useState("");
// New UE form // New UE form
const [newUeNom, setNewUeNom] = useState(""); const [newUeNom, setNewUeNom] = useState("");
@@ -38,8 +39,8 @@ export default function AdminUEs() {
async function load() { async function load() {
try { try {
const [uRes, umRes, mRes, pRes] = await Promise.all([ const [uRes, umRes, mRes, pRes] = await Promise.all([
fetch("/notes/api/ues"), fetch("/admin/api/ues"),
fetch("/notes/api/ue-modules"), fetch("/admin/api/ue-modules"),
fetch("/admin/api/modules"), fetch("/admin/api/modules"),
fetch("/students/api/promotions"), fetch("/students/api/promotions"),
]); ]);
@@ -68,7 +69,7 @@ export default function AdminUEs() {
if (!newUeNom.trim()) return; if (!newUeNom.trim()) return;
setCreatingUe(true); setCreatingUe(true);
try { try {
const res = await fetch("/notes/api/ues", { const res = await fetch("/admin/api/ues", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: newUeNom.trim() }), body: JSON.stringify({ nom: newUeNom.trim() }),
@@ -83,6 +84,21 @@ export default function AdminUEs() {
} }
} }
async function deleteUE(ue: UE) {
if (!confirm(`Supprimer la UE "${ue.nom}" et tous ses liens ?`)) return;
try {
const res = await fetch(`/admin/api/ues/${ue.id}`, { method: "DELETE" });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Suppression échouée");
}
if (selectedUe?.id === ue.id) setSelectedUe(null);
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
async function deleteUeModule( async function deleteUeModule(
idModule: string, idModule: string,
idUE: number, idUE: number,
@@ -91,7 +107,7 @@ export default function AdminUEs() {
if (!confirm("Supprimer ce module de la UE ?")) return; if (!confirm("Supprimer ce module de la UE ?")) return;
try { try {
const res = await fetch( const res = await fetch(
`/notes/api/ue-modules/${encodeURIComponent(idModule)}/${idUE}/${ `/admin/api/ue-modules/${encodeURIComponent(idModule)}/${idUE}/${
encodeURIComponent(idPromo) encodeURIComponent(idPromo)
}`, }`,
{ method: "DELETE" }, { method: "DELETE" },
@@ -116,7 +132,7 @@ export default function AdminUEs() {
setAdding(true); setAdding(true);
setAddError(null); setAddError(null);
try { try {
const res = await fetch("/notes/api/ue-modules", { const res = await fetch("/admin/api/ue-modules", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
@@ -149,7 +165,7 @@ export default function AdminUEs() {
) { ) {
try { try {
const res = await fetch( const res = await fetch(
`/notes/api/ue-modules/${encodeURIComponent(idModule)}/${idUE}/${ `/admin/api/ue-modules/${encodeURIComponent(idModule)}/${idUE}/${
encodeURIComponent(idPromo) encodeURIComponent(idPromo)
}`, }`,
{ {
@@ -169,6 +185,13 @@ export default function AdminUEs() {
const moduleMap = Object.fromEntries(modules.map((m) => [m.id, m])); const moduleMap = Object.fromEntries(modules.map((m) => [m.id, m]));
// Filter UEs by promo: keep UEs that have at least one ue_module for that promo
const filteredUes = filterPromo
? ues.filter((ue) =>
ueModules.some((um) => um.idUE === ue.id && um.idPromo === filterPromo)
)
: ues;
const selectedUeModules = selectedUe const selectedUeModules = selectedUe
? ueModules.filter((um) => um.idUE === selectedUe.id) ? ueModules.filter((um) => um.idUE === selectedUe.id)
: []; : [];
@@ -193,6 +216,20 @@ export default function AdminUEs() {
<div class="ue-panel-left"> <div class="ue-panel-left">
<div class="panel-box"> <div class="panel-box">
<p class="panel-box-title">UEs existantes</p> <p class="panel-box-title">UEs existantes</p>
<select
class="filter-select"
value={filterPromo}
onChange={(e) =>
setFilterPromo(
(e.target as HTMLSelectElement).value,
)}
style="width: 100%; margin-bottom: 0.5rem"
>
<option value="">Toutes les promos</option>
{promos.map((p) => (
<option key={p.id} value={p.id}>{p.id}</option>
))}
</select>
<div class="form-row" style="margin-bottom: 0.75rem"> <div class="form-row" style="margin-bottom: 0.75rem">
<input <input
class="form-input" class="form-input"
@@ -214,23 +251,56 @@ export default function AdminUEs() {
+ Nouvelle UE + Nouvelle UE
</button> </button>
<div> <div>
{ues.map((ue) => ( {filteredUes.map((ue) => (
<div <div
key={ue.id} key={ue.id}
class={`ue-list-item${ class={`ue-list-item${
selectedUe?.id === ue.id ? " active" : "" selectedUe?.id === ue.id ? " active" : ""
}`} }`}
onClick={() => { style="display: flex; align-items: center; justify-content: space-between"
setSelectedUe(ue);
setAddError(null);
}}
> >
{ue.nom} <span
style="flex: 1; cursor: pointer"
onClick={() => {
setSelectedUe(ue);
setAddError(null);
}}
>
{ue.nom}
</span>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={(e) => {
e.stopPropagation();
deleteUE(ue);
}}
title="Supprimer cette UE"
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M3 6h18" />
<path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
<rect
x="5"
y="6"
width="14"
height="16"
rx="1"
/>
</svg>
</button>
</div> </div>
))} ))}
{ues.length === 0 && ( {filteredUes.length === 0 && (
<p class="state-empty" style="padding: 1rem 0"> <p class="state-empty" style="padding: 1rem 0">
Aucune UE {filterPromo ? "Aucune UE pour cette promo" : "Aucune UE"}
</p> </p>
)} )}
</div> </div>
@@ -0,0 +1,531 @@
// @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 { useEffect, useRef } from "preact/hooks";
import { useSignal } from "@preact/signals";
import ImportResultPopup, {
type ImportDetail,
type ImportResult,
} from "$root/defaults/ImportResultPopup.tsx";
type ParsedUE = {
code: string | null;
name: string;
ects: number | null;
modules: ParsedModule[];
};
type ParsedModule = {
code: string;
name: string;
coeff: number;
};
type ParsedYear = {
label: string;
ues: ParsedUE[];
};
type Promo = { id: string; annee: string | null };
function parseMaquette(workbook: XLSX.WorkBook): ParsedYear[] {
const sheet = workbook.Sheets[workbook.SheetNames[0]];
const rows = XLSX.utils.sheet_to_json<(string | number | null)[]>(sheet, {
header: 1,
});
const years: ParsedYear[] = [];
let currentYear: ParsedYear | null = null;
let currentUE: ParsedUE | null = null;
let moduleIndex = 0;
for (const row of rows) {
if (!row || row.length === 0) continue;
const col0 = row[0] != null ? String(row[0]).trim() : "";
// Detect year row: INFO3A, INFO4A, INFO5A, INFOAPP3A, INFOAPP4A, etc.
if (/^(INFO|INFOAPP)\s*\d+A$/i.test(col0)) {
currentYear = { label: col0, ues: [] };
years.push(currentYear);
currentUE = null;
continue;
}
// Detect UE row: col[0] === "UE" or starts with "UE" (e.g., "UE51")
if (col0 === "UE" || (col0.startsWith("UE") && /^UE\d/.test(col0))) {
const ueCode = row[1] != null ? String(row[1]).trim() : null;
const ueName = row[2] != null ? String(row[2]).trim() : "UE sans nom";
const ects = typeof row[4] === "number" ? row[4] : null;
currentUE = { code: ueCode, name: ueName, ects, modules: [] };
if (currentYear) {
currentYear.ues.push(currentUE);
} else {
// No year detected yet — create a default one
currentYear = { label: "Maquette", ues: [currentUE] };
years.push(currentYear);
}
moduleIndex = 0;
continue;
}
// Detect semester header rows — just skip, don't reset UE
if (/^SEM\s*\d/i.test(col0)) {
currentUE = null;
continue;
}
// Detect module row: inside a UE, col[3] has a name, col[5] is a number (coeff)
if (currentUE && row[3] != null && typeof row[5] === "number") {
const modName = String(row[3]).trim();
if (!modName) continue;
let modCode = row[1] != null ? String(row[1]).trim() : "";
if (!modCode) {
const uePrefix = (currentUE.code || "MOD").replace(/[^A-Z0-9]/gi, "");
modCode = `${uePrefix}_${String(moduleIndex).padStart(2, "0")}`;
}
currentUE.modules.push({ code: modCode, name: modName, coeff: row[5] });
moduleIndex++;
}
}
return years;
}
export default function ImportMaquette() {
const file = useSignal<File | null>(null);
const dragging = useSignal(false);
const uploading = useSignal(false);
const error = useSignal<string | null>(null);
const importResult = useSignal<ImportResult | null>(null);
const preview = useSignal<ParsedYear[] | null>(null);
const promos = useSignal<Promo[]>([]);
// Map: year label -> selected promo id
const yearPromos = useSignal<Record<string, string>>({});
// Inline promo creation
const newPromoId = useSignal("");
const newPromoAnnee = useSignal("");
const creatingPromo = useSignal(false);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
fetch("/students/api/promotions")
.then((r) => (r.ok ? r.json() : []))
.then((data) => (promos.value = data));
}, []);
function pickFile(f: File) {
if (!f.name.match(/\.xlsx?$/i)) {
error.value = "Fichier invalide — format attendu : .xlsx";
return;
}
file.value = f;
error.value = null;
importResult.value = null;
preview.value = null;
yearPromos.value = {};
f.arrayBuffer().then((buf) => {
try {
const wb = XLSX.read(buf, { type: "array" });
preview.value = parseMaquette(wb);
} catch {
error.value = "Impossible de lire le fichier.";
}
});
}
async function createPromo() {
if (!newPromoId.value.trim() || !newPromoAnnee.value.trim()) return;
creatingPromo.value = true;
try {
const res = await fetch("/students/api/promotions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
idPromo: newPromoId.value.trim(),
annee: newPromoAnnee.value.trim(),
}),
});
if (res.ok) {
const created = await res.json();
promos.value = [...promos.value, { id: created.id, annee: created.annee }];
newPromoId.value = "";
newPromoAnnee.value = "";
} else {
error.value = "Erreur lors de la creation de la promotion.";
}
} finally {
creatingPromo.value = false;
}
}
function setYearPromo(yearLabel: string, promoId: string) {
yearPromos.value = { ...yearPromos.value, [yearLabel]: promoId };
}
// Check that at least one year has a promo assigned
function canImport(): boolean {
if (!preview.value || uploading.value) return false;
return preview.value.some((y) => yearPromos.value[y.label]);
}
async function doImport() {
if (!preview.value) return;
uploading.value = true;
error.value = null;
importResult.value = null;
let added = 0;
let ignored = 0;
let errCount = 0;
const details: ImportDetail[] = [];
try {
for (const year of preview.value) {
const promoId = yearPromos.value[year.label];
if (!promoId) {
ignored += year.ues.reduce((s, ue) => s + ue.modules.length + 1, 0);
details.push({
type: "error",
message: `${year.label} : ignoree (pas de promo selectionnee)`,
});
continue;
}
for (const ue of year.ues) {
const ueRes = await fetch("/admin/api/ues", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: ue.name }),
});
if (!ueRes.ok) {
errCount++;
details.push({
type: "error",
message: `UE "${ue.name}" : creation echouee`,
});
continue;
}
const createdUE = await ueRes.json();
added++;
details.push({
type: "change",
message: `UE "${ue.name}" creee (id: ${createdUE.id})`,
});
for (const mod of ue.modules) {
const modRes = await fetch("/admin/api/modules", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ id: mod.code, nom: mod.name }),
});
if (modRes.ok) {
added++;
details.push({
type: "change",
message: `Module ${mod.code} "${mod.name}" cree`,
});
} else if (modRes.status !== 409) {
errCount++;
details.push({
type: "error",
message: `Module "${mod.code}" : creation echouee`,
});
continue;
}
const linkRes = await fetch("/admin/api/ue-modules", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
idModule: mod.code,
idUE: createdUE.id,
idPromo: promoId,
coeff: mod.coeff,
}),
});
if (linkRes.ok) {
added++;
} else {
errCount++;
details.push({
type: "error",
message: `Lien ${mod.code} -> UE ${ue.name} : echoue`,
});
}
}
}
}
importResult.value = {
added,
modified: 0,
ignored,
errors: errCount,
details,
};
} catch {
error.value = "Erreur lors de l'import.";
} finally {
uploading.value = false;
}
}
function downloadTemplate() {
globalThis.open("/templates/modele_maquette.xlsx", "_blank");
}
function downloadExport() {
Promise.all([
fetch("/admin/api/ues").then((r) => r.json()),
fetch("/admin/api/ue-modules").then((r) => r.json()),
fetch("/admin/api/modules").then((r) => r.json()),
]).then(([uesData, ueModulesData, modulesData]) => {
const modMap = Object.fromEntries(
modulesData.map((m: { id: string; nom: string }) => [m.id, m]),
);
const data: (string | number | null)[][] = [
["Annee\nSemestres", "Codes APOGEE", null, null, "Credits\nECTS", "Coeff."],
];
for (const ue of uesData) {
const mods = ueModulesData.filter(
(um: { idUE: number }) => um.idUE === ue.id,
);
const totalCoeff = mods.reduce(
(s: number, um: { coeff: number }) => s + um.coeff,
0,
);
data.push(["UE", null, ue.nom, null, totalCoeff]);
for (const um of mods) {
const mod = modMap[um.idModule];
data.push([null, um.idModule, null, mod ? mod.nom : um.idModule, null, um.coeff]);
}
data.push([]);
}
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet(data);
XLSX.utils.book_append_sheet(wb, ws, "Maquette");
const buf = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const blob = new Blob([buf], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "export_maquette.xlsx";
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 100);
});
}
return (
<div>
<input
ref={inputRef}
type="file"
accept=".xlsx,.xls"
style="display:none"
onChange={(e) => {
const f = (e.target as HTMLInputElement).files?.[0];
if (f) pickFile(f);
}}
/>
<div
class={`drop-zone${dragging.value ? " dragging" : ""}`}
onDragOver={(e) => {
e.preventDefault();
dragging.value = true;
}}
onDragLeave={() => (dragging.value = false)}
onDrop={(e) => {
e.preventDefault();
dragging.value = false;
const f = e.dataTransfer?.files?.[0];
if (f) pickFile(f);
}}
onClick={() => inputRef.current?.click()}
>
<span class="drop-zone-icon"></span>
{file.value ? <span class="drop-zone-file">{file.value.name}</span> : (
<>
<span class="drop-zone-text">
Glisser le fichier maquette .xlsx ici
</span>
<span class="drop-zone-hint">ou cliquer pour parcourir</span>
</>
)}
</div>
{error.value && <p class="state-error">{error.value}</p>}
{importResult.value && (
<ImportResultPopup
result={importResult.value}
onClose={() => (importResult.value = null)}
/>
)}
{/* Create promo inline */}
<div class="create-promo-inline">
<label style="font-size: 0.82rem; font-weight: 600; display: block; margin-bottom: 0.25rem">
Creer une promotion
</label>
<div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap">
<input
type="text"
class="filter-select"
placeholder="ID (ex: 3AFISE24-25)"
value={newPromoId.value}
onInput={(e) =>
(newPromoId.value = (e.target as HTMLInputElement).value)}
style="min-width: 10rem"
/>
<input
type="text"
class="filter-select"
placeholder="Annee (ex: 2024-2025)"
value={newPromoAnnee.value}
onInput={(e) =>
(newPromoAnnee.value = (e.target as HTMLInputElement).value)}
style="min-width: 8rem"
/>
<button
type="button"
class="btn btn-secondary"
onClick={createPromo}
disabled={creatingPromo.value || !newPromoId.value.trim() ||
!newPromoAnnee.value.trim()}
style="white-space: nowrap"
>
{creatingPromo.value ? "..." : "+ Creer"}
</button>
</div>
</div>
{/* Preview grouped by year */}
{preview.value && preview.value.length > 0 && (
<div style="margin-bottom: 1rem">
{preview.value.map((year) => {
const totalMods = year.ues.reduce(
(s, ue) => s + ue.modules.length,
0,
);
return (
<div key={year.label} style="margin-bottom: 1.25rem">
<div style="display: flex; gap: 1rem; align-items: center; margin-bottom: 0.5rem; flex-wrap: wrap">
<p style="font-size: 0.85rem; font-weight: 700; margin: 0">
{year.label}
<span class="col-dim" style="font-weight: 400">
{" "} {year.ues.length} UE, {totalMods} modules
</span>
</p>
<select
class="filter-select"
value={yearPromos.value[year.label] || ""}
onChange={(e) =>
setYearPromo(
year.label,
(e.target as HTMLSelectElement).value,
)}
>
<option value=""> Ignorer </option>
{promos.value.map((p) => (
<option key={p.id} value={p.id}>{p.id}</option>
))}
</select>
</div>
<div
class="data-table-wrap"
style="max-height: 15rem; overflow-y: auto"
>
<table class="data-table">
<thead>
<tr>
<th>UE</th>
<th>Module</th>
<th>Code</th>
<th>Coeff</th>
</tr>
</thead>
<tbody>
{year.ues.map((ue, i) =>
ue.modules.length === 0
? (
<tr key={`ue-${i}`}>
<td style="font-weight: 600">{ue.name}</td>
<td class="col-dim" colspan={3}>
Aucun module
</td>
</tr>
)
: ue.modules.map((mod, j) => (
<tr key={`${i}-${j}`}>
{j === 0 && (
<td
rowSpan={ue.modules.length}
style="font-weight: 600; vertical-align: top"
>
{ue.name}
{ue.ects != null && (
<span class="col-dim">
{" "}({ue.ects} ECTS)
</span>
)}
</td>
)}
<td>{mod.name}</td>
<td class="col-dim">{mod.code}</td>
<td>{mod.coeff}</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
);
})}
</div>
)}
<div class="upload-actions">
<button
type="button"
class="btn btn-primary"
onClick={doImport}
disabled={!canImport()}
>
{uploading.value ? "..." : "+ Importer"}
</button>
<button
type="button"
class="btn btn-secondary"
onClick={downloadTemplate}
>
Telecharger Modele
</button>
<button
type="button"
class="btn btn-secondary"
onClick={downloadExport}
>
Exporter Maquette
</button>
</div>
<p class="upload-format">
Format : fichier maquette FISE / FISA avec lignes <strong>UE</strong>
{" "}et <strong>modules</strong> (colonnes code, nom, coefficient)
</p>
</div>
);
}
+4 -1
View File
@@ -10,8 +10,11 @@ const properties: AppProperties = {
permissions: "Permissions", permissions: "Permissions",
modules: "Modules", modules: "Modules",
enseignements: "Enseignements", enseignements: "Enseignements",
promotions: "Promotions",
ues: "UEs",
"import-maquette": "Import Maquette",
}, },
adminOnly: ["users", "roles", "permissions", "modules", "enseignements"], adminOnly: ["users", "roles", "permissions", "modules", "enseignements", "promotions", "ues", "import-maquette"],
hint: "PolyMPR module", hint: "PolyMPR module",
}; };
+13 -11
View File
@@ -4,17 +4,19 @@ import { enseignements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { and, eq } from "npm:drizzle-orm@0.45.2";
const _NOT_FOUND = new Response( const _NOT_FOUND = () =>
JSON.stringify({ error: "Ressource introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ressource introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
const FORBIDDEN = new Response(null, { status: 403 }); const FORBIDDEN = () => new Response(null, { status: 403 });
const CONFLICT = new Response( const CONFLICT = () =>
JSON.stringify({ error: "Cet enseignement existe déjà." }), new Response(
{ status: 409, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Cet enseignement existe déjà." }),
); { status: 409, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// GET /enseignements // GET /enseignements
@@ -39,7 +41,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
let body: { idProf: string; idModule: string; idPromo: string }; let body: { idProf: string; idModule: string; idPromo: string };
@@ -67,7 +69,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (existing) { if (existing) {
return CONFLICT; return CONFLICT();
} }
const [created] = await db const [created] = await db
@@ -4,12 +4,13 @@ import { enseignements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Ressource introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ressource introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
const FORBIDDEN = new Response(null, { status: 403 }); const FORBIDDEN = () => new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #30 GET /enseignements/{idProf}/{idModule}/{idPromo} // #30 GET /enseignements/{idProf}/{idModule}/{idPromo}
@@ -18,7 +19,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const idProf = context.params.idProf; const idProf = context.params.idProf;
@@ -37,7 +38,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!enseignement) return NOT_FOUND; if (!enseignement) return NOT_FOUND();
return new Response(JSON.stringify(enseignement), { return new Response(JSON.stringify(enseignement), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -50,7 +51,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const idProf = context.params.idProf; const idProf = context.params.idProf;
@@ -68,7 +69,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.returning(); .returning();
if (!deleted) return NOT_FOUND; if (!deleted) return NOT_FOUND();
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+1 -7
View File
@@ -8,14 +8,8 @@ export const handler: Handlers<null, AuthenticatedState> = {
// #23 GET /modules // #23 GET /modules
async GET( async GET(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, _context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return new Response(JSON.stringify([]), {
headers: { "content-type": "application/json" },
});
}
const rows = await db.select().from(modules); const rows = await db.select().from(modules);
return new Response(JSON.stringify(rows), { return new Response(JSON.stringify(rows), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
+31 -12
View File
@@ -1,13 +1,19 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { modules } from "$root/databases/schema.ts"; import {
enseignements,
modules,
notes,
ueModules,
} from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Ressource introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ressource introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #25 GET /modules/{idModule} // #25 GET /modules/{idModule}
@@ -21,7 +27,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(modules.id, context.params.idModule)) .where(eq(modules.id, context.params.idModule))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!module) return NOT_FOUND; if (!module) return NOT_FOUND();
return new Response(JSON.stringify(module), { return new Response(JSON.stringify(module), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -50,7 +56,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(modules.id, context.params.idModule)) .where(eq(modules.id, context.params.idModule))
.returning(); .returning();
if (!updated) return NOT_FOUND; if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -58,16 +64,29 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #27 DELETE /modules/{idModule} // #27 DELETE /modules/{idModule}
// Cascade: deletes notes, ue_modules, enseignements for this module.
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
const [deleted] = await db const idModule = context.params.idModule;
.delete(modules)
.where(eq(modules.id, context.params.idModule))
.returning();
if (!deleted) return NOT_FOUND; const mod = await db
.select()
.from(modules)
.where(eq(modules.id, idModule))
.then((r) => r[0] ?? null);
if (!mod) return NOT_FOUND();
await db.transaction(async (tx) => {
await tx.delete(notes).where(eq(notes.idModule, idModule));
await tx.delete(ueModules).where(eq(ueModules.idModule, idModule));
await tx.delete(enseignements).where(
eq(enseignements.idModule, idModule),
);
await tx.delete(modules).where(eq(modules.id, idModule));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+23 -14
View File
@@ -1,13 +1,14 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { rolePermissions, roles } from "$root/databases/schema.ts"; import { rolePermissions, roles, users } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Ressource introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ressource introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
async function getRoleWithPermissions( async function getRoleWithPermissions(
id: number, id: number,
@@ -41,7 +42,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const id = Number(context.params.idRole); const id = Number(context.params.idRole);
const role = await getRoleWithPermissions(id); const role = await getRoleWithPermissions(id);
if (!role) return NOT_FOUND; if (!role) return NOT_FOUND();
return new Response(JSON.stringify(role), { return new Response(JSON.stringify(role), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -62,7 +63,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(roles.id, id)) .where(eq(roles.id, id))
.returning(); .returning();
if (!updated) return NOT_FOUND; if (!updated) return NOT_FOUND();
// Reset permissions // Reset permissions
await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id)); await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id));
@@ -80,21 +81,29 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #69 DELETE /roles/{idRole} // #69 DELETE /roles/{idRole}
// Cascade: deletes role_permissions, detaches users (idRole set to null).
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
const id = Number(context.params.idRole); const id = Number(context.params.idRole);
// Cascade delete role_permissions first const role = await db
await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id)); .select()
.from(roles)
const [deleted] = await db
.delete(roles)
.where(eq(roles.id, id)) .where(eq(roles.id, id))
.returning(); .then((r) => r[0] ?? null);
if (!deleted) return NOT_FOUND; if (!role) return NOT_FOUND();
await db.transaction(async (tx) => {
await tx.delete(rolePermissions).where(eq(rolePermissions.idRole, id));
await tx
.update(users)
.set({ idRole: null })
.where(eq(users.idRole, id));
await tx.delete(roles).where(eq(roles.id, id));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
@@ -4,17 +4,19 @@ import { ueModules } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Association UE-Module introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Association UE-Module introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
const FORBIDDEN = new Response(null, { status: 403 }); const FORBIDDEN = () => new Response(null, { status: 403 });
const BAD_REQUEST = new Response( const BAD_REQUEST = () =>
JSON.stringify({ error: "Paramètres invalides" }), new Response(
{ status: 400, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Paramètres invalides" }),
); { status: 400, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #39 GET /ue-modules/{idModule}/{idUE}/{idPromo} // #39 GET /ue-modules/{idModule}/{idUE}/{idPromo}
@@ -23,7 +25,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const idModule = context.params.idModule; const idModule = context.params.idModule;
@@ -31,7 +33,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo; const idPromo = context.params.idPromo;
if (isNaN(idUE)) { if (isNaN(idUE)) {
return BAD_REQUEST; return BAD_REQUEST();
} }
const ueModuleAssociation = await db const ueModuleAssociation = await db
@@ -44,7 +46,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!ueModuleAssociation) return NOT_FOUND; if (!ueModuleAssociation) return NOT_FOUND();
return new Response(JSON.stringify(ueModuleAssociation), { return new Response(JSON.stringify(ueModuleAssociation), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -57,7 +59,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const idModule = context.params.idModule; const idModule = context.params.idModule;
@@ -65,7 +67,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo; const idPromo = context.params.idPromo;
if (isNaN(idUE)) { if (isNaN(idUE)) {
return BAD_REQUEST; return BAD_REQUEST();
} }
const body: { coeff: number } = await request.json(); const body: { coeff: number } = await request.json();
@@ -89,7 +91,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.returning(); .returning();
if (!updated) return NOT_FOUND; if (!updated) return NOT_FOUND();
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
@@ -110,7 +112,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const idModule = context.params.idModule; const idModule = context.params.idModule;
@@ -118,7 +120,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo; const idPromo = context.params.idPromo;
if (isNaN(idUE)) { if (isNaN(idUE)) {
return BAD_REQUEST; return BAD_REQUEST();
} }
const [deleted] = await db const [deleted] = await db
@@ -132,7 +134,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.returning(); .returning();
if (!deleted) return NOT_FOUND; if (!deleted) return NOT_FOUND();
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
@@ -1,6 +1,10 @@
import { Handlers } from "$fresh/server.ts"; import { Handlers } from "$fresh/server.ts";
import { db } from "../../../../../databases/db.ts"; import { db } from "../../../../../databases/db.ts";
import { ues } from "../../../../../databases/schema.ts"; import {
ajustements,
ueModules,
ues,
} from "../../../../../databases/schema.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
export const handler: Handlers = { export const handler: Handlers = {
@@ -87,6 +91,7 @@ export const handler: Handlers = {
}, },
// #36 DELETE /ues/:idUE // #36 DELETE /ues/:idUE
// Cascade: deletes ajustements, ue_modules for this UE.
async DELETE(_request, context) { async DELETE(_request, context) {
try { try {
const idUE = parseInt(context.params.idUE); const idUE = parseInt(context.params.idUE);
@@ -101,9 +106,9 @@ export const handler: Handlers = {
); );
} }
const result = await db.delete(ues).where(eq(ues.id, idUE)).returning(); const existing = await db.select().from(ues).where(eq(ues.id, idUE));
if (result.length === 0) { if (existing.length === 0) {
return new Response( return new Response(
JSON.stringify({ error: "Ressource introuvable" }), JSON.stringify({ error: "Ressource introuvable" }),
{ {
@@ -113,6 +118,12 @@ export const handler: Handlers = {
); );
} }
await db.transaction(async (tx) => {
await tx.delete(ajustements).where(eq(ajustements.idUE, idUE));
await tx.delete(ueModules).where(eq(ueModules.idUE, idUE));
await tx.delete(ues).where(eq(ues.id, idUE));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
} catch (error) { } catch (error) {
console.error("Error deleting UE:", error); console.error("Error deleting UE:", error);
+22 -12
View File
@@ -1,13 +1,14 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { users } from "$root/databases/schema.ts"; import { enseignements, users } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Ressource introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ressource introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #62 GET /users/{id} // #62 GET /users/{id}
@@ -21,7 +22,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(users.id, context.params.id)) .where(eq(users.id, context.params.id))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!user) return NOT_FOUND; if (!user) return NOT_FOUND();
return new Response(JSON.stringify(user), { return new Response(JSON.stringify(user), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -42,7 +43,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(users.id, context.params.id)) .where(eq(users.id, context.params.id))
.returning(); .returning();
if (!updated) return NOT_FOUND; if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -50,16 +51,25 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #64 DELETE /users/{id} // #64 DELETE /users/{id}
// Cascade: deletes enseignements for this user.
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
const [deleted] = await db const id = context.params.id;
.delete(users)
.where(eq(users.id, context.params.id))
.returning();
if (!deleted) return NOT_FOUND; const user = await db
.select()
.from(users)
.where(eq(users.id, id))
.then((r) => r[0] ?? null);
if (!user) return NOT_FOUND();
await db.transaction(async (tx) => {
await tx.delete(enseignements).where(eq(enseignements.idProf, id));
await tx.delete(users).where(eq(users.id, id));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
@@ -0,0 +1,23 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import ImportMaquette from "../(_islands)/ImportMaquette.tsx";
// deno-lint-ignore require-await
async function ImportMaquettePage(
_request: Request,
_context: FreshContext<State>,
) {
return (
<div class="page-content">
<h2 class="page-title">Importer une Maquette (UE & Modules)</h2>
<ImportMaquette />
</div>
);
}
export const config = getPartialsConfig();
export default makePartials(ImportMaquettePage);
@@ -4,7 +4,7 @@ import {
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts"; import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts"; import { State } from "$root/defaults/interfaces.ts";
import AdminPromotions from "../../(_islands)/AdminPromotions.tsx"; import AdminPromotions from "../(_islands)/AdminPromotions.tsx";
// deno-lint-ignore require-await // deno-lint-ignore require-await
async function Promotions( async function Promotions(
@@ -4,7 +4,7 @@ import {
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts"; import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts"; import { State } from "$root/defaults/interfaces.ts";
import AdminUEs from "../../(_islands)/AdminUEs.tsx"; import AdminUEs from "../(_islands)/AdminUEs.tsx";
// deno-lint-ignore require-await // deno-lint-ignore require-await
async function UEs( async function UEs(
+528 -59
View File
@@ -1,15 +1,61 @@
// @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts" // @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 * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs";
import { useRef } from "preact/hooks"; import { useEffect, useRef } from "preact/hooks";
import { useSignal } from "@preact/signals"; import { useSignal } from "@preact/signals";
import ImportResultPopup, {
type ImportDetail,
type ImportResult,
} from "$root/defaults/ImportResultPopup.tsx";
type Student = { numEtud: number; nom: string; prenom: string };
type ColumnInfo = {
index: number;
code: string;
name: string;
coeff: number | null;
type: "module" | "malus" | "ue" | "semester" | "unknown";
};
function parseHeader(header: string): { code: string; name: string } {
const parts = header.split(" - ");
if (parts.length >= 2) {
return { code: parts[0].trim(), name: parts.slice(1).join(" - ").trim() };
}
return { code: header.trim(), name: header.trim() };
}
function detectColumnType(
header: string,
_coeff: number | null,
): ColumnInfo["type"] {
const h = header.trim();
if (/^MALUS/i.test(h)) return "malus";
if (/^S\d+$/i.test(h)) return "semester";
// UE codes typically contain "U" followed by digits (e.g., JIN5U05, JTR5U01)
const { code } = parseHeader(h);
if (/U\d/i.test(code) && !/^MALUS/i.test(code)) return "ue";
return "module";
}
export default function ImportNotes() { export default function ImportNotes() {
const file = useSignal<File | null>(null); const file = useSignal<File | null>(null);
const dragging = useSignal(false); const dragging = useSignal(false);
const uploading = useSignal(false); const uploading = useSignal(false);
const error = useSignal<string | null>(null); const error = useSignal<string | null>(null);
const success = useSignal<string | null>(null); const importResult = useSignal<ImportResult | null>(null);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const students = useSignal<Student[]>([]);
const columns = useSignal<ColumnInfo[]>([]);
const sheetNames = useSignal<string[]>([]);
const selectedSheet = useSignal("");
const session = useSignal<"1" | "2">("1");
const workbookRef = useRef<XLSX.WorkBook | null>(null);
useEffect(() => {
fetch("/students/api/students")
.then((r) => (r.ok ? r.json() : []))
.then((data) => (students.value = data));
}, []);
function pickFile(f: File) { function pickFile(f: File) {
if (!f.name.match(/\.xlsx?$/i)) { if (!f.name.match(/\.xlsx?$/i)) {
@@ -18,76 +64,404 @@ export default function ImportNotes() {
} }
file.value = f; file.value = f;
error.value = null; error.value = null;
success.value = null; importResult.value = null;
columns.value = [];
f.arrayBuffer().then((buf) => {
try {
const wb = XLSX.read(buf, { type: "array" });
workbookRef.current = wb;
sheetNames.value = wb.SheetNames;
if (wb.SheetNames.length > 0) {
selectedSheet.value = wb.SheetNames[0];
parseSheet(wb, wb.SheetNames[0]);
}
} catch {
error.value = "Impossible de lire le fichier.";
}
});
} }
function onDragOver(e: DragEvent) { function parseSheet(wb: XLSX.WorkBook, sheetName: string) {
e.preventDefault(); const sheet = wb.Sheets[sheetName];
dragging.value = true; const rows = XLSX.utils.sheet_to_json<(string | number | null)[]>(sheet, {
header: 1,
});
if (rows.length < 2) {
columns.value = [];
return;
}
const headerRow = rows[0];
const coeffRow = rows[1];
const cols: ColumnInfo[] = [];
// First 2 columns are nom/prenom, skip them
for (let i = 2; i < headerRow.length; i++) {
const h = headerRow[i];
if (h == null || String(h).trim() === "") continue;
const header = String(h).trim();
const coeff = typeof coeffRow[i] === "number" ? coeffRow[i] : null;
const { code, name } = parseHeader(header);
const type = detectColumnType(header, coeff as number | null);
cols.push({ index: i, code, name, coeff: coeff as number | null, type });
}
columns.value = cols;
} }
function onDragLeave() { function onSheetChange(name: string) {
dragging.value = false; selectedSheet.value = name;
if (workbookRef.current) {
parseSheet(workbookRef.current, name);
}
} }
function onDrop(e: DragEvent) { function findStudent(
e.preventDefault(); nom: string,
dragging.value = false; prenom: string,
const f = e.dataTransfer?.files?.[0]; ): Student | undefined {
if (f) pickFile(f); const normNom = nom.toUpperCase().trim();
} const normPrenom = prenom.toUpperCase().trim();
return students.value.find(
function onInputChange(e: Event) { (s) =>
const f = (e.target as HTMLInputElement).files?.[0]; s.nom.toUpperCase().trim() === normNom &&
if (f) pickFile(f); s.prenom.toUpperCase().trim() === normPrenom,
);
} }
async function doImport() { async function doImport() {
if (!file.value) return; if (!workbookRef.current || !selectedSheet.value) return;
uploading.value = true; uploading.value = true;
error.value = null; error.value = null;
success.value = null; importResult.value = null;
try { try {
const arrayBuffer = await file.value.arrayBuffer(); const sheet = workbookRef.current.Sheets[selectedSheet.value];
const workbook = XLSX.read(arrayBuffer, { type: "array" }); const rows = XLSX.utils.sheet_to_json<(string | number | null)[]>(sheet, {
let imported = 0; header: 1,
let failed = 0; });
for (const sheetName of workbook.SheetNames) { const moduleCols = columns.value.filter((c) => c.type === "module");
const sheet = workbook.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json<{
numEtud: number;
idModule: string;
note: number;
}>(sheet, { header: ["numEtud", "idModule", "note"], range: 1 });
for (const row of rows) { let added = 0;
const res = await fetch("/notes/api/notes", { let modified = 0;
method: "POST", let ignored = 0;
headers: { "content-type": "application/json" }, let errors = 0;
body: JSON.stringify(row), const details: ImportDetail[] = [];
// Process data rows (skip header + coeff rows)
for (let r = 2; r < rows.length; r++) {
const row = rows[r];
if (!row || row.length < 3) continue;
const nom = row[0] != null ? String(row[0]).trim() : "";
const prenom = row[1] != null ? String(row[1]).trim() : "";
if (!nom || !prenom) continue;
const student = findStudent(nom, prenom);
if (!student) {
ignored++;
details.push({
type: "error",
message: `${nom} ${prenom} : Etudiant non trouve`,
}); });
if (res.ok) imported++; continue;
else failed++; }
// Import module notes
for (const col of moduleCols) {
const val = row[col.index];
if (val == null || typeof val !== "number") {
if (val != null && typeof val !== "number") {
errors++;
details.push({
type: "error",
message:
`${student.numEtud} : ${col.code} : Note "${val}" invalide`,
});
}
continue;
}
if (val < 0 || val > 20) {
errors++;
details.push({
type: "error",
message:
`${student.numEtud} : ${col.code} : Note ${val} hors limites`,
});
continue;
}
const noteField = session.value === "2" ? "noteSession2" : "note";
// Try PUT first (update), then POST (create)
const putRes = await fetch(
`/notes/api/notes/${student.numEtud}/${
encodeURIComponent(col.code)
}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ [noteField]: val }),
},
);
if (putRes.ok) {
const prev = await putRes.json();
const oldVal = session.value === "2"
? prev.noteSession2
: prev.note;
modified++;
details.push({
type: "change",
message: `${student.numEtud} : ${col.code} : ${
oldVal ?? "null"
} -> ${val}`,
});
} else if (putRes.status === 404) {
// Note doesn't exist yet, create it
const body: Record<string, unknown> = {
numEtud: student.numEtud,
idModule: col.code,
note: session.value === "1" ? val : 0,
};
if (session.value === "2") body.noteSession2 = val;
const postRes = await fetch("/notes/api/notes", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
if (postRes.ok) {
added++;
details.push({
type: "change",
message: `${student.numEtud} : ${col.code} : null -> ${val}`,
});
} else {
errors++;
details.push({
type: "error",
message:
`${student.numEtud} : ${col.code} : Matiere non trouvee`,
});
}
} else {
errors++;
details.push({
type: "error",
message: `${student.numEtud} : ${col.code} : Erreur serveur`,
});
}
} }
} }
success.value = `Import terminé — ${imported} ajouté${ importResult.value = { added, modified, ignored, errors, details };
imported !== 1 ? "s" : ""
}${failed > 0 ? `, ${failed} erreur${failed !== 1 ? "s" : ""}` : ""}`;
} catch { } catch {
error.value = "Erreur lors de la lecture du fichier."; error.value = "Erreur lors de l'import.";
} finally { } finally {
uploading.value = false; uploading.value = false;
} }
} }
function downloadTemplate() { function downloadTemplate() {
const wb = XLSX.utils.book_new(); globalThis.open("/templates/modele_notes.xlsx", "_blank");
const ws = XLSX.utils.aoa_to_sheet([["numEtud", "idModule", "note"]]); }
XLSX.utils.book_append_sheet(wb, ws, "Notes");
XLSX.writeFile(wb, "modele_notes.xlsx"); function downloadExport() {
// Export notes from the API in the same format
Promise.all([
fetch("/students/api/students").then((r) => r.json()),
fetch("/notes/api/notes").then((r) => r.json()),
fetch("/admin/api/modules").then((r) => r.json()),
fetch("/admin/api/ue-modules").then((r) => r.json()),
fetch("/admin/api/ues").then((r) => r.json()),
]).then(
([
studentsData,
notesData,
modulesData,
ueModulesData,
uesData,
]) => {
// Build module map
const modMap = new Map<string, string>(
modulesData.map((m: { id: string; nom: string }) => [m.id, m.nom]),
);
// Get unique module IDs from notes
const moduleIds = [
...new Set(
notesData.map((n: { idModule: string }) => n.idModule),
),
] as string[];
// Group ue-modules by UE
const ueMap = new Map<number, string>(
uesData.map((u: { id: number; nom: string }) => [u.id, u.nom]),
);
const umByUE = new Map<number, typeof ueModulesData>();
for (const um of ueModulesData) {
if (!umByUE.has(um.idUE)) umByUE.set(um.idUE, []);
umByUE.get(um.idUE)!.push(um);
}
// Build column order: group modules by UE, add UE avg columns
const orderedCols: {
id: string;
header: string;
coeff: number | null;
type: "module" | "ue";
ueId?: number;
}[] = [];
const usedModules = new Set<string>();
for (const [ueId, ums] of umByUE) {
for (const um of ums) {
if (!moduleIds.includes(um.idModule)) continue;
orderedCols.push({
id: um.idModule,
header: `${um.idModule} - ${
modMap.get(um.idModule) || um.idModule
}`,
coeff: um.coeff,
type: "module",
ueId,
});
usedModules.add(um.idModule);
}
const ueName = ueMap.get(ueId) || `UE ${ueId}`;
orderedCols.push({
id: `ue_${ueId}`,
header: ueName,
coeff: ums.reduce(
(s: number, um: { coeff: number }) => s + um.coeff,
0,
),
type: "ue",
ueId,
});
}
// Add modules not linked to any UE
for (const mId of moduleIds) {
if (usedModules.has(mId)) continue;
orderedCols.push({
id: mId,
header: `${mId} - ${modMap.get(mId) || mId}`,
coeff: null,
type: "module",
});
}
// Build note lookup: numEtud -> idModule -> note
const noteLookup = new Map<
number,
Map<string, { note: number; noteSession2: number | null }>
>();
for (const n of notesData) {
if (!noteLookup.has(n.numEtud)) noteLookup.set(n.numEtud, new Map());
noteLookup.get(n.numEtud)!.set(n.idModule, {
note: n.note,
noteSession2: n.noteSession2,
});
}
// Get students who have notes
const studentsWithNotes = studentsData.filter(
(s: Student) => noteLookup.has(s.numEtud),
);
// Build header rows
const headerRow: (string | null)[] = [null, null];
const coeffRow: (number | null)[] = [null, null];
for (const col of orderedCols) {
headerRow.push(col.header);
coeffRow.push(col.coeff);
}
// Build session 1 data rows
const s1Rows: (string | number | null)[][] = [];
for (const s of studentsWithNotes) {
const row: (string | number | null)[] = [s.nom, s.prenom];
const sNotes = noteLookup.get(s.numEtud) || new Map();
for (const col of orderedCols) {
if (col.type === "module") {
const n = sNotes.get(col.id);
row.push(n ? n.note : null);
} else {
// UE average - calculate
const ueMods = orderedCols.filter(
(c) => c.type === "module" && c.ueId === col.ueId,
);
let total = 0, coeffSum = 0;
for (const um of ueMods) {
const n = sNotes.get(um.id);
if (n && um.coeff) {
total += n.note * um.coeff;
coeffSum += um.coeff;
}
}
row.push(
coeffSum > 0
? Math.round((total / coeffSum) * 100) / 100
: null,
);
}
}
s1Rows.push(row);
}
// Build session 2 data rows
const s2Rows: (string | number | null)[][] = [];
for (const s of studentsWithNotes) {
const row: (string | number | null)[] = [s.nom, s.prenom];
const sNotes = noteLookup.get(s.numEtud) || new Map();
for (const col of orderedCols) {
if (col.type === "module") {
const n = sNotes.get(col.id);
// Use session 2 note if available, else session 1
row.push(n ? (n.noteSession2 ?? n.note) : null);
} else {
const ueMods = orderedCols.filter(
(c) => c.type === "module" && c.ueId === col.ueId,
);
let total = 0, coeffSum = 0;
for (const um of ueMods) {
const n = sNotes.get(um.id);
if (n && um.coeff) {
const noteVal = n.noteSession2 ?? n.note;
total += noteVal * um.coeff;
coeffSum += um.coeff;
}
}
row.push(
coeffSum > 0
? Math.round((total / coeffSum) * 100) / 100
: null,
);
}
}
s2Rows.push(row);
}
const wb = XLSX.utils.book_new();
const ws1 = XLSX.utils.aoa_to_sheet([headerRow, coeffRow, ...s1Rows]);
XLSX.utils.book_append_sheet(wb, ws1, "Session 1");
const ws2 = XLSX.utils.aoa_to_sheet([headerRow, coeffRow, ...s2Rows]);
XLSX.utils.book_append_sheet(wb, ws2, "Session 2");
const buf = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const blob = new Blob([buf], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "export_notes.xlsx";
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 100);
},
);
} }
return ( return (
@@ -97,14 +471,25 @@ export default function ImportNotes() {
type="file" type="file"
accept=".xlsx,.xls" accept=".xlsx,.xls"
style="display:none" style="display:none"
onChange={onInputChange} onChange={(e) => {
const f = (e.target as HTMLInputElement).files?.[0];
if (f) pickFile(f);
}}
/> />
<div <div
class={`drop-zone${dragging.value ? " dragging" : ""}`} class={`drop-zone${dragging.value ? " dragging" : ""}`}
onDragOver={onDragOver} onDragOver={(e) => {
onDragLeave={onDragLeave} e.preventDefault();
onDrop={onDrop} dragging.value = true;
}}
onDragLeave={() => (dragging.value = false)}
onDrop={(e) => {
e.preventDefault();
dragging.value = false;
const f = e.dataTransfer?.files?.[0];
if (f) pickFile(f);
}}
onClick={() => inputRef.current?.click()} onClick={() => inputRef.current?.click()}
> >
<span class="drop-zone-icon"></span> <span class="drop-zone-icon"></span>
@@ -117,10 +502,85 @@ export default function ImportNotes() {
</div> </div>
{error.value && <p class="state-error">{error.value}</p>} {error.value && <p class="state-error">{error.value}</p>}
{success.value && (
<p style="font-size:0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.75rem"> {importResult.value && (
{success.value} <ImportResultPopup
</p> result={importResult.value}
onClose={() => (importResult.value = null)}
/>
)}
{/* Sheet + session selector */}
{sheetNames.value.length > 0 && (
<div style="display: flex; gap: 1rem; margin-bottom: 0.75rem; flex-wrap: wrap">
<div>
<label style="font-size: 0.82rem; font-weight: 600; display: block; margin-bottom: 0.25rem">
Feuille
</label>
<select
class="filter-select"
value={selectedSheet.value}
onChange={(e) =>
onSheetChange((e.target as HTMLSelectElement).value)}
>
{sheetNames.value.map((name) => (
<option key={name} value={name}>{name}</option>
))}
</select>
</div>
<div>
<label style="font-size: 0.82rem; font-weight: 600; display: block; margin-bottom: 0.25rem">
Importer en tant que
</label>
<select
class="filter-select"
value={session.value}
onChange={(e) => (session.value = (e.target as HTMLSelectElement)
.value as "1" | "2")}
>
<option value="1">Session 1 (note)</option>
<option value="2">Session 2 (noteSession2)</option>
</select>
</div>
</div>
)}
{/* Column preview */}
{columns.value.length > 0 && (
<div style="margin-bottom: 1rem">
<p style="font-size: 0.82rem; font-weight: 600; margin-bottom: 0.5rem">
Colonnes detectees :
</p>
<div style="display: flex; flex-wrap: wrap; gap: 0.35rem">
{columns.value.map((col) => (
<span
key={col.index}
class={`numEtud-chip${
col.type === "module"
? ""
: col.type === "malus"
? " note-chip--fail"
: " note-chip--promo"
}`}
style="font-size: 0.72rem"
title={`${col.type}${col.name}${
col.coeff != null ? ` (coef ${col.coeff})` : ""
}`}
>
{col.type === "module"
? "M"
: col.type === "ue"
? "UE"
: col.type === "malus"
? "X"
: "?"} {col.code}
</span>
))}
</div>
<p class="col-dim" style="font-size: 0.72rem; margin-top: 0.35rem">
M = module (importe) | UE = moyenne UE (ignore) | X = malus
</p>
</div>
)} )}
<div class="upload-actions"> <div class="upload-actions">
@@ -128,22 +588,31 @@ export default function ImportNotes() {
type="button" type="button"
class="btn btn-primary" class="btn btn-primary"
onClick={doImport} onClick={doImport}
disabled={!file.value || uploading.value} disabled={!file.value || uploading.value ||
columns.value.filter((c) => c.type === "module").length === 0}
> >
{uploading.value ? "" : " Importer"} {uploading.value ? "..." : "+ Importer"}
</button> </button>
<button <button
type="button" type="button"
class="btn btn-secondary" class="btn btn-secondary"
onClick={downloadTemplate} onClick={downloadTemplate}
> >
Télécharger Modèle Telecharger Modele
</button>
<button
type="button"
class="btn btn-secondary"
onClick={downloadExport}
>
Exporter Notes
</button> </button>
</div> </div>
<p class="upload-format"> <p class="upload-format">
Format : <strong>numEtud</strong> | <strong>idModule</strong> |{" "} Format : <strong>Nom</strong> | <strong>Prenom</strong> |{" "}
<strong>note</strong> <strong>CODE - Module</strong> (colonnes notes){" "}
les colonnes UE et MALUS sont auto-detectees
</p> </p>
</div> </div>
); );
+267 -81
View File
@@ -14,8 +14,18 @@ type UEModule = {
coeff: number; coeff: number;
}; };
type Module = { id: string; nom: string }; type Module = { id: string; nom: string };
type Note = { numEtud: number; idModule: string; note: number }; type Note = {
type Ajustement = { numEtud: number; idUE: number; valeur: number }; numEtud: number;
idModule: string;
note: number;
noteSession2: number | null;
};
type Ajustement = {
numEtud: number;
idUE: number;
valeur: number;
malus: number;
};
type Props = { numEtud: number }; type Props = { numEtud: number };
@@ -27,31 +37,38 @@ function noteClass(n: number): string {
return n >= 10 ? "note-chip note-chip--ok" : "note-chip note-chip--fail"; return n >= 10 ? "note-chip note-chip--ok" : "note-chip note-chip--fail";
} }
/** Returns the effective note (session 2 if exists, otherwise session 1). */
function effectiveNote(n: Note): number {
return n.noteSession2 ?? n.note;
}
export default function NoteRecap({ numEtud }: Props) { export default function NoteRecap({ numEtud }: Props) {
const [student, setStudent] = useState<Student | null>(null); const [student, setStudent] = useState<Student | null>(null);
const [ueList, setUeList] = useState<UE[]>([]); const [ueList, setUeList] = useState<UE[]>([]);
const [ueModules, setUeModules] = useState<UEModule[]>([]); const [ueModules, setUeModules] = useState<UEModule[]>([]);
const [moduleMap, setModuleMap] = useState<Map<string, string>>(new Map()); const [moduleMap, setModuleMap] = useState<Map<string, string>>(new Map());
const [noteMap, setNoteMap] = useState<Map<string, number>>(new Map()); const [noteMap, setNoteMap] = useState<Map<string, Note>>(new Map());
const [ajustements, setAjustements] = useState<Ajustement[]>([]); const [ajustements, setAjustements] = useState<Ajustement[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [editingNote, setEditingNote] = useState< const [editingNote, setEditingNote] = useState<
{ idModule: string; value: string } | null { idModule: string; field: "note" | "noteSession2"; value: string } | null
>(null); >(null);
const [ajustInputs, setAjustInputs] = useState<Record<number, string>>({}); const [ajustInputs, setAjustInputs] = useState<
Record<number, { valeur: string; malus: string }>
>({});
async function load() { async function load() {
try { try {
const sRes = await fetch(`/students/api/students/${numEtud}`); const sRes = await fetch(`/students/api/students/${numEtud}`);
if (!sRes.ok) throw new Error("Élève introuvable"); if (!sRes.ok) throw new Error("Eleve introuvable");
const s: Student = await sRes.json(); const s: Student = await sRes.json();
setStudent(s); setStudent(s);
const [uesRes, umRes, mRes, notesRes, ajustRes] = await Promise.all([ const [uesRes, umRes, mRes, notesRes, ajustRes] = await Promise.all([
fetch("/notes/api/ues"), fetch("/admin/api/ues"),
fetch( fetch(
`/notes/api/ue-modules?idPromo=${encodeURIComponent(s.idPromo)}`, `/admin/api/ue-modules?idPromo=${encodeURIComponent(s.idPromo)}`,
), ),
fetch("/admin/api/modules"), fetch("/admin/api/modules"),
fetch(`/notes/api/notes?numEtud=${numEtud}`), fetch(`/notes/api/notes?numEtud=${numEtud}`),
@@ -66,13 +83,18 @@ export default function NoteRecap({ numEtud }: Props) {
} }
if (notesRes.ok) { if (notesRes.ok) {
const ns: Note[] = await notesRes.json(); const ns: Note[] = await notesRes.json();
setNoteMap(new Map(ns.map((n) => [n.idModule, n.note]))); setNoteMap(new Map(ns.map((n) => [n.idModule, n])));
} }
if (ajustRes.ok) { if (ajustRes.ok) {
const aj: Ajustement[] = await ajustRes.json(); const aj: Ajustement[] = await ajustRes.json();
setAjustements(aj); setAjustements(aj);
const inputs: Record<number, string> = {}; const inputs: Record<number, { valeur: string; malus: string }> = {};
for (const a of aj) inputs[a.idUE] = String(a.valeur); for (const a of aj) {
inputs[a.idUE] = {
valeur: String(a.valeur),
malus: String(a.malus),
};
}
setAjustInputs(inputs); setAjustInputs(inputs);
} }
} catch (e) { } catch (e) {
@@ -87,57 +109,108 @@ export default function NoteRecap({ numEtud }: Props) {
}, [numEtud]); }, [numEtud]);
function calcAvg(ueMods: UEModule[]): number | null { function calcAvg(ueMods: UEModule[]): number | null {
let total = 0, coeff = 0; let total = 0,
coeff = 0;
for (const um of ueMods) { for (const um of ueMods) {
const n = noteMap.get(um.idModule); const n = noteMap.get(um.idModule);
if (n === undefined) return null; if (n === undefined) return null;
total += n * um.coeff; const val = effectiveNote(n);
total += val * um.coeff;
coeff += um.coeff; coeff += um.coeff;
} }
return coeff > 0 ? total / coeff : null; return coeff > 0 ? total / coeff : null;
} }
async function saveNote(idModule: string, value: string) { async function saveNote(
idModule: string,
field: "note" | "noteSession2",
value: string,
) {
if (value.trim() === "" && field === "noteSession2") {
// Clear session 2 note
const res = await fetch(
`/notes/api/notes/${numEtud}/${encodeURIComponent(idModule)}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ noteSession2: null }),
},
);
if (res.ok) {
const updated: Note = await res.json();
setNoteMap((prev) => new Map(prev).set(idModule, updated));
}
setEditingNote(null);
return;
}
const note = parseFloat(value.replace(",", ".")); const note = parseFloat(value.replace(",", "."));
if (isNaN(note) || note < 0 || note > 20) { if (isNaN(note) || note < 0 || note > 20) {
setEditingNote(null); setEditingNote(null);
return; return;
} }
const res = await fetch(
`/notes/api/notes/${numEtud}/${encodeURIComponent(idModule)}`, const existing = noteMap.get(idModule);
{
method: "PUT", if (existing) {
// Update
const res = await fetch(
`/notes/api/notes/${numEtud}/${encodeURIComponent(idModule)}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ [field]: note }),
},
);
if (res.ok) {
const updated: Note = await res.json();
setNoteMap((prev) => new Map(prev).set(idModule, updated));
}
} else {
// Create
const body: Record<string, unknown> = {
numEtud,
idModule,
note: field === "note" ? note : 0,
};
if (field === "noteSession2") body.noteSession2 = note;
const res = await fetch("/notes/api/notes", {
method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ note }), body: JSON.stringify(body),
}, });
); if (res.ok) {
if (res.ok) { const created: Note = await res.json();
const updated: Note = await res.json(); setNoteMap((prev) => new Map(prev).set(idModule, created));
setNoteMap((prev) => new Map(prev).set(idModule, updated.note)); }
} }
setEditingNote(null); setEditingNote(null);
} }
async function applyAjust(idUE: number) { async function applyAjust(idUE: number) {
const val = parseFloat((ajustInputs[idUE] ?? "").replace(",", ".")); const inputs = ajustInputs[idUE];
const val = parseFloat((inputs?.valeur ?? "").replace(",", "."));
const malus = parseInt(inputs?.malus ?? "0");
if (isNaN(val) || val < 0 || val > 20) return; if (isNaN(val) || val < 0 || val > 20) return;
if (isNaN(malus) || malus < 0) return;
const existing = ajustements.find((a) => a.idUE === idUE); const existing = ajustements.find((a) => a.idUE === idUE);
const res = existing const res = existing
? await fetch(`/notes/api/ajustements/${numEtud}/${idUE}`, { ? await fetch(`/notes/api/ajustements/${numEtud}/${idUE}`, {
method: "PUT", method: "PUT",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ valeur: val }), body: JSON.stringify({ valeur: val, malus }),
}) })
: await fetch("/notes/api/ajustements", { : await fetch("/notes/api/ajustements", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ numEtud, idUE, valeur: val }), body: JSON.stringify({ numEtud, idUE, valeur: val, malus }),
}); });
if (res.ok) { if (res.ok) {
const updated: Ajustement = await res.json(); const updated: Ajustement = await res.json();
setAjustements((prev) => setAjustements((prev) =>
existing existing
? prev.map((a) => a.idUE === idUE ? updated : a) ? prev.map((a) => (a.idUE === idUE ? updated : a))
: [...prev, updated] : [...prev, updated]
); );
} }
@@ -160,7 +233,7 @@ export default function NoteRecap({ numEtud }: Props) {
if (loading) { if (loading) {
return ( return (
<div class="page-content"> <div class="page-content">
<p class="state-loading">Chargement</p> <p class="state-loading">Chargement...</p>
</div> </div>
); );
} }
@@ -180,19 +253,21 @@ export default function NoteRecap({ numEtud }: Props) {
href="/notes/courses" href="/notes/courses"
f-partial="/notes/partials/courses" f-partial="/notes/partials/courses"
> >
Retour à la liste Retour a la liste
</a> </a>
<h2 <h2
class="page-title" class="page-title"
style="border-bottom: none; margin-bottom: 0.5rem" style="border-bottom: none; margin-bottom: 0.5rem"
> >
Récap notes {student.prenom} {student.nom} Recap notes {student.prenom} {student.nom}
</h2> </h2>
<div class="info-bar" style="margin-bottom: 1.25rem"> <div class="info-bar" style="margin-bottom: 1.25rem">
<span class="numEtud-chip">{student.numEtud}</span> <span class="numEtud-chip">{student.numEtud}</span>
<span style="font-weight: 600">{student.prenom} {student.nom}</span> <span style="font-weight: 600">
{student.prenom} {student.nom}
</span>
<span class="note-chip note-chip--promo">{student.idPromo}</span> <span class="note-chip note-chip--promo">{student.idPromo}</span>
</div> </div>
@@ -201,7 +276,7 @@ export default function NoteRecap({ numEtud }: Props) {
{ueList.length === 0 {ueList.length === 0
? ( ? (
<p class="state-empty"> <p class="state-empty">
Aucune UE configurée pour cette promotion. Aucune UE configuree pour cette promotion.
</p> </p>
) )
: ueList.map((ue) => { : ueList.map((ue) => {
@@ -209,14 +284,26 @@ export default function NoteRecap({ numEtud }: Props) {
const avg = calcAvg(ueMods); const avg = calcAvg(ueMods);
const ajust = ajustements.find((a) => a.idUE === ue.id); const ajust = ajustements.find((a) => a.idUE === ue.id);
// Final displayed average: if ajust.valeur exists it replaces avg, then subtract malus
let finalAvg = avg;
if (ajust) {
finalAvg = ajust.valeur;
if (ajust.malus > 0) {
finalAvg = (finalAvg ?? 0) - ajust.malus;
}
}
return ( return (
<div key={ue.id} class="edit-section"> <div key={ue.id} class="edit-section">
{/* UE header */} {/* UE header */}
<div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.75rem; flex-wrap: wrap"> <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.75rem; flex-wrap: wrap">
<p class="edit-section-title" style="margin: 0">{ue.nom}</p> <p class="edit-section-title" style="margin: 0">{ue.nom}</p>
{avg !== null && ( {avg !== null && (
<span class={noteClass(avg)} style="font-size: 0.78rem"> <span
Moy. calculée : {fmt(avg)} class={noteClass(avg)}
style="font-size: 0.78rem"
>
Moy. calculee : {fmt(avg)}
</span> </span>
)} )}
{ajust && ( {ajust && (
@@ -224,7 +311,15 @@ export default function NoteRecap({ numEtud }: Props) {
class="note-chip note-chip--ajust" class="note-chip note-chip--ajust"
style="font-size: 0.78rem" style="font-size: 0.78rem"
> >
Ajust. actif : {fmt(ajust.valeur)} Ajust. actif : {fmt(ajust.valeur)}
</span>
)}
{ajust && ajust.malus > 0 && (
<span
class="note-chip note-chip--fail"
style="font-size: 0.78rem"
>
Malus : -{ajust.malus}
</span> </span>
)} )}
</div> </div>
@@ -236,21 +331,22 @@ export default function NoteRecap({ numEtud }: Props) {
class="col-dim" class="col-dim"
style="font-size: 0.8rem; padding: 0.25rem 0; margin-bottom: 0.75rem" style="font-size: 0.8rem; padding: 0.25rem 0; margin-bottom: 0.75rem"
> >
Aucun module associé à cette UE pour cette promotion. Aucun module associe a cette UE pour cette promotion.
</p> </p>
) )
: ( : (
<div style="margin-bottom: 0.75rem"> <div style="margin-bottom: 0.75rem">
{ueMods.map((um) => { {ueMods.map((um) => {
const noteVal = noteMap.get(um.idModule); const noteObj = noteMap.get(um.idModule);
const noteVal = noteObj?.note;
const noteS2 = noteObj?.noteSession2;
const effective = noteObj
? effectiveNote(noteObj)
: undefined;
const nomMod = moduleMap.get(um.idModule) ?? um.idModule; const nomMod = moduleMap.get(um.idModule) ?? um.idModule;
const isEditing = editingNote?.idModule === um.idModule;
return ( return (
<div <div key={um.idModule} class="note-row">
key={um.idModule}
class="note-row"
>
<span class="note-row-label"> <span class="note-row-label">
<span class="numEtud-chip note-row-chip"> <span class="numEtud-chip note-row-chip">
{um.idModule} {um.idModule}
@@ -260,17 +356,20 @@ export default function NoteRecap({ numEtud }: Props) {
<span class="col-dim note-row-coef"> <span class="col-dim note-row-coef">
coef {um.coeff} coef {um.coeff}
</span> </span>
{isEditing
{/* Session 1 note */}
{editingNote?.idModule === um.idModule &&
editingNote.field === "note"
? ( ? (
<div style="display: flex; align-items: center; gap: 0.25rem"> <div style="display: flex; align-items: center; gap: 0.25rem">
<input <input
class="form-input" class="form-input"
style="width: 5rem; text-align: center; font-size: 0.85rem" style="width: 5rem; text-align: center; font-size: 0.85rem"
value={editingNote!.value} value={editingNote.value}
autoFocus autoFocus
onInput={(e) => onInput={(e) =>
setEditingNote({ setEditingNote({
idModule: um.idModule, ...editingNote,
value: value:
(e.target as HTMLInputElement).value, (e.target as HTMLInputElement).value,
})} })}
@@ -278,7 +377,8 @@ export default function NoteRecap({ numEtud }: Props) {
if (e.key === "Enter") { if (e.key === "Enter") {
saveNote( saveNote(
um.idModule, um.idModule,
editingNote!.value, "note",
editingNote.value,
); );
} }
if (e.key === "Escape") { if (e.key === "Escape") {
@@ -286,7 +386,11 @@ export default function NoteRecap({ numEtud }: Props) {
} }
}} }}
onBlur={() => onBlur={() =>
saveNote(um.idModule, editingNote!.value)} saveNote(
um.idModule,
"note",
editingNote.value,
)}
/> />
<span <span
class="col-dim" class="col-dim"
@@ -302,76 +406,153 @@ export default function NoteRecap({ numEtud }: Props) {
? noteClass(noteVal) ? noteClass(noteVal)
: "note-chip note-chip--none"} : "note-chip note-chip--none"}
style="font-size: 0.78rem; cursor: pointer" style="font-size: 0.78rem; cursor: pointer"
title="Cliquer pour modifier" title="S1 — Cliquer pour modifier"
onClick={() => onClick={() =>
setEditingNote({ setEditingNote({
idModule: um.idModule, idModule: um.idModule,
field: "note",
value: noteVal !== undefined value: noteVal !== undefined
? String(noteVal) ? String(noteVal)
: "", : "",
})} })}
> >
S1:{" "}
{noteVal !== undefined ? fmt(noteVal) : "—/20"} {noteVal !== undefined ? fmt(noteVal) : "—/20"}
</span> </span>
)} )}
<button
type="button" {/* Session 2 note */}
class="btn btn-sm btn-secondary" {editingNote?.idModule === um.idModule &&
style="font-size: 0.75rem" editingNote.field === "noteSession2"
onClick={() => ? (
setEditingNote({ <div style="display: flex; align-items: center; gap: 0.25rem">
idModule: um.idModule, <input
value: noteVal !== undefined class="form-input"
? String(noteVal) style="width: 5rem; text-align: center; font-size: 0.85rem"
: "", value={editingNote.value}
})} autoFocus
> placeholder="vide = suppr"
<svg onInput={(e) =>
width="14" setEditingNote({
height="14" ...editingNote,
viewBox="0 0 24 24" value:
fill="none" (e.target as HTMLInputElement).value,
stroke="currentColor" })}
stroke-width="2" onKeyDown={(e) => {
if (e.key === "Enter") {
saveNote(
um.idModule,
"noteSession2",
editingNote.value,
);
}
if (e.key === "Escape") {
setEditingNote(null);
}
}}
onBlur={() =>
saveNote(
um.idModule,
"noteSession2",
editingNote.value,
)}
/>
<span
class="col-dim"
style="font-size: 0.75rem"
>
/20
</span>
</div>
)
: (
<span
class={noteS2 != null
? noteClass(noteS2)
: "note-chip note-chip--none"}
style="font-size: 0.78rem; cursor: pointer"
title="S2 — Cliquer pour modifier (vide = pas de session 2)"
onClick={() =>
setEditingNote({
idModule: um.idModule,
field: "noteSession2",
value: noteS2 != null ? String(noteS2) : "",
})}
>
S2: {noteS2 != null ? fmt(noteS2) : "—"}
</span>
)}
{/* Effective note indicator */}
{noteS2 != null && (
<span
class="col-dim"
style="font-size: 0.72rem; font-style: italic"
> >
<path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" /> {fmt(effective!)}
</svg>{" "} </span>
note )}
</button>
</div> </div>
); );
})} })}
</div> </div>
)} )}
{/* Ajustement */} {/* Ajustement + Malus */}
<div class="ajust-section"> <div class="ajust-section">
<p class="ajust-title">Ajustement de la moyenne UE</p> <p class="ajust-title">Ajustement de la moyenne UE</p>
<p class="ajust-hint"> <p class="ajust-hint">
Override ponctuel laisser vide pour utiliser la moy. La valeur remplace la moyenne calculee. Le malus est
calculée soustrait.
</p> </p>
<div style="display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap"> <div style="display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap">
<div style="display: flex; align-items: center; gap: 0.25rem"> <div style="display: flex; align-items: center; gap: 0.25rem">
<span class="col-dim" style="font-size: 0.8rem">
Val:
</span>
<input <input
class="form-input" class="form-input"
style="width: 4.5rem; text-align: center" style="width: 4.5rem; text-align: center"
placeholder="—" placeholder="—"
value={ajustInputs[ue.id] ?? ""} value={ajustInputs[ue.id]?.valeur ?? ""}
onInput={(e) => onInput={(e) =>
setAjustInputs((prev) => ({ setAjustInputs((prev) => ({
...prev, ...prev,
[ue.id]: (e.target as HTMLInputElement).value, [ue.id]: {
valeur: (e.target as HTMLInputElement).value,
malus: prev[ue.id]?.malus ?? "0",
},
}))} }))}
/> />
<span class="col-dim" style="font-size: 0.8rem">/20</span> <span class="col-dim" style="font-size: 0.8rem">/20</span>
</div> </div>
<div style="display: flex; align-items: center; gap: 0.25rem">
<span class="col-dim" style="font-size: 0.8rem">
Malus:
</span>
<input
type="number"
class="form-input"
style="width: 4rem; text-align: center"
placeholder="0"
min="0"
value={ajustInputs[ue.id]?.malus ?? ""}
onInput={(e) =>
setAjustInputs((prev) => ({
...prev,
[ue.id]: {
valeur: prev[ue.id]?.valeur ?? "",
malus: (e.target as HTMLInputElement).value,
},
}))}
/>
</div>
<button <button
type="button" type="button"
class="btn btn-sm btn-primary" class="btn btn-sm btn-primary"
onClick={() => applyAjust(ue.id)} onClick={() => applyAjust(ue.id)}
> >
Appliquer Appliquer
</button> </button>
{ajust && ( {ajust && (
<> <>
@@ -380,14 +561,19 @@ export default function NoteRecap({ numEtud }: Props) {
class="btn btn-sm btn-secondary" class="btn btn-sm btn-secondary"
onClick={() => resetAjust(ue.id)} onClick={() => resetAjust(ue.id)}
> >
Réinitialiser Reinitialiser
</button> </button>
<span <span
class="col-dim" class="col-dim"
style="font-size: 0.75rem; font-family: monospace" style="font-size: 0.75rem; font-family: monospace"
> >
Affiché à l'élève : {fmt(ajust.valeur)} Affiche : {fmt(ajust.valeur)}
{avg !== null ? ` (calculée : ${fmt(avg)})` : ""} {ajust.malus > 0
? ` - ${ajust.malus} = ${
fmt(ajust.valeur - ajust.malus)
}`
: ""}
{avg !== null ? ` (calculee : ${fmt(avg)})` : ""}
</span> </span>
</> </>
)} )}
+63 -37
View File
@@ -1,6 +1,11 @@
import { useEffect, useState } from "preact/hooks"; import { useEffect, useState } from "preact/hooks";
type Note = { numEtud: number; idModule: string; note: number }; type Note = {
numEtud: number;
idModule: string;
note: number;
noteSession2: number | null;
};
type UE = { id: number; nom: string }; type UE = { id: number; nom: string };
type UEModule = { type UEModule = {
idModule: string; idModule: string;
@@ -9,7 +14,12 @@ type UEModule = {
coeff: number; coeff: number;
}; };
type Module = { id: string; nom: string }; type Module = { id: string; nom: string };
type Ajustement = { numEtud: number; idUE: number; valeur: number }; type Ajustement = {
numEtud: number;
idUE: number;
valeur: number;
malus: number;
};
type Props = { type Props = {
numEtud: number | null; numEtud: number | null;
@@ -26,6 +36,11 @@ function avgClass(avg: number | null): string {
return avg >= 10 ? "avg-good" : "avg-warn"; return avg >= 10 ? "avg-good" : "avg-warn";
} }
/** Returns the effective note (session 2 if exists, otherwise session 1). */
function effectiveNote(n: Note): number {
return n.noteSession2 ?? n.note;
}
export default function NotesView({ numEtud, prenom }: Props) { export default function NotesView({ numEtud, prenom }: Props) {
const [notes, setNotes] = useState<Note[]>([]); const [notes, setNotes] = useState<Note[]>([]);
const [ues, setUes] = useState<UE[]>([]); const [ues, setUes] = useState<UE[]>([]);
@@ -47,8 +62,8 @@ export default function NotesView({ numEtud, prenom }: Props) {
try { try {
const [notesRes, uesRes, ueModRes, modRes, ajRes] = await Promise.all([ const [notesRes, uesRes, ueModRes, modRes, ajRes] = await Promise.all([
fetch(`/notes/api/notes?numEtud=${numEtud}`), fetch(`/notes/api/notes?numEtud=${numEtud}`),
fetch("/notes/api/ues"), fetch("/admin/api/ues"),
fetch("/notes/api/ue-modules"), fetch("/admin/api/ue-modules"),
fetch("/admin/api/modules"), fetch("/admin/api/modules"),
fetch(`/notes/api/ajustements?numEtud=${numEtud}`), fetch(`/notes/api/ajustements?numEtud=${numEtud}`),
]); ]);
@@ -72,7 +87,6 @@ export default function NotesView({ numEtud, prenom }: Props) {
setModules(modData); setModules(modData);
setAjustements(ajData); setAjustements(ajData);
// Derive promos from UE-modules for this student's notes
const noteModuleIds = new Set(notesData.map((n: Note) => n.idModule)); const noteModuleIds = new Set(notesData.map((n: Note) => n.idModule));
const relevantPromos = [ const relevantPromos = [
...new Set( ...new Set(
@@ -99,7 +113,7 @@ export default function NotesView({ numEtud, prenom }: Props) {
<div class="page-content"> <div class="page-content">
<p class="state-empty"> <p class="state-empty">
Bonjour {prenom}{" "} Bonjour {prenom}{" "}
aucun dossier étudiant n'est associé à votre compte. aucun dossier etudiant n'est associe a votre compte.
</p> </p>
</div> </div>
); );
@@ -108,7 +122,7 @@ export default function NotesView({ numEtud, prenom }: Props) {
if (loading) { if (loading) {
return ( return (
<div class="page-content"> <div class="page-content">
<p class="state-loading">Chargement</p> <p class="state-loading">Chargement...</p>
</div> </div>
); );
} }
@@ -121,20 +135,18 @@ export default function NotesView({ numEtud, prenom }: Props) {
); );
} }
// Filter UE-modules by active promo
const filteredUeModules = activePromo const filteredUeModules = activePromo
? ueModules.filter((um) => um.idPromo === activePromo) ? ueModules.filter((um) => um.idPromo === activePromo)
: ueModules; : ueModules;
// Group UE-modules by UE
const ueIds = [...new Set(filteredUeModules.map((um) => um.idUE))]; const ueIds = [...new Set(filteredUeModules.map((um) => um.idUE))];
const moduleMap = Object.fromEntries(modules.map((m) => [m.id, m])); const moduleMap = Object.fromEntries(modules.map((m) => [m.id, m]));
const noteMap = Object.fromEntries( const noteMap = Object.fromEntries(
notes.map((n) => [n.idModule, n.note]), notes.map((n) => [n.idModule, n]),
); );
const ajMap = Object.fromEntries( const ajMap = Object.fromEntries(
ajustements.map((a) => [a.idUE, a.valeur]), ajustements.map((a) => [a.idUE, a]),
); );
return ( return (
@@ -155,7 +167,7 @@ export default function NotesView({ numEtud, prenom }: Props) {
)} )}
{ueIds.length === 0 && ( {ueIds.length === 0 && (
<p class="state-empty">Aucune note disponible pour cette période.</p> <p class="state-empty">Aucune note disponible pour cette periode.</p>
)} )}
{ueIds.map((ueId) => { {ueIds.map((ueId) => {
@@ -166,51 +178,65 @@ export default function NotesView({ numEtud, prenom }: Props) {
let weightedSum = 0; let weightedSum = 0;
let coveredCoeff = 0; let coveredCoeff = 0;
ueModsForUE.forEach((um) => { ueModsForUE.forEach((um) => {
const note = noteMap[um.idModule]; const noteObj = noteMap[um.idModule];
if (note !== undefined) { if (noteObj) {
weightedSum += note * um.coeff; const val = effectiveNote(noteObj);
weightedSum += val * um.coeff;
coveredCoeff += um.coeff; coveredCoeff += um.coeff;
} }
}); });
const avg = coveredCoeff > 0 ? weightedSum / coveredCoeff : null; const avg = coveredCoeff > 0 ? weightedSum / coveredCoeff : null;
const ajustement = ajMap[ueId] ?? null; const ajust = ajMap[ueId] ?? null;
const finalAvg = avg !== null && ajustement !== null
? avg + ajustement // If ajust.valeur exists, it replaces the calculated average
: avg; // Then malus is subtracted
let finalAvg: number | null = avg;
if (ajust) {
finalAvg = ajust.valeur;
if (ajust.malus > 0) {
finalAvg = (finalAvg ?? 0) - ajust.malus;
}
}
return ( return (
<div key={ueId} class="ue-card"> <div key={ueId} class="ue-card">
<div class="ue-card-header"> <div class="ue-card-header">
<p class="ue-card-title">UE : {ue.nom}</p> <p class="ue-card-title">UE : {ue.nom}</p>
{finalAvg !== null && ( {finalAvg !== null
<p class={`ue-card-avg ${avgClass(finalAvg)}`}> ? (
Moyenne : {finalAvg.toFixed(2)}/20 <p class={`ue-card-avg ${avgClass(finalAvg)}`}>
{ajustement !== null && ajustement !== 0 && ( Moyenne : {finalAvg.toFixed(2)}/20
<span> {ajust && ajust.malus > 0 && (
{" "} <span>(malus : -{ajust.malus})</span>
(ajustement : {ajustement > 0 ? "+" : ""} )}
{ajustement}) </p>
</span> )
)} : <p class="ue-card-avg avg-warn">Notes non disponibles</p>}
</p>
)}
{finalAvg === null && (
<p class="ue-card-avg avg-warn">Notes non disponibles</p>
)}
</div> </div>
{ueModsForUE.map((um) => { {ueModsForUE.map((um) => {
const mod = moduleMap[um.idModule]; const mod = moduleMap[um.idModule];
const note = noteMap[um.idModule] ?? null; const noteObj = noteMap[um.idModule] ?? null;
const effective = noteObj ? effectiveNote(noteObj) : null;
const hasS2 = noteObj?.noteSession2 != null;
return ( return (
<div key={um.idModule} class="ue-module-row"> <div key={um.idModule} class="ue-module-row">
<span class="ue-module-name"> <span class="ue-module-name">
{mod ? mod.id : um.idModule} {" "} {mod ? mod.id : um.idModule} {" "}
{mod ? mod.nom : "Module inconnu"} (coef {um.coeff}) {mod ? mod.nom : "Module inconnu"} (coef {um.coeff})
</span> </span>
<span class={`score-chip ${scoreClass(note)}`}> <span class={`score-chip ${scoreClass(effective)}`}>
{note !== null ? `${note}/20` : "—"} {effective !== null ? `${effective}/20` : "—"}
{hasS2 && (
<span
style="font-size: 0.7rem; opacity: 0.7; margin-left: 0.35rem"
title={`Session 1 : ${noteObj!.note}/20`}
>
(S1: {noteObj!.note})
</span>
)}
</span> </span>
</div> </div>
); );
+2 -3
View File
@@ -7,10 +7,9 @@ const properties: AppProperties = {
index: "Accueil", index: "Accueil",
notes: "Mes notes", notes: "Mes notes",
courses: "Consulter", courses: "Consulter",
ues: "UEs", import: "Import Notes",
import: "Import xlsx",
}, },
adminOnly: ["courses", "ues", "import"], adminOnly: ["courses", "import"],
studentOnly: ["notes"], studentOnly: ["notes"],
hint: "Student grading management", hint: "Student grading management",
}; };
+17 -2
View File
@@ -52,8 +52,12 @@ export const handler: Handlers<null, AuthenticatedState> = {
} }
try { try {
const body: { numEtud: number; idUE: number; valeur: number } = const body: {
await request.json(); numEtud: number;
idUE: number;
valeur: number;
malus?: number;
} = await request.json();
if (!body.numEtud || !body.idUE || body.valeur === undefined) { if (!body.numEtud || !body.idUE || body.valeur === undefined) {
return new Response( return new Response(
@@ -62,12 +66,23 @@ export const handler: Handlers<null, AuthenticatedState> = {
); );
} }
if (
body.malus !== undefined &&
(!Number.isInteger(body.malus) || body.malus < 0)
) {
return new Response(
JSON.stringify({ error: "malus doit être un entier >= 0" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
}
const [created] = await db const [created] = await db
.insert(ajustements) .insert(ajustements)
.values({ .values({
numEtud: body.numEtud, numEtud: body.numEtud,
idUE: body.idUE, idUE: body.idUE,
valeur: body.valeur, valeur: body.valeur,
malus: body.malus ?? 0,
}) })
.returning(); .returning();
@@ -4,12 +4,13 @@ import { ajustements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Ajustement introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ajustement introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
const FORBIDDEN = new Response(null, { status: 403 }); const FORBIDDEN = () => new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #50 GET /ajustements/{numEtud}/{idUE} // #50 GET /ajustements/{numEtud}/{idUE}
@@ -18,7 +19,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -34,7 +35,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))) .where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE)))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!ajustement) return NOT_FOUND; if (!ajustement) return NOT_FOUND();
return new Response(JSON.stringify(ajustement), { return new Response(JSON.stringify(ajustement), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -47,7 +48,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -57,7 +58,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
return new Response("Paramètres invalides", { status: 400 }); return new Response("Paramètres invalides", { status: 400 });
} }
const body: { valeur: number } = await request.json(); const body: { valeur: number; malus?: number } = await request.json();
if (body.valeur === undefined) { if (body.valeur === undefined) {
return new Response(JSON.stringify({ error: "Champ requis: valeur" }), { return new Response(JSON.stringify({ error: "Champ requis: valeur" }), {
@@ -66,13 +67,28 @@ export const handler: Handlers<null, AuthenticatedState> = {
}); });
} }
if (
body.malus !== undefined &&
(!Number.isInteger(body.malus) || body.malus < 0)
) {
return new Response(
JSON.stringify({ error: "malus doit être un entier >= 0" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
}
const set: { valeur: number; malus?: number } = { valeur: body.valeur };
if (body.malus !== undefined) {
set.malus = body.malus;
}
const [updated] = await db const [updated] = await db
.update(ajustements) .update(ajustements)
.set({ valeur: body.valeur }) .set(set)
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))) .where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE)))
.returning(); .returning();
if (!updated) return NOT_FOUND; if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -85,7 +101,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -100,7 +116,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))) .where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE)))
.returning(); .returning();
if (!deleted) return NOT_FOUND; if (!deleted) return NOT_FOUND();
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+27 -2
View File
@@ -41,7 +41,7 @@ export const handler: Handlers = {
async POST(request) { async POST(request) {
try { try {
const body = await request.json(); const body = await request.json();
const { note, numEtud, idModule } = body; const { note, numEtud, idModule, noteSession2 } = body;
if (note === undefined || !numEtud || !idModule) { if (note === undefined || !numEtud || !idModule) {
return new Response("Champs 'note', 'numEtud' et 'idModule' requis", { return new Response("Champs 'note', 'numEtud' et 'idModule' requis", {
@@ -55,7 +55,32 @@ export const handler: Handlers = {
}); });
} }
const result = await db.insert(notes).values({ note, numEtud, idModule }) if (
noteSession2 !== undefined && noteSession2 !== null &&
(typeof noteSession2 !== "number" || noteSession2 < 0 ||
noteSession2 > 20)
) {
return new Response(
"Champ 'noteSession2' doit être un nombre entre 0 et 20",
{ status: 400 },
);
}
const values: {
note: number;
numEtud: number;
idModule: string;
noteSession2?: number | null;
} = {
note,
numEtud,
idModule,
};
if (noteSession2 !== undefined) {
values.noteSession2 = noteSession2;
}
const result = await db.insert(notes).values(values)
.returning(); .returning();
return new Response(JSON.stringify(result[0]), { return new Response(JSON.stringify(result[0]), {
@@ -64,13 +64,39 @@ export const handler: Handlers = {
} }
const body = await request.json(); const body = await request.json();
const { note } = body; const { note, noteSession2 } = body;
if (note === undefined) { if (note === undefined && noteSession2 === undefined) {
return new Response("Champ 'note' manquant", { status: 400 }); return new Response("Au moins 'note' ou 'noteSession2' requis", {
status: 400,
});
} }
const result = await db.update(notes).set({ note }).where( if (
note !== undefined &&
(typeof note !== "number" || note < 0 || note > 20)
) {
return new Response("Champ 'note' doit être un nombre entre 0 et 20", {
status: 400,
});
}
if (
noteSession2 !== undefined && noteSession2 !== null &&
(typeof noteSession2 !== "number" || noteSession2 < 0 ||
noteSession2 > 20)
) {
return new Response(
"Champ 'noteSession2' doit être un nombre entre 0 et 20",
{ status: 400 },
);
}
const set: { note?: number; noteSession2?: number | null } = {};
if (note !== undefined) set.note = note;
if (noteSession2 !== undefined) set.noteSession2 = noteSession2;
const result = await db.update(notes).set(set).where(
and( and(
eq(notes.numEtud, numEtud), eq(notes.numEtud, numEtud),
eq(notes.idModule, idModule), eq(notes.idModule, idModule),
+21 -3
View File
@@ -26,20 +26,38 @@ export const handler: Handlers = {
const rows = XLSX.utils.sheet_to_json(sheet) as { const rows = XLSX.utils.sheet_to_json(sheet) as {
numEtud: number; numEtud: number;
note: number; note: number;
noteSession2?: number;
}[]; }[];
for (const row of rows) { for (const row of rows) {
const { numEtud, note } = row; const { numEtud, note, noteSession2 } = row;
if (!numEtud || note === undefined) { if (!numEtud || note === undefined) {
continue; continue;
} }
const values: {
numEtud: number;
idModule: string;
note: number;
noteSession2?: number | null;
} = {
numEtud,
idModule,
note,
};
const set: { note: number; noteSession2?: number | null } = { note };
if (noteSession2 !== undefined) {
values.noteSession2 = noteSession2;
set.noteSession2 = noteSession2;
}
await db.insert(notes) await db.insert(notes)
.values({ numEtud, idModule, note }) .values(values)
.onConflictDoUpdate({ .onConflictDoUpdate({
target: [notes.numEtud, notes.idModule], target: [notes.numEtud, notes.idModule],
set: { note }, set,
}); });
} }
+33 -12
View File
@@ -6,31 +6,52 @@ import {
getPartialsConfig, getPartialsConfig,
makePartials, makePartials,
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { State } from "$root/defaults/interfaces.ts"; import { CasContent, State } from "$root/defaults/interfaces.ts";
import NotesView from "../(_islands)/NotesView.tsx"; import NotesView from "../(_islands)/NotesView.tsx";
async function Notes( async function Notes(
_request: Request, _request: Request,
context: FreshContext<State>, context: FreshContext<State>,
) { ) {
const session = const session = (context.state as unknown as { session: CasContent }).session;
(context.state as unknown as { session: { sn: string; givenName: string } })
.session;
const { sn, givenName } = session;
let numEtud: number | null = null; let numEtud: number | null = null;
try { try {
const student = await db if (session.eduPersonPrimaryAffiliation === "student") {
.select() // Students: uid is "<letter>21212006" in AMU CAS — strip non-digit prefix
.from(students) const etudId = parseInt(session.uid.replace(/^\D+/, ""), 10);
.where(and(eq(students.nom, sn), eq(students.prenom, givenName))) if (!isNaN(etudId)) {
.then((rows) => rows[0] ?? null); const student = await db
numEtud = student?.numEtud ?? null; .select()
.from(students)
.where(eq(students.numEtud, etudId))
.then((rows) => rows[0] ?? null);
numEtud = student?.numEtud ?? null;
}
} else {
// Employees: look up by nom/prenom
const student = await db
.select()
.from(students)
.where(
and(
eq(students.nom, session.sn),
eq(students.prenom, session.givenName),
),
)
.then((rows) => rows[0] ?? null);
numEtud = student?.numEtud ?? null;
}
} catch { } catch {
// DB lookup failed — island will show fallback message // DB lookup failed — island will show fallback message
} }
return <NotesView numEtud={numEtud} prenom={session.givenName} />; return (
<NotesView
numEtud={numEtud}
prenom={session.givenName || session.displayName}
/>
);
} }
export const config = getPartialsConfig(); export const config = getPartialsConfig();
@@ -15,6 +15,9 @@ export default function ConsultStudents() {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [filterPromo, setFilterPromo] = useState(""); const [filterPromo, setFilterPromo] = useState("");
const [filterNom, setFilterNom] = useState(""); const [filterNom, setFilterNom] = useState("");
const [selected, setSelected] = useState<Set<number>>(new Set());
const [bulkPromo, setBulkPromo] = useState("");
const [bulkBusy, setBulkBusy] = useState(false);
async function load() { async function load() {
try { try {
@@ -44,6 +47,11 @@ export default function ConsultStudents() {
}); });
if (!res.ok) throw new Error("Suppression échouée"); if (!res.ok) throw new Error("Suppression échouée");
await load(); await load();
setSelected((prev) => {
const next = new Set(prev);
next.delete(numEtud);
return next;
});
} catch (e) { } catch (e) {
setError(e instanceof Error ? e.message : "Erreur"); setError(e instanceof Error ? e.message : "Erreur");
} }
@@ -56,6 +64,85 @@ export default function ConsultStudents() {
return matchPromo && matchNom; return matchPromo && matchNom;
}); });
const filteredIds = new Set(filtered.map((s) => s.numEtud));
const selectedInView = [...selected].filter((id) => filteredIds.has(id));
const allFilteredSelected = filtered.length > 0 &&
filtered.every((s) => selected.has(s.numEtud));
function toggleOne(numEtud: number) {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(numEtud)) next.delete(numEtud);
else next.add(numEtud);
return next;
});
}
function toggleAll() {
if (allFilteredSelected) {
setSelected((prev) => {
const next = new Set(prev);
for (const s of filtered) next.delete(s.numEtud);
return next;
});
} else {
setSelected((prev) => {
const next = new Set(prev);
for (const s of filtered) next.add(s.numEtud);
return next;
});
}
}
async function bulkDelete() {
const count = selectedInView.length;
if (count === 0) return;
if (
!confirm(`Supprimer définitivement ${count} élève(s) sélectionné(s) ?`)
) return;
setBulkBusy(true);
try {
const results = await Promise.all(
selectedInView.map((id) =>
fetch(`/students/api/students/${id}`, { method: "DELETE" })
),
);
const failed = results.filter((r) => !r.ok).length;
if (failed > 0) setError(`${failed} suppression(s) échouée(s)`);
setSelected(new Set());
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setBulkBusy(false);
}
}
async function bulkChangePromo() {
if (!bulkPromo || selectedInView.length === 0) return;
setBulkBusy(true);
try {
const results = await Promise.all(
selectedInView.map((id) =>
fetch(`/students/api/students/${id}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ idPromo: bulkPromo }),
})
),
);
const failed = results.filter((r) => !r.ok).length;
if (failed > 0) setError(`${failed} modification(s) échouée(s)`);
setSelected(new Set());
setBulkPromo("");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setBulkBusy(false);
}
}
return ( return (
<div class="page-content"> <div class="page-content">
<h2 class="page-title">Gestion des Élèves</h2> <h2 class="page-title">Gestion des Élèves</h2>
@@ -93,6 +180,44 @@ export default function ConsultStudents() {
/> />
</div> </div>
{/* Bulk actions bar */}
{selectedInView.length > 0 && (
<div class="bulk-bar">
<span class="bulk-count">
{selectedInView.length} sélectionné(s)
</span>
<div class="bulk-actions">
<select
class="filter-select"
value={bulkPromo}
onChange={(e) =>
setBulkPromo((e.target as HTMLSelectElement).value)}
>
<option value="">Changer de promo</option>
{promos.map((p) => (
<option key={p.id} value={p.id}>{p.id}</option>
))}
</select>
<button
type="button"
class="btn btn-sm btn-primary"
disabled={!bulkPromo || bulkBusy}
onClick={bulkChangePromo}
>
Appliquer
</button>
<button
type="button"
class="btn btn-sm btn-danger"
disabled={bulkBusy}
onClick={bulkDelete}
>
Supprimer
</button>
</div>
</div>
)}
{loading {loading
? <p class="state-loading">Chargement</p> ? <p class="state-loading">Chargement</p>
: ( : (
@@ -100,6 +225,13 @@ export default function ConsultStudents() {
<table class="data-table"> <table class="data-table">
<thead> <thead>
<tr> <tr>
<th style="width: 2.5rem">
<input
type="checkbox"
checked={allFilteredSelected && filtered.length > 0}
onChange={toggleAll}
/>
</th>
<th>N° étud.</th> <th>N° étud.</th>
<th>Nom</th> <th>Nom</th>
<th>Prénom</th> <th>Prénom</th>
@@ -111,13 +243,23 @@ export default function ConsultStudents() {
{filtered.length === 0 {filtered.length === 0
? ( ? (
<tr> <tr>
<td colspan={5} class="state-empty"> <td colspan={6} class="state-empty">
Aucun élève trouvé Aucun élève trouvé
</td> </td>
</tr> </tr>
) )
: filtered.map((s) => ( : filtered.map((s) => (
<tr key={s.numEtud}> <tr
key={s.numEtud}
class={selected.has(s.numEtud) ? "row-selected" : ""}
>
<td>
<input
type="checkbox"
checked={selected.has(s.numEtud)}
onChange={() => toggleOne(s.numEtud)}
/>
</td>
<td class="col-dim">{s.numEtud}</td> <td class="col-dim">{s.numEtud}</td>
<td>{s.nom}</td> <td>{s.nom}</td>
<td>{s.prenom}</td> <td>{s.prenom}</td>
@@ -2,13 +2,17 @@
import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs"; import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs";
import { useRef } from "preact/hooks"; import { useRef } from "preact/hooks";
import { useSignal } from "@preact/signals"; import { useSignal } from "@preact/signals";
import ImportResultPopup, {
type ImportDetail,
type ImportResult,
} from "$root/defaults/ImportResultPopup.tsx";
export default function UploadStudents() { export default function UploadStudents() {
const file = useSignal<File | null>(null); const file = useSignal<File | null>(null);
const dragging = useSignal(false); const dragging = useSignal(false);
const uploading = useSignal(false); const uploading = useSignal(false);
const error = useSignal<string | null>(null); const error = useSignal<string | null>(null);
const success = useSignal<string | null>(null); const importResult = useSignal<ImportResult | null>(null);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
function pickFile(f: File) { function pickFile(f: File) {
@@ -18,7 +22,7 @@ export default function UploadStudents() {
} }
file.value = f; file.value = f;
error.value = null; error.value = null;
success.value = null; importResult.value = null;
} }
function onDragOver(e: DragEvent) { function onDragOver(e: DragEvent) {
@@ -46,36 +50,58 @@ export default function UploadStudents() {
if (!file.value) return; if (!file.value) return;
uploading.value = true; uploading.value = true;
error.value = null; error.value = null;
success.value = null; importResult.value = null;
try { try {
const arrayBuffer = await file.value.arrayBuffer(); const arrayBuffer = await file.value.arrayBuffer();
const workbook = XLSX.read(arrayBuffer, { type: "array" }); const workbook = XLSX.read(arrayBuffer, { type: "array" });
let imported = 0; let added = 0;
let failed = 0; let errors = 0;
const details: ImportDetail[] = [];
for (const sheetName of workbook.SheetNames) { for (const sheetName of workbook.SheetNames) {
const sheet = workbook.Sheets[sheetName]; const sheet = workbook.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json<{ const rows = XLSX.utils.sheet_to_json<{
numEtud: number;
nom: string; nom: string;
prenom: string; prenom: string;
}>(sheet, { header: ["numEtud", "nom", "prenom"], range: 1 }); numEtud: number;
idPromo: string;
}>(sheet, {
header: ["nom", "prenom", "numEtud", "idPromo"],
range: 2,
});
for (const row of rows) { for (const row of rows) {
const res = await fetch("/students/api/students", { const res = await fetch("/students/api/students", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ ...row, idPromo: sheetName }), body: JSON.stringify(row),
}); });
if (res.ok) imported++; if (res.ok) {
else failed++; added++;
details.push({
type: "change",
message:
`${row.numEtud} : ${row.nom} ${row.prenom} -> ${row.idPromo}`,
});
} else {
errors++;
const body = await res.json().catch(() => ({}));
details.push({
type: "error",
message: `${row.numEtud} : ${body.error ?? "Erreur creation"}`,
});
}
} }
} }
success.value = `Import terminé — ${imported} ajouté${ importResult.value = {
imported !== 1 ? "s" : "" added,
}${failed > 0 ? `, ${failed} erreur${failed !== 1 ? "s" : ""}` : ""}`; modified: 0,
ignored: 0,
errors,
details,
};
} catch { } catch {
error.value = "Erreur lors de la lecture du fichier."; error.value = "Erreur lors de la lecture du fichier.";
} finally { } finally {
@@ -84,10 +110,7 @@ export default function UploadStudents() {
} }
function downloadTemplate() { function downloadTemplate() {
const wb = XLSX.utils.book_new(); globalThis.open("/templates/modele_etudiants.xlsx", "_blank");
const ws = XLSX.utils.aoa_to_sheet([["numEtud", "nom", "prenom"]]);
XLSX.utils.book_append_sheet(wb, ws, "4A22");
XLSX.writeFile(wb, "modele_etudiants.xlsx");
} }
return ( return (
@@ -117,10 +140,12 @@ export default function UploadStudents() {
</div> </div>
{error.value && <p class="state-error">{error.value}</p>} {error.value && <p class="state-error">{error.value}</p>}
{success.value && (
<p style="font-size:0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.75rem"> {importResult.value && (
{success.value} <ImportResultPopup
</p> result={importResult.value}
onClose={() => (importResult.value = null)}
/>
)} )}
<div class="upload-actions"> <div class="upload-actions">
@@ -142,9 +167,8 @@ export default function UploadStudents() {
</div> </div>
<p class="upload-format"> <p class="upload-format">
Format : <strong>promo</strong> (nom de la feuille) |{" "} Format : <strong>Nom</strong> | <strong>Prenom</strong> |{" "}
<strong>numEtud</strong> | <strong>nom</strong> |{" "} <strong>Numero-etudiant</strong> | <strong>Promotion</strong>
<strong>prénom</strong>
</p> </p>
</div> </div>
); );
+1 -2
View File
@@ -6,10 +6,9 @@ const properties: AppProperties = {
pages: { pages: {
index: "Accueil", index: "Accueil",
consult: "Élèves", consult: "Élèves",
promotions: "Promotions",
upload: "Import xlsx", upload: "Import xlsx",
}, },
adminOnly: ["consult", "promotions", "upload"], adminOnly: ["consult", "upload"],
hint: "Create students promotion and see informations", hint: "Create students promotion and see informations",
}; };
@@ -1,15 +1,25 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { promotions } from "$root/databases/schema.ts"; import {
ajustements,
enseignements,
modules,
notes,
promotions,
students,
ueModules,
ues,
} from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Ressource introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ressource introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
const FORBIDDEN = new Response(null, { status: 403 }); const FORBIDDEN = () => new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #15 GET /promotions/{idPromo} // #15 GET /promotions/{idPromo}
@@ -18,7 +28,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const promo = await db const promo = await db
@@ -27,7 +37,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(promotions.id, context.params.idPromo)) .where(eq(promotions.id, context.params.idPromo))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!promo) return NOT_FOUND; if (!promo) return NOT_FOUND();
return new Response(JSON.stringify(promo), { return new Response(JSON.stringify(promo), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -40,7 +50,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const body: { annee: string } = await request.json(); const body: { annee: string } = await request.json();
@@ -51,7 +61,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(promotions.id, context.params.idPromo)) .where(eq(promotions.id, context.params.idPromo))
.returning(); .returning();
if (!updated) return NOT_FOUND; if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -59,20 +69,104 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #17 DELETE /promotions/{idPromo} // #17 DELETE /promotions/{idPromo}
// Blocked if students are still assigned (409).
// Cascade: deletes linked ue_modules, enseignements, and orphaned
// modules (+ their notes) & UEs (+ their ajustements).
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const [deleted] = await db const idPromo = context.params.idPromo;
.delete(promotions)
.where(eq(promotions.id, context.params.idPromo))
.returning();
if (!deleted) return NOT_FOUND; const promo = await db
.select()
.from(promotions)
.where(eq(promotions.id, idPromo))
.then((r) => r[0] ?? null);
if (!promo) return NOT_FOUND();
// Block deletion if students are still assigned
const assignedStudents = await db
.select()
.from(students)
.where(eq(students.idPromo, idPromo))
.then((r) => r.length);
if (assignedStudents > 0) {
return new Response(
JSON.stringify({
error:
`Impossible de supprimer : ${assignedStudents} étudiant(s) encore assigné(s) à cette promotion`,
}),
{ status: 409, headers: { "content-type": "application/json" } },
);
}
await db.transaction(async (tx) => {
// Collect linked module IDs and UE IDs before deleting junction rows
const linkedUeModules = await tx
.select({ idModule: ueModules.idModule, idUE: ueModules.idUE })
.from(ueModules)
.where(eq(ueModules.idPromo, idPromo));
const linkedEns = await tx
.select({ idModule: enseignements.idModule })
.from(enseignements)
.where(eq(enseignements.idPromo, idPromo));
const moduleIds = [
...new Set([
...linkedUeModules.map((um) => um.idModule),
...linkedEns.map((e) => e.idModule),
]),
];
const ueIds = [...new Set(linkedUeModules.map((um) => um.idUE))];
// Delete junction rows that directly reference this promo
await tx.delete(ueModules).where(eq(ueModules.idPromo, idPromo));
await tx.delete(enseignements).where(eq(enseignements.idPromo, idPromo));
// Delete orphaned modules (not used by another promo) and their notes
for (const modId of moduleIds) {
const stillInUeModules = await tx
.select()
.from(ueModules)
.where(eq(ueModules.idModule, modId))
.then((r) => r.length > 0);
const stillInEns = await tx
.select()
.from(enseignements)
.where(eq(enseignements.idModule, modId))
.then((r) => r.length > 0);
if (!stillInUeModules && !stillInEns) {
await tx.delete(notes).where(eq(notes.idModule, modId));
await tx.delete(modules).where(eq(modules.id, modId));
}
}
// Delete orphaned UEs (not used by another promo) and their ajustements
for (const ueId of ueIds) {
const stillUsed = await tx
.select()
.from(ueModules)
.where(eq(ueModules.idUE, ueId))
.then((r) => r.length > 0);
if (!stillUsed) {
await tx.delete(ajustements).where(eq(ajustements.idUE, ueId));
await tx.delete(ues).where(eq(ues.id, ueId));
}
}
// Delete the promotion
await tx.delete(promotions).where(eq(promotions.id, idPromo));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+14 -2
View File
@@ -44,13 +44,25 @@ export const handler: Handlers<null, AuthenticatedState> = {
idPromo: string; idPromo: string;
} = await request.json(); } = await request.json();
if (!body.nom || !body.prenom || !body.idPromo) { if (!body.nom || !body.prenom) {
return new Response(null, { status: 400 }); return new Response(null, { status: 400 });
} }
const values: {
numEtud?: number;
nom: string;
prenom: string;
idPromo?: string;
} = {
nom: body.nom,
prenom: body.prenom,
};
if (body.numEtud) values.numEtud = body.numEtud;
if (body.idPromo) values.idPromo = body.idPromo;
const [created] = await db const [created] = await db
.insert(students) .insert(students)
.values({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo }) .values(values)
.returning(); .returning();
return new Response(JSON.stringify(created), { return new Response(JSON.stringify(created), {
@@ -1,15 +1,21 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { students } from "$root/databases/schema.ts"; import {
ajustements,
mobility,
notes,
students,
} from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response( const NOT_FOUND = () =>
JSON.stringify({ error: "Ressource introuvable" }), new Response(
{ status: 404, headers: { "content-type": "application/json" } }, JSON.stringify({ error: "Ressource introuvable" }),
); { status: 404, headers: { "content-type": "application/json" } },
);
const FORBIDDEN = new Response(null, { status: 403 }); const FORBIDDEN = () => new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #10 GET /students/{numEtud} // #10 GET /students/{numEtud}
@@ -18,7 +24,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -28,7 +34,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(students.numEtud, numEtud)) .where(eq(students.numEtud, numEtud))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!student) return NOT_FOUND; if (!student) return NOT_FOUND();
return new Response(JSON.stringify(student), { return new Response(JSON.stringify(student), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -41,20 +47,32 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
const body: { nom: string; prenom: string; idPromo: string } = await request const body: { nom?: string; prenom?: string; idPromo?: string } =
.json(); await request.json();
const set: { nom?: string; prenom?: string; idPromo?: string } = {};
if (body.nom !== undefined) set.nom = body.nom;
if (body.prenom !== undefined) set.prenom = body.prenom;
if (body.idPromo !== undefined) set.idPromo = body.idPromo;
if (Object.keys(set).length === 0) {
return new Response(
JSON.stringify({ error: "Au moins un champ requis" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
}
const [updated] = await db const [updated] = await db
.update(students) .update(students)
.set({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo }) .set(set)
.where(eq(students.numEtud, numEtud)) .where(eq(students.numEtud, numEtud))
.returning(); .returning();
if (!updated) return NOT_FOUND; if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -62,21 +80,31 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #12 DELETE /students/{numEtud} // #12 DELETE /students/{numEtud}
// Cascade: deletes notes, ajustements, mobility for this student.
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN; return FORBIDDEN();
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
const [deleted] = await db
.delete(students)
.where(eq(students.numEtud, numEtud))
.returning();
if (!deleted) return NOT_FOUND; const student = await db
.select()
.from(students)
.where(eq(students.numEtud, numEtud))
.then((r) => r[0] ?? null);
if (!student) return NOT_FOUND();
await db.transaction(async (tx) => {
await tx.delete(notes).where(eq(notes.numEtud, numEtud));
await tx.delete(ajustements).where(eq(ajustements.numEtud, numEtud));
await tx.delete(mobility).where(eq(mobility.studentId, numEtud));
await tx.delete(students).where(eq(students.numEtud, numEtud));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+53 -21
View File
@@ -4,41 +4,73 @@ import { createJwt } from "@popov/jwt";
import { setCookie } from "$std/http/cookie.ts"; import { setCookie } from "$std/http/cookie.ts";
import { getKey } from "$root/routes/_middleware.ts"; import { getKey } from "$root/routes/_middleware.ts";
const FAKE_ADMIN: CasContent = { function makeFakeUser(
amuCampus: "local", role: "employee" | "student",
amuComposante: "local", numEtud?: string,
amuDateValidation: "", ): CasContent {
coGroup: "", if (role === "student" && numEtud) {
eduPersonPrimaryAffiliation: "employee", return {
eduPersonPrincipalName: "admin@local", amuCampus: "local",
mail: "admin@local", amuComposante: "local",
displayName: "Admin Local", amuDateValidation: "",
givenName: "Admin", coGroup: "",
memberOf: [], eduPersonPrimaryAffiliation: "student",
sn: "Local", eduPersonPrincipalName: `${numEtud}@local`,
supannCivilite: "", mail: `${numEtud}@local`,
supannEntiteAffectation: "", displayName: `Etudiant ${numEtud}`,
supannEtuAnneeInscription: "", givenName: "",
supannEtuEtape: "", memberOf: [],
uid: "admin-local", sn: "",
}; supannCivilite: "",
supannEntiteAffectation: "",
supannEtuAnneeInscription: "",
supannEtuEtape: "",
uid: `e${numEtud}`,
};
}
return {
amuCampus: "local",
amuComposante: "local",
amuDateValidation: "",
coGroup: "",
eduPersonPrimaryAffiliation: "employee",
eduPersonPrincipalName: "admin@local",
mail: "admin@local",
displayName: "Admin Local",
givenName: "Admin",
memberOf: [],
sn: "Local",
supannCivilite: "",
supannEntiteAffectation: "",
supannEtuAnneeInscription: "",
supannEtuEtape: "",
uid: "admin-local",
};
}
export const handler: Handlers<null, State> = { export const handler: Handlers<null, State> = {
async GET(_request: Request, _context: FreshContext<State, null>) { async GET(request: Request, _context: FreshContext<State, null>) {
if (Deno.env.get("LOCAL") !== "true") { if (Deno.env.get("LOCAL") !== "true") {
return new Response("Not available outside LOCAL mode.", { status: 403 }); return new Response("Not available outside LOCAL mode.", { status: 403 });
} }
const url = new URL(request.url);
const role = url.searchParams.get("role") === "student"
? "student"
: "employee";
const numEtud = url.searchParams.get("numEtud") ?? undefined;
const user = makeFakeUser(role, numEtud);
const now = Math.floor(Date.now() / 1000); const now = Math.floor(Date.now() / 1000);
const payload: LoginJWT = { const payload: LoginJWT = {
iss: "PolyMPR", iss: "PolyMPR",
iat: now, iat: now,
exp: now + 0xe10, exp: now + 0xe10,
aud: "PolyMPR", aud: "PolyMPR",
user: FAKE_ADMIN, user,
}; };
const token = await createJwt(payload, getKey(FAKE_ADMIN.uid)); const token = await createJwt(payload, getKey(user.uid));
const headers = new Headers(); const headers = new Headers();
setCookie(headers, { name: "sessionToken", value: token }); setCookie(headers, { name: "sessionToken", value: token });
headers.set("Location", "/apps"); headers.set("Location", "/apps");
+2
View File
@@ -45,6 +45,8 @@ function createUserJWT(casResponse: CasResponse): Promise<string> {
} }
}); });
console.log(fullUserInfos);
const now = Math.floor(Date.now() / 1000); const now = Math.floor(Date.now() / 1000);
const payload: LoginJWT = { const payload: LoginJWT = {
iss: "PolyMPR", iss: "PolyMPR",
+60
View File
@@ -0,0 +1,60 @@
// @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";
// --- Template 1: Students ---
{
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet([
[null, null, null, "Promotion peut etre vide mais doit prealablement Exister"],
["Nom", "Prenom", "Numero-etudiant", "Promotion"],
["NOM", "PRENOM", 12345678, "3AFISE24-25"],
]);
XLSX.utils.book_append_sheet(wb, ws, "Eleves");
XLSX.writeFile(wb, "static/templates/modele_etudiants.xlsx");
console.log("Created static/templates/modele_etudiants.xlsx");
}
// --- Template 2: Notes ---
{
const headers = [
null,
null,
"MOD01 - Module 1",
"MOD02 - Module 2",
"MOD03 - Module 3",
];
const coeffs = [null, null, 2, 3, 2];
const row1 = ["NOM", "PRENOM", 12, 15.5, 14];
const row2 = ["DUPONT", "JEAN", 8, 10, 16.5];
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet([headers, coeffs, row1, row2]);
XLSX.utils.book_append_sheet(wb, ws, "Session 1");
XLSX.writeFile(wb, "static/templates/modele_notes.xlsx");
console.log("Created static/templates/modele_notes.xlsx");
}
// --- Template 3: Maquette ---
{
const data = [
["Intitule du diplome", null, "Informatique - Annee 20.. - 20.."],
["Description des UE du diplome", null, null, null, null, null, "Nombre d'heures"],
["Annee\nSemestres", "Codes APOGEE", null, null, "Credits\n ECTS", "Coeff.", "CM", "TD", "TP"],
["INFO3A", null, null, null, "ECTS", "Coef", "CM", "TD", "TP"],
["SEM 5", null, null, null, 30],
["UE", "CODE_UE1", "Nom de l'UE 1", null, 6],
[null, "MOD01", null, "Module 1", null, 2, 10, 10, 10],
[null, "MOD02", null, "Module 2", null, 2, 10, 10, 10],
[null, "MOD03", null, "Module 3", null, 2, 10, 10, 10],
[],
["UE", "CODE_UE2", "Nom de l'UE 2", null, 4],
[null, "MOD04", null, "Module 4", null, 2, 10, 10, 10],
[null, "MOD05", null, "Module 5", null, 2, 10, 10, 10],
];
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet(data);
XLSX.utils.book_append_sheet(wb, ws, "Maquette");
XLSX.writeFile(wb, "static/templates/modele_maquette.xlsx");
console.log("Created static/templates/modele_maquette.xlsx");
}
+25
View File
@@ -0,0 +1,25 @@
// @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";
for (const file of ["FISE-INFO-2025.xlsx", "FISA-INFO-2025.xlsx"]) {
console.log(`\n=== ${file} ===`);
const wb = XLSX.read(Deno.readFileSync(`Excels/${file}`), { type: "array" });
console.log(`Sheets: ${wb.SheetNames.join(", ")}`);
for (const sheetName of wb.SheetNames) {
console.log(`\n--- Sheet: ${sheetName} ---`);
const sheet = wb.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json<(string | number | null)[]>(sheet, { header: 1 });
// Print first 5 cols of each row, mark rows that look like year/semester headers
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (!row || row.length === 0) continue;
const col0 = row[0] != null ? String(row[0]).trim() : "";
// Show rows that are structural (year, semester, UE headers)
if (col0 || (row[1] != null && String(row[1]).trim())) {
const preview = row.slice(0, 6).map(c => c != null ? String(c).substring(0, 25) : "").join(" | ");
console.log(` [${i}] ${preview}`);
}
}
}
}
+193
View File
@@ -391,6 +391,54 @@
gap: 1rem; gap: 1rem;
} }
/* -------------------------------------------------------
Bulk actions bar
------------------------------------------------------- */
.bulk-bar {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.5rem 0.75rem;
margin-bottom: 0.75rem;
border-radius: 6px;
background: light-dark(var(--light-accent-color), var(--dark-accent-color));
color: light-dark(
var(--light-background-color),
var(--dark-background-color)
);
font-size: 0.82rem;
flex-wrap: wrap;
}
.bulk-count {
font-weight: var(--font-weight-bold);
white-space: nowrap;
}
.bulk-actions {
display: flex;
align-items: center;
gap: 0.5rem;
margin-left: auto;
flex-wrap: wrap;
}
.bulk-bar .filter-select {
color: light-dark(
var(--light-foreground-color),
var(--dark-foreground-color)
);
font-size: 0.78rem;
}
.row-selected {
background: light-dark(
color-mix(in srgb, var(--light-accent-color) 8%, transparent),
color-mix(in srgb, var(--dark-accent-color) 12%, transparent)
);
}
/* ------------------------------------------------------- /* -------------------------------------------------------
Chips: perm, role, promo, module Chips: perm, role, promo, module
------------------------------------------------------- */ ------------------------------------------------------- */
@@ -852,6 +900,14 @@
margin-bottom: 0.75rem; margin-bottom: 0.75rem;
} }
.create-promo-inline {
margin-bottom: 1rem;
padding: 0.75rem;
border: 1px dashed
light-dark(var(--light-foreground-dimmer), var(--dark-foreground-dimmer));
border-radius: 6px;
}
.upload-format { .upload-format {
font-size: 0.72rem; font-size: 0.72rem;
font-family: monospace; font-family: monospace;
@@ -1008,3 +1064,140 @@
font-family: monospace; font-family: monospace;
margin-top: 0.25rem; margin-top: 0.25rem;
} }
/* -------------------------------------------------------
Import result popup
------------------------------------------------------- */
.import-popup-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.55);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.import-popup {
background: light-dark(
var(--light-background-color),
var(--dark-background-color)
);
border: 1px solid
light-dark(var(--light-border-color), var(--dark-border-color));
border-radius: 10px;
padding: 1.5rem 2rem;
min-width: 28rem;
max-width: 40rem;
max-height: 80vh;
overflow-y: auto;
}
.import-popup-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1.25rem;
}
.import-popup-title {
font-size: 1.1rem;
font-weight: var(--font-weight-bold);
margin: 0;
}
.import-popup-badge {
font-size: 0.78rem;
font-weight: 600;
padding: 0.25rem 0.75rem;
border-radius: 4px;
border: 1px solid;
}
.badge-error {
color: #f5a623;
border-color: #f5a623;
}
.badge-success {
color: light-dark(var(--light-accent-color), var(--dark-accent-color));
border-color: light-dark(var(--light-accent-color), var(--dark-accent-color));
}
.import-popup-stats {
display: flex;
flex-direction: column;
gap: 0.6rem;
margin-bottom: 1.25rem;
}
.import-stat-row {
display: flex;
align-items: center;
gap: 1.5rem;
}
.import-stat-label {
min-width: 6rem;
font-size: 0.85rem;
color: light-dark(var(--light-foreground-dim), var(--dark-foreground-dim));
}
.import-stat-value {
font-size: 0.85rem;
font-family: monospace;
padding: 0.2rem 0.6rem;
border-radius: 4px;
border: 1px solid;
min-width: 8rem;
}
.stat-added {
color: light-dark(var(--light-accent-color), var(--dark-accent-color));
border-color: light-dark(var(--light-accent-color), var(--dark-accent-color));
}
.stat-modified {
color: light-dark(var(--light-accent-color), var(--dark-accent-color));
border-color: light-dark(var(--light-accent-color), var(--dark-accent-color));
}
.stat-ignored {
color: light-dark(var(--light-foreground-dim), var(--dark-foreground-dim));
border-color: light-dark(var(--light-border-color), var(--dark-border-color));
}
.stat-errors {
color: #f5a623;
border-color: #f5a623;
}
.import-popup-actions {
display: flex;
gap: 0.75rem;
margin-bottom: 0.75rem;
}
.import-popup-details {
border-top: 1px solid
light-dark(var(--light-border-color), var(--dark-border-color));
padding-top: 0.75rem;
font-family: monospace;
font-size: 0.75rem;
max-height: 12rem;
overflow-y: auto;
}
.import-detail-change {
margin: 0.15rem 0;
color: light-dark(
var(--light-foreground-color),
var(--dark-foreground-color)
);
}
.import-detail-error {
margin: 0.15rem 0;
color: #f5a623;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -21,8 +21,8 @@ import {
import { handler as modulesHandler } from "$apps/admin/api/modules.ts"; import { handler as modulesHandler } from "$apps/admin/api/modules.ts";
import { handler as moduleHandler } from "$apps/admin/api/modules/[idModule].ts"; import { handler as moduleHandler } from "$apps/admin/api/modules/[idModule].ts";
import { handler as notesHandler } from "$apps/notes/api/notes.ts"; import { handler as notesHandler } from "$apps/notes/api/notes.ts";
import { handler as uesHandler } from "$apps/notes/api/ues.ts"; import { handler as uesHandler } from "$apps/admin/api/ues.ts";
import { handler as ueModulesHandler } from "$apps/notes/api/ue-modules.ts"; import { handler as ueModulesHandler } from "$apps/admin/api/ue-modules.ts";
import { handler as ajustementsHandler } from "$apps/notes/api/ajustements.ts"; import { handler as ajustementsHandler } from "$apps/notes/api/ajustements.ts";
import { handler as enseignementsHandler } from "$apps/admin/api/enseignements.ts"; import { handler as enseignementsHandler } from "$apps/admin/api/enseignements.ts";
import { handler as usersHandler } from "$apps/admin/api/users.ts"; import { handler as usersHandler } from "$apps/admin/api/users.ts";
+2 -2
View File
@@ -14,8 +14,8 @@ import {
seedUes, seedUes,
truncateAll, truncateAll,
} from "../helpers/db_integration.ts"; } from "../helpers/db_integration.ts";
import { handler as ueModulesHandler } from "$apps/notes/api/ue-modules.ts"; import { handler as ueModulesHandler } from "$apps/admin/api/ue-modules.ts";
import { handler as ueModuleHandler } from "$apps/notes/api/ue-modules/[idModule]/[idUE]/[idPromo].ts"; import { handler as ueModuleHandler } from "$apps/admin/api/ue-modules/[idModule]/[idUE]/[idPromo].ts";
import { ueModules as ueModulesTable } from "$root/databases/schema.ts"; import { ueModules as ueModulesTable } from "$root/databases/schema.ts";
import { testDb } from "../helpers/db_integration.ts"; import { testDb } from "../helpers/db_integration.ts";
+2 -2
View File
@@ -7,8 +7,8 @@ import {
makeJsonRequest, makeJsonRequest,
} from "../helpers/handler.ts"; } from "../helpers/handler.ts";
import { seedUes, truncateAll } from "../helpers/db_integration.ts"; import { seedUes, truncateAll } from "../helpers/db_integration.ts";
import { handler as uesHandler } from "$apps/notes/api/ues.ts"; import { handler as uesHandler } from "$apps/admin/api/ues.ts";
import { handler as ueHandler } from "$apps/notes/api/ues/[idUE].ts"; import { handler as ueHandler } from "$apps/admin/api/ues/[idUE].ts";
// --- GET /ues --- // --- GET /ues ---