Compare commits

..

21 Commits

Author SHA1 Message Date
djalim 6c38cd0019 feat: cascade deletes, student notes, import popups, module reorganization
- Cascade delete on all entities (student, module, UE, user, role, promotion)
- Fix Response body reuse bug (factory functions instead of constants)
- Student note viewing via CAS uid (strip non-digit prefix)
- Fix middleware page visibility for students in LOCAL mode
- Import result popup component (shared across all import pages)
- Fix student import to use numEtud from Excel
- Bulk student selection with promo change and delete
- Move UE/UE-Module API and pages from notes to admin module
- Move promotions page from students to admin module
- Multi-year maquette import with per-year promo selection
- Inline promo creation in maquette import
- Static Excel templates (students, notes, maquette)
- Fix XLSX export using blob download instead of writeFile
- Allow students to read modules list (GET /modules)
2026-04-30 13:47:16 +02:00
djalim 04be659d6b feat(app): add studentOnly pages and new routes
Add routes for modules, users, notes import, recap, and islands edit.
Update middleware to filter pages based on user role.

feat(admin): add modal for assigning teaching, replace delete icon with SVG

refactor(server): rename port variable to uppercase and add env support
feat(admin): add enseignants, users, filtering and role colors

refactor(AdminRoles): improve role UI and add permission mapping

feat(admin-users): add role colors, role filter, and modal for creating users

feat(admin): add EditModule component for module editing

feat(admin): add EditUser page for editing users and managing enseignements

feat(promo-select): display id and name in options for promo dropdown

feat: add edit module/user routes, inline coeff editing, UI tweaks

refactor: UI – icons, modal overlay, grid, subtitles, import margin
2026-04-29 09:12:55 +02:00
Clément Oudelet f71128a7f3 PMPR-44 : fix missing newline
Check Deno code / Check Deno code (pull_request) Successful in 5s
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Successful in 1m14s
Check Deno code / Check Deno code (push) Successful in 5s
Tests / Unit tests (push) Successful in 12s
Tests / Integration tests (push) Successful in 1m13s
2026-04-27 17:19:57 +00:00
Clément Oudelet 720a380be8 PMPR-44 : fix formatting 2026-04-27 17:19:57 +00:00
Clément Oudelet 6c602cb10a PMPR-44 : POST /notes/import-xlsx - importer des notes via Excel 2026-04-27 17:19:57 +00:00
djalim bb09c1cce5 chore: formated tests
Check Deno code / Check Deno code (pull_request) Successful in 5s
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Successful in 1m18s
Check Deno code / Check Deno code (push) Successful in 5s
Tests / Unit tests (push) Successful in 11s
Tests / Integration tests (push) Successful in 1m13s
2026-04-27 18:58:19 +02:00
djalim f162fcaadc feat: add role_write permission and update e2e tests
Check Deno code / Check Deno code (pull_request) Failing after 5s
Tests / Unit tests (pull_request) Successful in 13s
Tests / Integration tests (pull_request) Successful in 1m12s
Add role_write permission to permissions table and update migrations.
Update e2e tests to use DB integration and seed permissions.
Add seedPermissions helper.
2026-04-27 18:56:04 +02:00
djalim 2c5e4ebf11 feat(fresh.gen.ts): add routes for notes edition, recap and island recap
Check Deno code / Check Deno code (pull_request) Failing after 5s
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Failing after 1m17s
feat(notes): add NoteRecap island component for student grade recap

feat: add adjust controls to UI component

Add placeholder, value binding, onInput handler, apply/reset buttons,
and display of adjusted value.

feat(notes): add edition and recap pages, update styles and links
2026-04-27 18:22:23 +02:00
djalim 757e364af0 chore(docker): add .dockerignore and update Dockerfile
Add .dockerignore to exclude node_modules, .git, coverage, .env.
Update Dockerfile to install nodejs/npm, copy package.json, run npm install, and build.
Update compose.prod.yml to set working_dir, restart no, and use array command.
Move drizzle-kit from devDependencies to dependencies.
2026-04-27 17:29:31 +02:00
djalim 378cbb0c06 style: format import success message and drop zone JSX
Check Deno code / Check Deno code (pull_request) Successful in 5s
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Failing after 1m7s
Apply consistent string concatenation in ImportNotes and UploadStudents.
Format JSX drop zone for better readability.
2026-04-27 17:11:46 +02:00
djalim d3de5c29e7 refactor: add migration, seed permissions, update permissions API
feat(notes): add XLSX import island and admin route

feat(upload): add drag‑and‑drop upload, template download, UI tweaks
2026-04-27 17:08:58 +02:00
djalim 733259e317 feat : fixed some page not being as described in the figma 2026-04-27 11:21:32 +02:00
djalim 56019ad372 fix: fixed test ci 2026-04-27 00:04:28 +02:00
djalim fcc9547a30 feat(dev): add compose files and dev-login bypass route
- compose.prod.yml: production stack with registry image, healthcheck,
  migration service
- compose.test.yml: local test stack with source mount and LOCAL=true
- routes/dev-login.ts: fake admin JWT login, only active when LOCAL=true
- routes/_middleware.ts: expose /dev-login as public route

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 23:01:59 +02:00
djalim 5ba8b8cb68 feat(ui): implement full UI layer for all modules
Add interactive island components and server partials for notes,
students, and admin modules, following the Figma prototype design.

- static/styles/ui.css: shared component library (buttons, tables,
  chips, cards, filters, tabs, form inputs)
- notes: NotesView (student grade view with UE cards, promo tabs,
  weighted averages), AdminConsultNotes, AdminUEs islands + partials
- students: ConsultStudents (list/filter/delete), AdminPromotions
  (CRUD) islands + partials
- admin: AdminModules, AdminUsers, AdminRoles islands + partials
- All partials use State type with unknown cast for session access

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 22:54:10 +02:00
djalim 34b7ac0231 docs: update CLAUDE.md to reflect completed API layer
Mark all implemented endpoints as , document the 3-level test
architecture, and clarify that UI pages are the next priority.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 22:29:10 +02:00
djalim 714486f43c chore: formated tests
Check Deno code / Check Deno code (pull_request) Successful in 5s
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Successful in 1m9s
Check Deno code / Check Deno code (push) Successful in 6s
Tests / Unit tests (push) Successful in 12s
Tests / Integration tests (push) Successful in 1m13s
2026-04-26 19:07:15 +02:00
djalim b0930b8da2 fix: correct handler bugs exposed by test suite
Check Deno code / Check Deno code (pull_request) Failing after 6s
Tests / Unit tests (pull_request) Successful in 13s
Tests / Integration tests (pull_request) Successful in 1m17s
- ajustements [numEtud]/[idUE]: fix .where() missing and() — PUT/DELETE
  were applying only numEtud condition, modifying all rows for a student
- modules/users/enseignements POST: add try/catch, return 500 on invalid JSON
- modules/[idModule] PUT: add try/catch + type check on nom (string required)
- modules POST: add .trim() check to reject whitespace-only id/nom
- users POST: add .trim() check to reject whitespace-only id/nom/prenom
- ues POST: add .trim() check to reject whitespace-only nom
- notes POST: add type check (typeof number) and bounds check (0 ≤ note ≤ 20)
- ue-modules POST: add coeff >= 0 validation

Update robustness tests to reflect fixed behavior (remove [BUG] labels,
replace assertRejects with status code assertions).
2026-04-26 19:01:53 +02:00
djalim 2f4d8db1bf test: add full test coverage for notes, ues, ue-modules, ajustements, enseignements, users
Check Deno code / Check Deno code (pull_request) Failing after 6s
Tests / Unit tests (pull_request) Successful in 13s
Tests / Integration tests (pull_request) Failing after 1m14s
- Unit tests (mock DB + API) for all missing endpoints
- Integration tests (Drizzle direct) for all missing entities
- E2E tests (handler + real DB) for all missing endpoints
- Robustness tests: invalid inputs, SQL injection, type errors, business rule violations
- Seed helpers: seedNotes, seedUeModules, seedEnseignements, seedAjustements
- Add test:coverage and test:coverage:html tasks to deno.json

