Compare commits

..

16 Commits

Author SHA1 Message Date
djalim 07b6f1e347 chore(test-framework): remove endpoint-specific tests from framework branch
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Failing after 54s
Each endpoint's tests will be on their own issue branch (PMPR-109, etc.).
The framework branch only contains: CI config, db helpers, migrations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 13:55:21 +02:00
djalim c5018d9ced test(integration): add DB integration tests for students, promotions, roles, modules
Covers full CRUD for each resource via testDb:
- promotions: list, create, get by id, not found, update, delete
- students: list, filter by promo, create, get, not found, update, delete
- roles: list, create, get with permissions, update+reset perms, delete
- modules: list, create, duplicate id rejection, get, not found, update, delete

27 integration tests passing in CI (act + Gitea Actions).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 13:37:02 +02:00
djalim 367b0b2357 fix(ci): fix postgres TCP setup and truncateAll superuser error
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Successful in 58s
- Use apt-get install + configure listen_addresses + md5 auth in pg_hba
  so psql can connect via 127.0.0.1 (not just Unix socket)
- Use pg_ctlcluster restart after config changes + wait for pg_isready
- Replace session_replication_role (requires superuser) with a single
  TRUNCATE ... CASCADE which handles FK deps without elevated privileges
- All 3 integration tests now pass in CI (act + Gitea Actions)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-26 13:22:45 +02:00
djalim e0ac451372 fix(ci): use connection URL with ssl:false in drizzle config
Tests / Unit tests (pull_request) Successful in 13s
Tests / Integration tests (pull_request) Failing after 56s
2026-04-26 00:57:38 +02:00
djalim ae5d5b64ac debug(ci): add connection diagnostics before migrate
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Failing after 56s
2026-04-26 00:54:11 +02:00
djalim 7be13737d5 fix(ci): remove unsupported --verbose from drizzle-kit migrate
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Failing after 53s
2026-04-26 00:51:22 +02:00
djalim 32052ab1c9 fix(ci): add GRANT on public schema and verbose migrate output
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Failing after 54s
2026-04-26 00:48:57 +02:00
djalim ce807391c6 fix(ci): start postgres with pg_ctlcluster instead of systemctl
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Failing after 53s
2026-04-26 00:46:02 +02:00
djalim 182342aab0 fix(ci): install postgres via apt-get instead of docker
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Failing after 25s
2026-04-26 00:43:11 +02:00
djalim d32758b310 fix(ci): use docker run instead of services for postgres 2026-04-26 00:41:20 +02:00
djalim f26b2b044f fix(ci): use bash /dev/tcp for postgres readiness check
Tests / Unit tests (pull_request) Successful in 12s
Tests / Integration tests (pull_request) Has been cancelled
2026-04-26 00:37:21 +02:00
djalim af2562ef2b fix(ci): replace pg_isready with nc for postgres readiness check
Tests / Unit tests (pull_request) Successful in 11s
Tests / Integration tests (pull_request) Has been cancelled
2026-04-26 00:35:42 +02:00
djalim f739f94403 fix(ci): use deno install for unit tests, add postgres readiness check
Tests / Unit tests (pull_request) Successful in 13s
Tests / Integration tests (pull_request) Has been cancelled
2026-04-26 00:31:15 +02:00
djalim f66de20dad fix(ci): install npm deps before running unit tests
Tests / Unit tests (pull_request) Failing after 27s
Tests / Integration tests (pull_request) Failing after 27s
2026-04-26 00:27:07 +02:00
djalim ea61d83384 fix(lint): add version to drizzle-orm imports and prefix unused NOT_FOUND
Tests / Unit tests (pull_request) Failing after 6s
Tests / Integration tests (pull_request) Failing after 1m28s
2026-04-26 00:24:27 +02:00
djalim 6402f802e9 chore(test): set up integration test framework with postgres
- Generate Drizzle migrations (databases/migrations/)
- Add databases/schema.kit.ts for drizzle-kit (Node-compatible imports)
- Update drizzle.config.ts to use schema.kit.ts
- Add deno tasks: test:unit, test:integration, migrate
- Add tests/helpers/db_integration.ts: testDb, truncateAll, seed helpers
- Add .gitea/workflows/test.yml: CI with postgres service container
- Update lint.yml: run test:unit only (no DB needed)
- Update deploy.yml: add check-code job, gate deploy on it
2026-04-26 00:23:12 +02:00
129 changed files with 415 additions and 15428 deletions
-4
View File
@@ -1,4 +0,0 @@
node_modules
.git
coverage
.env
-17
View File
@@ -6,26 +6,9 @@ on:
- main - main
jobs: jobs:
check-code:
name: "Check Deno code"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- name: Check formatting
run: deno fmt --check
- name: Check linting
run: deno lint
deploy: deploy:
name: "Build Docker image" name: "Build Docker image"
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: check-code
steps: steps:
- name: Login to Docker Hub - name: Login to Docker Hub
uses: docker/login-action@v3 uses: docker/login-action@v3
+3 -4
View File
@@ -4,10 +4,6 @@ on:
pull_request: pull_request:
branches: branches:
- main - main
- develop
push:
branches:
- develop
permissions: permissions:
contents: read contents: read
@@ -28,3 +24,6 @@ jobs:
- name: Check linting - name: Check linting
run: deno lint run: deno lint
- name: Run tests
run: deno test -A --no-check tests/
-9
View File
@@ -68,12 +68,3 @@ jobs:
POSTGRES_PASS: test POSTGRES_PASS: test
POSTGRES_DB: polympr_test POSTGRES_DB: polympr_test
run: deno task test:integration run: deno task test:integration
- name: Run e2e tests
env:
POSTGRES_HOST: 127.0.0.1
POSTGRES_PORT: 5432
POSTGRES_USER: test
POSTGRES_PASS: test
POSTGRES_DB: polympr_test
run: deno task test:e2e
-79
View File
@@ -1,79 +0,0 @@
name: "Tests"
on:
pull_request:
branches:
- main
- develop
push:
branches:
- develop
jobs:
unit:
name: "Unit tests"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- name: Install dependencies
run: deno install
- name: Run unit tests
run: deno task test:unit
integration:
name: "Integration tests"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
- uses: denoland/setup-deno@v2
with:
deno-version: v2.x
- name: Start postgres
run: |
sudo apt-get update -qq && sudo apt-get install -y -qq postgresql > /dev/null
PG_VER=$(ls /etc/postgresql/)
sudo sed -i "s/^#*listen_addresses\s*=.*/listen_addresses = '127.0.0.1'/" /etc/postgresql/$PG_VER/main/postgresql.conf
echo "host all all 127.0.0.1/32 md5" | sudo tee -a /etc/postgresql/$PG_VER/main/pg_hba.conf
sudo pg_ctlcluster $PG_VER main restart
until sudo -u postgres pg_isready -h 127.0.0.1; do sleep 1; done
sudo -u postgres psql -c "CREATE USER test WITH PASSWORD 'test';"
sudo -u postgres psql -c "CREATE DATABASE polympr_test OWNER test;"
sudo -u postgres psql -d polympr_test -c "GRANT ALL ON SCHEMA public TO test;"
- name: Apply migrations
run: |
sed 's/--> statement-breakpoint/;/g' databases/migrations/0000_square_jetstream.sql | \
PGPASSWORD=test psql -h 127.0.0.1 -U test -d polympr_test
- name: Install dependencies
run: npm install --ignore-scripts && deno install
- name: Run integration tests
env:
POSTGRES_HOST: 127.0.0.1
POSTGRES_PORT: 5432
POSTGRES_USER: test
POSTGRES_PASS: test
POSTGRES_DB: polympr_test
run: deno task test:integration
- name: Run e2e tests
env:
POSTGRES_HOST: 127.0.0.1
POSTGRES_PORT: 5432
POSTGRES_USER: test
POSTGRES_PASS: test
POSTGRES_DB: polympr_test
run: deno task test:e2e
+67 -83
View File
@@ -18,8 +18,8 @@ role-based administration.
### Current Status ### Current Status
🚧 **In Progress** - API layer largely complete, UI pages not yet built. The 🚧 **In Progress** - Application is far from complete. The schema below is the
schema below is the **final/definitive schema** that guides all development. **final/definitive schema** that should guide all development.
--- ---
@@ -133,11 +133,15 @@ erDiagram
AJUSTEMENT }o--|| UE : "dans" AJUSTEMENT }o--|| UE : "dans"
``` ```
### Current Schema ### Current Schema (Incomplete)
The Drizzle ORM schema in `/databases/schema.ts` implements all tables: `roles`, The current Drizzle ORM schema in `/databases/schema.ts` only implements:
`permissions`, `rolePermissions`, `users`, `promotions`, `students`, `modules`,
`enseignements`, `ues`, `ueModules`, `notes`, `ajustements`, `mobility`. - `promotions`
- `students`
- `mobility`
**Migration needed**: Update schema to match the final ER diagram above.
--- ---
@@ -182,73 +186,71 @@ The Drizzle ORM schema in `/databases/schema.ts` implements all tables: `roles`,
### API Endpoints ### API Endpoints
Legend: ✅ implemented & tested | 📋 not yet implemented
**Students API** **Students API**
- GET `/students` (#7) - 📋 GET `/students` (#7)
- POST `/students` (#8) - 📋 POST `/students` (#8)
- POST `/students/import-csv` (#9) - 📋 POST `/students/import-csv` (#9)
- GET `/students/{numEtud}` (#10) - 📋 GET `/students/{numEtud}` (#10)
- PUT `/students/{numEtud}` (#11) - 📋 PUT `/students/{numEtud}` (#11)
- DELETE `/students/{numEtud}` (#12) - 📋 DELETE `/students/{numEtud}` (#12)
- GET `/promotions` (#13) - 📋 GET `/promotions` (#13)
- POST `/promotions` (#14) - 📋 POST `/promotions` (#14)
- GET `/promotions/{idPromo}` (#15) - 📋 GET `/promotions/{idPromo}` (#15)
- PUT `/promotions/{idPromo}` (#16) - 📋 PUT `/promotions/{idPromo}` (#16)
- DELETE `/promotions/{idPromo}` (#17) - 📋 DELETE `/promotions/{idPromo}` (#17)
**Administration API - Modules & Enseignements** **Administration API - Modules & Enseignements**
- GET `/modules` (#23) - 📋 GET `/modules` (#23)
- POST `/modules` (#24) - 📋 POST `/modules` (#24)
- GET `/modules/{idModule}` (#25) - 📋 GET `/modules/{idModule}` (#25)
- PUT `/modules/{idModule}` (#26) - 📋 PUT `/modules/{idModule}` (#26)
- DELETE `/modules/{idModule}` (#27) - 📋 DELETE `/modules/{idModule}` (#27)
- POST `/enseignements` (#29) - 📋 POST `/enseignements` (#29)
- GET `/enseignements/{idProf}/{idModule}/{idPromo}` (#30) - 📋 GET `/enseignements/{idProf}/{idModule}/{idPromo}` (#30)
- DELETE `/enseignements/{idProf}/{idModule}/{idPromo}` (#31) - 📋 DELETE `/enseignements/{idProf}/{idModule}/{idPromo}` (#31)
**Notes API - UEs & UE-Modules** **Notes API - UEs & UE-Modules**
- GET `/ues` (#32) - 📋 GET `/ues` (#32)
- POST `/ues` (#33) - 📋 POST `/ues` (#33)
- GET `/ues/{idUE}` (#34) - 📋 GET `/ues/{idUE}` (#34)
- PUT `/ues/{idUE}` (#35) - 📋 PUT `/ues/{idUE}` (#35)
- DELETE `/ues/{idUE}` (#36) - 📋 DELETE `/ues/{idUE}` (#36)
- GET `/ue-modules` (#37) - 📋 GET `/ue-modules` (#37)
- POST `/ue-modules` (#38) - 📋 POST `/ue-modules` (#38)
- GET `/ue-modules/{idModule}/{idUE}/{idPromo}` (#39) - 📋 GET `/ue-modules/{idModule}/{idUE}/{idPromo}` (#39)
- PUT `/ue-modules/{idModule}/{idUE}/{idPromo}` (#40) - 📋 PUT `/ue-modules/{idModule}/{idUE}/{idPromo}` (#40)
- DELETE `/ue-modules/{idModule}/{idUE}/{idPromo}` (#41) - 📋 DELETE `/ue-modules/{idModule}/{idUE}/{idPromo}` (#41)
**Notes API - Notes & Ajustements** **Notes API - Notes & Ajustements**
- GET `/notes` (#42) - 📋 GET `/notes` (#42)
- POST `/notes` (#43) - 📋 POST `/notes` (#43)
- 📋 POST `/notes/import-xlsx` (#44) - 📋 POST `/notes/import-xlsx` (#44)
- GET `/notes/{numEtud}/{idModule}` (#45) - 📋 GET `/notes/{numEtud}/{idModule}` (#45)
- PUT `/notes/{numEtud}/{idModule}` (#46) - 📋 PUT `/notes/{numEtud}/{idModule}` (#46)
- DELETE `/notes/{numEtud}/{idModule}` (#47) - 📋 DELETE `/notes/{numEtud}/{idModule}` (#47)
- GET `/ajustements` (#48) - 📋 GET `/ajustements` (#48)
- POST `/ajustements` (#49) - 📋 POST `/ajustements` (#49)
- GET `/ajustements/{numEtud}/{idUE}` (#50) - 📋 GET `/ajustements/{numEtud}/{idUE}` (#50)
- PUT `/ajustements/{numEtud}/{idUE}` (#51) - 📋 PUT `/ajustements/{numEtud}/{idUE}` (#51)
- DELETE `/ajustements/{numEtud}/{idUE}` (#52) - 📋 DELETE `/ajustements/{numEtud}/{idUE}` (#52)
**Administration API - Users, Roles & Permissions** **Administration API - Users, Roles & Permissions**
- GET `/users` (#60) - 📋 GET `/users` (#60)
- POST `/users` (#61) - 📋 POST `/users` (#61)
- GET `/users/{id}` (#62) - 📋 GET `/users/{id}` (#62)
- PUT `/users/{id}` (#63) - 📋 PUT `/users/{id}` (#63)
- DELETE `/users/{id}` (#64) - 📋 DELETE `/users/{id}` (#64)
- GET `/roles` (#65) - 📋 GET `/roles` (#65)
- POST `/roles` (#66) - 📋 POST `/roles` (#66)
- GET `/roles/{idRole}` (#67) - 📋 GET `/roles/{idRole}` (#67)
- PUT `/roles/{idRole}` (#68) - 📋 PUT `/roles/{idRole}` (#68)
- DELETE `/roles/{idRole}` (#69) - 📋 DELETE `/roles/{idRole}` (#69)
- GET `/permissions` (#70) - 📋 GET `/permissions` (#70)
--- ---
@@ -296,26 +298,10 @@ deno task check
### Testing ### Testing
3-level architecture — all 149 tests pass: - Write unit tests for business logic
- Integration tests for API endpoints
- **Unit** (`tests/unit/`) — pure logic with mock DB + mock API, no real DB - E2E tests with HappyDOM for UI interactions
- **Integration** (`tests/integration/`) — Drizzle ORM direct on real DB - Mock database with provided helpers
- **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
```
--- ---
@@ -341,14 +327,12 @@ nix run nixpkgs#act -- -j integration --no-cache-server # integration + e2e via
## 💡 Important Notes ## 💡 Important Notes
1. **Only missing API**: `POST /notes/import-xlsx` (#44) — all other endpoints 1. **Current Limitation**: The database schema in `/databases/schema.ts` does
are implemented. NOT match the final ER diagram. This is a priority migration task.
2. **Next priority**: UI pages (none built yet) — follow the Figma prototype. 2. **Design System**: Follow the Figma prototype for all UI work.
3. **Module Pattern**: Each module should follow the same pattern: routes, API 3. **Module Pattern**: Each module should follow the same pattern: routes, API
endpoints, components, and tests. endpoints, components, and tests.
4. **Permissions**: All admin operations should respect the ROLE_PERMISSION 4. **Permissions**: All admin operations should respect the ROLE_PERMISSION
system. system.
5. **Fresh Conventions**: Routes use Fresh's file-based routing convention 5. **Fresh Conventions**: Routes use Fresh's file-based routing convention
(e.g., `routes/path/index.tsx`). (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,12 +1,7 @@
FROM denoland/deno:alpine FROM denoland/deno:alpine
RUN apk add --no-cache nodejs npm
WORKDIR /app WORKDIR /app
COPY package.json ./
RUN npm install --omit=dev
COPY . . COPY . .
RUN deno cache main.ts --allow-import RUN deno cache main.ts --allow-import
RUN deno task build RUN deno task build
-38
View File
@@ -1,38 +0,0 @@
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
@@ -1,56 +0,0 @@
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
@@ -1,10 +0,0 @@
#!/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."
@@ -1,11 +0,0 @@
--> 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');
@@ -1,14 +0,0 @@
-- 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";
@@ -1,3 +0,0 @@
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,27 +8,6 @@
"when": 1777155028708, "when": 1777155028708,
"tag": "0000_square_jetstream", "tag": "0000_square_jetstream",
"breakpoints": true "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,7 +75,6 @@ export const notes = pgTable("notes", {
numEtud: integer("numEtud").notNull().references(() => students.numEtud), numEtud: integer("numEtud").notNull().references(() => students.numEtud),
idModule: text("idModule").notNull().references(() => modules.id), idModule: text("idModule").notNull().references(() => modules.id),
note: doublePrecision("note").notNull(), note: doublePrecision("note").notNull(),
noteSession2: doublePrecision("noteSession2"),
}, (t) => ({ }, (t) => ({
pk: primaryKey({ columns: [t.numEtud, t.idModule] }), pk: primaryKey({ columns: [t.numEtud, t.idModule] }),
})); }));
@@ -84,7 +83,6 @@ export const ajustements = pgTable("ajustements", {
numEtud: integer("numEtud").notNull().references(() => students.numEtud), numEtud: integer("numEtud").notNull().references(() => students.numEtud),
idUE: integer("idUE").notNull().references(() => ues.id), idUE: integer("idUE").notNull().references(() => ues.id),
valeur: doublePrecision("valeur").notNull(), valeur: doublePrecision("valeur").notNull(),
malus: integer("malus").notNull().default(0),
}, (t) => ({ }, (t) => ({
pk: primaryKey({ columns: [t.numEtud, t.idUE] }), pk: primaryKey({ columns: [t.numEtud, t.idUE] }),
})); }));
-358
View File
@@ -1,358 +0,0 @@
-- ============================================================
-- 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
@@ -1,102 +0,0 @@
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,7 +19,6 @@ export interface AppProperties {
icon: string; icon: string;
pages: Record<string, string>; pages: Record<string, string>;
adminOnly: string[]; adminOnly: string[];
studentOnly?: string[];
hint: string; hint: string;
} }
-3
View File
@@ -13,9 +13,6 @@
"test": "deno test -A --no-check tests/", "test": "deno test -A --no-check tests/",
"test:unit": "deno test -A --no-check tests/unit/", "test:unit": "deno test -A --no-check tests/unit/",
"test:integration": "deno test -A --no-check tests/integration/", "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" "migrate": "node_modules/.bin/drizzle-kit migrate"
}, },
"lint": { "lint": {
+1 -3
View File
@@ -2,9 +2,7 @@ import { defineConfig } from "drizzle-kit";
import process from "node:process"; import process from "node:process";
const url = process.env.DATABASE_URL ?? const url = process.env.DATABASE_URL ??
`postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASS}@${ `postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASS}@${process.env.POSTGRES_HOST ?? "localhost"}:${process.env.POSTGRES_PORT ?? 5432}/${process.env.POSTGRES_DB}`;
process.env.POSTGRES_HOST ?? "localhost"
}:${process.env.POSTGRES_PORT ?? 5432}/${process.env.POSTGRES_DB}`;
export default defineConfig({ export default defineConfig({
dialect: "postgresql", dialect: "postgresql",
-142
View File
@@ -4,55 +4,16 @@
import * as $_apps_layout from "./routes/(apps)/_layout.tsx"; import * as $_apps_layout from "./routes/(apps)/_layout.tsx";
import * as $_apps_middleware from "./routes/(apps)/_middleware.ts"; 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_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_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_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_index from "./routes/(apps)/mobility/partials/index.tsx";
import * as $_apps_mobility_partials_overview from "./routes/(apps)/mobility/partials/overview.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_index from "./routes/(apps)/notes/index.tsx";
import * as $_apps_notes_partials_admin_courses from "./routes/(apps)/notes/partials/(admin)/courses.tsx"; import * as $_apps_notes_partials_admin_courses from "./routes/(apps)/notes/partials/(admin)/courses.tsx";
import * as $_apps_notes_partials_admin_import from "./routes/(apps)/notes/partials/(admin)/import.tsx";
import * as $_apps_notes_partials_index from "./routes/(apps)/notes/partials/index.tsx"; import * as $_apps_notes_partials_index from "./routes/(apps)/notes/partials/index.tsx";
import * as $_apps_notes_partials_notes from "./routes/(apps)/notes/partials/notes.tsx"; import * as $_apps_notes_partials_notes from "./routes/(apps)/notes/partials/notes.tsx";
import * as $_apps_notes_recap_numEtud_ from "./routes/(apps)/notes/recap/[numEtud].tsx";
import * as $_apps_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 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_index from "./routes/(apps)/students/index.tsx";
import * as $_apps_students_partials_admin_consult from "./routes/(apps)/students/partials/(admin)/consult.tsx"; import * as $_apps_students_partials_admin_consult from "./routes/(apps)/students/partials/(admin)/consult.tsx";
import * as $_apps_students_partials_admin_upload from "./routes/(apps)/students/partials/(admin)/upload.tsx"; import * as $_apps_students_partials_admin_upload from "./routes/(apps)/students/partials/(admin)/upload.tsx";
@@ -63,29 +24,14 @@ import * as $_app from "./routes/_app.tsx";
import * as $_middleware from "./routes/_middleware.ts"; import * as $_middleware from "./routes/_middleware.ts";
import * as $about from "./routes/about.tsx"; import * as $about from "./routes/about.tsx";
import * as $apps from "./routes/apps.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 $index from "./routes/index.tsx";
import * as $login from "./routes/login.tsx"; import * as $login from "./routes/login.tsx";
import * as $logout from "./routes/logout.tsx"; import * as $logout from "./routes/logout.tsx";
import * as $_islands_AppNavigator from "./routes/(_islands)/AppNavigator.tsx"; import * as $_islands_AppNavigator from "./routes/(_islands)/AppNavigator.tsx";
import * as $_islands_Navbar from "./routes/(_islands)/Navbar.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_ConsultMobility from "./routes/(apps)/mobility/(_islands)/ConsultMobility.tsx";
import * as $_apps_mobility_islands_EditMobility from "./routes/(apps)/mobility/(_islands)/EditMobility.tsx"; import * as $_apps_mobility_islands_EditMobility from "./routes/(apps)/mobility/(_islands)/EditMobility.tsx";
import * as $_apps_mobility_islands_ImportFile from "./routes/(apps)/mobility/(_islands)/ImportFile.tsx"; import * as $_apps_mobility_islands_ImportFile from "./routes/(apps)/mobility/(_islands)/ImportFile.tsx";
import * as $_apps_notes_islands_AdminConsultNotes from "./routes/(apps)/notes/(_islands)/AdminConsultNotes.tsx";
import * as $_apps_notes_islands_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_ConsultStudents from "./routes/(apps)/students/(_islands)/ConsultStudents.tsx";
import * as $_apps_students_islands_EditStudents from "./routes/(apps)/students/(_islands)/EditStudents.tsx"; import * as $_apps_students_islands_EditStudents from "./routes/(apps)/students/(_islands)/EditStudents.tsx";
import * as $_apps_students_islands_UploadStudents from "./routes/(apps)/students/(_islands)/UploadStudents.tsx"; import * as $_apps_students_islands_UploadStudents from "./routes/(apps)/students/(_islands)/UploadStudents.tsx";
@@ -95,42 +41,6 @@ const manifest = {
routes: { routes: {
"./routes/(apps)/_layout.tsx": $_apps_layout, "./routes/(apps)/_layout.tsx": $_apps_layout,
"./routes/(apps)/_middleware.ts": $_apps_middleware, "./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": "./routes/(apps)/mobility/api/insert_mobility.ts":
$_apps_mobility_api_insert_mobility, $_apps_mobility_api_insert_mobility,
"./routes/(apps)/mobility/index.tsx": $_apps_mobility_index, "./routes/(apps)/mobility/index.tsx": $_apps_mobility_index,
@@ -140,35 +50,12 @@ const manifest = {
$_apps_mobility_partials_index, $_apps_mobility_partials_index,
"./routes/(apps)/mobility/partials/overview.tsx": "./routes/(apps)/mobility/partials/overview.tsx":
$_apps_mobility_partials_overview, $_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/index.tsx": $_apps_notes_index,
"./routes/(apps)/notes/partials/(admin)/courses.tsx": "./routes/(apps)/notes/partials/(admin)/courses.tsx":
$_apps_notes_partials_admin_courses, $_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/index.tsx": $_apps_notes_partials_index,
"./routes/(apps)/notes/partials/notes.tsx": $_apps_notes_partials_notes, "./routes/(apps)/notes/partials/notes.tsx": $_apps_notes_partials_notes,
"./routes/(apps)/notes/recap/[numEtud].tsx": $_apps_notes_recap_numEtud_,
"./routes/(apps)/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.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/index.tsx": $_apps_students_index,
"./routes/(apps)/students/partials/(admin)/consult.tsx": "./routes/(apps)/students/partials/(admin)/consult.tsx":
$_apps_students_partials_admin_consult, $_apps_students_partials_admin_consult,
@@ -182,7 +69,6 @@ const manifest = {
"./routes/_middleware.ts": $_middleware, "./routes/_middleware.ts": $_middleware,
"./routes/about.tsx": $about, "./routes/about.tsx": $about,
"./routes/apps.tsx": $apps, "./routes/apps.tsx": $apps,
"./routes/dev-login.ts": $dev_login,
"./routes/index.tsx": $index, "./routes/index.tsx": $index,
"./routes/login.tsx": $login, "./routes/login.tsx": $login,
"./routes/logout.tsx": $logout, "./routes/logout.tsx": $logout,
@@ -190,40 +76,12 @@ const manifest = {
islands: { islands: {
"./routes/(_islands)/AppNavigator.tsx": $_islands_AppNavigator, "./routes/(_islands)/AppNavigator.tsx": $_islands_AppNavigator,
"./routes/(_islands)/Navbar.tsx": $_islands_Navbar, "./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": "./routes/(apps)/mobility/(_islands)/ConsultMobility.tsx":
$_apps_mobility_islands_ConsultMobility, $_apps_mobility_islands_ConsultMobility,
"./routes/(apps)/mobility/(_islands)/EditMobility.tsx": "./routes/(apps)/mobility/(_islands)/EditMobility.tsx":
$_apps_mobility_islands_EditMobility, $_apps_mobility_islands_EditMobility,
"./routes/(apps)/mobility/(_islands)/ImportFile.tsx": "./routes/(apps)/mobility/(_islands)/ImportFile.tsx":
$_apps_mobility_islands_ImportFile, $_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": "./routes/(apps)/students/(_islands)/ConsultStudents.tsx":
$_apps_students_islands_ConsultStudents, $_apps_students_islands_ConsultStudents,
"./routes/(apps)/students/(_islands)/EditStudents.tsx": "./routes/(apps)/students/(_islands)/EditStudents.tsx":
+1 -1
View File
@@ -1,12 +1,12 @@
{ {
"dependencies": { "dependencies": {
"dotenv": "^17.4.0", "dotenv": "^17.4.0",
"drizzle-kit": "^0.31.10",
"drizzle-orm": "^0.45.2", "drizzle-orm": "^0.45.2",
"pg": "^8.20.0" "pg": "^8.20.0"
}, },
"devDependencies": { "devDependencies": {
"@types/pg": "^8.20.0", "@types/pg": "^8.20.0",
"drizzle-kit": "^0.31.10",
"tsx": "^4.21.0" "tsx": "^4.21.0"
} }
} }
+5 -14
View File
@@ -21,23 +21,14 @@ export const handler: MiddlewareHandler<AuthenticatedState>[] = [
`./${currentApp}/(_props)/props.ts` `./${currentApp}/(_props)/props.ts`
)).default; )).default;
context.state.availablePages = { ...properties.pages }; context.state.availablePages = properties.pages;
const isStudent = if (
context.state.session.eduPersonPrimaryAffiliation === "student"; context.state.session.eduPersonPrimaryAffiliation == "student" &&
const isLocal = Deno.env.get("LOCAL") === "true"; Deno.env.get("LOCAL") != "true"
) {
if (isStudent) {
// Students only see studentOnly pages (+ non-restricted pages)
properties.adminOnly.forEach((page) => properties.adminOnly.forEach((page) =>
delete context.state.availablePages[page] delete context.state.availablePages[page]
); );
} else if (isLocal) {
// In local mode, employees see all pages (admin + student)
} else {
// In prod, employees don't see studentOnly pages
properties.studentOnly?.forEach((page) =>
delete context.state.availablePages[page]
);
} }
return await context.next(); return await context.next();
@@ -1,331 +0,0 @@
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>
);
}
@@ -1,254 +0,0 @@
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>
);
}
@@ -1,128 +0,0 @@
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>
);
}
@@ -1,263 +0,0 @@
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>
);
}
@@ -1,323 +0,0 @@
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
@@ -1,516 +0,0 @@
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>
);
}
@@ -1,308 +0,0 @@
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>
);
}
@@ -1,344 +0,0 @@
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
@@ -1,391 +0,0 @@
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>
);
}
@@ -1,531 +0,0 @@
// @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>
);
}
+2 -10
View File
@@ -4,17 +4,9 @@ const properties: AppProperties = {
name: "Admin", name: "Admin",
icon: "school", icon: "school",
pages: { pages: {
index: "Accueil", index: "Homepage",
users: "Utilisateurs",
roles: "Rôles",
permissions: "Permissions",
modules: "Modules",
enseignements: "Enseignements",
promotions: "Promotions",
ues: "UEs",
"import-maquette": "Import Maquette",
}, },
adminOnly: ["users", "roles", "permissions", "modules", "enseignements", "promotions", "ues", "import-maquette"], adminOnly: [],
hint: "PolyMPR module", hint: "PolyMPR module",
}; };
+16 -35
View File
@@ -4,52 +4,33 @@ import { enseignements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { and, eq } from "npm:drizzle-orm@0.45.2";
const _NOT_FOUND = () => const _NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ressource introuvable" }),
JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
const FORBIDDEN = () => new Response(null, { status: 403 }); const FORBIDDEN = new Response(null, { status: 403 });
const CONFLICT = () => const CONFLICT = new Response(
new Response( JSON.stringify({ error: "Cet enseignement existe déjà." }),
JSON.stringify({ error: "Cet enseignement existe déjà." }), { status: 409, headers: { "content-type": "application/json" } },
{ status: 409, headers: { "content-type": "application/json" } }, );
);
export const handler: Handlers<null, AuthenticatedState> = { 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 // #29 POST /enseignements
async POST( async POST(
request: Request, request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
let body: { idProf: string; idModule: string; idPromo: string }; const body: {
try { idProf: string;
body = await request.json(); idModule: string;
} catch { idPromo: string;
return new Response(null, { status: 500 }); } = await request.json();
}
if (!body.idProf || !body.idModule || !body.idPromo) { if (!body.idProf || !body.idModule || !body.idPromo) {
return new Response(null, { status: 400 }); return new Response(null, { status: 400 });
@@ -69,7 +50,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (existing) { if (existing) {
return CONFLICT(); return CONFLICT;
} }
const [created] = await db const [created] = await db
@@ -4,13 +4,12 @@ import { enseignements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ressource introuvable" }),
JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
const FORBIDDEN = () => new Response(null, { status: 403 }); const FORBIDDEN = new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #30 GET /enseignements/{idProf}/{idModule}/{idPromo} // #30 GET /enseignements/{idProf}/{idModule}/{idPromo}
@@ -19,7 +18,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const idProf = context.params.idProf; const idProf = context.params.idProf;
@@ -38,7 +37,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!enseignement) return NOT_FOUND(); if (!enseignement) return NOT_FOUND;
return new Response(JSON.stringify(enseignement), { return new Response(JSON.stringify(enseignement), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -51,7 +50,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const idProf = context.params.idProf; const idProf = context.params.idProf;
@@ -69,7 +68,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.returning(); .returning();
if (!deleted) return NOT_FOUND(); if (!deleted) return NOT_FOUND;
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+9 -8
View File
@@ -8,8 +8,14 @@ export const handler: Handlers<null, AuthenticatedState> = {
// #23 GET /modules // #23 GET /modules
async GET( async GET(
_request: Request, _request: Request,
_context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return new Response(JSON.stringify([]), {
headers: { "content-type": "application/json" },
});
}
const rows = await db.select().from(modules); const rows = await db.select().from(modules);
return new Response(JSON.stringify(rows), { return new Response(JSON.stringify(rows), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -25,14 +31,9 @@ export const handler: Handlers<null, AuthenticatedState> = {
return new Response(null, { status: 403 }); return new Response(null, { status: 403 });
} }
let body: { id: string; nom: string }; const body: { id: string; nom: string } = await request.json();
try {
body = await request.json();
} catch {
return new Response(null, { status: 500 });
}
if (!body.id || !body.id.trim() || !body.nom || !body.nom.trim()) { if (!body.id || !body.nom) {
return new Response(null, { status: 400 }); return new Response(null, { status: 400 });
} }
+13 -41
View File
@@ -1,19 +1,13 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { import { modules } from "$root/databases/schema.ts";
enseignements,
modules,
notes,
ueModules,
} from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ressource introuvable" }),
JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #25 GET /modules/{idModule} // #25 GET /modules/{idModule}
@@ -27,7 +21,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(modules.id, context.params.idModule)) .where(eq(modules.id, context.params.idModule))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!module) return NOT_FOUND(); if (!module) return NOT_FOUND;
return new Response(JSON.stringify(module), { return new Response(JSON.stringify(module), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -39,16 +33,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
request: Request, request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
let body: { nom: string }; const body: { nom: string } = await request.json();
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 const [updated] = await db
.update(modules) .update(modules)
@@ -56,7 +41,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(modules.id, context.params.idModule)) .where(eq(modules.id, context.params.idModule))
.returning(); .returning();
if (!updated) return NOT_FOUND(); if (!updated) return NOT_FOUND;
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -64,29 +49,16 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #27 DELETE /modules/{idModule} // #27 DELETE /modules/{idModule}
// Cascade: deletes notes, ue_modules, enseignements for this module.
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
const idModule = context.params.idModule; const [deleted] = await db
.delete(modules)
.where(eq(modules.id, context.params.idModule))
.returning();
const mod = await db if (!deleted) return NOT_FOUND;
.select()
.from(modules)
.where(eq(modules.id, idModule))
.then((r) => r[0] ?? null);
if (!mod) return NOT_FOUND();
await db.transaction(async (tx) => {
await tx.delete(notes).where(eq(notes.idModule, idModule));
await tx.delete(ueModules).where(eq(ueModules.idModule, idModule));
await tx.delete(enseignements).where(
eq(enseignements.idModule, idModule),
);
await tx.delete(modules).where(eq(modules.id, idModule));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+15 -9
View File
@@ -1,15 +1,21 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { 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"; 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> = { export const handler: Handlers<null, AuthenticatedState> = {
async GET( GET(_request, _context): Response {
_request: Request, return new Response(JSON.stringify(PERMISSIONS), {
_context: FreshContext<AuthenticatedState>,
): Promise<Response> {
const result = await db.select().from(permissions);
return new Response(JSON.stringify(result), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
}); });
}, },
+14 -23
View File
@@ -1,14 +1,13 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { rolePermissions, roles, users } from "$root/databases/schema.ts"; import { rolePermissions, roles } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ressource introuvable" }),
JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
async function getRoleWithPermissions( async function getRoleWithPermissions(
id: number, id: number,
@@ -42,7 +41,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const id = Number(context.params.idRole); const id = Number(context.params.idRole);
const role = await getRoleWithPermissions(id); const role = await getRoleWithPermissions(id);
if (!role) return NOT_FOUND(); if (!role) return NOT_FOUND;
return new Response(JSON.stringify(role), { return new Response(JSON.stringify(role), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -63,7 +62,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(roles.id, id)) .where(eq(roles.id, id))
.returning(); .returning();
if (!updated) return NOT_FOUND(); if (!updated) return NOT_FOUND;
// Reset permissions // Reset permissions
await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id)); await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id));
@@ -81,29 +80,21 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #69 DELETE /roles/{idRole} // #69 DELETE /roles/{idRole}
// Cascade: deletes role_permissions, detaches users (idRole set to null).
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
const id = Number(context.params.idRole); const id = Number(context.params.idRole);
const role = await db // Cascade delete role_permissions first
.select() await db.delete(rolePermissions).where(eq(rolePermissions.idRole, id));
.from(roles)
const [deleted] = await db
.delete(roles)
.where(eq(roles.id, id)) .where(eq(roles.id, id))
.then((r) => r[0] ?? null); .returning();
if (!role) return NOT_FOUND(); if (!deleted) return NOT_FOUND;
await db.transaction(async (tx) => {
await tx.delete(rolePermissions).where(eq(rolePermissions.idRole, id));
await tx
.update(users)
.set({ idRole: null })
.where(eq(users.idRole, id));
await tx.delete(roles).where(eq(roles.id, id));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+3 -10
View File
@@ -27,17 +27,10 @@ export const handler: Handlers<null, AuthenticatedState> = {
request: Request, request: Request,
_context: FreshContext<AuthenticatedState>, _context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
let body: { id: string; nom: string; prenom: string; idRole: number }; const body: { id: string; nom: string; prenom: string; idRole: number } =
try { await request.json();
body = await request.json();
} catch {
return new Response(null, { status: 500 });
}
if ( if (!body.id || !body.nom || !body.prenom) {
!body.id || !body.id.trim() || !body.nom || !body.nom.trim() ||
!body.prenom || !body.prenom.trim()
) {
return new Response(null, { status: 400 }); return new Response(null, { status: 400 });
} }
+12 -22
View File
@@ -1,14 +1,13 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { enseignements, users } from "$root/databases/schema.ts"; import { users } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ressource introuvable" }),
JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #62 GET /users/{id} // #62 GET /users/{id}
@@ -22,7 +21,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(users.id, context.params.id)) .where(eq(users.id, context.params.id))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!user) return NOT_FOUND(); if (!user) return NOT_FOUND;
return new Response(JSON.stringify(user), { return new Response(JSON.stringify(user), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -43,7 +42,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(users.id, context.params.id)) .where(eq(users.id, context.params.id))
.returning(); .returning();
if (!updated) return NOT_FOUND(); if (!updated) return NOT_FOUND;
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -51,25 +50,16 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #64 DELETE /users/{id} // #64 DELETE /users/{id}
// Cascade: deletes enseignements for this user.
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
const id = context.params.id; const [deleted] = await db
.delete(users)
.where(eq(users.id, context.params.id))
.returning();
const user = await db if (!deleted) return NOT_FOUND;
.select()
.from(users)
.where(eq(users.id, id))
.then((r) => r[0] ?? null);
if (!user) return NOT_FOUND();
await db.transaction(async (tx) => {
await tx.delete(enseignements).where(eq(enseignements.idProf, id));
await tx.delete(users).where(eq(users.id, id));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
@@ -1,11 +0,0 @@
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} />;
}
@@ -1,18 +0,0 @@
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);
@@ -1,23 +0,0 @@
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);
+3 -34
View File
@@ -3,41 +3,10 @@ import {
makePartials, makePartials,
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts"; import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts"; import { State } from "$root/routes/_middleware.ts";
// deno-lint-ignore require-await export function Index(_request: Request, _context: FreshContext<State>) {
export async function Index( return <h2>Welcome to Admin.</h2>;
_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(); export const config = getPartialsConfig();
-18
View File
@@ -1,18 +0,0 @@
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);
@@ -1,18 +0,0 @@
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);
@@ -1,18 +0,0 @@
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
@@ -1,18 +0,0 @@
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
@@ -1,18 +0,0 @@
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
@@ -1,18 +0,0 @@
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
@@ -1,11 +0,0 @@
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} />;
}
@@ -1,155 +0,0 @@
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>
);
}
@@ -1,619 +0,0 @@
// @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>
);
}
@@ -1,587 +0,0 @@
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>
);
}
@@ -1,249 +0,0 @@
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>
);
}
+4 -6
View File
@@ -4,13 +4,11 @@ const properties: AppProperties = {
name: "PolyNotes", name: "PolyNotes",
icon: "school", icon: "school",
pages: { pages: {
index: "Accueil", index: "Homepage",
notes: "Mes notes", notes: "Notes",
courses: "Consulter", courses: "Courses management",
import: "Import Notes",
}, },
adminOnly: ["courses", "import"], adminOnly: ["courses", "students"],
studentOnly: ["notes"],
hint: "Student grading management", hint: "Student grading management",
}; };
+2 -17
View File
@@ -52,12 +52,8 @@ export const handler: Handlers<null, AuthenticatedState> = {
} }
try { try {
const body: { const body: { numEtud: number; idUE: number; valeur: number } =
numEtud: number; await request.json();
idUE: number;
valeur: number;
malus?: number;
} = await request.json();
if (!body.numEtud || !body.idUE || body.valeur === undefined) { if (!body.numEtud || !body.idUE || body.valeur === undefined) {
return new Response( return new Response(
@@ -66,23 +62,12 @@ export const handler: Handlers<null, AuthenticatedState> = {
); );
} }
if (
body.malus !== undefined &&
(!Number.isInteger(body.malus) || body.malus < 0)
) {
return new Response(
JSON.stringify({ error: "malus doit être un entier >= 0" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
}
const [created] = await db const [created] = await db
.insert(ajustements) .insert(ajustements)
.values({ .values({
numEtud: body.numEtud, numEtud: body.numEtud,
idUE: body.idUE, idUE: body.idUE,
valeur: body.valeur, valeur: body.valeur,
malus: body.malus ?? 0,
}) })
.returning(); .returning();
@@ -2,15 +2,14 @@ import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { ajustements } from "$root/databases/schema.ts"; import { ajustements } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ajustement introuvable" }),
JSON.stringify({ error: "Ajustement introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
const FORBIDDEN = () => new Response(null, { status: 403 }); const FORBIDDEN = new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #50 GET /ajustements/{numEtud}/{idUE} // #50 GET /ajustements/{numEtud}/{idUE}
@@ -19,7 +18,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -32,10 +31,10 @@ export const handler: Handlers<null, AuthenticatedState> = {
const ajustement = await db const ajustement = await db
.select() .select()
.from(ajustements) .from(ajustements)
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))) .where(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!ajustement) return NOT_FOUND(); if (!ajustement) return NOT_FOUND;
return new Response(JSON.stringify(ajustement), { return new Response(JSON.stringify(ajustement), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -48,7 +47,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -58,7 +57,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
return new Response("Paramètres invalides", { status: 400 }); return new Response("Paramètres invalides", { status: 400 });
} }
const body: { valeur: number; malus?: number } = await request.json(); const body: { valeur: number } = await request.json();
if (body.valeur === undefined) { if (body.valeur === undefined) {
return new Response(JSON.stringify({ error: "Champ requis: valeur" }), { return new Response(JSON.stringify({ error: "Champ requis: valeur" }), {
@@ -67,28 +66,13 @@ export const handler: Handlers<null, AuthenticatedState> = {
}); });
} }
if (
body.malus !== undefined &&
(!Number.isInteger(body.malus) || body.malus < 0)
) {
return new Response(
JSON.stringify({ error: "malus doit être un entier >= 0" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
}
const set: { valeur: number; malus?: number } = { valeur: body.valeur };
if (body.malus !== undefined) {
set.malus = body.malus;
}
const [updated] = await db const [updated] = await db
.update(ajustements) .update(ajustements)
.set(set) .set({ valeur: body.valeur })
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))) .where(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))
.returning(); .returning();
if (!updated) return NOT_FOUND(); if (!updated) return NOT_FOUND;
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -101,7 +85,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -113,10 +97,10 @@ export const handler: Handlers<null, AuthenticatedState> = {
const [deleted] = await db const [deleted] = await db
.delete(ajustements) .delete(ajustements)
.where(and(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))) .where(eq(ajustements.numEtud, numEtud), eq(ajustements.idUE, idUE))
.returning(); .returning();
if (!deleted) return NOT_FOUND(); if (!deleted) return NOT_FOUND;
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+2 -33
View File
@@ -41,7 +41,7 @@ export const handler: Handlers = {
async POST(request) { async POST(request) {
try { try {
const body = await request.json(); const body = await request.json();
const { note, numEtud, idModule, noteSession2 } = body; const { note, numEtud, idModule } = body;
if (note === undefined || !numEtud || !idModule) { if (note === undefined || !numEtud || !idModule) {
return new Response("Champs 'note', 'numEtud' et 'idModule' requis", { return new Response("Champs 'note', 'numEtud' et 'idModule' requis", {
@@ -49,38 +49,7 @@ export const handler: Handlers = {
}); });
} }
if (typeof note !== "number" || note < 0 || note > 20) { const result = await db.insert(notes).values({ note, numEtud, idModule })
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(); .returning();
return new Response(JSON.stringify(result[0]), { return new Response(JSON.stringify(result[0]), {
@@ -64,39 +64,13 @@ export const handler: Handlers = {
} }
const body = await request.json(); const body = await request.json();
const { note, noteSession2 } = body; const { note } = body;
if (note === undefined && noteSession2 === undefined) { if (note === undefined) {
return new Response("Au moins 'note' ou 'noteSession2' requis", { return new Response("Champ 'note' manquant", { status: 400 });
status: 400,
});
} }
if ( const result = await db.update(notes).set({ note }).where(
note !== undefined &&
(typeof note !== "number" || note < 0 || note > 20)
) {
return new Response("Champ 'note' doit être un nombre entre 0 et 20", {
status: 400,
});
}
if (
noteSession2 !== undefined && noteSession2 !== null &&
(typeof noteSession2 !== "number" || noteSession2 < 0 ||
noteSession2 > 20)
) {
return new Response(
"Champ 'noteSession2' doit être un nombre entre 0 et 20",
{ status: 400 },
);
}
const set: { note?: number; noteSession2?: number | null } = {};
if (note !== undefined) set.note = note;
if (noteSession2 !== undefined) set.noteSession2 = noteSession2;
const result = await db.update(notes).set(set).where(
and( and(
eq(notes.numEtud, numEtud), eq(notes.numEtud, numEtud),
eq(notes.idModule, idModule), eq(notes.idModule, idModule),
@@ -1,70 +0,0 @@
// @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 });
}
},
};
@@ -47,12 +47,6 @@ 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({ const result = await db.insert(ueModules).values({
idModule, idModule,
idUE, idUE,
@@ -4,19 +4,17 @@ import { ueModules } from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { and, eq } from "npm:drizzle-orm@0.45.2"; import { and, eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Association UE-Module introuvable" }),
JSON.stringify({ error: "Association UE-Module introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
const FORBIDDEN = () => new Response(null, { status: 403 }); const FORBIDDEN = new Response(null, { status: 403 });
const BAD_REQUEST = () => const BAD_REQUEST = new Response(
new Response( JSON.stringify({ error: "Paramètres invalides" }),
JSON.stringify({ error: "Paramètres invalides" }), { status: 400, headers: { "content-type": "application/json" } },
{ status: 400, headers: { "content-type": "application/json" } }, );
);
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #39 GET /ue-modules/{idModule}/{idUE}/{idPromo} // #39 GET /ue-modules/{idModule}/{idUE}/{idPromo}
@@ -25,7 +23,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const idModule = context.params.idModule; const idModule = context.params.idModule;
@@ -33,7 +31,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo; const idPromo = context.params.idPromo;
if (isNaN(idUE)) { if (isNaN(idUE)) {
return BAD_REQUEST(); return BAD_REQUEST;
} }
const ueModuleAssociation = await db const ueModuleAssociation = await db
@@ -46,7 +44,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!ueModuleAssociation) return NOT_FOUND(); if (!ueModuleAssociation) return NOT_FOUND;
return new Response(JSON.stringify(ueModuleAssociation), { return new Response(JSON.stringify(ueModuleAssociation), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -59,7 +57,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const idModule = context.params.idModule; const idModule = context.params.idModule;
@@ -67,7 +65,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo; const idPromo = context.params.idPromo;
if (isNaN(idUE)) { if (isNaN(idUE)) {
return BAD_REQUEST(); return BAD_REQUEST;
} }
const body: { coeff: number } = await request.json(); const body: { coeff: number } = await request.json();
@@ -91,7 +89,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.returning(); .returning();
if (!updated) return NOT_FOUND(); if (!updated) return NOT_FOUND;
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
@@ -112,7 +110,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const idModule = context.params.idModule; const idModule = context.params.idModule;
@@ -120,7 +118,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
const idPromo = context.params.idPromo; const idPromo = context.params.idPromo;
if (isNaN(idUE)) { if (isNaN(idUE)) {
return BAD_REQUEST(); return BAD_REQUEST;
} }
const [deleted] = await db const [deleted] = await db
@@ -134,7 +132,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
) )
.returning(); .returning();
if (!deleted) return NOT_FOUND(); if (!deleted) return NOT_FOUND;
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
@@ -24,7 +24,7 @@ export const handler: Handlers = {
const body = await request.json(); const body = await request.json();
const { nom } = body; const { nom } = body;
if (!nom || !nom.trim()) { if (!nom) {
return new Response("Champ 'nom' manquant", { status: 400 }); return new Response("Champ 'nom' manquant", { status: 400 });
} }
@@ -1,10 +1,6 @@
import { Handlers } from "$fresh/server.ts"; import { Handlers } from "$fresh/server.ts";
import { db } from "../../../../../databases/db.ts"; import { db } from "../../../../../databases/db.ts";
import { import { ues } from "../../../../../databases/schema.ts";
ajustements,
ueModules,
ues,
} from "../../../../../databases/schema.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
export const handler: Handlers = { export const handler: Handlers = {
@@ -91,7 +87,6 @@ export const handler: Handlers = {
}, },
// #36 DELETE /ues/:idUE // #36 DELETE /ues/:idUE
// Cascade: deletes ajustements, ue_modules for this UE.
async DELETE(_request, context) { async DELETE(_request, context) {
try { try {
const idUE = parseInt(context.params.idUE); const idUE = parseInt(context.params.idUE);
@@ -106,9 +101,9 @@ export const handler: Handlers = {
); );
} }
const existing = await db.select().from(ues).where(eq(ues.id, idUE)); const result = await db.delete(ues).where(eq(ues.id, idUE)).returning();
if (existing.length === 0) { if (result.length === 0) {
return new Response( return new Response(
JSON.stringify({ error: "Ressource introuvable" }), JSON.stringify({ error: "Ressource introuvable" }),
{ {
@@ -118,12 +113,6 @@ export const handler: Handlers = {
); );
} }
await db.transaction(async (tx) => {
await tx.delete(ajustements).where(eq(ajustements.idUE, idUE));
await tx.delete(ueModules).where(eq(ueModules.idUE, idUE));
await tx.delete(ues).where(eq(ues.id, idUE));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
} catch (error) { } catch (error) {
console.error("Error deleting UE:", error); console.error("Error deleting UE:", error);
-12
View File
@@ -1,12 +0,0 @@
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,12 +3,11 @@ import {
makePartials, makePartials,
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts"; import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts"; import { State } from "$root/routes/_middleware.ts";
import AdminConsultNotes from "../../(_islands)/AdminConsultNotes.tsx";
// deno-lint-ignore require-await // deno-lint-ignore require-await
async function Courses(_request: Request, _context: FreshContext<State>) { async function Courses(_request: Request, context: FreshContext<State>) {
return <AdminConsultNotes />; return <h2>Welcome to {context.state.session?.displayName}.</h2>;
} }
export const config = getPartialsConfig(); export const config = getPartialsConfig();
@@ -1,23 +0,0 @@
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);
+3 -45
View File
@@ -3,53 +3,11 @@ import {
makePartials, makePartials,
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts"; import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts"; import { State } from "$root/routes/_middleware.ts";
// deno-lint-ignore require-await // deno-lint-ignore require-await
export async function Index( export async function Index(_request: Request, context: FreshContext<State>) {
_request: Request, return <h2>Welcome to {context.state.session?.displayName}.</h2>;
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(); export const config = getPartialsConfig();
+5 -49
View File
@@ -1,57 +1,13 @@
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 { import {
getPartialsConfig, getPartialsConfig,
makePartials, makePartials,
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { CasContent, State } from "$root/defaults/interfaces.ts"; import { FreshContext } from "$fresh/server.ts";
import NotesView from "../(_islands)/NotesView.tsx"; import { State } from "$root/routes/_middleware.ts";
async function Notes( // deno-lint-ignore require-await
_request: Request, async function Notes(_request: Request, context: FreshContext<State>) {
context: FreshContext<State>, return <h2>Welcome to {context.state.session?.displayName}.</h2>;
) {
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(); export const config = getPartialsConfig();
-12
View File
@@ -1,12 +0,0 @@
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,313 +1,45 @@
import { useEffect, useState } from "preact/hooks"; import { useEffect, useState } from "preact/hooks";
import Promotion from "$root/routes/(apps)/students/(_components)/Promotion.tsx";
type Student = { type SingleUserResponse = { promo: Promotion; student: Student };
numEtud: number; type ManyUsersResponse = { promos: Promotion[]; students: Student[] };
nom: string;
prenom: string; type APIResponse = SingleUserResponse | ManyUsersResponse;
idPromo: string;
};
type Promotion = { id: string; annee: string };
export default function ConsultStudents() { export default function ConsultStudents() {
const [students, setStudents] = useState<Student[]>([]); const [data, setData] = useState<APIResponse | null>(null);
const [promos, setPromos] = useState<Promotion[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); 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(() => { useEffect(() => {
load(); 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();
}, []); }, []);
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 ( return (
<div class="page-content"> <>
<h2 class="page-title">Gestion des Élèves</h2> {error && <p className="error">{error}</p>}
{data && ((Object.hasOwn(data, "student"))
{error && <p class="state-error">{error}</p>} ? (
<Promotion
<div class="toolbar"> students={[(data as SingleUserResponse).student]}
<a promo={(data as SingleUserResponse).promo}
class="btn btn-primary" />
href="/students/upload" )
f-partial="/students/partials/upload" : (data as ManyUsersResponse).promos.map((promo) => (
style="margin-left: auto" <Promotion
> students={(data as ManyUsersResponse).students}
Importer xlsx promo={promo}
</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>
); );
} }
@@ -1,239 +0,0 @@
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,175 +1,111 @@
// @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts" // @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts"
import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs"; import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs";
import { useRef } from "preact/hooks"; import { Signal, useSignal } from "@preact/signals";
import { useSignal } from "@preact/signals";
import ImportResultPopup, {
type ImportDetail,
type ImportResult,
} from "$root/defaults/ImportResultPopup.tsx";
export default function UploadStudents() { /**
const file = useSignal<File | null>(null); * Create a new handler for file change that displays
const dragging = useSignal(false); * messages in statusMessage and gets file data in fileData.
const uploading = useSignal(false); * @param statusMessage The status message signal.
const error = useSignal<string | null>(null); * @param fileData The file data signal.
const importResult = useSignal<ImportResult | null>(null); * @returns The file change handler.
const inputRef = useRef<HTMLInputElement>(null); */
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";
}
};
}
function pickFile(f: File) { /**
if (!f.name.match(/\.xlsx?$/i)) { * Create a new handler that sends data file to server.
error.value = "Fichier invalide — format attendu : .xlsx"; * @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.";
return; return;
} }
file.value = f;
error.value = null;
importResult.value = null;
}
function onDragOver(e: DragEvent) { const reader = new FileReader();
e.preventDefault();
dragging.value = true;
}
function onDragLeave() { /**
dragging.value = false; * Send all data to the server.
} * @param event The finished progress event.
*/
function onDrop(e: DragEvent) { reader.onload = async (event: ProgressEvent<FileReader>) => {
e.preventDefault(); const arrayBuffer = event.target!.result as ArrayBuffer;
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" }); const workbook = XLSX.read(arrayBuffer, { type: "array" });
let added = 0; let allOK = true;
let errors = 0;
const details: ImportDetail[] = [];
for (const sheetName of workbook.SheetNames) { for (const sheetName of workbook.SheetNames) {
const sheet = workbook.Sheets[sheetName]; const sheet = workbook.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json<{ const data = XLSX.utils.sheet_to_json(sheet, {
nom: string; header: ["userId", "lastName", "firstName", "mail"],
prenom: string; range: 1,
numEtud: number;
idPromo: string;
}>(sheet, {
header: ["nom", "prenom", "numEtud", "idPromo"],
range: 2,
}); });
for (const row of rows) { const response = await fetch("/students/api/students", {
const res = await fetch("/students/api/students", { method: "POST",
method: "POST", headers: { "Content-Type": "application/json" },
headers: { "content-type": "application/json" }, body: JSON.stringify({ promoName: sheetName, data }),
body: JSON.stringify(row), });
});
if (res.ok) { if (!response.ok) {
added++; allOK = false;
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"}`,
});
}
} }
} }
importResult.value = { statusMessage.value = allOK
added, ? "Failed to insert all data."
modified: 0, : "Data uploaded and inserted successfully!";
ignored: 0, };
errors,
details,
};
} catch {
error.value = "Erreur lors de la lecture du fichier.";
} finally {
uploading.value = false;
}
}
function downloadTemplate() { /**
globalThis.open("/templates/modele_etudiants.xlsx", "_blank"); * 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);
return ( return (
<div> <>
<input <input type="file" accept=".xlsx, .xls" onChange={handleFileChange} />
ref={inputRef} <button type="button" onClick={confirmUpload}>Confirm Upload</button>
type="file" <p>{statusMessage.value}</p>
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", name: "Students",
icon: "badge", icon: "badge",
pages: { pages: {
index: "Accueil", index: "Homepage",
consult: "Élèves", upload: "Upload students",
upload: "Import xlsx", consult: "Consult students",
}, },
adminOnly: ["consult", "upload"], adminOnly: ["upload", "consult"],
hint: "Create students promotion and see informations", hint: "Create students promotion and see informations",
}; };
@@ -1,25 +1,15 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { import { promotions } from "$root/databases/schema.ts";
ajustements,
enseignements,
modules,
notes,
promotions,
students,
ueModules,
ues,
} from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ressource introuvable" }),
JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
const FORBIDDEN = () => new Response(null, { status: 403 }); const FORBIDDEN = new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #15 GET /promotions/{idPromo} // #15 GET /promotions/{idPromo}
@@ -28,7 +18,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const promo = await db const promo = await db
@@ -37,7 +27,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(promotions.id, context.params.idPromo)) .where(eq(promotions.id, context.params.idPromo))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!promo) return NOT_FOUND(); if (!promo) return NOT_FOUND;
return new Response(JSON.stringify(promo), { return new Response(JSON.stringify(promo), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -50,7 +40,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const body: { annee: string } = await request.json(); const body: { annee: string } = await request.json();
@@ -61,7 +51,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(promotions.id, context.params.idPromo)) .where(eq(promotions.id, context.params.idPromo))
.returning(); .returning();
if (!updated) return NOT_FOUND(); if (!updated) return NOT_FOUND;
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -69,104 +59,20 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #17 DELETE /promotions/{idPromo} // #17 DELETE /promotions/{idPromo}
// Blocked if students are still assigned (409).
// Cascade: deletes linked ue_modules, enseignements, and orphaned
// modules (+ their notes) & UEs (+ their ajustements).
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const idPromo = context.params.idPromo; const [deleted] = await db
.delete(promotions)
.where(eq(promotions.id, context.params.idPromo))
.returning();
const promo = await db if (!deleted) return NOT_FOUND;
.select()
.from(promotions)
.where(eq(promotions.id, idPromo))
.then((r) => r[0] ?? null);
if (!promo) return NOT_FOUND();
// Block deletion if students are still assigned
const assignedStudents = await db
.select()
.from(students)
.where(eq(students.idPromo, idPromo))
.then((r) => r.length);
if (assignedStudents > 0) {
return new Response(
JSON.stringify({
error:
`Impossible de supprimer : ${assignedStudents} étudiant(s) encore assigné(s) à cette promotion`,
}),
{ status: 409, headers: { "content-type": "application/json" } },
);
}
await db.transaction(async (tx) => {
// Collect linked module IDs and UE IDs before deleting junction rows
const linkedUeModules = await tx
.select({ idModule: ueModules.idModule, idUE: ueModules.idUE })
.from(ueModules)
.where(eq(ueModules.idPromo, idPromo));
const linkedEns = await tx
.select({ idModule: enseignements.idModule })
.from(enseignements)
.where(eq(enseignements.idPromo, idPromo));
const moduleIds = [
...new Set([
...linkedUeModules.map((um) => um.idModule),
...linkedEns.map((e) => e.idModule),
]),
];
const ueIds = [...new Set(linkedUeModules.map((um) => um.idUE))];
// Delete junction rows that directly reference this promo
await tx.delete(ueModules).where(eq(ueModules.idPromo, idPromo));
await tx.delete(enseignements).where(eq(enseignements.idPromo, idPromo));
// Delete orphaned modules (not used by another promo) and their notes
for (const modId of moduleIds) {
const stillInUeModules = await tx
.select()
.from(ueModules)
.where(eq(ueModules.idModule, modId))
.then((r) => r.length > 0);
const stillInEns = await tx
.select()
.from(enseignements)
.where(eq(enseignements.idModule, modId))
.then((r) => r.length > 0);
if (!stillInUeModules && !stillInEns) {
await tx.delete(notes).where(eq(notes.idModule, modId));
await tx.delete(modules).where(eq(modules.id, modId));
}
}
// Delete orphaned UEs (not used by another promo) and their ajustements
for (const ueId of ueIds) {
const stillUsed = await tx
.select()
.from(ueModules)
.where(eq(ueModules.idUE, ueId))
.then((r) => r.length > 0);
if (!stillUsed) {
await tx.delete(ajustements).where(eq(ajustements.idUE, ueId));
await tx.delete(ues).where(eq(ues.id, ueId));
}
}
// Delete the promotion
await tx.delete(promotions).where(eq(promotions.id, idPromo));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
+2 -14
View File
@@ -44,25 +44,13 @@ export const handler: Handlers<null, AuthenticatedState> = {
idPromo: string; idPromo: string;
} = await request.json(); } = await request.json();
if (!body.nom || !body.prenom) { if (!body.nom || !body.prenom || !body.idPromo) {
return new Response(null, { status: 400 }); return new Response(null, { status: 400 });
} }
const values: {
numEtud?: number;
nom: string;
prenom: string;
idPromo?: string;
} = {
nom: body.nom,
prenom: body.prenom,
};
if (body.numEtud) values.numEtud = body.numEtud;
if (body.idPromo) values.idPromo = body.idPromo;
const [created] = await db const [created] = await db
.insert(students) .insert(students)
.values(values) .values({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo })
.returning(); .returning();
return new Response(JSON.stringify(created), { return new Response(JSON.stringify(created), {
@@ -1,21 +1,15 @@
import { FreshContext, Handlers } from "$fresh/server.ts"; import { FreshContext, Handlers } from "$fresh/server.ts";
import { db } from "$root/databases/db.ts"; import { db } from "$root/databases/db.ts";
import { import { students } from "$root/databases/schema.ts";
ajustements,
mobility,
notes,
students,
} from "$root/databases/schema.ts";
import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts";
import { eq } from "npm:drizzle-orm@0.45.2"; import { eq } from "npm:drizzle-orm@0.45.2";
const NOT_FOUND = () => const NOT_FOUND = new Response(
new Response( JSON.stringify({ error: "Ressource introuvable" }),
JSON.stringify({ error: "Ressource introuvable" }), { status: 404, headers: { "content-type": "application/json" } },
{ status: 404, headers: { "content-type": "application/json" } }, );
);
const FORBIDDEN = () => new Response(null, { status: 403 }); const FORBIDDEN = new Response(null, { status: 403 });
export const handler: Handlers<null, AuthenticatedState> = { export const handler: Handlers<null, AuthenticatedState> = {
// #10 GET /students/{numEtud} // #10 GET /students/{numEtud}
@@ -24,7 +18,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
@@ -34,7 +28,7 @@ export const handler: Handlers<null, AuthenticatedState> = {
.where(eq(students.numEtud, numEtud)) .where(eq(students.numEtud, numEtud))
.then((rows) => rows[0] ?? null); .then((rows) => rows[0] ?? null);
if (!student) return NOT_FOUND(); if (!student) return NOT_FOUND;
return new Response(JSON.stringify(student), { return new Response(JSON.stringify(student), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -47,32 +41,20 @@ export const handler: Handlers<null, AuthenticatedState> = {
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
const body: { nom?: string; prenom?: string; idPromo?: string } = const body: { nom: string; prenom: string; idPromo: string } = await request
await request.json(); .json();
const set: { nom?: string; prenom?: string; idPromo?: string } = {};
if (body.nom !== undefined) set.nom = body.nom;
if (body.prenom !== undefined) set.prenom = body.prenom;
if (body.idPromo !== undefined) set.idPromo = body.idPromo;
if (Object.keys(set).length === 0) {
return new Response(
JSON.stringify({ error: "Au moins un champ requis" }),
{ status: 400, headers: { "content-type": "application/json" } },
);
}
const [updated] = await db const [updated] = await db
.update(students) .update(students)
.set(set) .set({ nom: body.nom, prenom: body.prenom, idPromo: body.idPromo })
.where(eq(students.numEtud, numEtud)) .where(eq(students.numEtud, numEtud))
.returning(); .returning();
if (!updated) return NOT_FOUND(); if (!updated) return NOT_FOUND;
return new Response(JSON.stringify(updated), { return new Response(JSON.stringify(updated), {
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -80,31 +62,21 @@ export const handler: Handlers<null, AuthenticatedState> = {
}, },
// #12 DELETE /students/{numEtud} // #12 DELETE /students/{numEtud}
// Cascade: deletes notes, ajustements, mobility for this student.
async DELETE( async DELETE(
_request: Request, _request: Request,
context: FreshContext<AuthenticatedState>, context: FreshContext<AuthenticatedState>,
): Promise<Response> { ): Promise<Response> {
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") { if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
return FORBIDDEN(); return FORBIDDEN;
} }
const numEtud = Number(context.params.numEtud); const numEtud = Number(context.params.numEtud);
const [deleted] = await db
const student = await db .delete(students)
.select()
.from(students)
.where(eq(students.numEtud, numEtud)) .where(eq(students.numEtud, numEtud))
.then((r) => r[0] ?? null); .returning();
if (!student) return NOT_FOUND(); if (!deleted) return NOT_FOUND;
await db.transaction(async (tx) => {
await tx.delete(notes).where(eq(notes.numEtud, numEtud));
await tx.delete(ajustements).where(eq(ajustements.numEtud, numEtud));
await tx.delete(mobility).where(eq(mobility.studentId, numEtud));
await tx.delete(students).where(eq(students.numEtud, numEtud));
});
return new Response(null, { status: 204 }); return new Response(null, { status: 204 });
}, },
-12
View File
@@ -1,12 +0,0 @@
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,7 +8,12 @@ import { State } from "$root/defaults/interfaces.ts";
// deno-lint-ignore require-await // deno-lint-ignore require-await
async function Students(_request: Request, _context: FreshContext<State>) { async function Students(_request: Request, _context: FreshContext<State>) {
return <ConsultStudents />; return (
<>
<h2>Consult students</h2>
<ConsultStudents />
</>
);
} }
export const config = getPartialsConfig(); export const config = getPartialsConfig();
@@ -9,10 +9,10 @@ import { State } from "$root/defaults/interfaces.ts";
// deno-lint-ignore require-await // deno-lint-ignore require-await
async function Students(_request: Request, _context: FreshContext<State>) { async function Students(_request: Request, _context: FreshContext<State>) {
return ( return (
<div class="page-content"> <>
<h2 class="page-title">Importer des Élèves</h2> <h2>Upload Students</h2>
<UploadStudents /> <UploadStudents />
</div> </>
); );
} }
+7 -35
View File
@@ -4,44 +4,16 @@ import {
} from "$root/defaults/makePartials.tsx"; } from "$root/defaults/makePartials.tsx";
import { FreshContext } from "$fresh/server.ts"; import { FreshContext } from "$fresh/server.ts";
import { State } from "$root/defaults/interfaces.ts"; import { State } from "$root/defaults/interfaces.ts";
import SelfPortrait from "$root/routes/(apps)/students/(_components)/SelfPortrait.tsx";
// deno-lint-ignore require-await // deno-lint-ignore require-await
export async function Index( export async function Index(_request: Request, context: FreshContext<State>) {
_request: Request,
context: FreshContext<State>,
) {
const isEmployee =
(context.state as unknown as { session: Record<string, string> }).session
.eduPersonPrimaryAffiliation === "employee";
return ( return (
<div class="page-content"> <>
<h2 class="page-title">Étudiants</h2> <h2>Welcome {context.state.session?.givenName}!</h2>
<p> <h3>Your amU identity</h3>
Bienvenue{" "} <SelfPortrait self={context.state.session!} />
<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>
); );
} }
+2 -3
View File
@@ -26,9 +26,8 @@ export default async function App(
/> />
<link rel="stylesheet" href="/styles/main.css" /> <link rel="stylesheet" href="/styles/main.css" />
<link rel="stylesheet" href="/styles/app.css" /> <link rel="stylesheet" href="/styles/app.css" />
<link rel="stylesheet" href="/styles/app-cards.css" /> <link rel="stylesheet" href="styles/app-cards.css" />
<link rel="stylesheet" href="/styles/students.css" /> <link rel="stylesheet" href="styles/students.css" />
<link rel="stylesheet" href="/styles/ui.css" />
</head> </head>
<body f-client-nav> <body f-client-nav>
<Header link={link} /> <Header link={link} />
-1
View File
@@ -10,7 +10,6 @@ const PUBLIC_ROUTES = [
"/about", "/about",
"/partials/about", "/partials/about",
"/contact", "/contact",
"/dev-login",
]; ];
const jwtKeyCache: Record<string, string> = {}; const jwtKeyCache: Record<string, string> = {};
-80
View File
@@ -1,80 +0,0 @@
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,8 +45,6 @@ function createUserJWT(casResponse: CasResponse): Promise<string> {
} }
}); });
console.log(fullUserInfos);
const now = Math.floor(Date.now() / 1000); const now = Math.floor(Date.now() / 1000);
const payload: LoginJWT = { const payload: LoginJWT = {
iss: "PolyMPR", iss: "PolyMPR",
-60
View File
@@ -1,60 +0,0 @@
// @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
@@ -1,25 +0,0 @@
// @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,10 +29,6 @@
font-family: var(--font-family-text); font-family: var(--font-family-text);
} }
html {
font-size: 130%; /* scale up from browser default 16px → ~20.8px */
}
html, body { html, body {
margin: 0; margin: 0;
padding: 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
@@ -1,349 +0,0 @@
// 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
@@ -1,240 +0,0 @@
// 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,
});
-210
View File
@@ -1,210 +0,0 @@
// #113 - E2E tests for /modules endpoints
import { assertEquals } from "@std/assert";
import {
makeContextWithAffiliation,
makeEmployeeContext,
makeGetRequest,
makeJsonRequest,
} from "../helpers/handler.ts";
import { seedModules, 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";
// --- GET /modules ---
Deno.test({
name: "e2e modules: GET /modules returns all as employee",
async fn() {
await truncateAll();
await seedModules([{ id: "MATH101", nom: "Mathématiques" }, {
id: "INFO101",
nom: "Informatique",
}]);
const res = await modulesHandler.GET!(
makeGetRequest("/modules"),
makeEmployeeContext(),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 2);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e modules: GET /modules returns empty for non-employee",
async fn() {
await truncateAll();
await seedModules([{ id: "MATH101", nom: "Mathématiques" }]);
const res = await modulesHandler.GET!(
makeGetRequest("/modules"),
makeContextWithAffiliation("student"),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.length, 0);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- POST /modules ---
Deno.test({
name: "e2e modules: POST /modules creates module (201)",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: "PHYS101", nom: "Physique" }),
makeEmployeeContext(),
);
assertEquals(res.status, 201);
const body = await res.json();
assertEquals(body.id, "PHYS101");
assertEquals(body.nom, "Physique");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e modules: POST /modules 409 on duplicate id",
async fn() {
await truncateAll();
await seedModules([{ id: "MATH101", nom: "Mathématiques" }]);
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: "MATH101", nom: "Doublon" }),
makeEmployeeContext(),
);
assertEquals(res.status, 409);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e modules: POST /modules 400 on missing fields",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: "X" }),
makeEmployeeContext(),
);
assertEquals(res.status, 400);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e modules: POST /modules 403 for non-employee",
async fn() {
await truncateAll();
const res = await modulesHandler.POST!(
makeJsonRequest("/modules", "POST", { id: "X", nom: "Y" }),
makeContextWithAffiliation("student"),
);
assertEquals(res.status, 403);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- GET /modules/:id ---
Deno.test({
name: "e2e modules: GET /modules/:id returns module",
async fn() {
await truncateAll();
await seedModules([{ id: "ELEC201", nom: "Électronique" }]);
const res = await moduleHandler.GET!(
makeGetRequest("/modules/ELEC201"),
makeEmployeeContext({ idModule: "ELEC201" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.nom, "Électronique");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e modules: GET /modules/:id 404 when not found",
async fn() {
await truncateAll();
const res = await moduleHandler.GET!(
makeGetRequest("/modules/GHOST"),
makeEmployeeContext({ idModule: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- PUT /modules/:id ---
Deno.test({
name: "e2e modules: PUT /modules/:id updates nom",
async fn() {
await truncateAll();
await seedModules([{ id: "CHIM101", nom: "Chimie" }]);
const res = await moduleHandler.PUT!(
makeJsonRequest("/modules/CHIM101", "PUT", { nom: "Chimie organique" }),
makeEmployeeContext({ idModule: "CHIM101" }),
);
assertEquals(res.status, 200);
const body = await res.json();
assertEquals(body.nom, "Chimie organique");
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e modules: PUT /modules/:id 404 when not found",
async fn() {
await truncateAll();
const res = await moduleHandler.PUT!(
makeJsonRequest("/modules/GHOST", "PUT", { nom: "X" }),
makeEmployeeContext({ idModule: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
// --- DELETE /modules/:id ---
Deno.test({
name: "e2e modules: DELETE /modules/:id returns 204",
async fn() {
await truncateAll();
await seedModules([{ id: "BIO101", nom: "Biologie" }]);
const res = await moduleHandler.DELETE!(
makeGetRequest("/modules/BIO101"),
makeEmployeeContext({ idModule: "BIO101" }),
);
assertEquals(res.status, 204);
},
sanitizeResources: false,
sanitizeOps: false,
});
Deno.test({
name: "e2e modules: DELETE /modules/:id 404 when not found",
async fn() {
await truncateAll();
const res = await moduleHandler.DELETE!(
makeGetRequest("/modules/GHOST"),
makeEmployeeContext({ idModule: "GHOST" }),
);
assertEquals(res.status, 404);
},
sanitizeResources: false,
sanitizeOps: false,
});
-283
View File
@@ -1,283 +0,0 @@
// 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
@@ -1,60 +0,0 @@
// #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,
});

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