Tests expose known handler bugs (marked [BUG] in test names):
- ajustements PUT/DELETE: .where() without and() modifies all rows for student
- Missing try/catch in modules, users, enseignements handlers
- Whitespace accepted as valid string values
- No type or business rule validation (note bounds, coeff >= 0)
2026-04-26 18:25:00 +02:00
djalim a3b55d0a1b fix: remove unused body variable in permissions e2e test
Check Deno code / Check Deno code (pull_request) Successful in 6s
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Successful in 1m19s
Check Deno code / Check Deno code (push) Successful in 6s
Tests / Unit tests (push) Successful in 11s
Tests / Integration tests (push) Successful in 1m7s
2026-04-26 13:34:43 +00:00
djalim 86080b8042 test(permissions): add unit and e2e tests for GET /permissions (#115)
Handler is static (no DB), tests verify the 9 known permissions are returned
with correct id/nom shapes.
2026-04-26 13:34:43 +00:00
110 changed files with 13067 additions and 412 deletions
+4
View File
@@ -0,0 +1,4 @@
node_modules
.git
coverage
.env
+83 -67
View File
@@ -18,8 +18,8 @@ role-based administration.
### Current Status
🚧 **In Progress** - Application is far from complete. The schema below is the
**final/definitive schema** that should guide all development.
🚧 **In Progress** - API layer largely complete, UI pages not yet built. The
schema below is the **final/definitive schema** that guides all development.
---
@@ -133,15 +133,11 @@ erDiagram
AJUSTEMENT }o--|| UE : "dans"
```
### Current Schema (Incomplete)
### Current Schema
The current Drizzle ORM schema in `/databases/schema.ts` only implements:
- `promotions`
- `students`
- `mobility`
**Migration needed**: Update schema to match the final ER diagram above.
The Drizzle ORM schema in `/databases/schema.ts` implements all tables: `roles`,
`permissions`, `rolePermissions`, `users`, `promotions`, `students`, `modules`,
`enseignements`, `ues`, `ueModules`, `notes`, `ajustements`, `mobility`.
---
@@ -186,71 +182,73 @@ The current Drizzle ORM schema in `/databases/schema.ts` only implements:
### API Endpoints
Legend: ✅ implemented & tested | 📋 not yet implemented
**Students API**
- 📋 GET `/students` (#7)
- 📋 POST `/students` (#8)
- 📋 POST `/students/import-csv` (#9)
- 📋 GET `/students/{numEtud}` (#10)
- 📋 PUT `/students/{numEtud}` (#11)
- 📋 DELETE `/students/{numEtud}` (#12)
- 📋 GET `/promotions` (#13)
- 📋 POST `/promotions` (#14)
- 📋 GET `/promotions/{idPromo}` (#15)
- 📋 PUT `/promotions/{idPromo}` (#16)
- 📋 DELETE `/promotions/{idPromo}` (#17)
- GET `/students` (#7)
- POST `/students` (#8)
- POST `/students/import-csv` (#9)
- GET `/students/{numEtud}` (#10)
- PUT `/students/{numEtud}` (#11)
- DELETE `/students/{numEtud}` (#12)
- GET `/promotions` (#13)
- POST `/promotions` (#14)
- GET `/promotions/{idPromo}` (#15)
- PUT `/promotions/{idPromo}` (#16)
- DELETE `/promotions/{idPromo}` (#17)
**Administration API - Modules & Enseignements**
- 📋 GET `/modules` (#23)
- 📋 POST `/modules` (#24)
- 📋 GET `/modules/{idModule}` (#25)
- 📋 PUT `/modules/{idModule}` (#26)
- 📋 DELETE `/modules/{idModule}` (#27)
- 📋 POST `/enseignements` (#29)
- 📋 GET `/enseignements/{idProf}/{idModule}/{idPromo}` (#30)
- 📋 DELETE `/enseignements/{idProf}/{idModule}/{idPromo}` (#31)
- GET `/modules` (#23)
- POST `/modules` (#24)
- GET `/modules/{idModule}` (#25)
- PUT `/modules/{idModule}` (#26)
- DELETE `/modules/{idModule}` (#27)
- POST `/enseignements` (#29)
- GET `/enseignements/{idProf}/{idModule}/{idPromo}` (#30)
- DELETE `/enseignements/{idProf}/{idModule}/{idPromo}` (#31)
**Notes API - UEs & UE-Modules**
- 📋 GET `/ues` (#32)
- 📋 POST `/ues` (#33)
- 📋 GET `/ues/{idUE}` (#34)
- 📋 PUT `/ues/{idUE}` (#35)
- 📋 DELETE `/ues/{idUE}` (#36)
- 📋 GET `/ue-modules` (#37)
- 📋 POST `/ue-modules` (#38)
- 📋 GET `/ue-modules/{idModule}/{idUE}/{idPromo}` (#39)
- 📋 PUT `/ue-modules/{idModule}/{idUE}/{idPromo}` (#40)
- 📋 DELETE `/ue-modules/{idModule}/{idUE}/{idPromo}` (#41)
- GET `/ues` (#32)
- POST `/ues` (#33)
- GET `/ues/{idUE}` (#34)
- PUT `/ues/{idUE}` (#35)
- DELETE `/ues/{idUE}` (#36)
- GET `/ue-modules` (#37)
- POST `/ue-modules` (#38)
- GET `/ue-modules/{idModule}/{idUE}/{idPromo}` (#39)
- PUT `/ue-modules/{idModule}/{idUE}/{idPromo}` (#40)
- DELETE `/ue-modules/{idModule}/{idUE}/{idPromo}` (#41)
**Notes API - Notes & Ajustements**
- 📋 GET `/notes` (#42)
- 📋 POST `/notes` (#43)
- GET `/notes` (#42)
- POST `/notes` (#43)
- 📋 POST `/notes/import-xlsx` (#44)
- 📋 GET `/notes/{numEtud}/{idModule}` (#45)
- 📋 PUT `/notes/{numEtud}/{idModule}` (#46)
- 📋 DELETE `/notes/{numEtud}/{idModule}` (#47)
- 📋 GET `/ajustements` (#48)
- 📋 POST `/ajustements` (#49)
- 📋 GET `/ajustements/{numEtud}/{idUE}` (#50)
- 📋 PUT `/ajustements/{numEtud}/{idUE}` (#51)
- 📋 DELETE `/ajustements/{numEtud}/{idUE}` (#52)
- GET `/notes/{numEtud}/{idModule}` (#45)
- PUT `/notes/{numEtud}/{idModule}` (#46)
- DELETE `/notes/{numEtud}/{idModule}` (#47)
- GET `/ajustements` (#48)
- POST `/ajustements` (#49)
- GET `/ajustements/{numEtud}/{idUE}` (#50)
- PUT `/ajustements/{numEtud}/{idUE}` (#51)
- DELETE `/ajustements/{numEtud}/{idUE}` (#52)
**Administration API - Users, Roles & Permissions**
- 📋 GET `/users` (#60)
- 📋 POST `/users` (#61)
- 📋 GET `/users/{id}` (#62)
- 📋 PUT `/users/{id}` (#63)
- 📋 DELETE `/users/{id}` (#64)
- 📋 GET `/roles` (#65)
- 📋 POST `/roles` (#66)
- 📋 GET `/roles/{idRole}` (#67)
- 📋 PUT `/roles/{idRole}` (#68)
- 📋 DELETE `/roles/{idRole}` (#69)
- 📋 GET `/permissions` (#70)
- GET `/users` (#60)
- POST `/users` (#61)
- GET `/users/{id}` (#62)
- PUT `/users/{id}` (#63)
- DELETE `/users/{id}` (#64)
- GET `/roles` (#65)
- POST `/roles` (#66)
- GET `/roles/{idRole}` (#67)
- PUT `/roles/{idRole}` (#68)
- DELETE `/roles/{idRole}` (#69)
- GET `/permissions` (#70)
---
@@ -298,10 +296,26 @@ deno task check
### Testing
- Write unit tests for business logic
- Integration tests for API endpoints
- E2E tests with HappyDOM for UI interactions
- Mock database with provided helpers
3-level architecture — all 149 tests pass:
- **Unit** (`tests/unit/`) — pure logic with mock DB + mock API, no real DB
- **Integration** (`tests/integration/`) — Drizzle ORM direct on real DB
- **E2E** (`tests/e2e/`) — Fresh handler + real DB (handler-level, not browser)
Helpers in `tests/helpers/`:
- `handler.ts` — builds fake Fresh contexts (`makeEmployeeContext`,
`makeJsonRequest`…)
- `db_integration.ts` — seed functions + `truncateAll()` for test isolation
- `db_mock.ts` / `api_mock.ts` — in-memory mocks for unit tests
```bash
deno task test # run all tests
deno task test:coverage # coverage report (terminal)
deno task test:coverage:html # coverage report (HTML → coverage/html/index.html)
nix run nixpkgs#act -- -j unit --no-cache-server # unit tests via GitHub Actions
nix run nixpkgs#act -- -j integration --no-cache-server # integration + e2e via GitHub Actions
```
---
@@ -327,12 +341,14 @@ deno task check
## 💡 Important Notes
1. **Current Limitation**: The database schema in `/databases/schema.ts` does
NOT match the final ER diagram. This is a priority migration task.
2. **Design System**: Follow the Figma prototype for all UI work.
1. **Only missing API**: `POST /notes/import-xlsx` (#44) — all other endpoints
are implemented.
2. **Next priority**: UI pages (none built yet) — follow the Figma prototype.
3. **Module Pattern**: Each module should follow the same pattern: routes, API
endpoints, components, and tests.
4. **Permissions**: All admin operations should respect the ROLE_PERMISSION
system.
5. **Fresh Conventions**: Routes use Fresh's file-based routing convention
(e.g., `routes/path/index.tsx`).
6. **Drizzle `.where()` pitfall**: Always wrap multiple conditions with `and()`.
`.where(eq(a), eq(b))` silently ignores the second argument.
+5
View File
@@ -1,7 +1,12 @@
FROM denoland/deno:alpine
RUN apk add --no-cache nodejs npm
WORKDIR /app
COPY package.json ./
RUN npm install --omit=dev
COPY . .
RUN deno cache main.ts --allow-import
RUN deno task build
+38
View File
@@ -0,0 +1,38 @@
services:
db:
image: postgres:17-alpine
restart: unless-stopped
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASS}
POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_DB: ${POSTGRES_DB:-polympr}
volumes:
- db_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres}"]
interval: 5s
timeout: 5s
retries: 10
migrate:
image: registry.docker.polytech.djalim.fr/polympr:latest
working_dir: /app
restart: "no"
command: ["node", "node_modules/.bin/drizzle-kit", "migrate"]
env_file: .env
depends_on:
db:
condition: service_healthy
app:
image: registry.docker.polytech.djalim.fr/polympr:latest
restart: unless-stopped
ports:
- "4430:443"
env_file: .env
depends_on:
migrate:
condition: service_completed_successfully
volumes:
db_data:
+56
View File
@@ -0,0 +1,56 @@
services:
db:
image: postgres:17-alpine
restart: unless-stopped
environment:
POSTGRES_PASSWORD: testpass
POSTGRES_USER: postgres
POSTGRES_DB: polympr_test
volumes:
- db_data_test:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 10
migrate:
image: node:alpine
working_dir: /app
restart: "no"
volumes:
- .:/app
command: node_modules/.bin/drizzle-kit migrate
environment:
POSTGRES_HOST: db
POSTGRES_PORT: "5432"
POSTGRES_USER: postgres
POSTGRES_PASS: testpass
POSTGRES_DB: polympr_test
depends_on:
db:
condition: service_healthy
app:
image: denoland/deno:alpine
working_dir: /app
volumes:
- .:/app
- deno_cache:/deno-dir
command: run -A --unstable-ffi main.ts
ports:
- "4430:443"
environment:
POSTGRES_HOST: db
POSTGRES_PORT: "5432"
POSTGRES_USER: postgres
POSTGRES_PASS: testpass
POSTGRES_DB: polympr_test
LOCAL: "true"
depends_on:
migrate:
condition: service_completed_successfully
volumes:
db_data_test:
deno_cache:
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Applied by postgres on first container startup via /docker-entrypoint-initdb.d.
# drizzle-kit migration files use "--> statement-breakpoint" markers which are
# not valid SQL — strip them before applying.
set -e
for f in /migrations/*.sql; do
echo "Applying $f..."
sed '/^-->/d' "$f" | psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB"
done
echo "All migrations applied."
@@ -0,0 +1,11 @@
--> statement-breakpoint
INSERT INTO "permissions" ("id", "nom") VALUES
('note_read', 'Consulter les notes des étudiants'),
('note_write', 'Saisir et modifier les notes'),
('student_read', 'Consulter la liste des étudiants'),
('student_write','Gérer les étudiants (ajout, modification, suppression)'),
('module_read', 'Consulter les modules et enseignements'),
('module_write', 'Gérer les modules et enseignements'),
('user_read', 'Consulter les utilisateurs et leurs rôles'),
('user_write', 'Gérer les utilisateurs et leurs rôles'),
('role_write', 'Gérer les rôles et leurs permissions');
@@ -0,0 +1,14 @@
-- Update permission names to French
-- This migration inserts or updates the permission labels used by the API.
--> statement-breakpoint
INSERT INTO "permissions" ("id", "nom") VALUES
('note_read', 'Consulter les notes des étudiants'),
('note_write', 'Saisir et modifier les notes'),
('student_read', 'Consulter la liste des étudiants'),
('student_write','Gérer les étudiants (ajout, modification, suppression)'),
('module_read', 'Consulter les modules et enseignements'),
('module_write', 'Gérer les modules et enseignements'),
('user_read', 'Consulter les utilisateurs et leurs rôles'),
('user_write', 'Gérer les utilisateurs et leurs rôles'),
('role_write', 'Gérer les rôles et leurs permissions')
ON CONFLICT ("id") DO UPDATE SET "nom" = EXCLUDED."nom";
@@ -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;
+21
View File
@@ -8,6 +8,27 @@
"when": 1777155028708,
"tag": "0000_square_jetstream",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1777155028709,
"tag": "0001_seed_permissions",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1777155028710,
"tag": "0002_update_permission_names",
"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),
idModule: text("idModule").notNull().references(() => modules.id),
note: doublePrecision("note").notNull(),
noteSession2: doublePrecision("noteSession2"),
}, (t) => ({
pk: primaryKey({ columns: [t.numEtud, t.idModule] }),
}));
@@ -83,6 +84,7 @@ export const ajustements = pgTable("ajustements", {
numEtud: integer("numEtud").notNull().references(() => students.numEtud),
idUE: integer("idUE").notNull().references(() => ues.id),
valeur: doublePrecision("valeur").notNull(),
malus: integer("malus").notNull().default(0),
}, (t) => ({
pk: primaryKey({ columns: [t.numEtud, t.idUE] }),
}));
+358
View File
@@ -0,0 +1,358 @@
-- ============================================================
-- PolyMPR — Test seed data
-- Source: JIN7SAA Semestre 7 Informatique FISE
-- ============================================================
-- ------------------------------------------------------------
-- 1. Promotion
-- ------------------------------------------------------------
INSERT INTO promotions ("idPromo", "annee") VALUES
('4AFISE', '2024')
ON CONFLICT ("idPromo") DO NOTHING;
-- ------------------------------------------------------------
-- 2. Students
-- ------------------------------------------------------------
INSERT INTO students ("numEtud", nom, prenom, "idPromo") VALUES
(24029625, 'MARTIN', 'Sophie', '4AFISE'),
(22005810, 'DUPONT', 'Lucas', '4AFISE'),
(24026283, 'BERNARD', 'Emma', '4AFISE'),
(24024101, 'THOMAS', 'Hugo', '4AFISE'),
(24021136, 'PETIT', 'Léa', '4AFISE'),
(24027947, 'ROBERT', 'Nathan', '4AFISE'),
(22001491, 'RICHARD', 'Alice', '4AFISE'),
(22023423, 'SIMON', 'Théo', '4AFISE'),
(21217292, 'LAURENT', 'Camille', '4AFISE'),
(24024550, 'LEFEBVRE', 'Maxime', '4AFISE'),
(22019957, 'MICHEL', 'Inès', '4AFISE'),
(22008222, 'GARCIA', 'Baptiste', '4AFISE'),
(22006557, 'DAVID', 'Manon', '4AFISE'),
(22019337, 'BERTRAND', 'Julien', '4AFISE'),
(22017498, 'ROUX', 'Chloé', '4AFISE'),
(22019070, 'VINCENT', 'Tom', '4AFISE'),
(21213966, 'FOURNIER', 'Jade', '4AFISE'),
(25027910, 'MOREL', 'Enzo', '4AFISE'),
(24025920, 'GIRARD', 'Anaïs', '4AFISE'),
(21212006, 'ANDRÉ', 'Romain', '4AFISE'),
(21230594, 'LEFÈVRE', 'Pauline', '4AFISE'),
(22010753, 'MERCIER', 'Axel', '4AFISE'),
(24031005, 'DUPUIS', 'Clara', '4AFISE'),
(24029523, 'LAMBERT', 'Florian', '4AFISE'),
(24025433, 'BONNET', 'Mathilde', '4AFISE'),
(23024748, 'FRANCOIS', 'Louis', '4AFISE'),
(24016406, 'MARTINEZ', 'Zoé', '4AFISE'),
(24028169, 'LEBLANC', 'Kévin', '4AFISE'),
(22017365, 'GARNIER', 'Julie', '4AFISE'),
(23026015, 'CHEVALIER', 'Antoine', '4AFISE')
ON CONFLICT ("numEtud") DO NOTHING;
-- ------------------------------------------------------------
-- 3. Role: Professeur
-- ------------------------------------------------------------
INSERT INTO roles (nom) VALUES ('Professeur')
ON CONFLICT DO NOTHING;
-- ------------------------------------------------------------
-- 4. Permissions du rôle Professeur
-- ------------------------------------------------------------
INSERT INTO role_permissions ("idRole", "idPermission")
SELECT r.id, p.id
FROM roles r, permissions p
WHERE r.nom = 'Professeur'
AND p.id IN ('note_read', 'note_write', 'student_read', 'module_read')
ON CONFLICT DO NOTHING;
-- ------------------------------------------------------------
-- 5. Professor users
-- ------------------------------------------------------------
INSERT INTO users (id, nom, prenom, "idRole")
SELECT prof.id, prof.nom, prof.prenom, r.id
FROM roles r,
(VALUES
('prof.jin701b', 'DUBOIS', 'Pierre'),
('prof.jin701c', 'MOREAU', 'Claire'),
('prof.jin710a', 'DURAND', 'François'),
('prof.jin702a', 'LEROY', 'Anne'),
('prof.jin702b', 'GIRARD', 'Michel'),
('prof.jin702c', 'MOREL', 'Patricia'),
('prof.jin703a', 'SIMON', 'Jacques'),
('prof.jin703b', 'LAURENT', 'Sylvie'),
('prof.jin703c', 'LEFEBVRE', 'René'),
('prof.jin712a', 'ROUSSEAU', 'Hélène'),
('prof.jin712b', 'BLANC', 'Philippe'),
('prof.jin712c', 'GUERIN', 'Stéphane'),
('prof.jtr701a', 'THOMAS', 'Sarah'),
('prof.jtr701d', 'ROBIN', 'Christine'),
('prof.jtr701e', 'DAVID', 'Bernard'),
('prof.jtr701f', 'FAURE', 'Daniel')
) AS prof(id, nom, prenom)
WHERE r.nom = 'Professeur'
ON CONFLICT (id) DO NOTHING;
-- ------------------------------------------------------------
-- 6. Modules
-- ------------------------------------------------------------
INSERT INTO modules (id, nom) VALUES
('JIN701B', 'Programmation distribuée'),
('JIN701C', 'Projet développement 1'),
('JIN710A', 'Virtualisation et Conteneurisation'),
('JIN702A', 'Probabilités'),
('JIN702B', 'Statistiques'),
('JIN702C', 'Optimisation'),
('JIN703A', 'Programmation graphique'),
('JIN703B', 'Analyse d''images'),
('JIN703C', 'Modélisation géométrique'),
('JIN712A', 'Apprentissage automatique'),
('JIN712B', 'Fouilles de données'),
('JIN712C', 'Base de données avancées'),
('JTR701A', 'Anglais'),
('JTR701D', 'Gestion commerciale et marketing'),
('JTR701E', 'Management de la qualité'),
('JTR701F', 'Management de Projet')
ON CONFLICT (id) DO NOTHING;
-- ------------------------------------------------------------
-- 7. UEs
-- ------------------------------------------------------------
INSERT INTO ues (nom) VALUES
('Conception et développement Avancés 1'),
('Mathématiques pour l''Informatique 2'),
('Introduction à la réalité mixte'),
('IA et Science des Données Avancées'),
('Langues et SHEJS 3')
ON CONFLICT DO NOTHING;
-- ------------------------------------------------------------
-- 8. UE-Module associations (coeff 1 for all)
-- ------------------------------------------------------------
INSERT INTO ue_modules ("idModule", "idUE", "idPromo", coeff)
SELECT m, u.id, '4AFISE', 1
FROM ues u,
(VALUES
('JIN701B', 'Conception et développement Avancés 1'),
('JIN701C', 'Conception et développement Avancés 1'),
('JIN710A', 'Conception et développement Avancés 1'),
('JIN702A', 'Mathématiques pour l''Informatique 2'),
('JIN702B', 'Mathématiques pour l''Informatique 2'),
('JIN702C', 'Mathématiques pour l''Informatique 2'),
('JIN703A', 'Introduction à la réalité mixte'),
('JIN703B', 'Introduction à la réalité mixte'),
('JIN703C', 'Introduction à la réalité mixte'),
('JIN712A', 'IA et Science des Données Avancées'),
('JIN712B', 'IA et Science des Données Avancées'),
('JIN712C', 'IA et Science des Données Avancées'),
('JTR701A', 'Langues et SHEJS 3'),
('JTR701D', 'Langues et SHEJS 3'),
('JTR701E', 'Langues et SHEJS 3'),
('JTR701F', 'Langues et SHEJS 3')
) AS mapping(m, ue_nom)
WHERE u.nom = mapping.ue_nom
ON CONFLICT DO NOTHING;
-- ------------------------------------------------------------
-- 9. Enseignements
-- ------------------------------------------------------------
INSERT INTO enseignements ("idProf", "idModule", "idPromo") VALUES
('prof.jin701b', 'JIN701B', '4AFISE'),
('prof.jin701c', 'JIN701C', '4AFISE'),
('prof.jin710a', 'JIN710A', '4AFISE'),
('prof.jin702a', 'JIN702A', '4AFISE'),
('prof.jin702b', 'JIN702B', '4AFISE'),
('prof.jin702c', 'JIN702C', '4AFISE'),
('prof.jin703a', 'JIN703A', '4AFISE'),
('prof.jin703b', 'JIN703B', '4AFISE'),
('prof.jin703c', 'JIN703C', '4AFISE'),
('prof.jin712a', 'JIN712A', '4AFISE'),
('prof.jin712b', 'JIN712B', '4AFISE'),
('prof.jin712c', 'JIN712C', '4AFISE'),
('prof.jtr701a', 'JTR701A', '4AFISE'),
('prof.jtr701d', 'JTR701D', '4AFISE'),
('prof.jtr701e', 'JTR701E', '4AFISE'),
('prof.jtr701f', 'JTR701F', '4AFISE')
ON CONFLICT DO NOTHING;
-- ------------------------------------------------------------
-- 10. Notes (ABI / #VALEUR! entries are skipped)
-- ------------------------------------------------------------
INSERT INTO notes ("numEtud", "idModule", note) VALUES
-- 24029625 MARTIN Sophie
(24029625,'JIN701B',14.00),(24029625,'JIN701C',13.50),(24029625,'JIN710A',15.00),
(24029625,'JIN702A',15.50),(24029625,'JIN702B',17.00),(24029625,'JIN702C',13.00),
(24029625,'JIN703A',15.00),(24029625,'JIN703B',14.00),(24029625,'JIN703C',8.44),
(24029625,'JIN712A',15.50),(24029625,'JIN712B',13.80),(24029625,'JIN712C',13.10),
(24029625,'JTR701A',16.10),(24029625,'JTR701D',11.00),(24029625,'JTR701E',14.21),(24029625,'JTR701F',15.48),
-- 22005810 DUPONT Lucas
(22005810,'JIN701B',10.50),(22005810,'JIN701C',14.00),(22005810,'JIN710A',14.00),
(22005810,'JIN702A',20.00),(22005810,'JIN702B',16.00),(22005810,'JIN702C',16.00),
(22005810,'JIN703A',15.00),(22005810,'JIN703B',13.00),(22005810,'JIN703C',7.50),
(22005810,'JIN712A',10.85),(22005810,'JIN712B',11.50),(22005810,'JIN712C',10.80),
(22005810,'JTR701A',12.10),(22005810,'JTR701D',10.00),(22005810,'JTR701E',11.85),(22005810,'JTR701F',12.47),
-- 24026283 BERNARD Emma
(24026283,'JIN701B',11.50),(24026283,'JIN701C',16.50),(24026283,'JIN710A',13.00),
(24026283,'JIN702A',17.00),(24026283,'JIN702B',15.00),(24026283,'JIN702C',14.00),
(24026283,'JIN703A',14.00),(24026283,'JIN703B',12.00),(24026283,'JIN703C',11.25),
(24026283,'JIN712A',13.25),(24026283,'JIN712B',13.00),(24026283,'JIN712C',15.70),
(24026283,'JTR701A',16.10),(24026283,'JTR701D',14.00),(24026283,'JTR701E',15.50),(24026283,'JTR701F',13.91),
-- 24024101 THOMAS Hugo
(24024101,'JIN701B',10.50),(24024101,'JIN701C',13.50),(24024101,'JIN710A',12.00),
(24024101,'JIN702A',13.00),(24024101,'JIN702B',11.00),(24024101,'JIN702C',14.00),
(24024101,'JIN703A',17.00),(24024101,'JIN703B',12.00),(24024101,'JIN703C',11.88),
(24024101,'JIN712A',6.50),(24024101,'JIN712B',18.30),(24024101,'JIN712C',13.90),
(24024101,'JTR701A',17.50),(24024101,'JTR701D',17.50),(24024101,'JTR701E',16.09),(24024101,'JTR701F',15.04),
-- 24021136 PETIT Léa
(24021136,'JIN701B',15.00),(24021136,'JIN701C',15.00),(24021136,'JIN710A',12.00),
(24021136,'JIN702A',16.50),(24021136,'JIN702B',17.00),(24021136,'JIN702C',10.00),
(24021136,'JIN703A',14.00),(24021136,'JIN703B',13.00),(24021136,'JIN703C',9.38),
(24021136,'JIN712A',8.50),(24021136,'JIN712B',13.90),(24021136,'JIN712C',15.20),
(24021136,'JTR701A',18.20),(24021136,'JTR701D',15.00),(24021136,'JTR701E',12.83),(24021136,'JTR701F',14.06),
-- 24027947 ROBERT Nathan
(24027947,'JIN701B',7.50),(24027947,'JIN701C',15.00),(24027947,'JIN710A',13.50),
(24027947,'JIN702A',20.00),(24027947,'JIN702B',17.00),(24027947,'JIN702C',14.00),
(24027947,'JIN703A',13.00),(24027947,'JIN703B',10.00),(24027947,'JIN703C',8.75),
(24027947,'JIN712A',7.50),(24027947,'JIN712B',13.90),(24027947,'JIN712C',10.00),
(24027947,'JTR701A',17.30),(24027947,'JTR701D',16.00),(24027947,'JTR701E',14.71),(24027947,'JTR701F',11.61),
-- 22001491 RICHARD Alice
(22001491,'JIN701B',17.50),(22001491,'JIN701C',13.50),(22001491,'JIN710A',15.00),
(22001491,'JIN702A',20.00),(22001491,'JIN702B',15.00),(22001491,'JIN702C',14.00),
(22001491,'JIN703A',15.00),(22001491,'JIN703B',15.00),(22001491,'JIN703C',15.94),
(22001491,'JIN712A',5.50),(22001491,'JIN712B',18.10),(22001491,'JIN712C',15.75),
(22001491,'JTR701A',17.70),(22001491,'JTR701D',11.50),(22001491,'JTR701E',14.35),(22001491,'JTR701F',15.61),
-- 22023423 SIMON Théo
(22023423,'JIN701B',13.00),(22023423,'JIN701C',16.00),(22023423,'JIN710A',13.00),
(22023423,'JIN702A',20.00),(22023423,'JIN702B',18.00),(22023423,'JIN702C',14.50),
(22023423,'JIN703A',13.00),(22023423,'JIN703B',11.00),(22023423,'JIN703C',14.69),
(22023423,'JIN712A',7.00),(22023423,'JIN712B',13.70),(22023423,'JIN712C',14.95),
(22023423,'JTR701A',18.10),(22023423,'JTR701D',18.00),(22023423,'JTR701E',14.82),(22023423,'JTR701F',14.36),
-- 21217292 LAURENT Camille
(21217292,'JIN701B',16.00),(21217292,'JIN701C',13.50),(21217292,'JIN710A',15.00),
(21217292,'JIN702A',5.00),(21217292,'JIN702B',8.00),(21217292,'JIN702C',19.00),
(21217292,'JIN703A',14.00),(21217292,'JIN703B',14.00),(21217292,'JIN703C',11.88),
(21217292,'JIN712A',15.00),(21217292,'JIN712B',16.10),(21217292,'JIN712C',12.95),
(21217292,'JTR701A',18.10),(21217292,'JTR701D',14.50),(21217292,'JTR701E',12.57),(21217292,'JTR701F',13.61),
-- 24024550 LEFEBVRE Maxime
(24024550,'JIN701B',16.00),(24024550,'JIN701C',13.50),(24024550,'JIN710A',13.00),
(24024550,'JIN702A',20.00),(24024550,'JIN702B',9.00),(24024550,'JIN702C',15.00),
(24024550,'JIN703A',17.00),(24024550,'JIN703B',12.00),(24024550,'JIN703C',10.31),
(24024550,'JIN712A',16.50),(24024550,'JIN712B',12.40),(24024550,'JIN712C',16.60),
(24024550,'JTR701A',16.80),(24024550,'JTR701D',18.00),(24024550,'JTR701E',14.70),(24024550,'JTR701F',13.41),
-- 22019957 MICHEL Inès (JIN703C=ABI skipped)
(22019957,'JIN701B',10.50),(22019957,'JIN701C',14.00),(22019957,'JIN710A',12.00),
(22019957,'JIN702A',14.00),(22019957,'JIN702B',18.00),(22019957,'JIN702C',11.50),
(22019957,'JIN703A',15.00),(22019957,'JIN703B',10.00),
(22019957,'JIN712A',4.00),(22019957,'JIN712B',15.90),(22019957,'JIN712C',10.00),
(22019957,'JTR701A',15.80),(22019957,'JTR701D',18.00),(22019957,'JTR701E',14.77),(22019957,'JTR701F',14.11),
-- 22008222 GARCIA Baptiste
(22008222,'JIN701B',16.00),(22008222,'JIN701C',14.00),(22008222,'JIN710A',18.00),
(22008222,'JIN702A',18.00),(22008222,'JIN702B',17.00),(22008222,'JIN702C',14.50),
(22008222,'JIN703A',15.00),(22008222,'JIN703B',13.00),(22008222,'JIN703C',15.31),
(22008222,'JIN712A',15.50),(22008222,'JIN712B',17.00),(22008222,'JIN712C',16.40),
(22008222,'JTR701A',17.90),(22008222,'JTR701D',16.00),(22008222,'JTR701E',13.62),(22008222,'JTR701F',13.04),
-- 22006557 DAVID Manon
(22006557,'JIN701B',13.50),(22006557,'JIN701C',17.50),(22006557,'JIN710A',14.00),
(22006557,'JIN702A',20.00),(22006557,'JIN702B',18.00),(22006557,'JIN702C',10.50),
(22006557,'JIN703A',15.00),(22006557,'JIN703B',15.00),(22006557,'JIN703C',9.38),
(22006557,'JIN712A',17.00),(22006557,'JIN712B',14.40),(22006557,'JIN712C',16.50),
(22006557,'JTR701A',13.80),(22006557,'JTR701D',17.00),(22006557,'JTR701E',15.77),(22006557,'JTR701F',14.75),
-- 22019337 BERTRAND Julien
(22019337,'JIN701B',11.00),(22019337,'JIN701C',14.00),(22019337,'JIN710A',13.50),
(22019337,'JIN702A',15.00),(22019337,'JIN702B',17.00),(22019337,'JIN702C',11.50),
(22019337,'JIN703A',15.00),(22019337,'JIN703B',13.00),(22019337,'JIN703C',10.00),
(22019337,'JIN712A',2.00),(22019337,'JIN712B',12.70),(22019337,'JIN712C',14.05),
(22019337,'JTR701A',14.20),(22019337,'JTR701D',10.00),(22019337,'JTR701E',10.84),(22019337,'JTR701F',14.23),
-- 22017498 ROUX Chloé
(22017498,'JIN701B',8.00),(22017498,'JIN701C',16.00),(22017498,'JIN710A',12.00),
(22017498,'JIN702A',20.00),(22017498,'JIN702B',18.00),(22017498,'JIN702C',10.00),
(22017498,'JIN703A',15.00),(22017498,'JIN703B',14.00),(22017498,'JIN703C',9.06),
(22017498,'JIN712A',16.00),(22017498,'JIN712B',10.60),(22017498,'JIN712C',16.00),
(22017498,'JTR701A',15.80),(22017498,'JTR701D',13.00),(22017498,'JTR701E',14.19),(22017498,'JTR701F',13.61),
-- 22019070 VINCENT Tom
(22019070,'JIN701B',18.00),(22019070,'JIN701C',15.00),(22019070,'JIN710A',13.50),
(22019070,'JIN702A',14.00),(22019070,'JIN702B',13.00),(22019070,'JIN702C',17.50),
(22019070,'JIN703A',16.00),(22019070,'JIN703B',14.00),(22019070,'JIN703C',16.88),
(22019070,'JIN712A',18.50),(22019070,'JIN712B',16.20),(22019070,'JIN712C',12.65),
(22019070,'JTR701A',18.80),(22019070,'JTR701D',16.50),(22019070,'JTR701E',11.63),(22019070,'JTR701F',15.11),
-- 21213966 FOURNIER Jade (JTR701D=ABI skipped)
(21213966,'JIN701B',7.50),(21213966,'JIN701C',14.00),(21213966,'JIN710A',14.00),
(21213966,'JIN702A',17.00),(21213966,'JIN702B',17.00),(21213966,'JIN702C',12.50),
(21213966,'JIN703A',15.00),(21213966,'JIN703B',13.00),(21213966,'JIN703C',3.75),
(21213966,'JIN712A',4.50),(21213966,'JIN712B',12.50),(21213966,'JIN712C',13.75),
(21213966,'JTR701A',11.00),(21213966,'JTR701E',15.99),(21213966,'JTR701F',11.61),
-- 25027910 MOREL Enzo
(25027910,'JIN701B',7.50),(25027910,'JIN701C',15.00),(25027910,'JIN710A',13.00),
(25027910,'JIN702A',3.00),(25027910,'JIN702B',4.00),(25027910,'JIN702C',10.50),
(25027910,'JIN703A',12.00),(25027910,'JIN703B',12.00),(25027910,'JIN703C',6.25),
(25027910,'JIN712A',7.85),(25027910,'JIN712B',10.20),(25027910,'JIN712C',13.00),
(25027910,'JTR701A',14.30),(25027910,'JTR701D',12.00),(25027910,'JTR701E',13.36),(25027910,'JTR701F',14.86),
-- 24025920 GIRARD Anaïs (JIN712C=ABI, JTR701D=ABI skipped)
(24025920,'JIN701B',10.50),(24025920,'JIN701C',12.00),(24025920,'JIN710A',13.00),
(24025920,'JIN702A',19.00),(24025920,'JIN702B',19.00),(24025920,'JIN702C',7.50),
(24025920,'JIN703A',11.00),(24025920,'JIN703B',10.00),(24025920,'JIN703C',7.19),
(24025920,'JIN712A',8.25),(24025920,'JIN712B',10.20),
(24025920,'JTR701A',10.60),(24025920,'JTR701E',4.29),(24025920,'JTR701F',8.73),
-- 21212006 ANDRÉ Romain
(21212006,'JIN701B',12.50),(21212006,'JIN701C',17.50),(21212006,'JIN710A',17.00),
(21212006,'JIN702A',12.00),(21212006,'JIN702B',9.00),(21212006,'JIN702C',10.00),
(21212006,'JIN703A',15.00),(21212006,'JIN703B',14.00),(21212006,'JIN703C',13.44),
(21212006,'JIN712A',16.50),(21212006,'JIN712B',12.00),(21212006,'JIN712C',16.40),
(21212006,'JTR701A',18.30),(21212006,'JTR701D',16.00),(21212006,'JTR701E',10.85),(21212006,'JTR701F',13.29),
-- 21230594 LEFÈVRE Pauline
(21230594,'JIN701B',18.00),(21230594,'JIN701C',16.50),(21230594,'JIN710A',11.00),
(21230594,'JIN702A',5.00),(21230594,'JIN702B',13.00),(21230594,'JIN702C',17.50),
(21230594,'JIN703A',11.00),(21230594,'JIN703B',12.00),(21230594,'JIN703C',18.44),
(21230594,'JIN712A',16.00),(21230594,'JIN712B',15.90),(21230594,'JIN712C',11.60),
(21230594,'JTR701A',18.80),(21230594,'JTR701D',16.00),(21230594,'JTR701E',14.61),(21230594,'JTR701F',14.61),
-- 22010753 MERCIER Axel
(22010753,'JIN701B',9.00),(22010753,'JIN701C',14.00),(22010753,'JIN710A',14.00),
(22010753,'JIN702A',17.00),(22010753,'JIN702B',15.00),(22010753,'JIN702C',13.00),
(22010753,'JIN703A',13.00),(22010753,'JIN703B',13.00),(22010753,'JIN703C',7.50),
(22010753,'JIN712A',5.50),(22010753,'JIN712B',15.00),(22010753,'JIN712C',15.15),
(22010753,'JTR701A',13.40),(22010753,'JTR701D',15.50),(22010753,'JTR701E',15.80),(22010753,'JTR701F',13.11),
-- 24031005 DUPUIS Clara
(24031005,'JIN701B',8.00),(24031005,'JIN701C',15.00),(24031005,'JIN710A',13.00),
(24031005,'JIN702A',16.00),(24031005,'JIN702B',19.00),(24031005,'JIN702C',9.50),
(24031005,'JIN703A',15.00),(24031005,'JIN703B',13.00),(24031005,'JIN703C',9.06),
(24031005,'JIN712A',5.00),(24031005,'JIN712B',10.90),(24031005,'JIN712C',14.35),
(24031005,'JTR701A',15.00),(24031005,'JTR701D',12.00),(24031005,'JTR701E',10.78),(24031005,'JTR701F',13.36),
-- 24029523 LAMBERT Florian
(24029523,'JIN701B',13.00),(24029523,'JIN701C',16.50),(24029523,'JIN710A',12.50),
(24029523,'JIN702A',14.00),(24029523,'JIN702B',6.00),(24029523,'JIN702C',10.50),
(24029523,'JIN703A',14.00),(24029523,'JIN703B',11.00),(24029523,'JIN703C',14.38),
(24029523,'JIN712A',11.50),(24029523,'JIN712B',9.50),(24029523,'JIN712C',15.60),
(24029523,'JTR701A',16.30),(24029523,'JTR701D',18.00),(24029523,'JTR701E',10.99),(24029523,'JTR701F',12.23),
-- 24025433 BONNET Mathilde
(24025433,'JIN701B',9.50),(24025433,'JIN701C',10.00),(24025433,'JIN710A',11.00),
(24025433,'JIN702A',8.00),(24025433,'JIN702B',6.00),(24025433,'JIN702C',20.00),
(24025433,'JIN703A',2.50),(24025433,'JIN703B',12.00),(24025433,'JIN703C',18.44),
(24025433,'JIN712A',13.50),(24025433,'JIN712B',14.20),(24025433,'JIN712C',5.25),
(24025433,'JTR701A',16.00),(24025433,'JTR701D',17.50),(24025433,'JTR701E',11.38),(24025433,'JTR701F',13.11),
-- 23024748 FRANCOIS Louis
(23024748,'JIN701B',11.50),(23024748,'JIN701C',11.00),(23024748,'JIN710A',15.00),
(23024748,'JIN702A',18.00),(23024748,'JIN702B',15.00),(23024748,'JIN702C',10.00),
(23024748,'JIN703A',15.00),(23024748,'JIN703B',13.00),(23024748,'JIN703C',7.50),
(23024748,'JIN712A',4.00),(23024748,'JIN712B',10.90),(23024748,'JIN712C',10.00),
(23024748,'JTR701A',14.30),(23024748,'JTR701D',12.00),(23024748,'JTR701E',14.42),(23024748,'JTR701F',12.61),
-- 24016406 MARTINEZ Zoé
(24016406,'JIN701B',11.50),(24016406,'JIN701C',16.50),(24016406,'JIN710A',12.00),
(24016406,'JIN702A',19.00),(24016406,'JIN702B',15.00),(24016406,'JIN702C',7.00),
(24016406,'JIN703A',15.00),(24016406,'JIN703B',14.00),(24016406,'JIN703C',11.56),
(24016406,'JIN712A',14.00),(24016406,'JIN712B',12.20),(24016406,'JIN712C',16.20),
(24016406,'JTR701A',18.50),(24016406,'JTR701D',13.00),(24016406,'JTR701E',15.01),(24016406,'JTR701F',12.81),
-- 24028169 LEBLANC Kévin
(24028169,'JIN701B',9.00),(24028169,'JIN701C',11.00),(24028169,'JIN710A',17.00),
(24028169,'JIN702A',15.50),(24028169,'JIN702B',13.00),(24028169,'JIN702C',14.50),
(24028169,'JIN703A',14.00),(24028169,'JIN703B',14.00),(24028169,'JIN703C',9.06),
(24028169,'JIN712A',7.00),(24028169,'JIN712B',15.10),(24028169,'JIN712C',13.30),
(24028169,'JTR701A',14.80),(24028169,'JTR701D',17.50),(24028169,'JTR701E',10.99),(24028169,'JTR701F',9.23),
-- 22017365 GARNIER Julie
(22017365,'JIN701B',15.50),(22017365,'JIN701C',17.50),(22017365,'JIN710A',15.00),
(22017365,'JIN702A',13.50),(22017365,'JIN702B',17.00),(22017365,'JIN702C',19.00),
(22017365,'JIN703A',15.00),(22017365,'JIN703B',14.00),(22017365,'JIN703C',17.50),
(22017365,'JIN712A',17.50),(22017365,'JIN712B',14.40),(22017365,'JIN712C',16.70),
(22017365,'JTR701A',17.50),(22017365,'JTR701D',15.00),(22017365,'JTR701E',15.35),(22017365,'JTR701F',15.61),
-- 23026015 CHEVALIER Antoine
(23026015,'JIN701B',9.00),(23026015,'JIN701C',11.00),(23026015,'JIN710A',15.00),
(23026015,'JIN702A',20.00),(23026015,'JIN702B',18.00),(23026015,'JIN702C',13.50),
(23026015,'JIN703A',14.00),(23026015,'JIN703B',12.00),(23026015,'JIN703C',11.56),
(23026015,'JIN712A',7.00),(23026015,'JIN712B',16.50),(23026015,'JIN712C',11.40),
(23026015,'JTR701A',12.30),(23026015,'JTR701D',11.00),(23026015,'JTR701E',10.67),(23026015,'JTR701F',12.40)
ON CONFLICT DO NOTHING;
+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>
);
}
+1
View File
@@ -19,6 +19,7 @@ export interface AppProperties {
icon: string;
pages: Record<string, string>;
adminOnly: string[];
studentOnly?: string[];
hint: string;
}
+2
View File
@@ -14,6 +14,8 @@
"test:unit": "deno test -A --no-check tests/unit/",
"test:integration": "deno test -A --no-check tests/integration/",
"test:e2e": "deno test -A --no-check tests/e2e/",
"test:coverage": "deno test -A --no-check --coverage=coverage tests/ && deno coverage coverage --exclude=tests/",
"test:coverage:html": "deno test -A --no-check --coverage=coverage tests/ && deno coverage coverage --exclude=tests/ --html",
"migrate": "node_modules/.bin/drizzle-kit migrate"
},
"lint": {
+142
View File
@@ -4,16 +4,55 @@
import * as $_apps_layout from "./routes/(apps)/_layout.tsx";
import * as $_apps_middleware from "./routes/(apps)/_middleware.ts";
import * as $_apps_admin_api_enseignements from "./routes/(apps)/admin/api/enseignements.ts";
import * as $_apps_admin_api_enseignements_idProf_idModule_idPromo_ from "./routes/(apps)/admin/api/enseignements/[idProf]/[idModule]/[idPromo].ts";
import * as $_apps_admin_api_example from "./routes/(apps)/admin/api/example.ts";
import * as $_apps_admin_api_modules from "./routes/(apps)/admin/api/modules.ts";
import * as $_apps_admin_api_modules_idModule_ from "./routes/(apps)/admin/api/modules/[idModule].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_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_id_ from "./routes/(apps)/admin/api/users/[id].ts";
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_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_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_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_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_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_index from "./routes/(apps)/mobility/index.tsx";
import * as $_apps_mobility_partials_admin_edit_mobility from "./routes/(apps)/mobility/partials/(admin)/edit_mobility.tsx";
import * as $_apps_mobility_partials_index from "./routes/(apps)/mobility/partials/index.tsx";
import * as $_apps_mobility_partials_overview from "./routes/(apps)/mobility/partials/overview.tsx";
import * as $_apps_notes_api_ajustements from "./routes/(apps)/notes/api/ajustements.ts";
import * as $_apps_notes_api_ajustements_numEtud_idUE_ from "./routes/(apps)/notes/api/ajustements/[numEtud]/[idUE].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_import_xlsx from "./routes/(apps)/notes/api/notes/import-xlsx.ts";
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_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_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_recap_numEtud_ from "./routes/(apps)/notes/recap/[numEtud].tsx";
import * as $_apps_students_api_promotions from "./routes/(apps)/students/api/promotions.ts";
import * as $_apps_students_api_promotions_idPromo_ from "./routes/(apps)/students/api/promotions/[idPromo].ts";
import * as $_apps_students_api_students from "./routes/(apps)/students/api/students.ts";
import * as $_apps_students_api_students_numEtud_ from "./routes/(apps)/students/api/students/[numEtud].ts";
import * as $_apps_students_api_students_import_csv from "./routes/(apps)/students/api/students/import-csv.ts";
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_partials_admin_consult from "./routes/(apps)/students/partials/(admin)/consult.tsx";
import * as $_apps_students_partials_admin_upload from "./routes/(apps)/students/partials/(admin)/upload.tsx";
@@ -24,14 +63,29 @@ import * as $_app from "./routes/_app.tsx";
import * as $_middleware from "./routes/_middleware.ts";
import * as $about from "./routes/about.tsx";
import * as $apps from "./routes/apps.tsx";
import * as $dev_login from "./routes/dev-login.ts";
import * as $index from "./routes/index.tsx";
import * as $login from "./routes/login.tsx";
import * as $logout from "./routes/logout.tsx";
import * as $_islands_AppNavigator from "./routes/(_islands)/AppNavigator.tsx";
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_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_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_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_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_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_EditMobility from "./routes/(apps)/mobility/(_islands)/EditMobility.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_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_NotesView from "./routes/(apps)/notes/(_islands)/NotesView.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_UploadStudents from "./routes/(apps)/students/(_islands)/UploadStudents.tsx";
@@ -41,6 +95,42 @@ const manifest = {
routes: {
"./routes/(apps)/_layout.tsx": $_apps_layout,
"./routes/(apps)/_middleware.ts": $_apps_middleware,
"./routes/(apps)/admin/api/enseignements.ts":
$_apps_admin_api_enseignements,
"./routes/(apps)/admin/api/enseignements/[idProf]/[idModule]/[idPromo].ts":
$_apps_admin_api_enseignements_idProf_idModule_idPromo_,
"./routes/(apps)/admin/api/example.ts": $_apps_admin_api_example,
"./routes/(apps)/admin/api/modules.ts": $_apps_admin_api_modules,
"./routes/(apps)/admin/api/modules/[idModule].ts":
$_apps_admin_api_modules_idModule_,
"./routes/(apps)/admin/api/permissions.ts": $_apps_admin_api_permissions,
"./routes/(apps)/admin/api/roles.ts": $_apps_admin_api_roles,
"./routes/(apps)/admin/api/roles/[idRole].ts":
$_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/[id].ts": $_apps_admin_api_users_id_,
"./routes/(apps)/admin/index.tsx": $_apps_admin_index,
"./routes/(apps)/admin/modules/[idModule].tsx":
$_apps_admin_modules_idModule_,
"./routes/(apps)/admin/partials/enseignements.tsx":
$_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/modules.tsx": $_apps_admin_partials_modules,
"./routes/(apps)/admin/partials/permissions.tsx":
$_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/ues.tsx": $_apps_admin_partials_ues,
"./routes/(apps)/admin/partials/users.tsx": $_apps_admin_partials_users,
"./routes/(apps)/admin/users/[id].tsx": $_apps_admin_users_id_,
"./routes/(apps)/mobility/api/insert_mobility.ts":
$_apps_mobility_api_insert_mobility,
"./routes/(apps)/mobility/index.tsx": $_apps_mobility_index,
@@ -50,12 +140,35 @@ const manifest = {
$_apps_mobility_partials_index,
"./routes/(apps)/mobility/partials/overview.tsx":
$_apps_mobility_partials_overview,
"./routes/(apps)/notes/api/ajustements.ts": $_apps_notes_api_ajustements,
"./routes/(apps)/notes/api/ajustements/[numEtud]/[idUE].ts":
$_apps_notes_api_ajustements_numEtud_idUE_,
"./routes/(apps)/notes/api/notes.ts": $_apps_notes_api_notes,
"./routes/(apps)/notes/api/notes/[numEtud]/[idModule].ts":
$_apps_notes_api_notes_numEtud_idModule_,
"./routes/(apps)/notes/api/notes/import-xlsx.ts":
$_apps_notes_api_notes_import_xlsx,
"./routes/(apps)/notes/edition/[numEtud].tsx":
$_apps_notes_edition_numEtud_,
"./routes/(apps)/notes/index.tsx": $_apps_notes_index,
"./routes/(apps)/notes/partials/(admin)/courses.tsx":
$_apps_notes_partials_admin_courses,
"./routes/(apps)/notes/partials/(admin)/import.tsx":
$_apps_notes_partials_admin_import,
"./routes/(apps)/notes/partials/index.tsx": $_apps_notes_partials_index,
"./routes/(apps)/notes/partials/notes.tsx": $_apps_notes_partials_notes,
"./routes/(apps)/notes/recap/[numEtud].tsx": $_apps_notes_recap_numEtud_,
"./routes/(apps)/students/api/promotions.ts":
$_apps_students_api_promotions,
"./routes/(apps)/students/api/promotions/[idPromo].ts":
$_apps_students_api_promotions_idPromo_,
"./routes/(apps)/students/api/students.ts": $_apps_students_api_students,
"./routes/(apps)/students/api/students/[numEtud].ts":
$_apps_students_api_students_numEtud_,
"./routes/(apps)/students/api/students/import-csv.ts":
$_apps_students_api_students_import_csv,
"./routes/(apps)/students/edit/[numEtud].tsx":
$_apps_students_edit_numEtud_,
"./routes/(apps)/students/index.tsx": $_apps_students_index,
"./routes/(apps)/students/partials/(admin)/consult.tsx":
$_apps_students_partials_admin_consult,
@@ -69,6 +182,7 @@ const manifest = {
"./routes/_middleware.ts": $_middleware,
"./routes/about.tsx": $about,
"./routes/apps.tsx": $apps,
"./routes/dev-login.ts": $dev_login,
"./routes/index.tsx": $index,
"./routes/login.tsx": $login,
"./routes/logout.tsx": $logout,
@@ -76,12 +190,40 @@ const manifest = {
islands: {
"./routes/(_islands)/AppNavigator.tsx": $_islands_AppNavigator,
"./routes/(_islands)/Navbar.tsx": $_islands_Navbar,
"./routes/(apps)/admin/(_islands)/AdminEnseignements.tsx":
$_apps_admin_islands_AdminEnseignements,
"./routes/(apps)/admin/(_islands)/AdminModules.tsx":
$_apps_admin_islands_AdminModules,
"./routes/(apps)/admin/(_islands)/AdminPermissions.tsx":
$_apps_admin_islands_AdminPermissions,
"./routes/(apps)/admin/(_islands)/AdminPromotions.tsx":
$_apps_admin_islands_AdminPromotions,
"./routes/(apps)/admin/(_islands)/AdminRoles.tsx":
$_apps_admin_islands_AdminRoles,
"./routes/(apps)/admin/(_islands)/AdminUEs.tsx":
$_apps_admin_islands_AdminUEs,
"./routes/(apps)/admin/(_islands)/AdminUsers.tsx":
$_apps_admin_islands_AdminUsers,
"./routes/(apps)/admin/(_islands)/EditModule.tsx":
$_apps_admin_islands_EditModule,
"./routes/(apps)/admin/(_islands)/EditUser.tsx":
$_apps_admin_islands_EditUser,
"./routes/(apps)/admin/(_islands)/ImportMaquette.tsx":
$_apps_admin_islands_ImportMaquette,
"./routes/(apps)/mobility/(_islands)/ConsultMobility.tsx":
$_apps_mobility_islands_ConsultMobility,
"./routes/(apps)/mobility/(_islands)/EditMobility.tsx":
$_apps_mobility_islands_EditMobility,
"./routes/(apps)/mobility/(_islands)/ImportFile.tsx":
$_apps_mobility_islands_ImportFile,
"./routes/(apps)/notes/(_islands)/AdminConsultNotes.tsx":
$_apps_notes_islands_AdminConsultNotes,
"./routes/(apps)/notes/(_islands)/ImportNotes.tsx":
$_apps_notes_islands_ImportNotes,
"./routes/(apps)/notes/(_islands)/NoteRecap.tsx":
$_apps_notes_islands_NoteRecap,
"./routes/(apps)/notes/(_islands)/NotesView.tsx":
$_apps_notes_islands_NotesView,
"./routes/(apps)/students/(_islands)/ConsultStudents.tsx":
$_apps_students_islands_ConsultStudents,
"./routes/(apps)/students/(_islands)/EditStudents.tsx":
+1 -1
View File
@@ -1,12 +1,12 @@
{
"dependencies": {
"dotenv": "^17.4.0",
"drizzle-kit": "^0.31.10",
"drizzle-orm": "^0.45.2",
"pg": "^8.20.0"
},
"devDependencies": {
"@types/pg": "^8.20.0",
"drizzle-kit": "^0.31.10",
"tsx": "^4.21.0"
}
}
+14 -5
View File
@@ -21,14 +21,23 @@ export const handler: MiddlewareHandler<AuthenticatedState>[] = [
`./${currentApp}/(_props)/props.ts`
)).default;
context.state.availablePages = properties.pages;
if (
context.state.session.eduPersonPrimaryAffiliation == "student" &&
Deno.env.get("LOCAL") != "true"
) {
context.state.availablePages = { ...properties.pages };
const isStudent =
context.state.session.eduPersonPrimaryAffiliation === "student";
const isLocal = Deno.env.get("LOCAL") === "true";
if (isStudent) {
// Students only see studentOnly pages (+ non-restricted pages)
properties.adminOnly.forEach((page) =>
delete context.state.availablePages[page]
);
} else if (isLocal) {
// In local mode, employees see all pages (admin + student)
} else {
// In prod, employees don't see studentOnly pages
properties.studentOnly?.forEach((page) =>
delete context.state.availablePages[page]
);
}
return await context.next();
@@ -0,0 +1,331 @@
import { useEffect, useState } from "preact/hooks";
type Enseignement = { idProf: string; idModule: string; idPromo: string };
type Module = { id: string; nom: string };
type Promo = { id: string; annee: string };
export default function AdminEnseignements() {
const [enseignements, setEnseignements] = useState<Enseignement[]>([]);
const [modules, setModules] = useState<Module[]>([]);
const [promos, setPromos] = useState<Promo[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Filters
const [filterPromo, setFilterPromo] = useState("");
const [filterModule, setFilterModule] = useState("");
const [filterEnseignant, setFilterEnseignant] = useState("");
// Add form
const [showAdd, setShowAdd] = useState(false);
const [addPromo, setAddPromo] = useState("");
const [addModule, setAddModule] = useState("");
const [addProf, setAddProf] = useState("");
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
async function load() {
try {
const [eRes, mRes, pRes] = await Promise.all([
fetch("/admin/api/enseignements"),
fetch("/admin/api/modules"),
fetch("/students/api/promotions"),
]);
if (!eRes.ok) throw new Error("Impossible de charger les enseignements");
setEnseignements(await eRes.json());
if (mRes.ok) setModules(await mRes.json());
if (pRes.ok) setPromos(await pRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, []);
async function deleteEnseignement(
idProf: string,
idModule: string,
idPromo: string,
) {
if (
!confirm(
`Supprimer l'assignation ${idProf}${idModule} / ${idPromo} ?`,
)
) return;
try {
const res = await fetch(
`/admin/api/enseignements/${encodeURIComponent(idProf)}/${
encodeURIComponent(idModule)
}/${encodeURIComponent(idPromo)}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Suppression échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
async function addEnseignement() {
if (!addProf.trim() || !addModule || !addPromo) {
setAddError("Tous les champs sont requis");
return;
}
setAdding(true);
setAddError(null);
try {
const res = await fetch("/admin/api/enseignements", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
idProf: addProf.trim(),
idModule: addModule,
idPromo: addPromo,
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setAddProf("");
setAddModule("");
setAddPromo("");
setShowAdd(false);
await load();
} catch (e) {
setAddError(e instanceof Error ? e.message : "Erreur");
} finally {
setAdding(false);
}
}
const moduleMap = Object.fromEntries(modules.map((m) => [m.id, m]));
const filtered = enseignements.filter((e) => {
const matchPromo = !filterPromo || e.idPromo === filterPromo;
const matchModule = !filterModule || e.idModule === filterModule;
const matchEns = !filterEnseignant ||
e.idProf.toLowerCase().includes(filterEnseignant.toLowerCase());
return matchPromo && matchModule && matchEns;
});
return (
<div class="page-content">
<h2 class="page-title">Assignations Enseignant Module / Promo</h2>
{error && <p class="state-error">{error}</p>}
<div class="filters">
<select
class="filter-select"
value={filterPromo}
onChange={(e) =>
setFilterPromo((e.target as HTMLSelectElement).value)}
>
<option value="">Promo </option>
{promos.map((p) => <option key={p.id} value={p.id}>{p.id}</option>)}
</select>
<select
class="filter-select"
value={filterModule}
onChange={(e) =>
setFilterModule((e.target as HTMLSelectElement).value)}
>
<option value="">Module </option>
{modules.map((m) => (
<option key={m.id} value={m.id}>{m.id} {m.nom}</option>
))}
</select>
<input
class="filter-input"
placeholder="Enseignant ▾"
value={filterEnseignant}
onInput={(e) =>
setFilterEnseignant((e.target as HTMLInputElement).value)}
/>
<button
type="button"
class="btn btn-secondary"
onClick={() => {
setFilterPromo("");
setFilterModule("");
setFilterEnseignant("");
}}
>
Filtrer
</button>
<button
type="button"
class="btn btn-primary"
onClick={() => setShowAdd((v) => !v)}
style="margin-left: auto"
>
+ Assigner
</button>
</div>
{showAdd && (
<div class="modal-overlay" onClick={() => setShowAdd(false)}>
<div class="modal-box" onClick={(e) => e.stopPropagation()}>
<p class="modal-title">Assigner un enseignement</p>
{addError && (
<p class="state-error" style="padding: 0.3rem 0.5rem">
{addError}
</p>
)}
<div class="modal-form">
<div class="form-field">
<label>Promo</label>
<select
class="filter-select"
value={addPromo}
onChange={(e) =>
setAddPromo((e.target as HTMLSelectElement).value)}
style="min-width: 0; width: 100%"
>
<option value="">Promo...</option>
{promos.map((p) => (
<option key={p.id} value={p.id}>{p.id}</option>
))}
</select>
</div>
<div class="form-field">
<label>Module</label>
<select
class="filter-select"
value={addModule}
onChange={(e) =>
setAddModule((e.target as HTMLSelectElement).value)}
style="min-width: 0; width: 100%"
>
<option value="">Module...</option>
{modules.map((m) => (
<option key={m.id} value={m.id}>
{m.id} -- {m.nom}
</option>
))}
</select>
</div>
<div class="form-field">
<label>User ID enseignant</label>
<input
class="form-input"
placeholder="User ID enseignant..."
value={addProf}
onInput={(e) =>
setAddProf((e.target as HTMLInputElement).value)}
style="min-width: 0; width: 100%"
/>
</div>
</div>
<div class="modal-actions">
<button
type="button"
class="btn btn-secondary"
onClick={() => setShowAdd(false)}
>
Annuler
</button>
<button
type="button"
class="btn btn-primary"
onClick={addEnseignement}
disabled={adding}
>
{adding ? "..." : "+ Assigner"}
</button>
</div>
</div>
</div>
)}
{loading
? <p class="state-loading">Chargement</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>Promo</th>
<th>Module</th>
<th>Enseignant (User.id)</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{filtered.length === 0
? (
<tr>
<td colspan={4} class="state-empty">
Aucun enseignement trouvé
</td>
</tr>
)
: filtered.map((e) => {
const mod = moduleMap[e.idModule];
return (
<tr key={`${e.idProf}-${e.idModule}-${e.idPromo}`}>
<td>
<span class="promo-chip">{e.idPromo}</span>
</td>
<td class="col-promo">
{mod ? `${mod.id} ${mod.nom}` : e.idModule}
</td>
<td>{e.idProf}</td>
<td>
<div class="col-actions">
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() =>
deleteEnseignement(
e.idProf,
e.idModule,
e.idPromo,
)}
>
<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>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
<div class="info-note">
<p>
Un même module peut être enseigné par plusieurs utilisateurs sur une
même promo.
</p>
<p class="info-note-dim">
Clé composite = idProf (User.Id) + idModule + idPromo
</p>
</div>
</div>
);
}
@@ -0,0 +1,254 @@
import { useEffect, useState } from "preact/hooks";
type Module = { id: string; nom: string };
type Enseignement = { idProf: string; idModule: string; idPromo: string };
type User = { id: string; nom: string; prenom: string };
export default function AdminModules() {
const [modules, setModules] = useState<Module[]>([]);
const [enseignements, setEnseignements] = useState<Enseignement[]>([]);
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [newId, setNewId] = useState("");
const [newNom, setNewNom] = useState("");
const [creating, setCreating] = useState(false);
const [filterNom, setFilterNom] = useState("");
async function load() {
try {
const [mRes, eRes, uRes] = await Promise.all([
fetch("/admin/api/modules"),
fetch("/admin/api/enseignements"),
fetch("/admin/api/users"),
]);
if (!mRes.ok) throw new Error("Impossible de charger les modules");
setModules(await mRes.json());
if (eRes.ok) setEnseignements(await eRes.json());
if (uRes.ok) setUsers(await uRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, []);
async function createModule() {
if (!newId.trim() || !newNom.trim()) return;
setCreating(true);
try {
const res = await fetch("/admin/api/modules", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ id: newId.trim(), nom: newNom.trim() }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setNewId("");
setNewNom("");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setCreating(false);
}
}
async function deleteModule(id: string) {
if (!confirm(`Supprimer le module ${id} ?`)) return;
try {
const res = await fetch(
`/admin/api/modules/${encodeURIComponent(id)}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Suppression échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
const userMap = Object.fromEntries(
users.map((u) => [u.id, u]),
);
function enseignantsForModule(moduleId: string): string {
const profs = [
...new Set(
enseignements
.filter((e) => e.idModule === moduleId)
.map((e) => e.idProf),
),
];
if (profs.length === 0) return "";
return profs
.map((id) => {
const u = userMap[id];
return u ? `${u.nom} ${u.prenom.charAt(0)}.` : id;
})
.join(", ");
}
const filtered = modules.filter((m) =>
!filterNom ||
`${m.id} ${m.nom}`.toLowerCase().includes(filterNom.toLowerCase())
);
return (
<div class="page-content">
<h2 class="page-title">Gestion des Modules</h2>
{error && <p class="state-error">{error}</p>}
<div class="filters">
<input
class="filter-input"
placeholder="Rechercher..."
value={filterNom}
onInput={(e) => setFilterNom((e.target as HTMLInputElement).value)}
/>
<button
type="button"
class="btn btn-primary"
onClick={() => {
const el = document.getElementById("new-module-section");
if (el) el.scrollIntoView({ behavior: "smooth" });
}}
style="margin-left: auto"
>
+ Ajouter module
</button>
</div>
{loading
? <p class="state-loading">Chargement...</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>id (code)</th>
<th>Nom du module</th>
<th>Enseignants assignes</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{filtered.length === 0
? (
<tr>
<td colspan={4} class="state-empty">
Aucun module enregistré
</td>
</tr>
)
: filtered.map((m) => {
const profs = enseignantsForModule(m.id);
return (
<tr key={m.id}>
<td class="col-dim">{m.id}</td>
<td>{m.nom}</td>
<td>
{profs
? (
<span style="font-size: 0.78rem">
{profs}
</span>
)
: <span class="col-dim">--</span>}
</td>
<td>
<div class="col-actions">
<a
class="btn btn-sm btn-secondary"
href={`/admin/modules/${
encodeURIComponent(m.id)
}`}
f-client-nav={false}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
</svg>{" "}
edit
</a>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() => deleteModule(m.id)}
>
<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>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{/* Nouveau module */}
<div
id="new-module-section"
class="edit-section"
style="margin-top: 1.5rem"
>
<p class="edit-section-title">Nouveau module</p>
<div class="form-row">
<input
class="form-input"
placeholder="Code"
value={newId}
onInput={(e) => setNewId((e.target as HTMLInputElement).value)}
style="min-width: 8rem; max-width: 10rem"
/>
<input
class="form-input"
placeholder="Nom du module"
value={newNom}
onInput={(e) => setNewNom((e.target as HTMLInputElement).value)}
/>
<button
type="button"
class="btn btn-primary"
onClick={createModule}
disabled={creating}
>
{creating ? "..." : "+ Créer"}
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,128 @@
import { useEffect, useState } from "preact/hooks";
type Perm = { id: string; nom: string };
type Role = { id: number; nom: string; permissions: string[] };
const ROLE_COLORS = [
"#22c55e",
"#d4a017",
"#e07020",
"#8b5cf6",
"#06b6d4",
"#ec4899",
];
function roleColor(roleId: number): string {
return ROLE_COLORS[(roleId - 1) % ROLE_COLORS.length];
}
export default function AdminPermissions() {
const [permissions, setPermissions] = useState<Perm[]>([]);
const [roles, setRoles] = useState<Role[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function load() {
try {
const [pRes, rRes] = await Promise.all([
fetch("/admin/api/permissions"),
fetch("/admin/api/roles"),
]);
if (!pRes.ok) throw new Error("Impossible de charger les permissions");
setPermissions(await pRes.json());
if (rRes.ok) setRoles(await rRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
load();
}, []);
function rolesForPerm(permId: string): Role[] {
return roles.filter((r) => r.permissions.includes(permId));
}
const MAX_ROLE_CHIPS = 2;
return (
<div class="page-content">
<h2 class="page-title">Permissions</h2>
<div class="info-note" style="margin-top: 0; margin-bottom: 1.25rem">
<p>
Les permissions sont définies statiquement par le serveur.
</p>
<p class="info-note-dim">
Elles ne peuvent pas être créées ou supprimées via l'API.
</p>
</div>
{error && <p class="state-error">{error}</p>}
{loading
? <p class="state-loading">Chargement</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>idPermission</th>
<th>nomPermission</th>
<th>Rôles associés</th>
</tr>
</thead>
<tbody>
{permissions.map((p) => {
const associated = rolesForPerm(p.id);
const shown = associated.slice(0, MAX_ROLE_CHIPS);
const overflow = associated.length - MAX_ROLE_CHIPS;
return (
<tr key={p.id}>
<td>
<span
class="col-promo"
style="font-family: monospace"
>
{p.id}
</span>
</td>
<td>{p.nom}</td>
<td>
<div style="display: flex; flex-wrap: wrap; align-items: center; gap: 0.1rem">
{shown.map((r) => (
<span
key={r.id}
class="role-chip"
style={`border-color: ${
roleColor(r.id)
}; color: ${roleColor(r.id)}`}
>
{r.nom}
</span>
))}
{overflow > 0 && (
<span
class="col-dim"
style="font-size: 0.72rem; margin-left: 0.2rem"
>
+{overflow}
</span>
)}
{associated.length === 0 && (
<span class="col-dim"></span>
)}
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,263 @@
import { useEffect, useState } from "preact/hooks";
type Promotion = { id: string; annee: string | null };
type Student = { numEtud: number; idPromo: string };
function parsePromo(id: string) {
const m = id.match(/^(\d+A)(FISE|FISA)(.+)$/);
if (!m) return { annee: id, filiere: "?", anneeSco: "?" };
return { annee: m[1], filiere: m[2], anneeSco: m[3] };
}
const ANNEES = ["3A", "4A", "5A"];
const FILIERES = ["FISE", "FISA"];
export default function AdminPromotions() {
const [promos, setPromos] = useState<Promotion[]>([]);
const [students, setStudents] = useState<Student[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [creating, setCreating] = useState(false);
// PromoBuilder state
const [selectedAnnee, setSelectedAnnee] = useState("4A");
const [selectedFiliere, setSelectedFiliere] = useState("FISE");
const [anneeSco, setAnneeSco] = useState("");
const generatedId = anneeSco.trim()
? `${selectedAnnee}${selectedFiliere}${anneeSco.trim().replace(/\//g, "-")}`
: "";
async function load() {
try {
const [pRes, sRes] = await Promise.all([
fetch("/students/api/promotions"),
fetch("/students/api/students"),
]);
if (!pRes.ok) throw new Error("Impossible de charger les promotions");
setPromos(await pRes.json());
if (sRes.ok) setStudents(await sRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, []);
async function createPromo() {
if (!generatedId) return;
setCreating(true);
try {
const res = await fetch("/students/api/promotions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
idPromo: generatedId,
annee: selectedAnnee,
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setAnneeSco("");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setCreating(false);
}
}
async function deletePromo(id: string) {
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 {
const res = await fetch(
`/students/api/promotions/${encodeURIComponent(id)}`,
{ method: "DELETE" },
);
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Suppression échouée");
}
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
function studentCount(idPromo: string) {
return students.filter((s) => s.idPromo === idPromo).length;
}
return (
<div class="page-content">
<h2 class="page-title">Gestion des Promotions</h2>
{error && <p class="state-error">{error}</p>}
{/* PromoBuilder */}
<div class="promo-builder">
<p class="promo-builder-title">Créer une promotion</p>
<p class="promo-builder-subtitle">
idPromo est généré automatiquement
</p>
<div class="promo-builder-row">
<div class="promo-builder-field">
<label>Année</label>
<div class="pill-group">
{ANNEES.map((a) => (
<button
key={a}
type="button"
class={`pill-btn${selectedAnnee === a ? " active" : ""}`}
onClick={() => setSelectedAnnee(a)}
>
{a}
</button>
))}
</div>
</div>
<div class="promo-builder-field">
<label>Filière</label>
<div class="pill-group">
{FILIERES.map((f) => (
<button
key={f}
type="button"
class={`pill-btn${selectedFiliere === f ? " active" : ""}`}
onClick={() => setSelectedFiliere(f)}
>
{f}
</button>
))}
</div>
</div>
<div class="promo-builder-field">
<label>Année scolaire</label>
<input
class="form-input"
placeholder="ex: 25-26, 24-27…"
value={anneeSco}
onInput={(e) => setAnneeSco((e.target as HTMLInputElement).value)}
style="min-width: 9rem"
/>
</div>
</div>
<div style="display: flex; align-items: center; gap: 1rem; flex-wrap: wrap">
<div style="display: flex; align-items: center; gap: 0.5rem">
<span style="font-size: 0.78rem; color: light-dark(var(--light-foreground-dim), var(--dark-foreground-dim))">
idPromo généré :
</span>
<span class="promo-id-preview">
{generatedId || "—"}
</span>
</div>
<button
type="button"
class="btn btn-primary"
onClick={createPromo}
disabled={creating || !generatedId}
>
{creating ? "…" : "+ Créer la promo"}
</button>
</div>
</div>
{/* Existing promotions table */}
<p style="font-size: 0.82rem; font-weight: var(--font-weight-bold); margin-bottom: 0.5rem">
Promotions existantes
</p>
{loading
? <p class="state-loading">Chargement</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>idPromo</th>
<th>Année</th>
<th>Filière</th>
<th>Année sco.</th>
<th>Nb étudiants</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{promos.length === 0
? (
<tr>
<td colspan={6} class="state-empty">
Aucune promotion enregistrée
</td>
</tr>
)
: promos.map((p) => {
const parsed = parsePromo(p.id);
const count = studentCount(p.id);
return (
<tr key={p.id}>
<td>
<span class="promo-chip">{p.id}</span>
</td>
<td>{parsed.annee}</td>
<td>
<span class="filiere-chip">{parsed.filiere}</span>
</td>
<td>{parsed.anneeSco}</td>
<td class="col-dim">
{count} étudiant{count !== 1 ? "s" : ""}
</td>
<td>
<button
type="button"
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)}
>
<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>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,323 @@
import { useEffect, useState } from "preact/hooks";
type Role = { id: number; nom: string; permissions: string[] };
type Perm = { id: string; nom: string };
const MAX_CHIPS = 3;
export default function AdminRoles() {
const [roles, setRoles] = useState<Role[]>([]);
const [permissions, setPermissions] = useState<Perm[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [newNom, setNewNom] = useState("");
const [creating, setCreating] = useState(false);
// Manage-perms sub-view
const [managingRole, setManagingRole] = useState<Role | null>(null);
const [editPerms, setEditPerms] = useState<Set<string>>(new Set());
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
async function load() {
try {
const [rRes, pRes] = await Promise.all([
fetch("/admin/api/roles"),
fetch("/admin/api/permissions"),
]);
if (!rRes.ok) throw new Error("Impossible de charger les rôles");
setRoles(await rRes.json());
if (pRes.ok) setPermissions(await pRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, []);
async function createRole() {
if (!newNom.trim()) return;
setCreating(true);
try {
const res = await fetch("/admin/api/roles", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: newNom.trim() }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setNewNom("");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setCreating(false);
}
}
async function deleteRole(id: number) {
if (!confirm("Supprimer ce rôle ?")) return;
try {
const res = await fetch(`/admin/api/roles/${id}`, { method: "DELETE" });
if (!res.ok) throw new Error("Suppression échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
function openManage(role: Role) {
setManagingRole(role);
setEditPerms(new Set(role.permissions));
setSaveError(null);
}
function togglePerm(permId: string) {
setEditPerms((prev) => {
const next = new Set(prev);
if (next.has(permId)) next.delete(permId);
else next.add(permId);
return next;
});
}
async function savePerms() {
if (!managingRole) return;
setSaving(true);
setSaveError(null);
try {
const res = await fetch(`/admin/api/roles/${managingRole.id}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
nom: managingRole.nom,
permissions: [...editPerms],
}),
});
if (!res.ok) throw new Error("Enregistrement échoué");
await load();
setManagingRole(null);
} catch (e) {
setSaveError(e instanceof Error ? e.message : "Erreur");
} finally {
setSaving(false);
}
}
// ---- Manage-perms view ----
if (managingRole) {
const activeCount = editPerms.size;
return (
<div class="page-content">
<a
class="back-link"
href="#"
onClick={(e) => {
e.preventDefault();
setManagingRole(null);
}}
>
Retour à la liste des rôles
</a>
<h2 class="page-title">
Permissions du rôle {managingRole.nom}
</h2>
{saveError && <p class="state-error">{saveError}</p>}
<div class="perm-header-bar">
<div style="display: flex; align-items: center; gap: 0.6rem">
<span class="numEtud-chip">idRole : {managingRole.id}</span>
<span style="font-weight: var(--font-weight-bold); font-size: 0.9rem">
{managingRole.nom}
</span>
<span style="font-size: 0.8rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color))">
{activeCount} permission{activeCount !== 1 ? "s" : ""} active
{activeCount !== 1 ? "s" : ""}
</span>
</div>
<button
type="button"
class="btn btn-primary"
onClick={savePerms}
disabled={saving}
>
{saving ? "..." : "Enregistrer"}
</button>
</div>
<div style="margin-bottom: 0.5rem; display: flex; justify-content: space-between">
<span style="font-size: 0.78rem; font-weight: var(--font-weight-bold)">
Permissions disponibles
</span>
<span style="font-size: 0.72rem; color: light-dark(var(--light-foreground-dim), var(--dark-foreground-dim))">
Activer = inclure dans le rôle
</span>
</div>
<div class="perm-toggle-grid">
{permissions.map((p) => {
const active = editPerms.has(p.id);
return (
<label
key={p.id}
class={`perm-toggle-card${active ? " active" : ""}`}
>
<div class="perm-toggle-label">
<span class="perm-toggle-id">{p.id}</span>
<span class="perm-toggle-nom">{p.nom}</span>
</div>
<span class="toggle-switch">
<input
type="checkbox"
checked={active}
onChange={() => togglePerm(p.id)}
/>
<span class="toggle-slider" />
</span>
</label>
);
})}
</div>
</div>
);
}
const permMap = Object.fromEntries(permissions.map((p) => [p.id, p.nom]));
// ---- Main list view ----
return (
<div class="page-content">
<h2 class="page-title">Gestion des Rôles</h2>
{error && <p class="state-error">{error}</p>}
<div class="toolbar">
<input
class="form-input"
placeholder="Nom du rôle..."
value={newNom}
onInput={(e) => setNewNom((e.target as HTMLInputElement).value)}
onKeyDown={(e) => e.key === "Enter" && createRole()}
style="min-width: 14rem"
/>
<button
type="button"
class="btn btn-primary"
onClick={createRole}
disabled={creating}
>
+ Créer rôle
</button>
</div>
{loading
? <p class="state-loading">Chargement...</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>idRole</th>
<th>Nom du rôle</th>
<th>Permissions</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{roles.length === 0
? (
<tr>
<td colspan={4} class="state-empty">
Aucun rôle enregistré
</td>
</tr>
)
: roles.map((r) => {
const shown = r.permissions.slice(0, MAX_CHIPS);
const overflow = r.permissions.length - MAX_CHIPS;
return (
<tr key={r.id}>
<td class="col-dim">{r.id}</td>
<td style="font-weight: var(--font-weight-bold)">
{r.nom}
</td>
<td>
<div style="display: flex; flex-wrap: wrap; align-items: center; gap: 0.1rem">
{shown.map((p) => (
<span key={p} class="perm-chip">
{permMap[p] ?? p}
</span>
))}
{overflow > 0 && (
<span
class="col-dim"
style="font-size: 0.72rem; margin-left: 0.2rem"
>
+{overflow}
</span>
)}
</div>
</td>
<td>
<div class="col-actions">
<button
type="button"
class="btn btn-sm btn-primary"
onClick={() => openManage(r)}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z" />
</svg>{" "}
Gérer perms
</button>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() => deleteRole(r.id)}
>
<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>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
);
}
+516
View File
@@ -0,0 +1,516 @@
import { useEffect, useState } from "preact/hooks";
type UE = { id: number; nom: string };
type UEModule = {
idModule: string;
idUE: number;
idPromo: string;
coeff: number;
};
type Module = { id: string; nom: string };
type Promo = { id: string; annee: string };
export default function AdminUEs() {
const [ues, setUes] = useState<UE[]>([]);
const [ueModules, setUeModules] = useState<UEModule[]>([]);
const [modules, setModules] = useState<Module[]>([]);
const [promos, setPromos] = useState<Promo[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedUe, setSelectedUe] = useState<UE | null>(null);
const [filterPromo, setFilterPromo] = useState("");
// New UE form
const [newUeNom, setNewUeNom] = useState("");
const [creatingUe, setCreatingUe] = useState(false);
// Add UE-module form
const [addModuleId, setAddModuleId] = useState("");
const [addPromoId, setAddPromoId] = useState("");
const [addCoeff, setAddCoeff] = useState("1");
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
// Inline coeff editing
const [editingCoeff, setEditingCoeff] = useState<string | null>(null);
const [editCoeffValue, setEditCoeffValue] = useState("");
async function load() {
try {
const [uRes, umRes, mRes, pRes] = await Promise.all([
fetch("/admin/api/ues"),
fetch("/admin/api/ue-modules"),
fetch("/admin/api/modules"),
fetch("/students/api/promotions"),
]);
if (!uRes.ok) throw new Error("Impossible de charger les UEs");
const uesData: UE[] = await uRes.json();
setUes(uesData);
if (umRes.ok) setUeModules(await umRes.json());
if (mRes.ok) setModules(await mRes.json());
if (pRes.ok) setPromos(await pRes.json());
// Keep selection in sync
setSelectedUe((prev) =>
prev ? uesData.find((u) => u.id === prev.id) ?? null : null
);
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, []);
async function createUE() {
if (!newUeNom.trim()) return;
setCreatingUe(true);
try {
const res = await fetch("/admin/api/ues", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: newUeNom.trim() }),
});
if (!res.ok) throw new Error("Création échouée");
setNewUeNom("");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setCreatingUe(false);
}
}
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(
idModule: string,
idUE: number,
idPromo: string,
) {
if (!confirm("Supprimer ce module de la UE ?")) return;
try {
const res = await fetch(
`/admin/api/ue-modules/${encodeURIComponent(idModule)}/${idUE}/${
encodeURIComponent(idPromo)
}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Suppression échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
async function addUeModule() {
if (!selectedUe || !addModuleId || !addPromoId) {
setAddError("Module et Promo sont requis");
return;
}
const coeff = parseFloat(addCoeff);
if (isNaN(coeff) || coeff <= 0) {
setAddError("Coefficient invalide");
return;
}
setAdding(true);
setAddError(null);
try {
const res = await fetch("/admin/api/ue-modules", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
idModule: addModuleId,
idUE: selectedUe.id,
idPromo: addPromoId,
coeff,
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setAddModuleId("");
setAddPromoId("");
setAddCoeff("1");
await load();
} catch (e) {
setAddError(e instanceof Error ? e.message : "Erreur");
} finally {
setAdding(false);
}
}
async function updateCoeff(
idModule: string,
idUE: number,
idPromo: string,
coeff: number,
) {
try {
const res = await fetch(
`/admin/api/ue-modules/${encodeURIComponent(idModule)}/${idUE}/${
encodeURIComponent(idPromo)
}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ coeff }),
},
);
if (!res.ok) throw new Error("Modification échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setEditingCoeff(null);
}
}
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
? ueModules.filter((um) => um.idUE === selectedUe.id)
: [];
return (
<div class="page-content">
<h2 class="page-title">Gestion des UEs</h2>
<p
class="col-dim"
style="font-size: 0.78rem; margin: -0.5rem 0 1rem"
>
UE = Unité d'Enseignement regroupant plusieurs modules
</p>
{error && <p class="state-error">{error}</p>}
{loading
? <p class="state-loading">Chargement</p>
: (
<div class="ue-split">
{/* Left panel UE list */}
<div class="ue-panel-left">
<div class="panel-box">
<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">
<input
class="form-input"
placeholder="Nom de la nouvelle UE…"
value={newUeNom}
onInput={(e) =>
setNewUeNom((e.target as HTMLInputElement).value)}
onKeyDown={(e) => e.key === "Enter" && createUE()}
style="min-width: 0; flex: 1"
/>
</div>
<button
type="button"
class="btn btn-primary"
onClick={createUE}
disabled={creatingUe}
style="width: 100%; justify-content: center; margin-bottom: 0.5rem"
>
+ Nouvelle UE
</button>
<div>
{filteredUes.map((ue) => (
<div
key={ue.id}
class={`ue-list-item${
selectedUe?.id === ue.id ? " active" : ""
}`}
style="display: flex; align-items: center; justify-content: space-between"
>
<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>
))}
{filteredUes.length === 0 && (
<p class="state-empty" style="padding: 1rem 0">
{filterPromo ? "Aucune UE pour cette promo" : "Aucune UE"}
</p>
)}
</div>
</div>
</div>
{/* Right panel UE detail */}
<div class="ue-panel-right">
{selectedUe
? (
<div class="panel-box">
<p class="panel-box-title">{selectedUe.nom}</p>
<p style="font-size: 0.78rem; font-weight: var(--font-weight-bold); margin: 0 0 0.5rem">
Modules assignés (UE_Module)
</p>
<div class="data-table-wrap" style="margin-bottom: 1rem">
<table class="data-table">
<thead>
<tr>
<th>Module</th>
<th>Promo</th>
<th>Coeff</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{selectedUeModules.length === 0
? (
<tr>
<td colspan={4} class="state-empty">
Aucun module assigné
</td>
</tr>
)
: selectedUeModules.map((um) => {
const mod = moduleMap[um.idModule];
return (
<tr
key={`${um.idModule}-${um.idPromo}`}
>
<td class="col-promo">
{mod
? `${mod.id} ${mod.nom}`
: um.idModule}
</td>
<td>
<span class="promo-chip">{um.idPromo}</span>
</td>
<td
onClick={() => {
const key =
`${um.idModule}-${um.idUE}-${um.idPromo}`;
setEditingCoeff(key);
setEditCoeffValue(String(um.coeff));
}}
style="cursor: pointer"
>
{editingCoeff ===
`${um.idModule}-${um.idUE}-${um.idPromo}`
? (
<input
type="number"
class="form-input"
value={editCoeffValue}
min="0.1"
step="0.5"
style="width: 5rem; padding: 0.2rem 0.4rem; font-size: 0.82rem"
autoFocus
onInput={(e) =>
setEditCoeffValue(
(e.target as HTMLInputElement)
.value,
)}
onBlur={() => {
const v = parseFloat(
editCoeffValue,
);
if (!isNaN(v) && v > 0) {
updateCoeff(
um.idModule,
um.idUE,
um.idPromo,
v,
);
} else {
setEditingCoeff(null);
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
(e.target as HTMLInputElement)
.blur();
}
if (e.key === "Escape") {
setEditingCoeff(null);
}
}}
/>
)
: um.coeff}
</td>
<td>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() =>
deleteUeModule(
um.idModule,
um.idUE,
um.idPromo,
)}
>
<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>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<p style="font-size: 0.78rem; font-weight: var(--font-weight-bold); margin: 0 0 0.5rem">
Ajouter un module à cette UE
</p>
{addError && (
<p class="state-error" style="padding: 0.3rem 0.5rem">
{addError}
</p>
)}
<div class="form-row">
<select
class="filter-select"
value={addModuleId}
onChange={(e) =>
setAddModuleId(
(e.target as HTMLSelectElement).value,
)}
style="min-width: 12rem"
>
<option value="">Module </option>
{modules.map((m) => (
<option key={m.id} value={m.id}>
{m.id} {m.nom}
</option>
))}
</select>
<select
class="filter-select"
value={addPromoId}
onChange={(e) =>
setAddPromoId(
(e.target as HTMLSelectElement).value,
)}
style="min-width: 9rem"
>
<option value="">Promo </option>
{promos.map((p) => (
<option key={p.id} value={p.id}>{p.id}</option>
))}
</select>
<input
type="number"
class="form-input"
placeholder="Coeff"
value={addCoeff}
min="0.1"
step="0.5"
onInput={(e) =>
setAddCoeff((e.target as HTMLInputElement).value)}
style="min-width: 5rem; max-width: 6rem"
/>
<button
type="button"
class="btn btn-primary"
onClick={addUeModule}
disabled={adding}
>
{adding ? "…" : "+ Ajouter"}
</button>
</div>
</div>
)
: (
<div class="panel-box">
<p class="state-empty" style="padding: 2rem 0">
Sélectionnez une UE pour voir ses modules
</p>
</div>
)}
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,308 @@
import { useEffect, useState } from "preact/hooks";
type User = { id: string; nom: string; prenom: string; idRole: number | null };
type Role = { id: number; nom: string };
const ROLE_COLORS = [
"#22c55e",
"#d4a017",
"#e07020",
"#8b5cf6",
"#06b6d4",
"#ec4899",
];
function roleColor(roleId: number): string {
return ROLE_COLORS[(roleId - 1) % ROLE_COLORS.length];
}
export default function AdminUsers() {
const [users, setUsers] = useState<User[]>([]);
const [roles, setRoles] = useState<Role[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [showCreate, setShowCreate] = useState(false);
const [newId, setNewId] = useState("");
const [newNom, setNewNom] = useState("");
const [newPrenom, setNewPrenom] = useState("");
const [newIdRole, setNewIdRole] = useState("");
const [creating, setCreating] = useState(false);
const [filterNom, setFilterNom] = useState("");
const [filterRole, setFilterRole] = useState("");
async function load() {
try {
const [uRes, rRes] = await Promise.all([
fetch("/admin/api/users"),
fetch("/admin/api/roles"),
]);
if (!uRes.ok) throw new Error("Impossible de charger les utilisateurs");
setUsers(await uRes.json());
if (rRes.ok) setRoles(await rRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, []);
async function createUser() {
if (!newId.trim() || !newNom.trim() || !newPrenom.trim()) return;
setCreating(true);
try {
const res = await fetch("/admin/api/users", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
id: newId.trim(),
nom: newNom.trim(),
prenom: newPrenom.trim(),
idRole: newIdRole ? Number(newIdRole) : null,
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setNewId("");
setNewNom("");
setNewPrenom("");
setNewIdRole("");
setShowCreate(false);
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setCreating(false);
}
}
async function deleteUser(id: string) {
if (!confirm(`Supprimer l'utilisateur ${id} ?`)) return;
try {
const res = await fetch(`/admin/api/users/${encodeURIComponent(id)}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Suppression échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
const roleMap = Object.fromEntries(roles.map((r) => [r.id, r.nom]));
const filtered = users.filter((u) => {
const matchNom = !filterNom ||
`${u.nom} ${u.prenom} ${u.id}`.toLowerCase().includes(
filterNom.toLowerCase(),
);
const matchRole = !filterRole || String(u.idRole) === filterRole;
return matchNom && matchRole;
});
return (
<div class="page-content">
<h2 class="page-title">Gestion des Utilisateurs</h2>
{error && <p class="state-error">{error}</p>}
<div class="filters">
<input
class="filter-input"
placeholder="Rechercher..."
value={filterNom}
onInput={(e) => setFilterNom((e.target as HTMLInputElement).value)}
/>
<select
class="filter-select"
value={filterRole}
onChange={(e) => setFilterRole((e.target as HTMLSelectElement).value)}
>
<option value="">Role</option>
{roles.map((r) => <option key={r.id} value={r.id}>{r.nom}</option>)}
</select>
<button
type="button"
class="btn btn-primary"
onClick={() => setShowCreate(true)}
style="margin-left: auto"
>
+ Créer utilisateur
</button>
</div>
{/* Creation modal */}
{showCreate && (
<div
class="modal-overlay"
onClick={() => setShowCreate(false)}
>
<div class="modal-box" onClick={(e) => e.stopPropagation()}>
<p class="modal-title">Créer un utilisateur</p>
<div class="modal-form">
<div class="form-field">
<label>Login (uid)</label>
<input
class="form-input"
placeholder="Login (uid)"
value={newId}
onInput={(e) =>
setNewId((e.target as HTMLInputElement).value)}
style="min-width: 0; width: 100%"
/>
</div>
<div class="form-field">
<label>Nom</label>
<input
class="form-input"
placeholder="Nom"
value={newNom}
onInput={(e) =>
setNewNom((e.target as HTMLInputElement).value)}
style="min-width: 0; width: 100%"
/>
</div>
<div class="form-field">
<label>Prénom</label>
<input
class="form-input"
placeholder="Prénom"
value={newPrenom}
onInput={(e) =>
setNewPrenom((e.target as HTMLInputElement).value)}
style="min-width: 0; width: 100%"
/>
</div>
<div class="form-field">
<label>Rôle</label>
<select
class="filter-select"
value={newIdRole}
onChange={(e) =>
setNewIdRole((e.target as HTMLSelectElement).value)}
style="min-width: 0; width: 100%"
>
<option value="">Aucun rôle</option>
{roles.map((r) => (
<option key={r.id} value={r.id}>{r.nom}</option>
))}
</select>
</div>
</div>
<div class="modal-actions">
<button
type="button"
class="btn btn-secondary"
onClick={() => setShowCreate(false)}
>
Annuler
</button>
<button
type="button"
class="btn btn-primary"
onClick={createUser}
disabled={creating}
>
{creating ? "..." : "+ Créer"}
</button>
</div>
</div>
</div>
)}
{loading
? <p class="state-loading">Chargement...</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>id (login)</th>
<th>Nom</th>
<th>Prénom</th>
<th>Rôle(s)</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{filtered.length === 0
? (
<tr>
<td colspan={5} class="state-empty">
Aucun utilisateur trouvé
</td>
</tr>
)
: filtered.map((u) => (
<tr key={u.id}>
<td class="col-dim">{u.id}</td>
<td>{u.nom}</td>
<td>{u.prenom}</td>
<td>
{u.idRole
? (
<span
class="role-chip"
style={`border-color: ${
roleColor(u.idRole)
}; color: ${roleColor(u.idRole)}`}
>
{roleMap[u.idRole] ?? `#${u.idRole}`}
</span>
)
: <span class="col-dim">--</span>}
</td>
<td>
<div class="col-actions">
<a
class="btn btn-sm btn-secondary"
href={`/admin/users/${encodeURIComponent(u.id)}`}
f-client-nav={false}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
</svg>{" "}
edit
</a>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() => deleteUser(u.id)}
>
<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>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,344 @@
import { useEffect, useState } from "preact/hooks";
type Module = { id: string; nom: string };
type Enseignement = { idProf: string; idModule: string; idPromo: string };
type User = { id: string; nom: string; prenom: string };
type Promo = { id: string; annee: string };
type Props = { moduleId: string };
export default function EditModule({ moduleId }: Props) {
const [mod, setMod] = useState<Module | null>(null);
const [enseignements, setEnseignements] = useState<Enseignement[]>([]);
const [users, setUsers] = useState<User[]>([]);
const [promos, setPromos] = useState<Promo[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [saveMsg, setSaveMsg] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [nom, setNom] = useState("");
// Add enseignement
const [addProf, setAddProf] = useState("");
const [addPromo, setAddPromo] = useState("");
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
async function load() {
try {
const [mRes, eRes, uRes, pRes] = await Promise.all([
fetch(`/admin/api/modules/${encodeURIComponent(moduleId)}`),
fetch("/admin/api/enseignements"),
fetch("/admin/api/users"),
fetch("/students/api/promotions"),
]);
if (!mRes.ok) throw new Error("Module introuvable");
const m: Module = await mRes.json();
setMod(m);
setNom(m.nom);
if (eRes.ok) {
const all: Enseignement[] = await eRes.json();
setEnseignements(all.filter((e) => e.idModule === moduleId));
}
if (uRes.ok) setUsers(await uRes.json());
if (pRes.ok) setPromos(await pRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, [moduleId]);
async function saveInfos() {
if (!mod) return;
setSaving(true);
setSaveMsg(null);
try {
const res = await fetch(
`/admin/api/modules/${encodeURIComponent(moduleId)}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ nom: nom.trim() }),
},
);
if (!res.ok) throw new Error("Modification échouée");
const updated: Module = await res.json();
setMod(updated);
setSaveMsg("Module enregistré.");
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setSaving(false);
}
}
async function deleteModule() {
if (!confirm(`Supprimer définitivement le module ${moduleId} ?`)) return;
try {
const res = await fetch(
`/admin/api/modules/${encodeURIComponent(moduleId)}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Suppression échouée");
globalThis.location.href = "/admin/modules";
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
async function addEnseignement() {
if (!addProf || !addPromo) {
setAddError("Enseignant et Promo sont requis");
return;
}
setAdding(true);
setAddError(null);
try {
const res = await fetch("/admin/api/enseignements", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
idProf: addProf,
idModule: moduleId,
idPromo: addPromo,
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setAddProf("");
setAddPromo("");
await load();
} catch (e) {
setAddError(e instanceof Error ? e.message : "Erreur");
} finally {
setAdding(false);
}
}
async function removeEnseignement(idProf: string, idPromo: string) {
if (!confirm("Retirer cet enseignement ?")) return;
try {
const res = await fetch(
`/admin/api/enseignements/${encodeURIComponent(idProf)}/${
encodeURIComponent(moduleId)
}/${encodeURIComponent(idPromo)}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Suppression échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
const userMap = Object.fromEntries(users.map((u) => [u.id, u]));
if (loading) {
return (
<div class="page-content">
<p class="state-loading">Chargement...</p>
</div>
);
}
if (error && !mod) {
return (
<div class="page-content">
<p class="state-error">{error}</p>
</div>
);
}
if (!mod) return null;
return (
<div class="page-content">
<a
class="back-link"
href="/admin/modules"
f-partial="/admin/partials/modules"
>
&larr; Retour a la liste
</a>
<h2
class="page-title"
style="border-bottom: none; margin-bottom: 0.5rem"
>
Module -- {mod.id}
</h2>
<div class="info-bar">
<span class="module-chip">{mod.id}</span>
<span>{mod.nom}</span>
</div>
{error && <p class="state-error">{error}</p>}
{saveMsg && (
<p style="font-size: 0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.5rem">
{saveMsg}
</p>
)}
{/* Section 1: Infos */}
<div class="edit-section">
<p class="edit-section-title">Informations</p>
<div class="form-grid">
<div class="form-field">
<label>Code</label>
<input
class="form-input"
value={mod.id}
disabled
style="opacity: 0.6"
/>
</div>
<div class="form-field">
<label>Nom du module</label>
<input
class="form-input"
value={nom}
onInput={(e) => setNom((e.target as HTMLInputElement).value)}
/>
</div>
</div>
<div style="display: flex; gap: 0.5rem; justify-content: space-between; flex-wrap: wrap">
<button
type="button"
class="btn btn-primary"
onClick={saveInfos}
disabled={saving}
>
{saving ? "..." : "Enregistrer"}
</button>
<button
type="button"
class="btn btn-danger"
onClick={deleteModule}
>
Supprimer le module
</button>
</div>
</div>
{/* Section 2: Enseignements */}
<div class="edit-section">
<p class="edit-section-title">Enseignants assignes</p>
{enseignements.length > 0
? (
<div class="data-table-wrap" style="margin-bottom: 1rem">
<table class="data-table">
<thead>
<tr>
<th>Enseignant</th>
<th>Promo</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{enseignements.map((e) => {
const u = userMap[e.idProf];
return (
<tr key={`${e.idProf}-${e.idPromo}`}>
<td>
{u ? `${u.nom} ${u.prenom.charAt(0)}.` : e.idProf}
</td>
<td>
<span class="promo-chip">{e.idPromo}</span>
</td>
<td>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() =>
removeEnseignement(e.idProf, e.idPromo)}
>
<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>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)
: (
<p
class="state-empty"
style="padding: 1rem 0; text-align: left"
>
Aucun enseignant assigne.
</p>
)}
<p style="font-size: 0.78rem; font-weight: var(--font-weight-bold); margin: 0 0 0.5rem">
Ajouter un enseignant
</p>
{addError && (
<p class="state-error" style="padding: 0.3rem 0.5rem">
{addError}
</p>
)}
<div class="form-row">
<select
class="filter-select"
value={addProf}
onChange={(e) => setAddProf((e.target as HTMLSelectElement).value)}
style="min-width: 12rem"
>
<option value="">Enseignant</option>
{users.map((u) => (
<option key={u.id} value={u.id}>
{u.nom} {u.prenom} ({u.id})
</option>
))}
</select>
<select
class="filter-select"
value={addPromo}
onChange={(e) => setAddPromo((e.target as HTMLSelectElement).value)}
style="min-width: 9rem"
>
<option value="">Promo</option>
{promos.map((p) => <option key={p.id} value={p.id}>{p.id}</option>)}
</select>
<button
type="button"
class="btn btn-primary"
onClick={addEnseignement}
disabled={adding}
>
{adding ? "..." : "+ Ajouter"}
</button>
</div>
</div>
</div>
);
}
+391
View File
@@ -0,0 +1,391 @@
import { useEffect, useState } from "preact/hooks";
type User = { id: string; nom: string; prenom: string; idRole: number | null };
type Role = { id: number; nom: string };
type Enseignement = { idProf: string; idModule: string; idPromo: string };
type Module = { id: string; nom: string };
type Promo = { id: string; annee: string };
type Props = { userId: string };
export default function EditUser({ userId }: Props) {
const [user, setUser] = useState<User | null>(null);
const [roles, setRoles] = useState<Role[]>([]);
const [enseignements, setEnseignements] = useState<Enseignement[]>([]);
const [modules, setModules] = useState<Module[]>([]);
const [promos, setPromos] = useState<Promo[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [saveMsg, setSaveMsg] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [nom, setNom] = useState("");
const [prenom, setPrenom] = useState("");
const [idRole, setIdRole] = useState("");
// Add enseignement form
const [addModule, setAddModule] = useState("");
const [addPromo, setAddPromo] = useState("");
const [adding, setAdding] = useState(false);
const [addError, setAddError] = useState<string | null>(null);
async function load() {
try {
const [uRes, rRes, eRes, mRes, pRes] = await Promise.all([
fetch(`/admin/api/users/${encodeURIComponent(userId)}`),
fetch("/admin/api/roles"),
fetch("/admin/api/enseignements"),
fetch("/admin/api/modules"),
fetch("/students/api/promotions"),
]);
if (!uRes.ok) throw new Error("Utilisateur introuvable");
const u: User = await uRes.json();
setUser(u);
setNom(u.nom);
setPrenom(u.prenom);
setIdRole(u.idRole !== null ? String(u.idRole) : "");
if (rRes.ok) setRoles(await rRes.json());
if (eRes.ok) {
const allEns: Enseignement[] = await eRes.json();
setEnseignements(allEns.filter((e) => e.idProf === userId));
}
if (mRes.ok) setModules(await mRes.json());
if (pRes.ok) setPromos(await pRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, [userId]);
async function saveInfos() {
if (!user) return;
setSaving(true);
setSaveMsg(null);
try {
const res = await fetch(
`/admin/api/users/${encodeURIComponent(userId)}`,
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
nom: nom.trim(),
prenom: prenom.trim(),
idRole: idRole ? Number(idRole) : null,
}),
},
);
if (!res.ok) throw new Error("Modification échouée");
const updated: User = await res.json();
setUser(updated);
setSaveMsg("Informations enregistrées.");
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setSaving(false);
}
}
async function deleteUser() {
if (!confirm(`Supprimer définitivement l'utilisateur ${userId} ?`)) return;
try {
const res = await fetch(
`/admin/api/users/${encodeURIComponent(userId)}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Suppression échouée");
globalThis.location.href = "/admin/users";
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
async function addEnseignement() {
if (!addModule || !addPromo) {
setAddError("Module et Promo sont requis");
return;
}
setAdding(true);
setAddError(null);
try {
const res = await fetch("/admin/api/enseignements", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
idProf: userId,
idModule: addModule,
idPromo: addPromo,
}),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? "Création échouée");
}
setAddModule("");
setAddPromo("");
await load();
} catch (e) {
setAddError(e instanceof Error ? e.message : "Erreur");
} finally {
setAdding(false);
}
}
async function removeEnseignement(idModule: string, idPromo: string) {
if (!confirm("Retirer cet enseignement ?")) return;
try {
const res = await fetch(
`/admin/api/enseignements/${encodeURIComponent(userId)}/${
encodeURIComponent(idModule)
}/${encodeURIComponent(idPromo)}`,
{ method: "DELETE" },
);
if (!res.ok) throw new Error("Suppression échouée");
await load();
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
const moduleMap = Object.fromEntries(modules.map((m) => [m.id, m]));
const roleMap = Object.fromEntries(roles.map((r) => [r.id, r.nom]));
if (loading) {
return (
<div class="page-content">
<p class="state-loading">Chargement...</p>
</div>
);
}
if (error && !user) {
return (
<div class="page-content">
<p class="state-error">{error}</p>
</div>
);
}
if (!user) return null;
return (
<div class="page-content">
<a
class="back-link"
href="/admin/users"
f-partial="/admin/partials/users"
>
&larr; Retour a la liste
</a>
<h2
class="page-title"
style="border-bottom: none; margin-bottom: 0.5rem"
>
Edition -- {user.prenom} {user.nom}
</h2>
<div class="info-bar">
<span class="numEtud-chip">{user.id}</span>
<span>
{user.idRole
? (roleMap[user.idRole] ?? `Role #${user.idRole}`)
: "Aucun role"}
</span>
</div>
{error && <p class="state-error">{error}</p>}
{saveMsg && (
<p style="font-size: 0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.5rem">
{saveMsg}
</p>
)}
{/* Section 1: Informations generales */}
<div class="edit-section">
<p class="edit-section-title">Informations generales</p>
<div class="form-grid">
<div class="form-field">
<label>Nom</label>
<input
class="form-input"
value={nom}
onInput={(e) => setNom((e.target as HTMLInputElement).value)}
/>
</div>
<div class="form-field">
<label>Prenom</label>
<input
class="form-input"
value={prenom}
onInput={(e) => setPrenom((e.target as HTMLInputElement).value)}
/>
</div>
<div class="form-field">
<label>Login</label>
<input
class="form-input"
value={user.id}
disabled
style="opacity: 0.6"
/>
</div>
<div class="form-field">
<label>Role</label>
<select
class="filter-select"
value={idRole}
onChange={(e) => setIdRole((e.target as HTMLSelectElement).value)}
style="min-width: 0"
>
<option value="">Aucun role</option>
{roles.map((r) => <option key={r.id} value={r.id}>{r.nom}
</option>)}
</select>
</div>
</div>
<div style="display: flex; gap: 0.5rem; justify-content: space-between; flex-wrap: wrap">
<button
type="button"
class="btn btn-primary"
onClick={saveInfos}
disabled={saving}
>
{saving ? "..." : "Enregistrer"}
</button>
<button
type="button"
class="btn btn-danger"
onClick={deleteUser}
>
Supprimer l'utilisateur
</button>
</div>
</div>
{/* Section 2: Enseignements */}
<div class="edit-section">
<p class="edit-section-title">Enseignements</p>
<p
class="col-dim"
style="font-size: 0.75rem; margin: 0 0 0.75rem"
>
Modules enseignes par cet utilisateur
</p>
{enseignements.length > 0
? (
<div class="data-table-wrap" style="margin-bottom: 1rem">
<table class="data-table">
<thead>
<tr>
<th>Module</th>
<th>Promo</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{enseignements.map((e) => {
const mod = moduleMap[e.idModule];
return (
<tr key={`${e.idModule}-${e.idPromo}`}>
<td class="col-promo">
{mod ? `${mod.id} -- ${mod.nom}` : e.idModule}
</td>
<td>
<span class="promo-chip">{e.idPromo}</span>
</td>
<td>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() =>
removeEnseignement(e.idModule, e.idPromo)}
>
<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>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)
: (
<p
class="state-empty"
style="padding: 1rem 0; text-align: left"
>
Aucun enseignement assigne.
</p>
)}
<p style="font-size: 0.78rem; font-weight: var(--font-weight-bold); margin: 0 0 0.5rem">
Ajouter un enseignement
</p>
{addError && (
<p class="state-error" style="padding: 0.3rem 0.5rem">
{addError}
</p>
)}
<div class="form-row">
<select
class="filter-select"
value={addModule}
onChange={(e) =>
setAddModule((e.target as HTMLSelectElement).value)}
style="min-width: 12rem"
>
<option value="">Module</option>
{modules.map((m) => (
<option key={m.id} value={m.id}>
{m.id} -- {m.nom}
</option>
))}
</select>
<select
class="filter-select"
value={addPromo}
onChange={(e) => setAddPromo((e.target as HTMLSelectElement).value)}
style="min-width: 9rem"
>
<option value="">Promo</option>
{promos.map((p) => <option key={p.id} value={p.id}>{p.id}</option>)}
</select>
<button
type="button"
class="btn btn-primary"
onClick={addEnseignement}
disabled={adding}
>
{adding ? "..." : "+ Ajouter"}
</button>
</div>
</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>
);
}
+10 -2
View File
@@ -4,9 +4,17 @@ const properties: AppProperties = {
name: "Admin",
icon: "school",
pages: {
index: "Homepage",
index: "Accueil",
users: "Utilisateurs",
roles: "Rôles",
permissions: "Permissions",
modules: "Modules",
enseignements: "Enseignements",
promotions: "Promotions",
ues: "UEs",
"import-maquette": "Import Maquette",
},
adminOnly: [],
adminOnly: ["users", "roles", "permissions", "modules", "enseignements", "promotions", "ues", "import-maquette"],
hint: "PolyMPR module",
};
+35 -16
View File
@@ -4,33 +4,52 @@ import { enseignements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2";
const _NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const _NOT_FOUND = () =>
new Response(
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(
JSON.stringify({ error: "Cet enseignement existe déjà." }),
{ status: 409, headers: { "content-type": "application/json" } },
);
const CONFLICT = () =>
new Response(
JSON.stringify({ error: "Cet enseignement existe déjà." }),
{ status: 409, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = {
// GET /enseignements
async GET(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return new Response(JSON.stringify([]), {
headers: { "content-type": "application/json" },
});
}
const rows = await db.select().from(enseignements);
return new Response(JSON.stringify(rows), {
headers: { "content-type": "application/json" },
});
},
// #29 POST /enseignements
async POST(
request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const body: {
idProf: string;
idModule: string;
idPromo: string;
} = await request.json();
let body: { idProf: string; idModule: string; idPromo: string };
try {
body = await request.json();
} catch {
return new Response(null, { status: 500 });
}
if (!body.idProf || !body.idModule || !body.idPromo) {
return new Response(null, { status: 400 });
@@ -50,7 +69,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.then((rows) => rows[0] ?? null);
if (existing) {
return CONFLICT;
return CONFLICT();
}
const [created] = await db
@@ -4,12 +4,13 @@ import { enseignements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
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> = {
// #30 GET /enseignements/{idProf}/{idModule}/{idPromo}
@@ -18,7 +19,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const idProf = context.params.idProf;
@@ -37,7 +38,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
)
.then((rows) => rows[0] ?? null);
if (!enseignement) return NOT_FOUND;
if (!enseignement) return NOT_FOUND();
return new Response(JSON.stringify(enseignement), {
headers: { "content-type": "application/json" },
@@ -50,7 +51,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const idProf = context.params.idProf;
@@ -68,7 +69,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
)
.returning();
if (!deleted) return NOT_FOUND;
if (!deleted) return NOT_FOUND();
return new Response(null, { status: 204 });
},
+8 -9
View File
@@ -8,14 +8,8 @@ export const handler: Handlers<null, AuthenticatedState> = {
// #23 GET /modules
async GET(
_request: Request,
context: FreshContext<AuthenticatedState>,
_context: FreshContext<AuthenticatedState>,
): 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);
return new Response(JSON.stringify(rows), {
headers: { "content-type": "application/json" },
@@ -31,9 +25,14 @@ export const handler: Handlers<null, AuthenticatedState> = {
return new Response(null, { status: 403 });
}
const body: { id: string; nom: string } = await request.json();
let body: { id: string; nom: string };
try {
body = await request.json();
} catch {
return new Response(null, { status: 500 });
}
if (!body.id || !body.nom) {
if (!body.id || !body.id.trim() || !body.nom || !body.nom.trim()) {
return new Response(null, { status: 400 });
}
+41 -13
View File
@@ -1,13 +1,19 @@
import { FreshContext, Handlers } from "$fresh/server.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 { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = {
// #25 GET /modules/{idModule}
@@ -21,7 +27,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(modules.id, context.params.idModule))
.then((rows) => rows[0] ?? null);
if (!module) return NOT_FOUND;
if (!module) return NOT_FOUND();
return new Response(JSON.stringify(module), {
headers: { "content-type": "application/json" },
@@ -33,7 +39,16 @@ export const handler: Handlers<null, AuthenticatedState> = {
request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const body: { nom: string } = await request.json();
let body: { nom: string };
try {
body = await request.json();
} catch {
return new Response(null, { status: 500 });
}
if (typeof body.nom !== "string") {
return new Response(null, { status: 400 });
}
const [updated] = await db
.update(modules)
@@ -41,7 +56,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(modules.id, context.params.idModule))
.returning();
if (!updated) return NOT_FOUND;
if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" },
@@ -49,16 +64,29 @@ export const handler: Handlers<null, AuthenticatedState> = {
},
// #27 DELETE /modules/{idModule}
// Cascade: deletes notes, ue_modules, enseignements for this module.
async DELETE(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const [deleted] = await db
.delete(modules)
.where(eq(modules.id, context.params.idModule))
.returning();
const idModule = context.params.idModule;
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 });
},
+9 -15
View File
@@ -1,21 +1,15 @@
import { Handlers } from "$fresh/server.ts";
import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts";
import { permissions } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
const PERMISSIONS = [
{ id: "student_read", nom: "Consulter les élèves" },
{ id: "student_write", nom: "Gérer les élèves" },
{ id: "note_read", nom: "Consulter les notes" },
{ id: "note_write", nom: "Gérer les notes" },
{ id: "module_read", nom: "Consulter les modules" },
{ id: "module_write", nom: "Gérer les modules" },
{ id: "user_read", nom: "Consulter les utilisateurs" },
{ id: "user_write", nom: "Gérer les utilisateurs" },
{ id: "role_write", nom: "Gérer les rôles" },
] as const;
export const handler: Handlers<null, AuthenticatedState> = {
GET(_request, _context): Response {
return new Response(JSON.stringify(PERMISSIONS), {
async GET(
_request: Request,
_context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const result = await db.select().from(permissions);
return new Response(JSON.stringify(result), {
headers: { "content-type": "application/json" },
});
},
+23 -14
View File
@@ -1,13 +1,14 @@
import { FreshContext, Handlers } from "$fresh/server.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 { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
async function getRoleWithPermissions(
id: number,
@@ -41,7 +42,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const id = Number(context.params.idRole);
const role = await getRoleWithPermissions(id);
if (!role) return NOT_FOUND;
if (!role) return NOT_FOUND();
return new Response(JSON.stringify(role), {
headers: { "content-type": "application/json" },
@@ -62,7 +63,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(roles.id, id))
.returning();
if (!updated) return NOT_FOUND;
if (!updated) return NOT_FOUND();
// Reset permissions
await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id));
@@ -80,21 +81,29 @@ export const handler: Handlers<null, AuthenticatedState> = {
},
// #69 DELETE /roles/{idRole}
// Cascade: deletes role_permissions, detaches users (idRole set to null).
async DELETE(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const id = Number(context.params.idRole);
// Cascade delete role_permissions first
await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id));
const [deleted] = await db
.delete(roles)
const role = await db
.select()
.from(roles)
.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 });
},
@@ -47,6 +47,12 @@ export const handler: Handlers = {
);
}
if (typeof coeff !== "number" || coeff < 0) {
return new Response("Champ 'coeff' doit être un nombre >= 0", {
status: 400,
});
}
const result = await db.insert(ueModules).values({
idModule,
idUE,
@@ -4,17 +4,19 @@ import { ueModules } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Association UE-Module introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
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(
JSON.stringify({ error: "Paramètres invalides" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
const BAD_REQUEST = () =>
new Response(
JSON.stringify({ error: "Paramètres invalides" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = {
// #39 GET /ue-modules/{idModule}/{idUE}/{idPromo}
@@ -23,7 +25,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const idModule = context.params.idModule;
@@ -31,7 +33,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo;
if (isNaN(idUE)) {
return BAD_REQUEST;
return BAD_REQUEST();
}
const ueModuleAssociation = await db
@@ -44,7 +46,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
)
.then((rows) => rows[0] ?? null);
if (!ueModuleAssociation) return NOT_FOUND;
if (!ueModuleAssociation) return NOT_FOUND();
return new Response(JSON.stringify(ueModuleAssociation), {
headers: { "content-type": "application/json" },
@@ -57,7 +59,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const idModule = context.params.idModule;
@@ -65,7 +67,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo;
if (isNaN(idUE)) {
return BAD_REQUEST;
return BAD_REQUEST();
}
const body: { coeff: number } = await request.json();
@@ -89,7 +91,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
)
.returning();
if (!updated) return NOT_FOUND;
if (!updated) return NOT_FOUND();
return new Response(
JSON.stringify({
@@ -110,7 +112,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const idModule = context.params.idModule;
@@ -118,7 +120,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo;
if (isNaN(idUE)) {
return BAD_REQUEST;
return BAD_REQUEST();
}
const [deleted] = await db
@@ -132,7 +134,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
)
.returning();
if (!deleted) return NOT_FOUND;
if (!deleted) return NOT_FOUND();
return new Response(null, { status: 204 });
},
@@ -24,7 +24,7 @@ export const handler: Handlers = {
const body = await request.json();
const { nom } = body;
if (!nom) {
if (!nom || !nom.trim()) {
return new Response("Champ 'nom' manquant", { status: 400 });
}
@@ -1,6 +1,10 @@
import { Handlers } from "$fresh/server.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";
export const handler: Handlers = {
@@ -87,6 +91,7 @@ export const handler: Handlers = {
},
// #36 DELETE /ues/:idUE
// Cascade: deletes ajustements, ue_modules for this UE.
async DELETE(_request, context) {
try {
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(
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 });
} catch (error) {
console.error("Error deleting UE:", error);
+10 -3
View File
@@ -27,10 +27,17 @@ export const handler: Handlers<null, AuthenticatedState> = {
request: Request,
_context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const body: { id: string; nom: string; prenom: string; idRole: number } =
await request.json();
let body: { id: string; nom: string; prenom: string; idRole: number };
try {
body = await request.json();
} catch {
return new Response(null, { status: 500 });
}
if (!body.id || !body.nom || !body.prenom) {
if (
!body.id || !body.id.trim() || !body.nom || !body.nom.trim() ||
!body.prenom || !body.prenom.trim()
) {
return new Response(null, { status: 400 });
}
+22 -12
View File
@@ -1,13 +1,14 @@
import { FreshContext, Handlers } from "$fresh/server.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 { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
export const handler: Handlers<null, AuthenticatedState> = {
// #62 GET /users/{id}
@@ -21,7 +22,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(users.id, context.params.id))
.then((rows) => rows[0] ?? null);
if (!user) return NOT_FOUND;
if (!user) return NOT_FOUND();
return new Response(JSON.stringify(user), {
headers: { "content-type": "application/json" },
@@ -42,7 +43,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(users.id, context.params.id))
.returning();
if (!updated) return NOT_FOUND;
if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" },
@@ -50,16 +51,25 @@ export const handler: Handlers<null, AuthenticatedState> = {
},
// #64 DELETE /users/{id}
// Cascade: deletes enseignements for this user.
async DELETE(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const [deleted] = await db
.delete(users)
.where(eq(users.id, context.params.id))
.returning();
const id = context.params.id;
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 });
},
@@ -0,0 +1,11 @@
import { FreshContext } from "$fresh/server.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import EditModule from "../(_islands)/EditModule.tsx";
// deno-lint-ignore require-await
export default async function EditModulePage(
_request: Request,
context: FreshContext<AuthenticatedState>,
) {
return <EditModule moduleId={context.params.idModule} />;
}
@@ -0,0 +1,18 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminEnseignements from "../(_islands)/AdminEnseignements.tsx";
// deno-lint-ignore require-await
async function Enseignements(
_request: Request,
_context: FreshContext<State>,
) {
return <AdminEnseignements />;
}
export const config = getPartialsConfig();
export default makePartials(Enseignements);
@@ -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);
+34 -3
View File
@@ -3,10 +3,41 @@ import {
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/routes/_middleware.ts";
import { State } from "$root/defaults/interfaces.ts";
export function Index(_request: Request, _context: FreshContext<State>) {
return <h2>Welcome to Admin.</h2>;
// deno-lint-ignore require-await
export async function Index(
_request: Request,
context: FreshContext<State>,
) {
return (
<div class="page-content">
<h2 class="page-title">Administration</h2>
<p>
Bienvenue{" "}
<strong>
{(context.state as unknown as { session: Record<string, string> })
.session.displayName}
</strong>
.
</p>
<p>
Gérez les{" "}
<a href="/admin/modules" f-partial="/admin/partials/modules">
modules
</a>
,{" "}
<a href="/admin/users" f-partial="/admin/partials/users">
utilisateurs
</a>
,{" "}
<a href="/admin/roles" f-partial="/admin/partials/roles">
rôles
</a>{" "}
depuis la barre de navigation.
</p>
</div>
);
}
export const config = getPartialsConfig();
+18
View File
@@ -0,0 +1,18 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminModules from "../(_islands)/AdminModules.tsx";
// deno-lint-ignore require-await
async function Modules(
_request: Request,
_context: FreshContext<State>,
) {
return <AdminModules />;
}
export const config = getPartialsConfig();
export default makePartials(Modules);
@@ -0,0 +1,18 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminPermissions from "../(_islands)/AdminPermissions.tsx";
// deno-lint-ignore require-await
async function Permissions(
_request: Request,
_context: FreshContext<State>,
) {
return <AdminPermissions />;
}
export const config = getPartialsConfig();
export default makePartials(Permissions);
@@ -0,0 +1,18 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminPromotions from "../(_islands)/AdminPromotions.tsx";
// deno-lint-ignore require-await
async function Promotions(
_request: Request,
_context: FreshContext<State>,
) {
return <AdminPromotions />;
}
export const config = getPartialsConfig();
export default makePartials(Promotions);
+18
View File
@@ -0,0 +1,18 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminRoles from "../(_islands)/AdminRoles.tsx";
// deno-lint-ignore require-await
async function Roles(
_request: Request,
_context: FreshContext<State>,
) {
return <AdminRoles />;
}
export const config = getPartialsConfig();
export default makePartials(Roles);
+18
View File
@@ -0,0 +1,18 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminUEs from "../(_islands)/AdminUEs.tsx";
// deno-lint-ignore require-await
async function UEs(
_request: Request,
_context: FreshContext<State>,
) {
return <AdminUEs />;
}
export const config = getPartialsConfig();
export default makePartials(UEs);
+18
View File
@@ -0,0 +1,18 @@
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminUsers from "../(_islands)/AdminUsers.tsx";
// deno-lint-ignore require-await
async function Users(
_request: Request,
_context: FreshContext<State>,
) {
return <AdminUsers />;
}
export const config = getPartialsConfig();
export default makePartials(Users);
+11
View File
@@ -0,0 +1,11 @@
import { FreshContext } from "$fresh/server.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import EditUser from "../(_islands)/EditUser.tsx";
// deno-lint-ignore require-await
export default async function EditUserPage(
_request: Request,
context: FreshContext<AuthenticatedState>,
) {
return <EditUser userId={context.params.id} />;
}
@@ -0,0 +1,155 @@
import { useEffect, useState } from "preact/hooks";
type Student = {
numEtud: number;
nom: string;
prenom: string;
idPromo: string;
};
type Promotion = { id: string; annee: string | null };
export default function AdminConsultNotes() {
const [students, setStudents] = useState<Student[]>([]);
const [promos, setPromos] = useState<Promotion[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [filterPromo, setFilterPromo] = useState("");
const [filterNom, setFilterNom] = useState("");
const [filterPrenom, setFilterPrenom] = useState("");
const [applied, setApplied] = useState({
promo: "",
nom: "",
prenom: "",
});
useEffect(() => {
async function load() {
try {
const [sRes, pRes] = await Promise.all([
fetch("/students/api/students"),
fetch("/students/api/promotions"),
]);
if (!sRes.ok) throw new Error("Impossible de charger les étudiants");
setStudents(await sRes.json());
if (pRes.ok) setPromos(await pRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
load();
}, []);
const filtered = students.filter((s) => {
if (applied.promo && s.idPromo !== applied.promo) return false;
if (
applied.nom &&
!s.nom.toLowerCase().includes(applied.nom.toLowerCase())
) return false;
if (
applied.prenom &&
!s.prenom.toLowerCase().includes(applied.prenom.toLowerCase())
) return false;
return true;
});
function applyFilters() {
setApplied({ promo: filterPromo, nom: filterNom, prenom: filterPrenom });
}
return (
<div class="page-content">
<div class="toolbar">
<h2 class="page-title">Consulter les Notes</h2>
</div>
{error && <p class="state-error">{error}</p>}
<div class="filters">
<select
class="filter-select"
value={filterPromo}
onChange={(e) =>
setFilterPromo((e.target as HTMLSelectElement).value)}
>
<option value="">Toutes les promos</option>
{promos.map((p) => <option key={p.id} value={p.id}>{p.id}</option>)}
</select>
<input
class="filter-input"
placeholder="Nom"
value={filterNom}
onInput={(e) => setFilterNom((e.target as HTMLInputElement).value)}
/>
<input
class="filter-input"
placeholder="Prénom"
value={filterPrenom}
onInput={(e) => setFilterPrenom((e.target as HTMLInputElement).value)}
/>
<button type="button" class="btn btn-primary" onClick={applyFilters}>
Filtrer
</button>
</div>
{loading
? <p class="state-loading">Chargement</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th>Promo</th>
<th>Nom</th>
<th>Prénom</th>
<th>N° Étudiant</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{filtered.length === 0
? (
<tr>
<td colspan={5} class="state-empty">
Aucun étudiant trouvé
</td>
</tr>
)
: filtered.map((s) => (
<tr key={s.numEtud}>
<td class="col-promo">{s.idPromo}</td>
<td>{s.nom}</td>
<td>{s.prenom}</td>
<td class="col-dim">{s.numEtud}</td>
<td>
<div class="col-actions">
<a
class="btn btn-sm btn-secondary"
href={`/notes/edition/${s.numEtud}`}
f-client-nav={false}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
</svg>{" "}
édit
</a>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,619 @@
// @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 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() {
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 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) {
if (!f.name.match(/\.xlsx?$/i)) {
error.value = "Fichier invalide — format attendu : .xlsx";
return;
}
file.value = f;
error.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 parseSheet(wb: XLSX.WorkBook, sheetName: string) {
const sheet = wb.Sheets[sheetName];
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 onSheetChange(name: string) {
selectedSheet.value = name;
if (workbookRef.current) {
parseSheet(workbookRef.current, name);
}
}
function findStudent(
nom: string,
prenom: string,
): Student | undefined {
const normNom = nom.toUpperCase().trim();
const normPrenom = prenom.toUpperCase().trim();
return students.value.find(
(s) =>
s.nom.toUpperCase().trim() === normNom &&
s.prenom.toUpperCase().trim() === normPrenom,
);
}
async function doImport() {
if (!workbookRef.current || !selectedSheet.value) return;
uploading.value = true;
error.value = null;
importResult.value = null;
try {
const sheet = workbookRef.current.Sheets[selectedSheet.value];
const rows = XLSX.utils.sheet_to_json<(string | number | null)[]>(sheet, {
header: 1,
});
const moduleCols = columns.value.filter((c) => c.type === "module");
let added = 0;
let modified = 0;
let ignored = 0;
let errors = 0;
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`,
});
continue;
}
// 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`,
});
}
}
}
importResult.value = { added, modified, ignored, errors, details };
} catch {
error.value = "Erreur lors de l'import.";
} finally {
uploading.value = false;
}
}
function downloadTemplate() {
globalThis.open("/templates/modele_notes.xlsx", "_blank");
}
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 (
<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 .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)}
/>
)}
{/* 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">
<button
type="button"
class="btn btn-primary"
onClick={doImport}
disabled={!file.value || uploading.value ||
columns.value.filter((c) => c.type === "module").length === 0}
>
{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 Notes
</button>
</div>
<p class="upload-format">
Format : <strong>Nom</strong> | <strong>Prenom</strong> |{" "}
<strong>CODE - Module</strong> (colonnes notes){" "}
les colonnes UE et MALUS sont auto-detectees
</p>
</div>
);
}
@@ -0,0 +1,587 @@
import { useEffect, useState } from "preact/hooks";
type Student = {
numEtud: number;
nom: string;
prenom: string;
idPromo: string;
};
type UE = { id: number; nom: string };
type UEModule = {
idModule: string;
idUE: number;
idPromo: string;
coeff: number;
};
type Module = { id: string; nom: string };
type Note = {
numEtud: number;
idModule: string;
note: number;
noteSession2: number | null;
};
type Ajustement = {
numEtud: number;
idUE: number;
valeur: number;
malus: number;
};
type Props = { numEtud: number };
function fmt(n: number): string {
return `${Math.round(n * 10) / 10}/20`;
}
function noteClass(n: number): string {
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) {
const [student, setStudent] = useState<Student | null>(null);
const [ueList, setUeList] = useState<UE[]>([]);
const [ueModules, setUeModules] = useState<UEModule[]>([]);
const [moduleMap, setModuleMap] = useState<Map<string, string>>(new Map());
const [noteMap, setNoteMap] = useState<Map<string, Note>>(new Map());
const [ajustements, setAjustements] = useState<Ajustement[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [editingNote, setEditingNote] = useState<
{ idModule: string; field: "note" | "noteSession2"; value: string } | null
>(null);
const [ajustInputs, setAjustInputs] = useState<
Record<number, { valeur: string; malus: string }>
>({});
async function load() {
try {
const sRes = await fetch(`/students/api/students/${numEtud}`);
if (!sRes.ok) throw new Error("Eleve introuvable");
const s: Student = await sRes.json();
setStudent(s);
const [uesRes, umRes, mRes, notesRes, ajustRes] = await Promise.all([
fetch("/admin/api/ues"),
fetch(
`/admin/api/ue-modules?idPromo=${encodeURIComponent(s.idPromo)}`,
),
fetch("/admin/api/modules"),
fetch(`/notes/api/notes?numEtud=${numEtud}`),
fetch(`/notes/api/ajustements?numEtud=${numEtud}`),
]);
if (uesRes.ok) setUeList(await uesRes.json());
if (umRes.ok) setUeModules(await umRes.json());
if (mRes.ok) {
const mods: Module[] = await mRes.json();
setModuleMap(new Map(mods.map((m) => [m.id, m.nom])));
}
if (notesRes.ok) {
const ns: Note[] = await notesRes.json();
setNoteMap(new Map(ns.map((n) => [n.idModule, n])));
}
if (ajustRes.ok) {
const aj: Ajustement[] = await ajustRes.json();
setAjustements(aj);
const inputs: Record<number, { valeur: string; malus: string }> = {};
for (const a of aj) {
inputs[a.idUE] = {
valeur: String(a.valeur),
malus: String(a.malus),
};
}
setAjustInputs(inputs);
}
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
load();
}, [numEtud]);
function calcAvg(ueMods: UEModule[]): number | null {
let total = 0,
coeff = 0;
for (const um of ueMods) {
const n = noteMap.get(um.idModule);
if (n === undefined) return null;
const val = effectiveNote(n);
total += val * um.coeff;
coeff += um.coeff;
}
return coeff > 0 ? total / coeff : null;
}
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(",", "."));
if (isNaN(note) || note < 0 || note > 20) {
setEditingNote(null);
return;
}
const existing = noteMap.get(idModule);
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" },
body: JSON.stringify(body),
});
if (res.ok) {
const created: Note = await res.json();
setNoteMap((prev) => new Map(prev).set(idModule, created));
}
}
setEditingNote(null);
}
async function applyAjust(idUE: number) {
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(malus) || malus < 0) return;
const existing = ajustements.find((a) => a.idUE === idUE);
const res = existing
? await fetch(`/notes/api/ajustements/${numEtud}/${idUE}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ valeur: val, malus }),
})
: await fetch("/notes/api/ajustements", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ numEtud, idUE, valeur: val, malus }),
});
if (res.ok) {
const updated: Ajustement = await res.json();
setAjustements((prev) =>
existing
? prev.map((a) => (a.idUE === idUE ? updated : a))
: [...prev, updated]
);
}
}
async function resetAjust(idUE: number) {
const res = await fetch(`/notes/api/ajustements/${numEtud}/${idUE}`, {
method: "DELETE",
});
if (res.ok) {
setAjustements((prev) => prev.filter((a) => a.idUE !== idUE));
setAjustInputs((prev) => {
const c = { ...prev };
delete c[idUE];
return c;
});
}
}
if (loading) {
return (
<div class="page-content">
<p class="state-loading">Chargement...</p>
</div>
);
}
if (error && !student) {
return (
<div class="page-content">
<p class="state-error">{error}</p>
</div>
);
}
if (!student) return null;
return (
<div class="page-content">
<a
class="back-link"
href="/notes/courses"
f-partial="/notes/partials/courses"
>
Retour a la liste
</a>
<h2
class="page-title"
style="border-bottom: none; margin-bottom: 0.5rem"
>
Recap notes {student.prenom} {student.nom}
</h2>
<div class="info-bar" style="margin-bottom: 1.25rem">
<span class="numEtud-chip">{student.numEtud}</span>
<span style="font-weight: 600">
{student.prenom} {student.nom}
</span>
<span class="note-chip note-chip--promo">{student.idPromo}</span>
</div>
{error && <p class="state-error">{error}</p>}
{ueList.length === 0
? (
<p class="state-empty">
Aucune UE configuree pour cette promotion.
</p>
)
: ueList.map((ue) => {
const ueMods = ueModules.filter((um) => um.idUE === ue.id);
const avg = calcAvg(ueMods);
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 (
<div key={ue.id} class="edit-section">
{/* UE header */}
<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>
{avg !== null && (
<span
class={noteClass(avg)}
style="font-size: 0.78rem"
>
Moy. calculee : {fmt(avg)}
</span>
)}
{ajust && (
<span
class="note-chip note-chip--ajust"
style="font-size: 0.78rem"
>
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>
)}
</div>
{/* Module rows */}
{ueMods.length === 0
? (
<p
class="col-dim"
style="font-size: 0.8rem; padding: 0.25rem 0; margin-bottom: 0.75rem"
>
Aucun module associe a cette UE pour cette promotion.
</p>
)
: (
<div style="margin-bottom: 0.75rem">
{ueMods.map((um) => {
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;
return (
<div key={um.idModule} class="note-row">
<span class="note-row-label">
<span class="numEtud-chip note-row-chip">
{um.idModule}
</span>
{nomMod}
</span>
<span class="col-dim note-row-coef">
coef {um.coeff}
</span>
{/* Session 1 note */}
{editingNote?.idModule === um.idModule &&
editingNote.field === "note"
? (
<div style="display: flex; align-items: center; gap: 0.25rem">
<input
class="form-input"
style="width: 5rem; text-align: center; font-size: 0.85rem"
value={editingNote.value}
autoFocus
onInput={(e) =>
setEditingNote({
...editingNote,
value:
(e.target as HTMLInputElement).value,
})}
onKeyDown={(e) => {
if (e.key === "Enter") {
saveNote(
um.idModule,
"note",
editingNote.value,
);
}
if (e.key === "Escape") {
setEditingNote(null);
}
}}
onBlur={() =>
saveNote(
um.idModule,
"note",
editingNote.value,
)}
/>
<span
class="col-dim"
style="font-size: 0.75rem"
>
/20
</span>
</div>
)
: (
<span
class={noteVal !== undefined
? noteClass(noteVal)
: "note-chip note-chip--none"}
style="font-size: 0.78rem; cursor: pointer"
title="S1 — Cliquer pour modifier"
onClick={() =>
setEditingNote({
idModule: um.idModule,
field: "note",
value: noteVal !== undefined
? String(noteVal)
: "",
})}
>
S1:{" "}
{noteVal !== undefined ? fmt(noteVal) : "—/20"}
</span>
)}
{/* Session 2 note */}
{editingNote?.idModule === um.idModule &&
editingNote.field === "noteSession2"
? (
<div style="display: flex; align-items: center; gap: 0.25rem">
<input
class="form-input"
style="width: 5rem; text-align: center; font-size: 0.85rem"
value={editingNote.value}
autoFocus
placeholder="vide = suppr"
onInput={(e) =>
setEditingNote({
...editingNote,
value:
(e.target as HTMLInputElement).value,
})}
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"
>
{fmt(effective!)}
</span>
)}
</div>
);
})}
</div>
)}
{/* Ajustement + Malus */}
<div class="ajust-section">
<p class="ajust-title">Ajustement de la moyenne UE</p>
<p class="ajust-hint">
La valeur remplace la moyenne calculee. Le malus est
soustrait.
</p>
<div style="display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap">
<div style="display: flex; align-items: center; gap: 0.25rem">
<span class="col-dim" style="font-size: 0.8rem">
Val:
</span>
<input
class="form-input"
style="width: 4.5rem; text-align: center"
placeholder="—"
value={ajustInputs[ue.id]?.valeur ?? ""}
onInput={(e) =>
setAjustInputs((prev) => ({
...prev,
[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>
</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
type="button"
class="btn btn-sm btn-primary"
onClick={() => applyAjust(ue.id)}
>
Appliquer
</button>
{ajust && (
<>
<button
type="button"
class="btn btn-sm btn-secondary"
onClick={() => resetAjust(ue.id)}
>
Reinitialiser
</button>
<span
class="col-dim"
style="font-size: 0.75rem; font-family: monospace"
>
Affiche : {fmt(ajust.valeur)}
{ajust.malus > 0
? ` - ${ajust.malus} = ${
fmt(ajust.valeur - ajust.malus)
}`
: ""}
{avg !== null ? ` (calculee : ${fmt(avg)})` : ""}
</span>
</>
)}
</div>
</div>
</div>
);
})}
</div>
);
}
@@ -0,0 +1,249 @@
import { useEffect, useState } from "preact/hooks";
type Note = {
numEtud: number;
idModule: string;
note: number;
noteSession2: number | null;
};
type UE = { id: number; nom: string };
type UEModule = {
idModule: string;
idUE: number;
idPromo: string;
coeff: number;
};
type Module = { id: string; nom: string };
type Ajustement = {
numEtud: number;
idUE: number;
valeur: number;
malus: number;
};
type Props = {
numEtud: number | null;
prenom: string;
};
function scoreClass(score: number | null): string {
if (score === null) return "score-none";
return score >= 10 ? "score-good" : "score-warn";
}
function avgClass(avg: number | null): string {
if (avg === null) return "";
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) {
const [notes, setNotes] = useState<Note[]>([]);
const [ues, setUes] = useState<UE[]>([]);
const [ueModules, setUeModules] = useState<UEModule[]>([]);
const [modules, setModules] = useState<Module[]>([]);
const [ajustements, setAjustements] = useState<Ajustement[]>([]);
const [promos, setPromos] = useState<string[]>([]);
const [activePromo, setActivePromo] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (numEtud === null) {
setLoading(false);
return;
}
async function load() {
try {
const [notesRes, uesRes, ueModRes, modRes, ajRes] = await Promise.all([
fetch(`/notes/api/notes?numEtud=${numEtud}`),
fetch("/admin/api/ues"),
fetch("/admin/api/ue-modules"),
fetch("/admin/api/modules"),
fetch(`/notes/api/ajustements?numEtud=${numEtud}`),
]);
if (!notesRes.ok || !uesRes.ok || !ueModRes.ok) {
throw new Error("Erreur lors du chargement");
}
const [notesData, uesData, ueModData, modData, ajData] = await Promise
.all([
notesRes.json(),
uesRes.json(),
ueModRes.json(),
modRes.ok ? modRes.json() : [],
ajRes.ok ? ajRes.json() : [],
]);
setNotes(notesData);
setUes(uesData);
setUeModules(ueModData);
setModules(modData);
setAjustements(ajData);
const noteModuleIds = new Set(notesData.map((n: Note) => n.idModule));
const relevantPromos = [
...new Set(
ueModData
.filter((um: UEModule) => noteModuleIds.has(um.idModule))
.map((um: UEModule) => um.idPromo),
),
] as string[];
setPromos(relevantPromos);
if (relevantPromos.length > 0) setActivePromo(relevantPromos[0]);
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur inconnue");
} finally {
setLoading(false);
}
}
load();
}, [numEtud]);
if (numEtud === null) {
return (
<div class="page-content">
<p class="state-empty">
Bonjour {prenom}{" "}
aucun dossier etudiant n'est associe a votre compte.
</p>
</div>
);
}
if (loading) {
return (
<div class="page-content">
<p class="state-loading">Chargement...</p>
</div>
);
}
if (error) {
return (
<div class="page-content">
<p class="state-error">{error}</p>
</div>
);
}
const filteredUeModules = activePromo
? ueModules.filter((um) => um.idPromo === activePromo)
: ueModules;
const ueIds = [...new Set(filteredUeModules.map((um) => um.idUE))];
const moduleMap = Object.fromEntries(modules.map((m) => [m.id, m]));
const noteMap = Object.fromEntries(
notes.map((n) => [n.idModule, n]),
);
const ajMap = Object.fromEntries(
ajustements.map((a) => [a.idUE, a]),
);
return (
<div class="page-content">
{promos.length > 1 && (
<div class="tabs">
{promos.map((p) => (
<button
type="button"
key={p}
class={`tab-btn${activePromo === p ? " active" : ""}`}
onClick={() => setActivePromo(p)}
>
{p}
</button>
))}
</div>
)}
{ueIds.length === 0 && (
<p class="state-empty">Aucune note disponible pour cette periode.</p>
)}
{ueIds.map((ueId) => {
const ue = ues.find((u) => u.id === ueId);
if (!ue) return null;
const ueModsForUE = filteredUeModules.filter((um) => um.idUE === ueId);
let weightedSum = 0;
let coveredCoeff = 0;
ueModsForUE.forEach((um) => {
const noteObj = noteMap[um.idModule];
if (noteObj) {
const val = effectiveNote(noteObj);
weightedSum += val * um.coeff;
coveredCoeff += um.coeff;
}
});
const avg = coveredCoeff > 0 ? weightedSum / coveredCoeff : null;
const ajust = ajMap[ueId] ?? null;
// If ajust.valeur exists, it replaces the calculated average
// Then malus is subtracted
let finalAvg: number | null = avg;
if (ajust) {
finalAvg = ajust.valeur;
if (ajust.malus > 0) {
finalAvg = (finalAvg ?? 0) - ajust.malus;
}
}
return (
<div key={ueId} class="ue-card">
<div class="ue-card-header">
<p class="ue-card-title">UE : {ue.nom}</p>
{finalAvg !== null
? (
<p class={`ue-card-avg ${avgClass(finalAvg)}`}>
Moyenne : {finalAvg.toFixed(2)}/20
{ajust && ajust.malus > 0 && (
<span>(malus : -{ajust.malus})</span>
)}
</p>
)
: <p class="ue-card-avg avg-warn">Notes non disponibles</p>}
</div>
{ueModsForUE.map((um) => {
const mod = moduleMap[um.idModule];
const noteObj = noteMap[um.idModule] ?? null;
const effective = noteObj ? effectiveNote(noteObj) : null;
const hasS2 = noteObj?.noteSession2 != null;
return (
<div key={um.idModule} class="ue-module-row">
<span class="ue-module-name">
{mod ? mod.id : um.idModule} {" "}
{mod ? mod.nom : "Module inconnu"} (coef {um.coeff})
</span>
<span class={`score-chip ${scoreClass(effective)}`}>
{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>
</div>
);
})}
</div>
);
})}
</div>
);
}
+6 -4
View File
@@ -4,11 +4,13 @@ const properties: AppProperties = {
name: "PolyNotes",
icon: "school",
pages: {
index: "Homepage",
notes: "Notes",
courses: "Courses management",
index: "Accueil",
notes: "Mes notes",
courses: "Consulter",
import: "Import Notes",
},
adminOnly: ["courses", "students"],
adminOnly: ["courses", "import"],
studentOnly: ["notes"],
hint: "Student grading management",
};
+17 -2
View File
@@ -52,8 +52,12 @@ export const handler: Handlers<null, AuthenticatedState> = {
}
try {
const body: { numEtud: number; idUE: number; valeur: number } =
await request.json();
const body: {
numEtud: number;
idUE: number;
valeur: number;
malus?: number;
} = await request.json();
if (!body.numEtud || !body.idUE || body.valeur === undefined) {
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
.insert(ajustements)
.values({
numEtud: body.numEtud,
idUE: body.idUE,
valeur: body.valeur,
malus: body.malus ?? 0,
})
.returning();
@@ -2,14 +2,15 @@ import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts";
import { ajustements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2";
import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ajustement introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
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> = {
// #50 GET /ajustements/{numEtud}/{idUE}
@@ -18,7 +19,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const numEtud = Number(context.params.numEtud);
@@ -31,10 +32,10 @@ export const handler: Handlers<null, AuthenticatedState> = {
const ajustement = await db
.select()
.from(ajustements)
.where(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE)))
.then((rows) => rows[0] ?? null);
if (!ajustement) return NOT_FOUND;
if (!ajustement) return NOT_FOUND();
return new Response(JSON.stringify(ajustement), {
headers: { "content-type": "application/json" },
@@ -47,7 +48,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const numEtud = Number(context.params.numEtud);
@@ -57,7 +58,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
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) {
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
.update(ajustements)
.set({ valeur: body.valeur })
.where(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))
.set(set)
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE)))
.returning();
if (!updated) return NOT_FOUND;
if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" },
@@ -85,7 +101,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const numEtud = Number(context.params.numEtud);
@@ -97,10 +113,10 @@ export const handler: Handlers<null, AuthenticatedState> = {
const [deleted] = await db
.delete(ajustements)
.where(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE)))
.returning();
if (!deleted) return NOT_FOUND;
if (!deleted) return NOT_FOUND();
return new Response(null, { status: 204 });
},
+33 -2
View File
@@ -41,7 +41,7 @@ export const handler: Handlers = {
async POST(request) {
try {
const body = await request.json();
const { note, numEtud, idModule } = body;
const { note, numEtud, idModule, noteSession2 } = body;
if (note === undefined || !numEtud || !idModule) {
return new Response("Champs 'note', 'numEtud' et 'idModule' requis", {
@@ -49,7 +49,38 @@ export const handler: Handlers = {
});
}
const result = await db.insert(notes).values({ note, numEtud, idModule })
if (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 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();
return new Response(JSON.stringify(result[0]), {
@@ -64,13 +64,39 @@ export const handler: Handlers = {
}
const body = await request.json();
const { note } = body;
const { note, noteSession2 } = body;
if (note === undefined) {
return new Response("Champ 'note' manquant", { status: 400 });
if (note === undefined && noteSession2 === undefined) {
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(
eq(notes.numEtud, numEtud),
eq(notes.idModule, idModule),
@@ -0,0 +1,70 @@
// @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 { Handlers } from "$fresh/server.ts";
import { db } from "../../../../../databases/db.ts";
import { notes } from "../../../../../databases/schema.ts";
export const handler: Handlers = {
//# 44 POST /notes/import-xlsx
async POST(request) {
try {
const formData = await request.formData();
const file = formData.get("file");
const idModule = formData.get("idModule");
if (!file || !(file instanceof File)) {
return new Response("Champ 'file' manquant", { status: 400 });
}
if (!idModule || typeof idModule !== "string") {
return new Response("Champ 'idModule' manquant", { status: 400 });
}
const buffer = await file.arrayBuffer();
const workbook = XLSX.read(buffer);
const sheet = workbook.Sheets[workbook.SheetNames[0]];
const rows = XLSX.utils.sheet_to_json(sheet) as {
numEtud: number;
note: number;
noteSession2?: number;
}[];
for (const row of rows) {
const { numEtud, note, noteSession2 } = row;
if (!numEtud || note === undefined) {
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)
.values(values)
.onConflictDoUpdate({
target: [notes.numEtud, notes.idModule],
set,
});
}
return new Response(null, { status: 204 });
} catch (error) {
console.error("Error importing notes:", error);
return new Response("Failed to import notes", { status: 500 });
}
},
};
+12
View File
@@ -0,0 +1,12 @@
import { FreshContext } from "$fresh/server.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import NoteRecap from "../(_islands)/NoteRecap.tsx";
// deno-lint-ignore require-await
export default async function EditionPage(
_request: Request,
context: FreshContext<AuthenticatedState>,
) {
const numEtud = Number(context.params.numEtud);
return <NoteRecap numEtud={numEtud} />;
}
@@ -3,11 +3,12 @@ import {
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/routes/_middleware.ts";
import { State } from "$root/defaults/interfaces.ts";
import AdminConsultNotes from "../../(_islands)/AdminConsultNotes.tsx";
// deno-lint-ignore require-await
async function Courses(_request: Request, context: FreshContext<State>) {
return <h2>Welcome to {context.state.session?.displayName}.</h2>;
async function Courses(_request: Request, _context: FreshContext<State>) {
return <AdminConsultNotes />;
}
export const config = getPartialsConfig();
@@ -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 ImportNotes from "../../(_islands)/ImportNotes.tsx";
// deno-lint-ignore require-await
async function ImportNotesPage(
_request: Request,
_context: FreshContext<State>,
) {
return (
<div class="page-content">
<h2 class="page-title">Importer des Notes</h2>
<ImportNotes />
</div>
);
}
export const config = getPartialsConfig();
export default makePartials(ImportNotesPage);
+45 -3
View File
@@ -3,11 +3,53 @@ import {
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/routes/_middleware.ts";
import { State } from "$root/defaults/interfaces.ts";
// deno-lint-ignore require-await
export async function Index(_request: Request, context: FreshContext<State>) {
return <h2>Welcome to {context.state.session?.displayName}.</h2>;
export async function Index(
_request: Request,
context: FreshContext<State>,
) {
const isEmployee =
(context.state as unknown as { session: Record<string, string> }).session
.eduPersonPrimaryAffiliation === "employee";
return (
<div class="page-content">
<h2 class="page-title">PolyNotes</h2>
<p>
Bienvenue{" "}
<strong>
{(context.state as unknown as { session: Record<string, string> })
.session.displayName}
</strong>
.
</p>
{isEmployee
? (
<p>
Consultez les{" "}
<a href="/notes/courses" f-partial="/notes/partials/courses">
notes des élèves
</a>{" "}
ou gérez les{" "}
<a href="/notes/ues" f-partial="/notes/partials/ues">
UEs
</a>
.
</p>
)
: (
<p>
Consultez vos{" "}
<a href="/notes/notes" f-partial="/notes/partials/notes">
notes
</a>
.
</p>
)}
</div>
);
}
export const config = getPartialsConfig();
+49 -5
View File
@@ -1,13 +1,57 @@
import { FreshContext } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts";
import { students } from "$root/databases/schema.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2";
import {
getPartialsConfig,
makePartials,
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/routes/_middleware.ts";
import { CasContent, State } from "$root/defaults/interfaces.ts";
import NotesView from "../(_islands)/NotesView.tsx";
// deno-lint-ignore require-await
async function Notes(_request: Request, context: FreshContext<State>) {
return <h2>Welcome to {context.state.session?.displayName}.</h2>;
async function Notes(
_request: Request,
context: FreshContext<State>,
) {
const session = (context.state as unknown as { session: CasContent }).session;
let numEtud: number | null = null;
try {
if (session.eduPersonPrimaryAffiliation === "student") {
// Students: uid is "<letter>21212006" in AMU CAS — strip non-digit prefix
const etudId = parseInt(session.uid.replace(/^\D+/, ""), 10);
if (!isNaN(etudId)) {
const student = await db
.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 {
// DB lookup failed — island will show fallback message
}
return (
<NotesView
numEtud={numEtud}
prenom={session.givenName || session.displayName}
/>
);
}
export const config = getPartialsConfig();
+12
View File
@@ -0,0 +1,12 @@
import { FreshContext } from "$fresh/server.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import NoteRecap from "../(_islands)/NoteRecap.tsx";
// deno-lint-ignore require-await
export default async function RecapPage(
_request: Request,
context: FreshContext<AuthenticatedState>,
) {
const numEtud = Number(context.params.numEtud);
return <NoteRecap numEtud={numEtud} />;
}
@@ -1,45 +1,313 @@
import { useEffect, useState } from "preact/hooks";
import Promotion from "$root/routes/(apps)/students/(_components)/Promotion.tsx";
type SingleUserResponse = { promo: Promotion; student: Student };
type ManyUsersResponse = { promos: Promotion[]; students: Student[] };
type APIResponse = SingleUserResponse | ManyUsersResponse;
type Student = {
numEtud: number;
nom: string;
prenom: string;
idPromo: string;
};
type Promotion = { id: string; annee: string };
export default function ConsultStudents() {
const [data, setData] = useState<APIResponse | null>(null);
const [students, setStudents] = useState<Student[]>([]);
const [promos, setPromos] = useState<Promotion[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [filterPromo, setFilterPromo] = 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() {
try {
const [sRes, pRes] = await Promise.all([
fetch("/students/api/students"),
fetch("/students/api/promotions"),
]);
if (!sRes.ok) throw new Error("Impossible de charger les élèves");
setStudents(await sRes.json());
if (pRes.ok) setPromos(await pRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
useEffect(() => {
const fetchData = async () => {
const response = await fetch("/students/api/students");
if (!response.ok) {
setError("Failed to load data. Please try again later.");
}
const result: APIResponse = await response.json();
setData(result);
};
fetchData();
load();
}, []);
async function deleteStudent(numEtud: number) {
if (!confirm(`Supprimer l'élève #${numEtud} ?`)) return;
try {
const res = await fetch(`/students/api/students/${numEtud}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Suppression échouée");
await load();
setSelected((prev) => {
const next = new Set(prev);
next.delete(numEtud);
return next;
});
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
const filtered = students.filter((s) => {
const matchPromo = !filterPromo || s.idPromo === filterPromo;
const matchNom = !filterNom ||
`${s.nom} ${s.prenom}`.toLowerCase().includes(filterNom.toLowerCase());
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 (
<>
{error && <p className="error">{error}</p>}
{data && ((Object.hasOwn(data, "student"))
? (
<Promotion
students={[(data as SingleUserResponse).student]}
promo={(data as SingleUserResponse).promo}
/>
)
: (data as ManyUsersResponse).promos.map((promo) => (
<Promotion
students={(data as ManyUsersResponse).students}
promo={promo}
/>
)))}
</>
<div class="page-content">
<h2 class="page-title">Gestion des Élèves</h2>
{error && <p class="state-error">{error}</p>}
<div class="toolbar">
<a
class="btn btn-primary"
href="/students/upload"
f-partial="/students/partials/upload"
style="margin-left: auto"
>
Importer xlsx
</a>
</div>
<div class="filters">
<select
class="filter-select"
value={filterPromo}
onChange={(e) =>
setFilterPromo((e.target as HTMLSelectElement).value)}
>
<option value="">Toutes les promos</option>
{promos.map((p) => (
<option key={p.id} value={p.id}>{p.id} {p.annee}</option>
))}
</select>
<input
class="filter-input"
placeholder="Rechercher par nom…"
value={filterNom}
onInput={(e) => setFilterNom((e.target as HTMLInputElement).value)}
/>
</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
? <p class="state-loading">Chargement</p>
: (
<div class="data-table-wrap">
<table class="data-table">
<thead>
<tr>
<th style="width: 2.5rem">
<input
type="checkbox"
checked={allFilteredSelected && filtered.length > 0}
onChange={toggleAll}
/>
</th>
<th>N° étud.</th>
<th>Nom</th>
<th>Prénom</th>
<th>Promo</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{filtered.length === 0
? (
<tr>
<td colspan={6} class="state-empty">
Aucun élève trouvé
</td>
</tr>
)
: filtered.map((s) => (
<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>{s.nom}</td>
<td>{s.prenom}</td>
<td>{s.idPromo}</td>
<td>
<div class="col-actions">
<a
class="btn btn-sm btn-secondary"
href={`/students/edit/${s.numEtud}`}
f-client-nav={false}
>
<svg
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<path d="M17 3a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
</svg>
</a>
<button
type="button"
class="btn btn-sm btn-danger"
onClick={() => deleteStudent(s.numEtud)}
>
<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>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,239 @@
import { useEffect, useState } from "preact/hooks";
type Student = {
numEtud: number;
nom: string;
prenom: string;
idPromo: string;
};
type Promo = { id: string; annee: string };
type Module = { id: string; nom: string };
type Props = { numEtud: number };
function anneeLabel(idPromo: string): string {
const m = idPromo.match(/^(\d+)A/);
if (!m) return "";
const n = m[1];
if (n === "3") return "3ème année";
if (n === "4") return "4ème année";
if (n === "5") return "5ème année";
return `${n}ème année`;
}
export default function EditStudents({ numEtud }: Props) {
const [student, setStudent] = useState<Student | null>(null);
const [promos, setPromos] = useState<Promo[]>([]);
const [_modules, setModules] = useState<Module[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [saveMsg, setSaveMsg] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
// Edit form state
const [nom, setNom] = useState("");
const [prenom, setPrenom] = useState("");
const [idPromo, setIdPromo] = useState("");
useEffect(() => {
async function load() {
try {
const [sRes, pRes, mRes] = await Promise.all([
fetch(`/students/api/students/${numEtud}`),
fetch("/students/api/promotions"),
fetch("/admin/api/modules"),
]);
if (!sRes.ok) throw new Error("Élève introuvable");
const s: Student = await sRes.json();
setStudent(s);
setNom(s.nom);
setPrenom(s.prenom);
setIdPromo(s.idPromo);
if (pRes.ok) setPromos(await pRes.json());
if (mRes.ok) setModules(await mRes.json());
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setLoading(false);
}
}
load();
}, [numEtud]);
async function saveInfos() {
if (!student) return;
setSaving(true);
setSaveMsg(null);
try {
const res = await fetch(`/students/api/students/${numEtud}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
nom: nom.trim(),
prenom: prenom.trim(),
idPromo,
}),
});
if (!res.ok) throw new Error("Modification échouée");
const updated: Student = await res.json();
setStudent(updated);
setSaveMsg("Informations enregistrées.");
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
} finally {
setSaving(false);
}
}
async function deleteStudent() {
if (!confirm(`Supprimer définitivement l'élève #${numEtud} ?`)) return;
try {
const res = await fetch(`/students/api/students/${numEtud}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("Suppression échouée");
globalThis.location.href = "/students/consult";
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
}
if (loading) {
return (
<div class="page-content">
<p class="state-loading">Chargement</p>
</div>
);
}
if (error && !student) {
return (
<div class="page-content">
<p class="state-error">{error}</p>
</div>
);
}
if (!student) return null;
return (
<div class="page-content">
<a
class="back-link"
href="/students/consult"
f-partial="/students/partials/consult"
>
Retour à la liste
</a>
<h2 class="page-title" style="border-bottom: none; margin-bottom: 0.5rem">
Édition {student.prenom} {student.nom}
</h2>
{/* Info bar */}
<div class="info-bar">
<span class="numEtud-chip">{student.numEtud}</span>
<span>{student.idPromo}</span>
<span class="col-dim">{anneeLabel(student.idPromo)}</span>
</div>
{error && <p class="state-error">{error}</p>}
{saveMsg && (
<p style="font-size: 0.82rem; color: light-dark(var(--light-accent-color), var(--dark-accent-color)); margin-bottom: 0.5rem">
{saveMsg}
</p>
)}
{/* Section 1: Informations générales */}
<div class="edit-section">
<p class="edit-section-title">Informations générales</p>
<div class="form-grid">
<div class="form-field">
<label>Nom</label>
<input
class="form-input"
value={nom}
onInput={(e) => setNom((e.target as HTMLInputElement).value)}
/>
</div>
<div class="form-field">
<label>Prénom</label>
<input
class="form-input"
value={prenom}
onInput={(e) => setPrenom((e.target as HTMLInputElement).value)}
/>
</div>
<div class="form-field">
<label>N° Étudiant</label>
<input
class="form-input"
value={student.numEtud}
disabled
style="opacity: 0.6"
/>
</div>
<div class="form-field">
<label>Promo</label>
<select
class="filter-select"
value={idPromo}
onChange={(e) =>
setIdPromo((e.target as HTMLSelectElement).value)}
style="min-width: 0"
>
{promos.map((p) => <option key={p.id} value={p.id}>{p.id}
</option>)}
</select>
</div>
</div>
<div style="display: flex; gap: 0.5rem; justify-content: space-between; flex-wrap: wrap">
<button
type="button"
class="btn btn-primary"
onClick={saveInfos}
disabled={saving}
>
{saving ? "…" : "Enregistrer infos"}
</button>
<button
type="button"
class="btn btn-danger"
onClick={deleteStudent}
>
Supprimer l'élève
</button>
</div>
</div>
{/* Section 2: Spécialisations */}
<div class="edit-section">
<p class="edit-section-title">Spécialisations</p>
<p
class="state-empty"
style="padding: 1rem 0; text-align: left"
>
Fonctionnalité non disponible (endpoint non implémenté).
</p>
</div>
{/* Section 3: Notes lecture seule */}
<div class="edit-section">
<p class="edit-section-title">Notes (lecture seule)</p>
<div style="display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap">
<span class="col-dim" style="font-size: 0.82rem">
Voir le récap complet des notes et moyennes de cet étudiant
</span>
<a
class="btn btn-secondary"
href={`/notes/recap/${numEtud}`}
f-client-nav={false}
>
Récap notes
</a>
</div>
</div>
</div>
);
}
@@ -1,111 +1,175 @@
// @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 { Signal, useSignal } from "@preact/signals";
import { useRef } from "preact/hooks";
import { useSignal } from "@preact/signals";
import ImportResultPopup, {
type ImportDetail,
type ImportResult,
} from "$root/defaults/ImportResultPopup.tsx";
/**
* Create a new handler for file change that displays
* messages in statusMessage and gets file data in fileData.
* @param statusMessage The status message signal.
* @param fileData The file data signal.
* @returns The file change handler.
*/
function getFileChangeHandler(
statusMessage: Signal<string>,
fileData: Signal<File | null>,
): (event: Event) => void {
/**
* Handle file change.
* @param event The file change event.
*/
return (event: Event) => {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
fileData.value = input.files[0];
statusMessage.value = `File selected: ${input.files[0].name}`;
} else {
fileData.value = null;
statusMessage.value = "No file selected";
}
};
}
export default function UploadStudents() {
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 inputRef = useRef<HTMLInputElement>(null);
/**
* Create a new handler that sends data file to server.
* @param statusMessage The status message signal.
* @param fileData The file data signal.
* @returns The file confirmation handler.
*/
function getUploadConfirmationFunction(
statusMessage: Signal<string>,
fileData: Signal<File | null>,
): () => void {
/**
* Add students to database.
* @returns Confirm upload of students.
*/
return () => {
if (!fileData.value) {
statusMessage.value = "Please select a file before confirming upload.";
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;
}
const reader = new FileReader();
function onDragOver(e: DragEvent) {
e.preventDefault();
dragging.value = true;
}
/**
* Send all data to the server.
* @param event The finished progress event.
*/
reader.onload = async (event: ProgressEvent<FileReader>) => {
const arrayBuffer = event.target!.result as ArrayBuffer;
function onDragLeave() {
dragging.value = false;
}
function onDrop(e: DragEvent) {
e.preventDefault();
dragging.value = false;
const f = e.dataTransfer?.files?.[0];
if (f) pickFile(f);
}
function onInputChange(e: Event) {
const f = (e.target as HTMLInputElement).files?.[0];
if (f) pickFile(f);
}
async function doImport() {
if (!file.value) return;
uploading.value = true;
error.value = null;
importResult.value = null;
try {
const arrayBuffer = await file.value.arrayBuffer();
const workbook = XLSX.read(arrayBuffer, { type: "array" });
let allOK = true;
let added = 0;
let errors = 0;
const details: ImportDetail[] = [];
for (const sheetName of workbook.SheetNames) {
const sheet = workbook.Sheets[sheetName];
const data = XLSX.utils.sheet_to_json(sheet, {
header: ["userId", "lastName", "firstName", "mail"],
range: 1,
const rows = XLSX.utils.sheet_to_json<{
nom: string;
prenom: string;
numEtud: number;
idPromo: string;
}>(sheet, {
header: ["nom", "prenom", "numEtud", "idPromo"],
range: 2,
});
const response = await fetch("/students/api/students", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ promoName: sheetName, data }),
});
if (!response.ok) {
allOK = false;
for (const row of rows) {
const res = await fetch("/students/api/students", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(row),
});
if (res.ok) {
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"}`,
});
}
}
}
statusMessage.value = allOK
? "Failed to insert all data."
: "Data uploaded and inserted successfully!";
};
importResult.value = {
added,
modified: 0,
ignored: 0,
errors,
details,
};
} catch {
error.value = "Erreur lors de la lecture du fichier.";
} finally {
uploading.value = false;
}
}
/**
* Display error message if any.
*/
reader.onerror = () => {
statusMessage.value = "Error reading the file.";
};
reader.readAsArrayBuffer(fileData.value);
};
}
export default function UploadStudents() {
const statusMessage = useSignal<string>("");
const fileData = useSignal<File | null>(null);
const handleFileChange = getFileChangeHandler(statusMessage, fileData);
const confirmUpload = getUploadConfirmationFunction(statusMessage, fileData);
function downloadTemplate() {
globalThis.open("/templates/modele_etudiants.xlsx", "_blank");
}
return (
<>
<input type="file" accept=".xlsx, .xls" onChange={handleFileChange} />
<button type="button" onClick={confirmUpload}>Confirm Upload</button>
<p>{statusMessage.value}</p>
</>
<div>
<input
ref={inputRef}
type="file"
accept=".xlsx,.xls"
style="display:none"
onChange={onInputChange}
/>
<div
class={`drop-zone${dragging.value ? " dragging" : ""}`}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
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 .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)}
/>
)}
<div class="upload-actions">
<button
type="button"
class="btn btn-primary"
onClick={doImport}
disabled={!file.value || uploading.value}
>
{uploading.value ? "…" : "⊕ Importer"}
</button>
<button
type="button"
class="btn btn-secondary"
onClick={downloadTemplate}
>
Télécharger Modèle
</button>
</div>
<p class="upload-format">
Format : <strong>Nom</strong> | <strong>Prenom</strong> |{" "}
<strong>Numero-etudiant</strong> | <strong>Promotion</strong>
</p>
</div>
);
}
+4 -4
View File
@@ -4,11 +4,11 @@ const properties: AppProperties = {
name: "Students",
icon: "badge",
pages: {
index: "Homepage",
upload: "Upload students",
consult: "Consult students",
index: "Accueil",
consult: "Élèves",
upload: "Import xlsx",
},
adminOnly: ["upload", "consult"],
adminOnly: ["consult", "upload"],
hint: "Create students promotion and see informations",
};
@@ -1,15 +1,25 @@
import { FreshContext, Handlers } from "$fresh/server.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 { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
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> = {
// #15 GET /promotions/{idPromo}
@@ -18,7 +28,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const promo = await db
@@ -27,7 +37,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(promotions.id, context.params.idPromo))
.then((rows) => rows[0] ?? null);
if (!promo) return NOT_FOUND;
if (!promo) return NOT_FOUND();
return new Response(JSON.stringify(promo), {
headers: { "content-type": "application/json" },
@@ -40,7 +50,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const body: { annee: string } = await request.json();
@@ -51,7 +61,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(promotions.id, context.params.idPromo))
.returning();
if (!updated) return NOT_FOUND;
if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" },
@@ -59,20 +69,104 @@ export const handler: Handlers<null, AuthenticatedState> = {
},
// #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(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const [deleted] = await db
.delete(promotions)
.where(eq(promotions.id, context.params.idPromo))
.returning();
const idPromo = context.params.idPromo;
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 });
},
+14 -2
View File
@@ -44,13 +44,25 @@ export const handler: Handlers<null, AuthenticatedState> = {
idPromo: string;
} = await request.json();
if (!body.nom || !body.prenom || !body.idPromo) {
if (!body.nom || !body.prenom) {
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
.insert(students)
.values({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo })
.values(values)
.returning();
return new Response(JSON.stringify(created), {
@@ -1,15 +1,21 @@
import { FreshContext, Handlers } from "$fresh/server.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 { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = new Response(
JSON.stringify({ error: "Ressource introuvable" }),
{ status: 404, headers: { "content-type": "application/json" } },
);
const NOT_FOUND = () =>
new Response(
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> = {
// #10 GET /students/{numEtud}
@@ -18,7 +24,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const numEtud = Number(context.params.numEtud);
@@ -28,7 +34,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(students.numEtud, numEtud))
.then((rows) => rows[0] ?? null);
if (!student) return NOT_FOUND;
if (!student) return NOT_FOUND();
return new Response(JSON.stringify(student), {
headers: { "content-type": "application/json" },
@@ -41,20 +47,32 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
const numEtud = Number(context.params.numEtud);
const body: { nom: string; prenom: string; idPromo: string } = await request
.json();
const body: { nom?: string; prenom?: string; idPromo?: string } =
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
.update(students)
.set({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo })
.set(set)
.where(eq(students.numEtud, numEtud))
.returning();
if (!updated) return NOT_FOUND;
if (!updated) return NOT_FOUND();
return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" },
@@ -62,21 +80,31 @@ export const handler: Handlers<null, AuthenticatedState> = {
},
// #12 DELETE /students/{numEtud}
// Cascade: deletes notes, ajustements, mobility for this student.
async DELETE(
_request: Request,
context: FreshContext<AuthenticatedState>,
): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN;
return FORBIDDEN();
}
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 });
},
+12
View File
@@ -0,0 +1,12 @@
import { FreshContext } from "$fresh/server.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import EditStudents from "../(_islands)/EditStudents.tsx";
// deno-lint-ignore require-await
export default async function EditPage(
_request: Request,
context: FreshContext<AuthenticatedState>,
) {
const numEtud = Number(context.params.numEtud);
return <EditStudents numEtud={numEtud} />;
}
@@ -8,12 +8,7 @@ import { State } from "$root/defaults/interfaces.ts";
// deno-lint-ignore require-await
async function Students(_request: Request, _context: FreshContext<State>) {
return (
<>
<h2>Consult students</h2>
<ConsultStudents />
</>
);
return <ConsultStudents />;
}
export const config = getPartialsConfig();
@@ -9,10 +9,10 @@ import { State } from "$root/defaults/interfaces.ts";
// deno-lint-ignore require-await
async function Students(_request: Request, _context: FreshContext<State>) {
return (
<>
<h2>Upload Students</h2>
<div class="page-content">
<h2 class="page-title">Importer des Élèves</h2>
<UploadStudents />
</>
</div>
);
}
+35 -7
View File
@@ -4,16 +4,44 @@ import {
} from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts";
import SelfPortrait from "$root/routes/(apps)/students/(_components)/SelfPortrait.tsx";
// deno-lint-ignore require-await
export async function Index(_request: Request, context: FreshContext<State>) {
export async function Index(
_request: Request,
context: FreshContext<State>,
) {
const isEmployee =
(context.state as unknown as { session: Record<string, string> }).session
.eduPersonPrimaryAffiliation === "employee";
return (
<>
<h2>Welcome {context.state.session?.givenName}!</h2>
<h3>Your amU identity</h3>
<SelfPortrait self={context.state.session!} />
</>
<div class="page-content">
<h2 class="page-title">Étudiants</h2>
<p>
Bienvenue{" "}
<strong>
{(context.state as unknown as { session: Record<string, string> })
.session.displayName}
</strong>
.
</p>
{isEmployee && (
<p>
Consultez la{" "}
<a href="/students/consult" f-partial="/students/partials/consult">
liste des élèves
</a>{" "}
ou gérez les{" "}
<a
href="/students/promotions"
f-partial="/students/partials/promotions"
>
promotions
</a>
.
</p>
)}
</div>
);
}
+3 -2
View File
@@ -26,8 +26,9 @@ export default async function App(
/>
<link rel="stylesheet" href="/styles/main.css" />
<link rel="stylesheet" href="/styles/app.css" />
<link rel="stylesheet" href="styles/app-cards.css" />
<link rel="stylesheet" href="styles/students.css" />
<link rel="stylesheet" href="/styles/app-cards.css" />
<link rel="stylesheet" href="/styles/students.css" />
<link rel="stylesheet" href="/styles/ui.css" />
</head>
<body f-client-nav>
<Header link={link} />
+1
View File
@@ -10,6 +10,7 @@ const PUBLIC_ROUTES = [
"/about",
"/partials/about",
"/contact",
"/dev-login",
];
const jwtKeyCache: Record<string, string> = {};
+80
View File
@@ -0,0 +1,80 @@
import { FreshContext, Handlers } from "$fresh/server.ts";
import { CasContent, LoginJWT, State } from "$root/defaults/interfaces.ts";
import { createJwt } from "@popov/jwt";
import { setCookie } from "$std/http/cookie.ts";
import { getKey } from "$root/routes/_middleware.ts";
function makeFakeUser(
role: "employee" | "student",
numEtud?: string,
): CasContent {
if (role === "student" && numEtud) {
return {
amuCampus: "local",
amuComposante: "local",
amuDateValidation: "",
coGroup: "",
eduPersonPrimaryAffiliation: "student",
eduPersonPrincipalName: `${numEtud}@local`,
mail: `${numEtud}@local`,
displayName: `Etudiant ${numEtud}`,
givenName: "",
memberOf: [],
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> = {
async GET(request: Request, _context: FreshContext<State, null>) {
if (Deno.env.get("LOCAL") !== "true") {
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 payload: LoginJWT = {
iss: "PolyMPR",
iat: now,
exp: now + 0xe10,
aud: "PolyMPR",
user,
};
const token = await createJwt(payload, getKey(user.uid));
const headers = new Headers();
setCookie(headers, { name: "sessionToken", value: token });
headers.set("Location", "/apps");
return new Response(null, { status: 302, headers });
},
};
+2
View File
@@ -45,6 +45,8 @@ function createUserJWT(casResponse: CasResponse): Promise<string> {
}
});
console.log(fullUserInfos);
const now = Math.floor(Date.now() / 1000);
const payload: LoginJWT = {
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}`);
}
}
}
}
+4
View File
@@ -29,6 +29,10 @@
font-family: var(--font-family-text);
}
html {
font-size: 130%; /* scale up from browser default 16px → ~20.8px */
}
html, body {
margin: 0;
padding: 0;
+1203
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
+349
View File
@@ -0,0 +1,349 @@
// E2E tests for /ajustements endpoints — handler + real DB
import { assertEquals, assertExists } from "@std/assert";
import {
makeContextWithAffiliation,
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedAjustements,
seedPromotions,
seedStudents,
seedUes,
truncateAll,
} from "../helpers/db_integration.ts";
import { handler as ajustementsHandler } from "$apps/notes/api/ajustements.ts";
import { handler as ajustementHandler } from "$apps/notes/api/ajustements/[numEtud]/[idUE].ts";
import { ajustements as ajustementsTable } from "$root/databases/schema.ts";
import { testDb } from "../helpers/db_integration.ts";
// --- GET /ajustements ---
Deno.test({
name: "e2e ajustements: GET /ajustements returns all",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Dupont",
prenom: "Jean",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
await seedAjustements([{ numEtud: s.numEtud, idUE: ue.id, valeur: 13.0 }]);
const res = await ajustementsHandler.GET!(
makeGetRequest("/ajustements"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 1);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: GET /ajustements?numEtud filters by student",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s1] = await seedStudents([{
nom: "Dupont",
prenom: "Jean",
idPromo: "P1",
}]);
const [s2] = await seedStudents([{
nom: "Martin",
prenom: "Alice",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
await seedAjustements([
{ numEtud: s1.numEtud, idUE: ue.id, valeur: 13.0 },
{ numEtud: s2.numEtud, idUE: ue.id, valeur: 15.0 },
]);
const res = await ajustementsHandler.GET!(
makeGetRequest("/ajustements", { numEtud: String(s1.numEtud) }),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 1);
assertEquals(body[0].numEtud, s1.numEtud);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: GET /ajustements?numEtud=NaN returns 400",
async fn() {
await truncateAll();
const res = await ajustementsHandler.GET!(
makeGetRequest("/ajustements", { numEtud: "abc" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /ajustements ---
Deno.test({
name:
"e2e ajustements: POST /ajustements creates ajustement (201) as employee",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Leroy",
prenom: "Paul",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
const res = await ajustementsHandler.POST!(
makeJsonRequest("/ajustements", "POST", {
numEtud: s.numEtud,
idUE: ue.id,
valeur: 14.5,
}),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertExists(body.numEtud);
assertEquals(body.valeur, 14.5);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: POST /ajustements 403 for non-employee",
async fn() {
await truncateAll();
const res = await ajustementsHandler.POST!(
makeJsonRequest("/ajustements", "POST", {
numEtud: 1,
idUE: 1,
valeur: 10.0,
}),
makeContextWithAffiliation("student"),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: POST /ajustements 400 on missing fields",
async fn() {
await truncateAll();
const res = await ajustementsHandler.POST!(
makeJsonRequest("/ajustements", "POST", { numEtud: 12345 }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /ajustements/:numEtud/:idUE ---
Deno.test({
name:
"e2e ajustements: GET /ajustements/:numEtud/:idUE returns correct ajustement (employee)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s1, s2] = await seedStudents([
{ nom: "Bernard", prenom: "Lucie", idPromo: "P1" },
{ nom: "Dupont", prenom: "Jean", idPromo: "P1" },
]);
const [ue1, ue2] = await seedUes([{ nom: "UE Maths" }, { nom: "UE Info" }]);
// Plusieurs lignes partageant numEtud=s1 — le handler doit discriminer par idUE
await seedAjustements([
{ numEtud: s1.numEtud, idUE: ue1.id, valeur: 16.0 },
{ numEtud: s1.numEtud, idUE: ue2.id, valeur: 8.0 },
{ numEtud: s2.numEtud, idUE: ue1.id, valeur: 12.0 },
]);
const res = await ajustementHandler.GET!(
makeGetRequest(`/ajustements/${s1.numEtud}/${ue1.id}`),
makeEmployeeContext({
numEtud: String(s1.numEtud),
idUE: String(ue1.id),
}),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.valeur, 16.0);
assertEquals(body.numEtud, s1.numEtud);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: GET /ajustements/:numEtud/:idUE 403 for non-employee",
async fn() {
await truncateAll();
const res = await ajustementHandler.GET!(
makeGetRequest("/ajustements/1/1"),
makeContextWithAffiliation("student", { numEtud: "1", idUE: "1" }),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: GET /ajustements/:numEtud/:idUE 404 when not found",
async fn() {
await truncateAll();
const res = await ajustementHandler.GET!(
makeGetRequest("/ajustements/99999/99"),
makeEmployeeContext({ numEtud: "99999", idUE: "99" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /ajustements/:numEtud/:idUE ---
Deno.test({
name:
"e2e ajustements: PUT /ajustements/:numEtud/:idUE updates only targeted row (employee)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Thomas",
prenom: "Eva",
idPromo: "P1",
}]);
const [ue1, ue2] = await seedUes([{ nom: "UE Physique" }, {
nom: "UE Chimie",
}]);
// Deux ajustements pour le même étudiant — seul ue1 doit être modifié
await seedAjustements([
{ numEtud: s.numEtud, idUE: ue1.id, valeur: 10.0 },
{ numEtud: s.numEtud, idUE: ue2.id, valeur: 7.0 },
]);
const res = await ajustementHandler.PUT!(
makeJsonRequest(`/ajustements/${s.numEtud}/${ue1.id}`, "PUT", {
valeur: 19.0,
}),
makeEmployeeContext({ numEtud: String(s.numEtud), idUE: String(ue1.id) }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.valeur, 19.0);
// ue2 doit rester intact
const unchanged = await testDb.select().from(ajustementsTable);
const ue2Row = unchanged.find((a) => a.idUE === ue2.id);
assertEquals(ue2Row?.valeur, 7.0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: PUT /ajustements/:numEtud/:idUE 403 for non-employee",
async fn() {
await truncateAll();
const res = await ajustementHandler.PUT!(
makeJsonRequest("/ajustements/1/1", "PUT", { valeur: 10.0 }),
makeContextWithAffiliation("student", { numEtud: "1", idUE: "1" }),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ajustements: PUT /ajustements/:numEtud/:idUE 404 when not found",
async fn() {
await truncateAll();
const res = await ajustementHandler.PUT!(
makeJsonRequest("/ajustements/99999/99", "PUT", { valeur: 10.0 }),
makeEmployeeContext({ numEtud: "99999", idUE: "99" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /ajustements/:numEtud/:idUE ---
Deno.test({
name:
"e2e ajustements: DELETE /ajustements/:numEtud/:idUE deletes only targeted row (employee)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Petit",
prenom: "Hugo",
idPromo: "P1",
}]);
const [ue1, ue2] = await seedUes([{ nom: "UE Chimie" }, { nom: "UE Bio" }]);
// Deux ajustements pour le même étudiant — seul ue1 doit être supprimé
await seedAjustements([
{ numEtud: s.numEtud, idUE: ue1.id, valeur: 11.0 },
{ numEtud: s.numEtud, idUE: ue2.id, valeur: 14.0 },
]);
const res = await ajustementHandler.DELETE!(
makeGetRequest(`/ajustements/${s.numEtud}/${ue1.id}`),
makeEmployeeContext({ numEtud: String(s.numEtud), idUE: String(ue1.id) }),
);
assertEquals(res.status, 204);
// ue2 doit toujours exister
const remaining = await testDb.select().from(ajustementsTable);
assertEquals(remaining.length, 1);
assertEquals(remaining[0].idUE, ue2.id);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ajustements: DELETE /ajustements/:numEtud/:idUE 403 for non-employee",
async fn() {
await truncateAll();
const res = await ajustementHandler.DELETE!(
makeGetRequest("/ajustements/1/1"),
makeContextWithAffiliation("student", { numEtud: "1", idUE: "1" }),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ajustements: DELETE /ajustements/:numEtud/:idUE 404 when not found",
async fn() {
await truncateAll();
const res = await ajustementHandler.DELETE!(
makeGetRequest("/ajustements/99999/99"),
makeEmployeeContext({ numEtud: "99999", idUE: "99" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+240
View File
@@ -0,0 +1,240 @@
// E2E tests for /enseignements endpoints — handler + real DB
import { assertEquals, assertExists } from "@std/assert";
import {
makeContextWithAffiliation,
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedEnseignements,
seedModules,
seedPromotions,
seedUsers,
truncateAll,
} from "../helpers/db_integration.ts";
import { handler as enseignementsHandler } from "$apps/admin/api/enseignements.ts";
import { handler as enseignementHandler } from "$apps/admin/api/enseignements/[idProf]/[idModule]/[idPromo].ts";
// --- POST /enseignements ---
Deno.test({
name:
"e2e enseignements: POST /enseignements creates enseignement (201) as employee",
async fn() {
await truncateAll();
await seedUsers([{ id: "prof.dupont", nom: "Dupont", prenom: "Jean" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedPromotions([{ id: "P1" }]);
const res = await enseignementsHandler.POST!(
makeJsonRequest("/enseignements", "POST", {
idProf: "prof.dupont",
idModule: "M1",
idPromo: "P1",
}),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertExists(body.idProf);
assertEquals(body.idModule, "M1");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e enseignements: POST /enseignements 403 for non-employee",
async fn() {
await truncateAll();
const res = await enseignementsHandler.POST!(
makeJsonRequest("/enseignements", "POST", {
idProf: "p",
idModule: "M1",
idPromo: "P1",
}),
makeContextWithAffiliation("student"),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e enseignements: POST /enseignements 400 on missing fields",
async fn() {
await truncateAll();
const res = await enseignementsHandler.POST!(
makeJsonRequest("/enseignements", "POST", { idProf: "prof.dupont" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e enseignements: POST /enseignements 409 on duplicate",
async fn() {
await truncateAll();
await seedUsers([{ id: "prof.dupont", nom: "Dupont", prenom: "Jean" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedPromotions([{ id: "P1" }]);
await seedEnseignements([{
idProf: "prof.dupont",
idModule: "M1",
idPromo: "P1",
}]);
const res = await enseignementsHandler.POST!(
makeJsonRequest("/enseignements", "POST", {
idProf: "prof.dupont",
idModule: "M1",
idPromo: "P1",
}),
makeEmployeeContext(),
);
assertEquals(res.status, 409);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /enseignements/:idProf/:idModule/:idPromo ---
Deno.test({
name:
"e2e enseignements: GET /enseignements/:idProf/:idModule/:idPromo returns enseignement (employee)",
async fn() {
await truncateAll();
await seedUsers([{ id: "prof.dupont", nom: "Dupont", prenom: "Jean" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedPromotions([{ id: "P1" }]);
await seedEnseignements([{
idProf: "prof.dupont",
idModule: "M1",
idPromo: "P1",
}]);
const res = await enseignementHandler.GET!(
makeGetRequest("/enseignements/prof.dupont/M1/P1"),
makeEmployeeContext({
idProf: "prof.dupont",
idModule: "M1",
idPromo: "P1",
}),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.idProf, "prof.dupont");
assertEquals(body.idModule, "M1");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e enseignements: GET /enseignements/:idProf/:idModule/:idPromo 403 for non-employee",
async fn() {
await truncateAll();
const res = await enseignementHandler.GET!(
makeGetRequest("/enseignements/p/M1/P1"),
makeContextWithAffiliation("student", {
idProf: "p",
idModule: "M1",
idPromo: "P1",
}),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e enseignements: GET /enseignements/:idProf/:idModule/:idPromo 404 when not found",
async fn() {
await truncateAll();
const res = await enseignementHandler.GET!(
makeGetRequest("/enseignements/ghost/GHOST/GHOST"),
makeEmployeeContext({
idProf: "ghost",
idModule: "GHOST",
idPromo: "GHOST",
}),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /enseignements/:idProf/:idModule/:idPromo ---
Deno.test({
name:
"e2e enseignements: DELETE /enseignements/:idProf/:idModule/:idPromo returns 204 (employee)",
async fn() {
await truncateAll();
await seedUsers([{ id: "prof.dupont", nom: "Dupont", prenom: "Jean" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedPromotions([{ id: "P1" }]);
await seedEnseignements([{
idProf: "prof.dupont",
idModule: "M1",
idPromo: "P1",
}]);
const res = await enseignementHandler.DELETE!(
makeGetRequest("/enseignements/prof.dupont/M1/P1"),
makeEmployeeContext({
idProf: "prof.dupont",
idModule: "M1",
idPromo: "P1",
}),
);
assertEquals(res.status, 204);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e enseignements: DELETE /enseignements/:idProf/:idModule/:idPromo 403 for non-employee",
async fn() {
await truncateAll();
const res = await enseignementHandler.DELETE!(
makeGetRequest("/enseignements/p/M1/P1"),
makeContextWithAffiliation("student", {
idProf: "p",
idModule: "M1",
idPromo: "P1",
}),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e enseignements: DELETE /enseignements/:idProf/:idModule/:idPromo 404 when not found",
async fn() {
await truncateAll();
const res = await enseignementHandler.DELETE!(
makeGetRequest("/enseignements/ghost/GHOST/GHOST"),
makeEmployeeContext({
idProf: "ghost",
idModule: "GHOST",
idPromo: "GHOST",
}),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+283
View File
@@ -0,0 +1,283 @@
// E2E tests for /notes endpoints — handler + real DB
import { assertEquals, assertExists } from "@std/assert";
import {
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedModules,
seedNotes,
seedPromotions,
seedStudents,
truncateAll,
} from "../helpers/db_integration.ts";
import { handler as notesHandler } from "$apps/notes/api/notes.ts";
import { handler as noteHandler } from "$apps/notes/api/notes/[numEtud]/[idModule].ts";
// --- GET /notes ---
Deno.test({
name: "e2e notes: GET /notes returns all notes",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Dupont",
prenom: "Jean",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod A" }, { id: "M2", nom: "Mod B" }]);
await seedNotes([
{ numEtud: s.numEtud, idModule: "M1", note: 15.0 },
{ numEtud: s.numEtud, idModule: "M2", note: 12.0 },
]);
const res = await notesHandler.GET!(
makeGetRequest("/notes"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e notes: GET /notes?numEtud filters by student",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s1] = await seedStudents([{
nom: "Dupont",
prenom: "Jean",
idPromo: "P1",
}]);
const [s2] = await seedStudents([{
nom: "Martin",
prenom: "Alice",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedNotes([
{ numEtud: s1.numEtud, idModule: "M1", note: 15.0 },
{ numEtud: s2.numEtud, idModule: "M1", note: 12.0 },
]);
const res = await notesHandler.GET!(
makeGetRequest("/notes", { numEtud: String(s1.numEtud) }),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 1);
assertEquals(body[0].numEtud, s1.numEtud);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e notes: GET /notes?numEtud=NaN returns 400",
async fn() {
await truncateAll();
const res = await notesHandler.GET!(
makeGetRequest("/notes", { numEtud: "abc" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e notes: GET /notes?idModule filters by module",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Dupont",
prenom: "Jean",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod A" }, { id: "M2", nom: "Mod B" }]);
await seedNotes([
{ numEtud: s.numEtud, idModule: "M1", note: 15.0 },
{ numEtud: s.numEtud, idModule: "M2", note: 10.0 },
]);
const res = await notesHandler.GET!(
makeGetRequest("/notes", { idModule: "M1" }),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 1);
assertEquals(body[0].idModule, "M1");
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /notes ---
Deno.test({
name: "e2e notes: POST /notes creates note (201)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Leroy",
prenom: "Paul",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
const res = await notesHandler.POST!(
makeJsonRequest("/notes", "POST", {
numEtud: s.numEtud,
idModule: "M1",
note: 14.0,
}),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertExists(body.numEtud);
assertEquals(body.note, 14.0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e notes: POST /notes 400 on missing fields",
async fn() {
await truncateAll();
const res = await notesHandler.POST!(
makeJsonRequest("/notes", "POST", { numEtud: 12345 }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /notes/:numEtud/:idModule ---
Deno.test({
name: "e2e notes: GET /notes/:numEtud/:idModule returns note",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Bernard",
prenom: "Lucie",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedNotes([{ numEtud: s.numEtud, idModule: "M1", note: 18.0 }]);
const res = await noteHandler.GET!(
makeGetRequest(`/notes/${s.numEtud}/M1`),
makeEmployeeContext({ numEtud: String(s.numEtud), idModule: "M1" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.note, 18.0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e notes: GET /notes/:numEtud/:idModule 404 when not found",
async fn() {
await truncateAll();
const res = await noteHandler.GET!(
makeGetRequest("/notes/99999/GHOST"),
makeEmployeeContext({ numEtud: "99999", idModule: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /notes/:numEtud/:idModule ---
Deno.test({
name: "e2e notes: PUT /notes/:numEtud/:idModule updates note",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Thomas",
prenom: "Eva",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedNotes([{ numEtud: s.numEtud, idModule: "M1", note: 10.0 }]);
const res = await noteHandler.PUT!(
makeJsonRequest(`/notes/${s.numEtud}/M1`, "PUT", { note: 16.0 }),
makeEmployeeContext({ numEtud: String(s.numEtud), idModule: "M1" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.note, 16.0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e notes: PUT /notes/:numEtud/:idModule 404 when not found",
async fn() {
await truncateAll();
const res = await noteHandler.PUT!(
makeJsonRequest("/notes/99999/GHOST", "PUT", { note: 10.0 }),
makeEmployeeContext({ numEtud: "99999", idModule: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /notes/:numEtud/:idModule ---
Deno.test({
name: "e2e notes: DELETE /notes/:numEtud/:idModule returns 204",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Petit",
prenom: "Hugo",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
await seedNotes([{ numEtud: s.numEtud, idModule: "M1", note: 9.0 }]);
const res = await noteHandler.DELETE!(
makeGetRequest(`/notes/${s.numEtud}/M1`),
makeEmployeeContext({ numEtud: String(s.numEtud), idModule: "M1" }),
);
assertEquals(res.status, 204);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e notes: DELETE /notes/:numEtud/:idModule 404 when not found",
async fn() {
await truncateAll();
const res = await noteHandler.DELETE!(
makeGetRequest("/notes/99999/GHOST"),
makeEmployeeContext({ numEtud: "99999", idModule: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+60
View File
@@ -0,0 +1,60 @@
// #115 - E2E tests for GET /permissions
import { assertEquals, assertExists } from "@std/assert";
import { makeEmployeeContext, makeGetRequest } from "../helpers/handler.ts";
import { seedPermissions, truncateAll } from "../helpers/db_integration.ts";
import { handler as permissionsHandler } from "$apps/admin/api/permissions.ts";
const PERMISSIONS = [
{ id: "note_read", nom: "Consulter les notes des étudiants" },
{ id: "note_write", nom: "Saisir et modifier les notes" },
{ id: "student_read", nom: "Consulter la liste des étudiants" },
{
id: "student_write",
nom: "Gérer les étudiants (ajout, modification, suppression)",
},
{ id: "module_read", nom: "Consulter les modules et enseignements" },
{ id: "module_write", nom: "Gérer les modules et enseignements" },
{ id: "user_read", nom: "Consulter les utilisateurs et leurs rôles" },
{ id: "user_write", nom: "Gérer les utilisateurs et leurs rôles" },
{ id: "role_write", nom: "Gérer les rôles et leurs permissions" },
];
Deno.test({
name: "e2e permissions: GET /permissions returns all 9 permissions",
async fn() {
await truncateAll();
await seedPermissions(PERMISSIONS);
const res = await permissionsHandler.GET!(
makeGetRequest("/permissions"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const text = await res.text();
const data = JSON.parse(text);
assertEquals(data.length, 9);
assertExists(data.find((p: { id: string }) => p.id === "student_read"));
assertExists(data.find((p: { id: string }) => p.id === "role_write"));
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e permissions: GET /permissions - all entries have id and nom",
async fn() {
await truncateAll();
await seedPermissions(PERMISSIONS);
const res = await permissionsHandler.GET!(
makeGetRequest("/permissions"),
makeEmployeeContext(),
);
const data: { id: string; nom: string }[] = await res.json();
for (const p of data) {
assertEquals(typeof p.id, "string");
assertEquals(typeof p.nom, "string");
}
},
sanitizeResources: false,
sanitizeOps: false,
});
+592
View File
@@ -0,0 +1,592 @@
// Robustness tests — input validation & side-effect isolation
//
// Chaque test documente le comportement réel du handler face à des entrées invalides.
// Les tests marqués [BUG] représentent le comportement ATTENDU — ils échouent
// intentionnellement pour exposer un bug dans le handler ciblé.
import { assertEquals } from "@std/assert";
import {
makeContextWithAffiliation,
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedModules,
seedPromotions,
seedStudents,
seedUes,
truncateAll,
} from "../helpers/db_integration.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 notesHandler } from "$apps/notes/api/notes.ts";
import { handler as uesHandler } from "$apps/admin/api/ues.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 enseignementsHandler } from "$apps/admin/api/enseignements.ts";
import { handler as usersHandler } from "$apps/admin/api/users.ts";
// Helper : request POST avec un body JSON invalide
function makeMalformedRequest(path: string): Request {
return new Request(`http://localhost${path}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: "{ ceci n'est pas du json }",
});
}
// Helper : request POST sans body du tout
function makeEmptyBodyRequest(path: string, method = "POST"): Request {
return new Request(`http://localhost${path}`, { method });
}
// =============================================================================
// JSON MALFORMÉ
// =============================================================================
// Handlers AVEC try/catch → retournent 500
// Handlers SANS try/catch → throwent (assertRejects)
Deno.test({
name: "robustness: POST /notes malformed JSON → 500 (try/catch présent)",
async fn() {
await truncateAll();
const res = await notesHandler.POST!(
makeMalformedRequest("/notes"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /ues malformed JSON → 500 (try/catch présent)",
async fn() {
await truncateAll();
const res = await uesHandler.POST!(
makeMalformedRequest("/ues"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /ue-modules malformed JSON → 500 (try/catch présent)",
async fn() {
await truncateAll();
const res = await ueModulesHandler.POST!(
makeMalformedRequest("/ue-modules"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"robustness: POST /ajustements malformed JSON → 500 (try/catch présent)",
async fn() {
await truncateAll();
const res = await ajustementsHandler.POST!(
makeMalformedRequest("/ajustements"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /modules malformed JSON → 500",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeMalformedRequest("/modules"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /enseignements malformed JSON → 500",
async fn() {
await truncateAll();
const res = await enseignementsHandler.POST!(
makeMalformedRequest("/enseignements"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /users malformed JSON → 500",
async fn() {
await truncateAll();
const res = await usersHandler.POST!(
makeMalformedRequest("/users"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// BODY ABSENT
// =============================================================================
Deno.test({
name: "robustness: POST /notes sans body → 500",
async fn() {
await truncateAll();
const res = await notesHandler.POST!(
makeEmptyBodyRequest("/notes"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /modules sans body → 500",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeEmptyBodyRequest("/modules"),
makeEmployeeContext(),
);
assertEquals(res.status, 500);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// CHAÎNES VIDES — comportement correct ✓
// =============================================================================
Deno.test({
name: "robustness: POST /modules id vide → 400",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: "", nom: "Test" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /modules nom vide → 400",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: "M1", nom: "" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /ues nom vide → 400",
async fn() {
await truncateAll();
const res = await uesHandler.POST!(
makeJsonRequest("/ues", "POST", { nom: "" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// CHAÎNES AVEC ESPACES SEULS — [BUG] passent !field et s'insèrent en DB
// =============================================================================
Deno.test({
name: "robustness: POST /modules id=espaces → 400",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: " ", nom: "Test" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /ues nom=espaces → 400",
async fn() {
await truncateAll();
const res = await uesHandler.POST!(
makeJsonRequest("/ues", "POST", { nom: " " }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /users id=espaces → 400",
async fn() {
await truncateAll();
const res = await usersHandler.POST!(
makeJsonRequest("/users", "POST", { id: " ", nom: "X", prenom: "Y" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// MAUVAIS TYPES
// =============================================================================
Deno.test({
name: "robustness: POST /notes note=string → 400",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Test",
prenom: "User",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod" }]);
const res = await notesHandler.POST!(
makeJsonRequest("/notes", "POST", {
note: "pas-un-nombre",
numEtud: s.numEtud,
idModule: "M1",
}),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: PUT /modules/:id nom=number → 400",
async fn() {
await truncateAll();
await seedModules([{ id: "M1", nom: "Mod" }]);
const res = await moduleHandler.PUT!(
makeJsonRequest("/modules/M1", "PUT", { nom: 42 }),
makeEmployeeContext({ idModule: "M1" }),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// VALEUR ZÉRO — falsy bug sur numEtud/idUE
// =============================================================================
Deno.test({
name:
"robustness [BUG]: POST /ajustements numEtud=0 → 400 pour mauvaise raison",
async fn() {
await truncateAll();
const [ue] = await seedUes([{ nom: "UE Info" }]);
const res = await ajustementsHandler.POST!(
makeJsonRequest("/ajustements", "POST", {
numEtud: 0,
idUE: ue.id,
valeur: 10.0,
}),
makeEmployeeContext(),
);
// !0 === true → retourne 400 à cause du falsy check, pas d'une vraie validation
// Comportement attendu : 422 ou message d'erreur explicite sur numEtud invalide
// Comportement réel : 400 générique "champs requis"
assertEquals(res.status, 400); // passe, mais pour la mauvaise raison — le message est trompeur
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness [BUG]: POST /ajustements idUE=0 → 400 pour mauvaise raison",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Test",
prenom: "User",
idPromo: "P1",
}]);
const res = await ajustementsHandler.POST!(
makeJsonRequest("/ajustements", "POST", {
numEtud: s.numEtud,
idUE: 0,
valeur: 10.0,
}),
makeEmployeeContext(),
);
assertEquals(res.status, 400); // !0 → 400, message trompeur
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// VALEUR ZÉRO CORRECTEMENT GÉRÉE — coeff=0 est valide
// =============================================================================
Deno.test({
name:
"robustness: POST /ue-modules coeff=0 → 201 (zéro est une valeur valide)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
await seedModules([{ id: "M1", nom: "Mod" }]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
const res = await ueModulesHandler.POST!(
makeJsonRequest("/ue-modules", "POST", {
idModule: "M1",
idUE: ue.id,
idPromo: "P1",
coeff: 0,
}),
makeEmployeeContext(),
);
// coeff === undefined → false pour 0 → passe ✓
assertEquals(res.status, 201);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// INJECTION SQL DANS LES PARAMÈTRES D'URL
// Drizzle utilise des requêtes paramétrées → les injections sont neutralisées
// =============================================================================
Deno.test({
name:
"robustness: GET /modules avec SQL injection dans id → 404 (Drizzle paramètre)",
async fn() {
await truncateAll();
const injectionId = "'; DROP TABLE modules; --";
const res = await moduleHandler.GET!(
makeGetRequest(`/modules/${encodeURIComponent(injectionId)}`),
makeEmployeeContext({ idModule: injectionId }),
);
// Drizzle génère WHERE id = $1 avec $1 = "'; DROP TABLE modules; --"
// Aucune injection possible → module non trouvé → 404
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"robustness: POST /modules avec SQL injection dans id → s'insère littéralement (safe)",
async fn() {
await truncateAll();
const injectionId = "'; DROP TABLE modules; --";
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: injectionId, nom: "Test" }),
makeEmployeeContext(),
);
// Drizzle paramètre la valeur → s'insère comme une chaîne ordinaire → 201
assertEquals(res.status, 201);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// ABSENCE DE VALIDATION MÉTIER — valeurs hors limites acceptées
// =============================================================================
Deno.test({
name: "robustness: POST /notes note > 20 → 400",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Test",
prenom: "User",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod" }]);
const res = await notesHandler.POST!(
makeJsonRequest("/notes", "POST", {
note: 999,
numEtud: s.numEtud,
idModule: "M1",
}),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /notes note < 0 → 400",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Test",
prenom: "User",
idPromo: "P1",
}]);
await seedModules([{ id: "M1", nom: "Mod" }]);
const res = await notesHandler.POST!(
makeJsonRequest("/notes", "POST", {
note: -5,
numEtud: s.numEtud,
idModule: "M1",
}),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "robustness: POST /ue-modules coeff négatif → 400",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
await seedModules([{ id: "M1", nom: "Mod" }]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
const res = await ueModulesHandler.POST!(
makeJsonRequest("/ue-modules", "POST", {
idModule: "M1",
idUE: ue.id,
idPromo: "P1",
coeff: -3,
}),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// ISOLATION DES EFFETS DE BORD
// Vérification que truncateAll() isole correctement chaque test
// =============================================================================
Deno.test({
name: "robustness: isolation — données du test précédent non visibles",
async fn() {
// Ce test crée un module
await truncateAll();
await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", {
id: "ISOLATION-TEST",
nom: "Test",
}),
makeEmployeeContext(),
);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"robustness: isolation — truncateAll efface bien les données du test précédent",
async fn() {
await truncateAll();
// Le module créé dans le test précédent ne doit plus exister
const res = await moduleHandler.GET!(
makeGetRequest("/modules/ISOLATION-TEST"),
makeEmployeeContext({ idModule: "ISOLATION-TEST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// CHAMPS SUPPLÉMENTAIRES INCONNUS — doivent être ignorés silencieusement
// =============================================================================
Deno.test({
name: "robustness: POST /modules avec champs inconnus → 201 (champs ignorés)",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", {
id: "M-EXTRA",
nom: "Test",
champInconnu: "valeur",
_admin: true,
__proto__: { polluted: true },
}),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
},
sanitizeResources: false,
sanitizeOps: false,
});
// =============================================================================
// ACCÈS NON AUTHENTIFIÉ — vérification que l'état auth est bien contrôlé
// =============================================================================
Deno.test({
name: "robustness: POST /modules sans affiliation employee → 403",
async fn() {
await truncateAll();
for (const role of ["student", "alumni", "", "EMPLOYEE", "admin"]) {
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: `M-${role}`, nom: "Test" }),
makeContextWithAffiliation(role),
);
assertEquals(res.status, 403, `role "${role}" devrait être 403`);
}
},
sanitizeResources: false,
sanitizeOps: false,
});
+312
View File
@@ -0,0 +1,312 @@
// E2E tests for /ue-modules endpoints — handler + real DB
import { assertEquals, assertExists } from "@std/assert";
import {
makeContextWithAffiliation,
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedModules,
seedPromotions,
seedUeModules,
seedUes,
truncateAll,
} from "../helpers/db_integration.ts";
import { handler as ueModulesHandler } from "$apps/admin/api/ue-modules.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 { testDb } from "../helpers/db_integration.ts";
// --- GET /ue-modules ---
Deno.test({
name: "e2e ue_modules: GET /ue-modules returns all associations",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
await seedModules([{ id: "M1", nom: "Mod A" }, { id: "M2", nom: "Mod B" }]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
await seedUeModules([
{ idModule: "M1", idUE: ue.id, idPromo: "P1", coeff: 2.0 },
{ idModule: "M2", idUE: ue.id, idPromo: "P1", coeff: 3.0 },
]);
const res = await ueModulesHandler.GET!(
makeGetRequest("/ue-modules"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ue_modules: GET /ue-modules?idPromo filters by promo",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }, { id: "P2" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
await seedUeModules([
{ idModule: "M1", idUE: ue.id, idPromo: "P1", coeff: 2.0 },
{ idModule: "M1", idUE: ue.id, idPromo: "P2", coeff: 3.0 },
]);
const res = await ueModulesHandler.GET!(
makeGetRequest("/ue-modules", { idPromo: "P1" }),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 1);
assertEquals(body[0].idPromo, "P1");
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /ue-modules ---
Deno.test({
name: "e2e ue_modules: POST /ue-modules creates association (201)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
const res = await ueModulesHandler.POST!(
makeJsonRequest("/ue-modules", "POST", {
idModule: "M1",
idUE: ue.id,
idPromo: "P1",
coeff: 4.0,
}),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertExists(body.idModule);
assertEquals(body.coeff, 4.0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ue_modules: POST /ue-modules 400 on missing fields",
async fn() {
await truncateAll();
const res = await ueModulesHandler.POST!(
makeJsonRequest("/ue-modules", "POST", { idModule: "M1" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /ue-modules/:idModule/:idUE/:idPromo ---
Deno.test({
name:
"e2e ue_modules: GET /ue-modules/:idModule/:idUE/:idPromo returns correct association (employee)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }, { id: "P2" }]);
await seedModules([{ id: "M1", nom: "Mod A" }, { id: "M2", nom: "Mod B" }]);
const [ue1, ue2] = await seedUes([{ nom: "UE Info" }, { nom: "UE Maths" }]);
// Plusieurs lignes qui partagent idModule="M1" — le handler doit discriminer par idUE ET idPromo
await seedUeModules([
{ idModule: "M1", idUE: ue1.id, idPromo: "P1", coeff: 3.5 },
{ idModule: "M1", idUE: ue2.id, idPromo: "P1", coeff: 1.0 },
{ idModule: "M1", idUE: ue1.id, idPromo: "P2", coeff: 2.0 },
{ idModule: "M2", idUE: ue1.id, idPromo: "P1", coeff: 4.0 },
]);
const res = await ueModuleHandler.GET!(
makeGetRequest(`/ue-modules/M1/${ue1.id}/P1`),
makeEmployeeContext({
idModule: "M1",
idUE: String(ue1.id),
idPromo: "P1",
}),
);
assertEquals(res.status, 200);
const body = await res.json();
// Doit retourner exactement M1/ue1/P1 avec coeff 3.5, pas une autre ligne
assertEquals(body.coeff, 3.5);
assertEquals(body.idPromo, "P1");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ue_modules: GET /ue-modules/:idModule/:idUE/:idPromo 403 for non-employee",
async fn() {
await truncateAll();
const res = await ueModuleHandler.GET!(
makeGetRequest("/ue-modules/M1/1/P1"),
makeContextWithAffiliation("student", {
idModule: "M1",
idUE: "1",
idPromo: "P1",
}),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ue_modules: GET /ue-modules/:idModule/:idUE/:idPromo 404 when not found",
async fn() {
await truncateAll();
const res = await ueModuleHandler.GET!(
makeGetRequest("/ue-modules/GHOST/1/GHOST"),
makeEmployeeContext({ idModule: "GHOST", idUE: "1", idPromo: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /ue-modules/:idModule/:idUE/:idPromo ---
Deno.test({
name:
"e2e ue_modules: PUT /ue-modules/:idModule/:idUE/:idPromo updates only the targeted row (employee)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }, { id: "P2" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
const [ue1, ue2] = await seedUes([{ nom: "UE Info" }, { nom: "UE Maths" }]);
// Deux lignes avec même idModule — le PUT ne doit modifier que celle ciblée
await seedUeModules([
{ idModule: "M1", idUE: ue1.id, idPromo: "P1", coeff: 2.0 },
{ idModule: "M1", idUE: ue2.id, idPromo: "P2", coeff: 9.0 },
]);
const res = await ueModuleHandler.PUT!(
makeJsonRequest(`/ue-modules/M1/${ue1.id}/P1`, "PUT", { coeff: 5.0 }),
makeEmployeeContext({
idModule: "M1",
idUE: String(ue1.id),
idPromo: "P1",
}),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.coeff, 5.0);
assertEquals(body.idPromo, "P1");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ue_modules: PUT /ue-modules/:idModule/:idUE/:idPromo 403 for non-employee",
async fn() {
await truncateAll();
const res = await ueModuleHandler.PUT!(
makeJsonRequest("/ue-modules/M1/1/P1", "PUT", { coeff: 5.0 }),
makeContextWithAffiliation("student", {
idModule: "M1",
idUE: "1",
idPromo: "P1",
}),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ue_modules: PUT /ue-modules/:idModule/:idUE/:idPromo 404 when not found",
async fn() {
await truncateAll();
const res = await ueModuleHandler.PUT!(
makeJsonRequest("/ue-modules/GHOST/1/GHOST", "PUT", { coeff: 5.0 }),
makeEmployeeContext({ idModule: "GHOST", idUE: "1", idPromo: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /ue-modules/:idModule/:idUE/:idPromo ---
Deno.test({
name:
"e2e ue_modules: DELETE /ue-modules/:idModule/:idUE/:idPromo deletes only targeted row (employee)",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }, { id: "P2" }]);
await seedModules([{ id: "M1", nom: "Mod A" }]);
const [ue1, ue2] = await seedUes([{ nom: "UE Info" }, { nom: "UE Maths" }]);
// Deux lignes avec même idModule — seule celle ciblée doit être supprimée
await seedUeModules([
{ idModule: "M1", idUE: ue1.id, idPromo: "P1", coeff: 2.0 },
{ idModule: "M1", idUE: ue2.id, idPromo: "P2", coeff: 4.0 },
]);
const res = await ueModuleHandler.DELETE!(
makeGetRequest(`/ue-modules/M1/${ue1.id}/P1`),
makeEmployeeContext({
idModule: "M1",
idUE: String(ue1.id),
idPromo: "P1",
}),
);
assertEquals(res.status, 204);
// L'autre ligne doit toujours exister
const remaining = await testDb.select().from(ueModulesTable);
assertEquals(remaining.length, 1);
assertEquals(remaining[0].idUE, ue2.id);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ue_modules: DELETE /ue-modules/:idModule/:idUE/:idPromo 403 for non-employee",
async fn() {
await truncateAll();
const res = await ueModuleHandler.DELETE!(
makeGetRequest("/ue-modules/M1/1/P1"),
makeContextWithAffiliation("student", {
idModule: "M1",
idUE: "1",
idPromo: "P1",
}),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"e2e ue_modules: DELETE /ue-modules/:idModule/:idUE/:idPromo 404 when not found",
async fn() {
await truncateAll();
const res = await ueModuleHandler.DELETE!(
makeGetRequest("/ue-modules/GHOST/1/GHOST"),
makeEmployeeContext({ idModule: "GHOST", idUE: "1", idPromo: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+178
View File
@@ -0,0 +1,178 @@
// E2E tests for /ues endpoints — handler + real DB
import { assertEquals, assertExists } from "@std/assert";
import {
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import { seedUes, truncateAll } from "../helpers/db_integration.ts";
import { handler as uesHandler } from "$apps/admin/api/ues.ts";
import { handler as ueHandler } from "$apps/admin/api/ues/[idUE].ts";
// --- GET /ues ---
Deno.test({
name: "e2e ues: GET /ues returns all UEs",
async fn() {
await truncateAll();
await seedUes([{ nom: "UE Informatique" }, { nom: "UE Mathématiques" }]);
const res = await uesHandler.GET!(
makeGetRequest("/ues"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ues: GET /ues returns empty when no UEs",
async fn() {
await truncateAll();
const res = await uesHandler.GET!(
makeGetRequest("/ues"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 0);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /ues ---
Deno.test({
name: "e2e ues: POST /ues creates UE (201)",
async fn() {
await truncateAll();
const res = await uesHandler.POST!(
makeJsonRequest("/ues", "POST", { nom: "UE Physique" }),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertExists(body.id);
assertEquals(body.nom, "UE Physique");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ues: POST /ues 400 on missing nom",
async fn() {
await truncateAll();
const res = await uesHandler.POST!(
makeJsonRequest("/ues", "POST", {}),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /ues/:id ---
Deno.test({
name: "e2e ues: GET /ues/:id returns UE",
async fn() {
await truncateAll();
const [ue] = await seedUes([{ nom: "UE Chimie" }]);
const res = await ueHandler.GET!(
makeGetRequest(`/ues/${ue.id}`),
makeEmployeeContext({ idUE: String(ue.id) }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.nom, "UE Chimie");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ues: GET /ues/:id 404 when not found",
async fn() {
await truncateAll();
const res = await ueHandler.GET!(
makeGetRequest("/ues/99999"),
makeEmployeeContext({ idUE: "99999" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /ues/:id ---
Deno.test({
name: "e2e ues: PUT /ues/:id updates nom",
async fn() {
await truncateAll();
const [ue] = await seedUes([{ nom: "UE Biologie" }]);
const res = await ueHandler.PUT!(
makeJsonRequest(`/ues/${ue.id}`, "PUT", {
nom: "UE Biologie moléculaire",
}),
makeEmployeeContext({ idUE: String(ue.id) }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.nom, "UE Biologie moléculaire");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ues: PUT /ues/:id 404 when not found",
async fn() {
await truncateAll();
const res = await ueHandler.PUT!(
makeJsonRequest("/ues/99999", "PUT", { nom: "X" }),
makeEmployeeContext({ idUE: "99999" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /ues/:id ---
Deno.test({
name: "e2e ues: DELETE /ues/:id returns 204",
async fn() {
await truncateAll();
const [ue] = await seedUes([{ nom: "UE à supprimer" }]);
const res = await ueHandler.DELETE!(
makeGetRequest(`/ues/${ue.id}`),
makeEmployeeContext({ idUE: String(ue.id) }),
);
assertEquals(res.status, 204);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e ues: DELETE /ues/:id 404 when not found",
async fn() {
await truncateAll();
const res = await ueHandler.DELETE!(
makeGetRequest("/ues/99999"),
makeEmployeeContext({ idUE: "99999" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+239
View File
@@ -0,0 +1,239 @@
// E2E tests for /users endpoints — handler + real DB
import { assertEquals, assertExists } from "@std/assert";
import {
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import {
seedRoles,
seedUsers,
truncateAll,
} from "../helpers/db_integration.ts";
import { handler as usersHandler } from "$apps/admin/api/users.ts";
import { handler as userHandler } from "$apps/admin/api/users/[id].ts";
// --- GET /users ---
Deno.test({
name: "e2e users: GET /users returns all users",
async fn() {
await truncateAll();
await seedUsers([
{ id: "dupont.jean", nom: "Dupont", prenom: "Jean" },
{ id: "martin.alice", nom: "Martin", prenom: "Alice" },
]);
const res = await usersHandler.GET!(
makeGetRequest("/users"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
assertExists(body.find((u: { id: string }) => u.id === "dupont.jean"));
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: GET /users returns empty when no users",
async fn() {
await truncateAll();
const res = await usersHandler.GET!(
makeGetRequest("/users"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: GET /users?idRole filters by role",
async fn() {
await truncateAll();
const [role1] = await seedRoles([{ nom: "admin" }]);
const [role2] = await seedRoles([{ nom: "employee" }]);
await seedUsers([
{ id: "admin.user", nom: "Admin", prenom: "User", idRole: role1.id },
{ id: "emp.user", nom: "Emp", prenom: "User", idRole: role2.id },
]);
const res = await usersHandler.GET!(
makeGetRequest("/users", { idRole: String(role1.id) }),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 1);
assertEquals(body[0].id, "admin.user");
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /users ---
Deno.test({
name: "e2e users: POST /users creates user (201)",
async fn() {
await truncateAll();
const res = await usersHandler.POST!(
makeJsonRequest("/users", "POST", {
id: "new.user",
nom: "New",
prenom: "User",
}),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertEquals(body.id, "new.user");
assertEquals(body.nom, "New");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: POST /users 400 on missing fields",
async fn() {
await truncateAll();
const res = await usersHandler.POST!(
makeJsonRequest("/users", "POST", { id: "x" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: POST /users 409 on duplicate id",
async fn() {
await truncateAll();
await seedUsers([{ id: "dupont.jean", nom: "Dupont", prenom: "Jean" }]);
const res = await usersHandler.POST!(
makeJsonRequest("/users", "POST", {
id: "dupont.jean",
nom: "Doublon",
prenom: "X",
}),
makeEmployeeContext(),
);
assertEquals(res.status, 409);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /users/:id ---
Deno.test({
name: "e2e users: GET /users/:id returns user",
async fn() {
await truncateAll();
await seedUsers([{ id: "bernard.lucie", nom: "Bernard", prenom: "Lucie" }]);
const res = await userHandler.GET!(
makeGetRequest("/users/bernard.lucie"),
makeEmployeeContext({ id: "bernard.lucie" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.id, "bernard.lucie");
assertEquals(body.nom, "Bernard");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: GET /users/:id 404 when not found",
async fn() {
await truncateAll();
const res = await userHandler.GET!(
makeGetRequest("/users/ghost.user"),
makeEmployeeContext({ id: "ghost.user" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /users/:id ---
Deno.test({
name: "e2e users: PUT /users/:id updates user",
async fn() {
await truncateAll();
await seedUsers([{ id: "thomas.eva", nom: "Thomas", prenom: "Eva" }]);
const res = await userHandler.PUT!(
makeJsonRequest("/users/thomas.eva", "PUT", {
nom: "Thomas-Modifié",
prenom: "Eva",
idRole: null,
}),
makeEmployeeContext({ id: "thomas.eva" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.nom, "Thomas-Modifié");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: PUT /users/:id 404 when not found",
async fn() {
await truncateAll();
const res = await userHandler.PUT!(
makeJsonRequest("/users/ghost.user", "PUT", {
nom: "X",
prenom: "Y",
idRole: null,
}),
makeEmployeeContext({ id: "ghost.user" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /users/:id ---
Deno.test({
name: "e2e users: DELETE /users/:id returns 204",
async fn() {
await truncateAll();
await seedUsers([{ id: "petit.hugo", nom: "Petit", prenom: "Hugo" }]);
const res = await userHandler.DELETE!(
makeGetRequest("/users/petit.hugo"),
makeEmployeeContext({ id: "petit.hugo" }),
);
assertEquals(res.status, 204);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e users: DELETE /users/:id 404 when not found",
async fn() {
await truncateAll();
const res = await userHandler.DELETE!(
makeGetRequest("/users/ghost.user"),
makeEmployeeContext({ id: "ghost.user" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
+30
View File
@@ -87,3 +87,33 @@ export async function seedUsers(
): Promise<typeof schema.users.$inferSelect[]> {
return await testDb.insert(schema.users).values(rows).returning();
}
export async function seedNotes(
rows: { numEtud: number; idModule: string; note: number }[],
): Promise<typeof schema.notes.$inferSelect[]> {
return await testDb.insert(schema.notes).values(rows).returning();
}
export async function seedUeModules(
rows: { idModule: string; idUE: number; idPromo: string; coeff: number }[],
): Promise<typeof schema.ueModules.$inferSelect[]> {
return await testDb.insert(schema.ueModules).values(rows).returning();
}
export async function seedEnseignements(
rows: { idProf: string; idModule: string; idPromo: string }[],
): Promise<typeof schema.enseignements.$inferSelect[]> {
return await testDb.insert(schema.enseignements).values(rows).returning();
}
export async function seedAjustements(
rows: { numEtud: number; idUE: number; valeur: number }[],
): Promise<typeof schema.ajustements.$inferSelect[]> {
return await testDb.insert(schema.ajustements).values(rows).returning();
}
export async function seedPermissions(
rows: { id: string; nom: string }[],
): Promise<typeof schema.permissions.$inferSelect[]> {
return await testDb.insert(schema.permissions).values(rows).returning();
}
+160
View File
@@ -0,0 +1,160 @@
// Integration tests for /ajustements — Drizzle ORM direct on real DB
import { assertEquals, assertExists, assertRejects } from "@std/assert";
import {
seedAjustements,
seedPromotions,
seedStudents,
seedUes,
testDb,
truncateAll,
} from "../helpers/db_integration.ts";
import { ajustements } from "$root/databases/schema.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2";
Deno.test({
name: "integration ajustements: list all ajustements",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Dupont",
prenom: "Jean",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
await seedAjustements([{ numEtud: s.numEtud, idUE: ue.id, valeur: 13.0 }]);
const rows = await testDb.select().from(ajustements);
assertEquals(rows.length, 1);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration ajustements: create and retrieve by composite key",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Martin",
prenom: "Alice",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Maths" }]);
const [created] = await testDb
.insert(ajustements)
.values({ numEtud: s.numEtud, idUE: ue.id, valeur: 15.5 })
.returning();
assertExists(created);
assertEquals(created.valeur, 15.5);
const row = await testDb
.select()
.from(ajustements)
.where(
and(eq(ajustements.numEtud, s.numEtud), eq(ajustements.idUE, ue.id)),
)
.then((r) => r[0] ?? null);
assertExists(row);
assertEquals(row.valeur, 15.5);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name:
"integration ajustements: get by composite key returns null when not found",
async fn() {
await truncateAll();
const row = await testDb
.select()
.from(ajustements)
.where(and(eq(ajustements.numEtud, 99999), eq(ajustements.idUE, 99)))
.then((r) => r[0] ?? null);
assertEquals(row, null);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration ajustements: duplicate composite key insert fails",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Durand",
prenom: "Claire",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Info" }]);
await seedAjustements([{ numEtud: s.numEtud, idUE: ue.id, valeur: 12.0 }]);
await assertRejects(() =>
testDb.insert(ajustements).values({
numEtud: s.numEtud,
idUE: ue.id,
valeur: 13.0,
})
);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration ajustements: update valeur",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Bernard",
prenom: "Lucie",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Physique" }]);
await seedAjustements([{ numEtud: s.numEtud, idUE: ue.id, valeur: 10.0 }]);
const [updated] = await testDb
.update(ajustements)
.set({ valeur: 18.0 })
.where(
and(eq(ajustements.numEtud, s.numEtud), eq(ajustements.idUE, ue.id)),
)
.returning();
assertEquals(updated.valeur, 18.0);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "integration ajustements: delete removes the ajustement",
async fn() {
await truncateAll();
await seedPromotions([{ id: "P1" }]);
const [s] = await seedStudents([{
nom: "Thomas",
prenom: "Eva",
idPromo: "P1",
}]);
const [ue] = await seedUes([{ nom: "UE Chimie" }]);
await seedAjustements([{ numEtud: s.numEtud, idUE: ue.id, valeur: 11.0 }]);
await testDb.delete(ajustements).where(
and(eq(ajustements.numEtud, s.numEtud), eq(ajustements.idUE, ue.id)),
);
const row = await testDb
.select()
.from(ajustements)
.where(
and(eq(ajustements.numEtud, s.numEtud), eq(ajustements.idUE, ue.id)),
)
.then((r) => r[0] ?? null);
assertEquals(row, null);
},
sanitizeResources: false,
sanitizeOps: false,
});

Some files were not shown because too many files have changed in this diff Show More