Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 080f7606a7 | |||
| 4e220f72d7 | |||
| 61207e4f21 | |||
| 204a590b37 | |||
| edb20db2ef | |||
| 56430f9991 | |||
| 808bf8c9c7 | |||
| e111d5be28 | |||
| c70d4a5f11 | |||
| ad5c271b05 | |||
| 19a588ac25 | |||
| ad524978df | |||
| 2ce78547b7 | |||
| 81a3fc0e03 | |||
| 2615961bf1 | |||
| fb967e3af3 | |||
| c283a34784 | |||
| a48c616ecc | |||
| cd1149a23a | |||
| 58c8ff56ba | |||
| 91f7b6c022 | |||
| 8f1088a0f8 | |||
| ccbec884e8 | |||
| a9a2f6f390 | |||
| 4c54283bfd | |||
| e88045c952 | |||
| 4ff76fdf6f |
@@ -0,0 +1,27 @@
|
||||
name: "Build and push image"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: "Build Docker image"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: registry.docker.polytech.djalim.fr
|
||||
username: ${{ secrets.registry_login }}
|
||||
password: ${{ secrets.registry_pass }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
push: true
|
||||
tags: registry.docker.polytech.djalim.fr/polympr:latest
|
||||
@@ -24,3 +24,6 @@ jobs:
|
||||
|
||||
- name: Check linting
|
||||
run: deno lint
|
||||
|
||||
- name: Run tests
|
||||
run: deno test -A --no-check tests/
|
||||
+1
-1
@@ -3,7 +3,7 @@ FROM denoland/deno:alpine
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
RUN deno cache main.ts --allow-import flag
|
||||
RUN deno cache main.ts --allow-import
|
||||
RUN deno task build
|
||||
|
||||
USER deno
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Contributing
|
||||
|
||||
Thank you for your interest in contributing to our project! We appreciate your
|
||||
help in making this project better. To get started with contributing, please
|
||||
refer to our
|
||||
[Contributing Guide](https://github.com/fedyna-k/PolyMPR/wiki/Contributing) on
|
||||
the project's wiki.
|
||||
|
||||
The Contributing Guide provides detailed information on how to:
|
||||
|
||||
- Set up your development environment
|
||||
- Submit issues and feature requests
|
||||
- Fork the repository and create pull requests
|
||||
- Follow our coding standards and guidelines
|
||||
- Report bugs and suggest improvements
|
||||
|
||||
If you have any questions or need further assistance, feel free to reach out to
|
||||
us by opening an issue or contacting the maintainers directly.
|
||||
|
||||
Happy coding! 💻✨
|
||||
@@ -1,6 +1,5 @@
|
||||
create table promotions (
|
||||
id integer primary key autoincrement,
|
||||
name text,
|
||||
endyear integer,
|
||||
current integer
|
||||
);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { type RegularTagNode, type TextNode } from "@melvdouc/xml-parser";
|
||||
import { AsyncRoute } from "$fresh/src/server/types.ts";
|
||||
|
||||
interface AuthenticatedState {
|
||||
export interface AuthenticatedState {
|
||||
isAuthenticated: true;
|
||||
session: CasContent;
|
||||
availablePages: Record<string, string>;
|
||||
}
|
||||
|
||||
interface UnauthenticatedState {
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
"start": "deno run -A --unstable-ffi --watch=static/,routes/ dev.ts",
|
||||
"build": "deno run -A --unstable-ffi dev.ts build",
|
||||
"preview": "deno run -A --unstable-ffi main.ts",
|
||||
"update": "deno run -A -r https://fresh.deno.dev/update ."
|
||||
"update": "deno run -A -r https://fresh.deno.dev/update .",
|
||||
"test": "deno test -A --no-check tests/"
|
||||
},
|
||||
"lint": {
|
||||
"rules": {
|
||||
@@ -29,12 +30,17 @@
|
||||
"@popov/jwt": "jsr:@popov/jwt@^1.0.1",
|
||||
"@psych/sheet": "jsr:@psych/sheet@^1.0.6",
|
||||
"@std/cli": "jsr:@std/cli@^1.0.10",
|
||||
"@std/dotenv": "jsr:@std/dotenv@^0.225.3",
|
||||
"preact": "https://esm.sh/preact@10.22.0",
|
||||
"preact/": "https://esm.sh/preact@10.22.0/",
|
||||
"@preact/signals": "https://esm.sh/*@preact/signals@1.2.2",
|
||||
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.5.1",
|
||||
"$std/": "https://deno.land/std@0.216.0/",
|
||||
"$root/": "./"
|
||||
"@std/assert": "jsr:@std/assert@^1.0.0",
|
||||
"@std/testing": "jsr:@std/testing@^1.0.0",
|
||||
"happy-dom": "npm:happy-dom@^16.0.0",
|
||||
"$root/": "./",
|
||||
"$apps/": "./routes/(apps)/"
|
||||
},
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
#Local mode, set to true to access admin pages with any users
|
||||
LOCAL=false
|
||||
@@ -1,6 +1,8 @@
|
||||
import { defineConfig } from "$fresh/server.ts";
|
||||
import ensureDatabases from "$root/databases/ensure.ts";
|
||||
import { load } from "@std/dotenv";
|
||||
|
||||
await load({ envPath: "./.env", export: true });
|
||||
await ensureDatabases();
|
||||
export default defineConfig({
|
||||
server: {
|
||||
|
||||
+6
-6
@@ -3,6 +3,7 @@
|
||||
// This file is automatically updated during development when running `dev.ts`.
|
||||
|
||||
import * as $_apps_layout from "./routes/(apps)/_layout.tsx";
|
||||
import * as $_apps_middleware from "./routes/(apps)/_middleware.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_partials_admin_edit_mobility from "./routes/(apps)/mobility/partials/(admin)/edit_mobility.tsx";
|
||||
@@ -12,12 +13,12 @@ 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_index from "./routes/(apps)/notes/partials/index.tsx";
|
||||
import * as $_apps_notes_partials_notes from "./routes/(apps)/notes/partials/notes.tsx";
|
||||
import * as $_apps_students_api_insert_students from "./routes/(apps)/students/api/insert_students.ts";
|
||||
import * as $_apps_students_api_students from "./routes/(apps)/students/api/students.ts";
|
||||
import * as $_apps_students_index from "./routes/(apps)/students/index.tsx";
|
||||
import * as $_apps_students_partials_admin_consult from "./routes/(apps)/students/partials/(admin)/consult.tsx";
|
||||
import * as $_apps_students_partials_admin_upload from "./routes/(apps)/students/partials/(admin)/upload.tsx";
|
||||
import * as $_apps_students_partials_index from "./routes/(apps)/students/partials/index.tsx";
|
||||
import * as $_apps_students_partials_overview from "./routes/(apps)/students/partials/overview.tsx";
|
||||
import * as $_apps_students_types_d from "./routes/(apps)/students/types.d.ts";
|
||||
import * as $_404 from "./routes/_404.tsx";
|
||||
import * as $_app from "./routes/_app.tsx";
|
||||
import * as $_middleware from "./routes/_middleware.ts";
|
||||
@@ -39,6 +40,7 @@ import type { Manifest } from "$fresh/server.ts";
|
||||
const manifest = {
|
||||
routes: {
|
||||
"./routes/(apps)/_layout.tsx": $_apps_layout,
|
||||
"./routes/(apps)/_middleware.ts": $_apps_middleware,
|
||||
"./routes/(apps)/mobility/api/insert_mobility.ts":
|
||||
$_apps_mobility_api_insert_mobility,
|
||||
"./routes/(apps)/mobility/index.tsx": $_apps_mobility_index,
|
||||
@@ -53,8 +55,7 @@ const manifest = {
|
||||
$_apps_notes_partials_admin_courses,
|
||||
"./routes/(apps)/notes/partials/index.tsx": $_apps_notes_partials_index,
|
||||
"./routes/(apps)/notes/partials/notes.tsx": $_apps_notes_partials_notes,
|
||||
"./routes/(apps)/students/api/insert_students.ts":
|
||||
$_apps_students_api_insert_students,
|
||||
"./routes/(apps)/students/api/students.ts": $_apps_students_api_students,
|
||||
"./routes/(apps)/students/index.tsx": $_apps_students_index,
|
||||
"./routes/(apps)/students/partials/(admin)/consult.tsx":
|
||||
$_apps_students_partials_admin_consult,
|
||||
@@ -62,8 +63,7 @@ const manifest = {
|
||||
$_apps_students_partials_admin_upload,
|
||||
"./routes/(apps)/students/partials/index.tsx":
|
||||
$_apps_students_partials_index,
|
||||
"./routes/(apps)/students/partials/overview.tsx":
|
||||
$_apps_students_partials_overview,
|
||||
"./routes/(apps)/students/types.d.ts": $_apps_students_types_d,
|
||||
"./routes/_404.tsx": $_404,
|
||||
"./routes/_app.tsx": $_app,
|
||||
"./routes/_middleware.ts": $_middleware,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
Copyright 2025 - PolyMPR team @ Polytech Marseille
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the “Software”), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,4 +1,89 @@
|
||||
# ✨ PolyMPR ✨
|
||||
|
||||
The ✨ Poly Module de Pilotage des Ressources ✨ is the ultimate tool to handle
|
||||
various HR task in the INFO department.
|
||||
**PolyMPR** (Poly Management Platform for Resources) is a modern, modular
|
||||
framework built on **Deno** and **Fresh**, designed to help organizations
|
||||
transition their HR systems to the cloud. With its **modulith architecture**,
|
||||
PolyMPR simplifies the development, deployment, and maintenance of HR
|
||||
applications, making it the perfect choice for teams looking to modernize their
|
||||
workflows. 🌐
|
||||
|
||||
## Features ✨
|
||||
|
||||
- **Modular Design**: Easily add, remove, or update features without disrupting
|
||||
the entire system. 🧩
|
||||
- **Cloud-Native**: Built for the cloud, enabling seamless integration with
|
||||
cloud services (amU DataCenter). ☁️
|
||||
- **Deno-Powered**: Utilizes Deno's secure runtime for TypeScript. 🦕
|
||||
- **Fresh Framework**: Delivers fast, edge-ready web applications with minimal
|
||||
overhead. ⚡
|
||||
- **HR-Focused**: Tailored to meet the unique needs of INFO's HR. 👩💼👨💼
|
||||
|
||||
## Getting Started 🛠️
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Deno**: Install Deno by following the
|
||||
[official guide](https://deno.land/#installation).
|
||||
- **Docker** (optional): Install Docker for containerized deployments. Follow
|
||||
the [Docker installation guide](https://docs.docker.com/get-docker/).
|
||||
|
||||
### Installation
|
||||
|
||||
1. Clone the PolyMPR repository:
|
||||
```bash
|
||||
git clone https://github.com/fedyna-k/PolyMPR.git
|
||||
cd PolyMPR
|
||||
```
|
||||
2. Start the application:
|
||||
```bash
|
||||
deno task start
|
||||
```
|
||||
3. Access the application at `https://localhost`.
|
||||
|
||||
For detailed installation instructions, check out the
|
||||
[Installation Guide](./wiki/installation).
|
||||
|
||||
## Modules Overview 🧩
|
||||
|
||||
PolyMPR comes with a variety of modules to streamline HR processes.
|
||||
|
||||
To learn how to create a module, visit the [Module Overview](./wiki/modules).
|
||||
|
||||
## CLI Documentation 📄
|
||||
|
||||
The **PolyMPR CLI** simplifies development tasks. Here are some common commands:
|
||||
|
||||
- Create a new module:
|
||||
```bash
|
||||
pmpr module create <module-name-kebab-case>
|
||||
```
|
||||
|
||||
For detailed CLI usage, check out the [CLI Documentation](./wiki/cli).
|
||||
|
||||
## Contributing 🤝
|
||||
|
||||
We welcome contributions from the community! Whether you're fixing bugs, adding
|
||||
features, or improving documentation, your help is appreciated. Here’s how to
|
||||
get started:
|
||||
|
||||
1. Create a new issue.
|
||||
2. Create a new branch for your changes:
|
||||
```bash
|
||||
git checkout -b PMPR-:ISSUE_ID:
|
||||
```
|
||||
3. Commit your changes and push them to your branch.
|
||||
4. Submit a pull request.
|
||||
|
||||
For more details, read the [Contributing Guide](./contributing).
|
||||
|
||||
## Community and Support 🌟
|
||||
|
||||
Join the PolyMPR community to connect with other users and developers:
|
||||
|
||||
- **GitHub Discussions**: Ask questions and share ideas. 💬
|
||||
- **Issue Tracker**: Report bugs or request features. 🐛
|
||||
|
||||
## License 📜
|
||||
|
||||
PolyMPR is open-source and released under the **MIT License**. Feel free to use,
|
||||
modify, and distribute it as per the license terms.
|
||||
|
||||
@@ -1,22 +1,19 @@
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { Partial } from "$fresh/runtime.ts";
|
||||
import { State } from "$root/defaults/interfaces.ts";
|
||||
import { AppProperties } from "$root/defaults/interfaces.ts";
|
||||
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
|
||||
import Navbar from "$root/routes/(_islands)/Navbar.tsx";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
export default async function AppLayout(
|
||||
request: Request,
|
||||
context: FreshContext<State>,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
) {
|
||||
const pathname = new URL(request.url).pathname;
|
||||
const currentApp = pathname.split("/")[1];
|
||||
const properties: AppProperties = (await import(
|
||||
`./${currentApp}/(_props)/props.ts`
|
||||
)).default;
|
||||
|
||||
return (
|
||||
<section id="app">
|
||||
<Navbar currentApp={currentApp} pages={properties.pages} />
|
||||
<Navbar currentApp={currentApp} pages={context.state.availablePages} />
|
||||
<section id="app-body">
|
||||
<Partial name="body">
|
||||
<context.Component />
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { FreshContext, MiddlewareHandler } from "$fresh/server.ts";
|
||||
import {
|
||||
AppProperties,
|
||||
AuthenticatedState,
|
||||
} from "$root/defaults/interfaces.ts";
|
||||
|
||||
export const handler: MiddlewareHandler<AuthenticatedState>[] = [
|
||||
/**
|
||||
* Get all available pages for current user.
|
||||
* @param request The HTTP incomming request.
|
||||
* @param context The Fresh context object with custom `AuthenticatedState`.
|
||||
* @returns The response from the next middleware.
|
||||
*/
|
||||
async function getAllAvailablePages(
|
||||
request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
const pathname = new URL(request.url).pathname;
|
||||
const currentApp = pathname.split("/")[1];
|
||||
const properties: AppProperties = (await import(
|
||||
`./${currentApp}/(_props)/props.ts`
|
||||
)).default;
|
||||
|
||||
context.state.availablePages = properties.pages;
|
||||
if (
|
||||
context.state.session.eduPersonPrimaryAffiliation == "student" &&
|
||||
Deno.env.get("LOCAL") != "true"
|
||||
) {
|
||||
properties.adminOnly.forEach((page) =>
|
||||
delete context.state.availablePages[page]
|
||||
);
|
||||
}
|
||||
|
||||
return await context.next();
|
||||
},
|
||||
];
|
||||
@@ -240,7 +240,7 @@ export default function EditMobility() {
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
<button onClick={handleSave} disabled={isSaving}>
|
||||
<button type="button" onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? "Saving..." : "Confirm"}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import Student from "$root/routes/(apps)/students/(_components)/Student.tsx";
|
||||
|
||||
type PromotionProps = { students: Student[]; promo: Promotion };
|
||||
|
||||
export default function Promotion(props: PromotionProps) {
|
||||
if (!props.promo) {
|
||||
return <p>Unable to find user in database.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={props.promo.id}>
|
||||
<h3>Promotion {props.promo.endyear}</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>First Name</th>
|
||||
<th>Last Name</th>
|
||||
<th>Email</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{props.students
|
||||
.filter((student) => student.promotionId === props.promo.id)
|
||||
.map((student) => <Student key={student.id} student={student} />)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { CasContent } from "$root/defaults/interfaces.ts";
|
||||
|
||||
type SelfPortraitProps = { self: CasContent };
|
||||
|
||||
const regex =
|
||||
/^(?<year>\d{4})(?<month>\d{2})(?<date>\d{2})(?<hours>\d{2})(?<minutes>\d{2})(?<seconds>\d{2})Z$/;
|
||||
|
||||
export default function SelfPortrait(props: SelfPortraitProps) {
|
||||
const { year, month, date, hours, minutes, seconds } = props.self
|
||||
.amuDateValidation.match(regex)!.groups!;
|
||||
|
||||
const validationIsoDate =
|
||||
`${year}-${month}-${date}T${hours}:${minutes}:${seconds}Z`;
|
||||
|
||||
const validationDate = new Date(validationIsoDate);
|
||||
|
||||
return (
|
||||
<div id="self-portrait">
|
||||
<div>Identity</div>
|
||||
<div>{props.self.supannCivilite} {props.self.displayName}</div>
|
||||
<div>Student number</div>
|
||||
<div>{props.self.uid}</div>
|
||||
<div>amU mail</div>
|
||||
<div>{props.self.mail}</div>
|
||||
<div>First amU registration</div>
|
||||
<div>{validationDate.toLocaleString()}</div>
|
||||
<div>amU class code</div>
|
||||
<div>{props.self.supannEtuEtape}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type StudentProps = { student: Student; promo?: number };
|
||||
|
||||
export default function Student(props: StudentProps) {
|
||||
return (
|
||||
<tr key={props.student.userId}>
|
||||
<td>{props.student.userId}</td>
|
||||
<td>{props.student.firstName}</td>
|
||||
<td>{props.student.lastName}</td>
|
||||
<td>{props.student.mail}</td>
|
||||
{props.promo && <td>{props.promo}</td>}
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
@@ -1,75 +1,45 @@
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import Promotion from "$root/routes/(apps)/students/(_components)/Promotion.tsx";
|
||||
|
||||
interface Promotion {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
type SingleUserResponse = { promo: Promotion; student: Student };
|
||||
type ManyUsersResponse = { promos: Promotion[]; students: Student[] };
|
||||
|
||||
interface Student {
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
mail: string;
|
||||
promotionId: number;
|
||||
}
|
||||
type APIResponse = SingleUserResponse | ManyUsersResponse;
|
||||
|
||||
export default function ConsultStudents() {
|
||||
const [data, setData] = useState<
|
||||
{ promotions: Promotion[]; students: Student[] } | null
|
||||
>(null);
|
||||
const [data, setData] = useState<APIResponse | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const response = await fetch("/students/api/insert_students");
|
||||
const response = await fetch("/students/api/students");
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching data: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
console.log("Fetched data:", result);
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
console.error("Error fetching data:", err);
|
||||
setError("Failed to load data. Please try again later.");
|
||||
}
|
||||
|
||||
const result: APIResponse = await response.json();
|
||||
setData(result);
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h2>Consult Students</h2>
|
||||
<>
|
||||
{error && <p className="error">{error}</p>}
|
||||
{data?.promotions.map((promo) => (
|
||||
<div key={promo.id}>
|
||||
<h3>Promotion: {promo.name}</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>First Name</th>
|
||||
<th>Last Name</th>
|
||||
<th>Email</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.students
|
||||
.filter((student) => student.promotionId === promo.id)
|
||||
.map((student) => (
|
||||
<tr key={student.userId}>
|
||||
<td>{student.userId}</td>
|
||||
<td>{student.firstName}</td>
|
||||
<td>{student.lastName}</td>
|
||||
<td>{student.mail}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
{data && ((Object.hasOwn(data, "student"))
|
||||
? (
|
||||
<Promotion
|
||||
students={[(data as SingleUserResponse).student]}
|
||||
promo={(data as SingleUserResponse).promo}
|
||||
/>
|
||||
)
|
||||
: (data as ManyUsersResponse).promos.map((promo) => (
|
||||
<Promotion
|
||||
students={(data as ManyUsersResponse).students}
|
||||
promo={promo}
|
||||
/>
|
||||
)))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,75 +1,111 @@
|
||||
// @deno-types="https://cdn.sheetjs.com/xlsx-0.20.3/package/types/index.d.ts"
|
||||
import * as XLSX from "https://cdn.sheetjs.com/xlsx-0.20.3/package/xlsx.mjs";
|
||||
import { useSignal } from "@preact/signals";
|
||||
import { Signal, useSignal } from "@preact/signals";
|
||||
|
||||
export default function UploadStudents() {
|
||||
const statusMessage = useSignal<string>("");
|
||||
const fileData = useSignal<File | null>(null);
|
||||
|
||||
const handleFileChange = (event: Event) => {
|
||||
/**
|
||||
* Create a new handler for file change that displays
|
||||
* messages in statusMessage and gets file data in fileData.
|
||||
* @param statusMessage The status message signal.
|
||||
* @param fileData The file data signal.
|
||||
* @returns The file change handler.
|
||||
*/
|
||||
function getFileChangeHandler(
|
||||
statusMessage: Signal<string>,
|
||||
fileData: Signal<File | null>,
|
||||
): (event: Event) => void {
|
||||
/**
|
||||
* Handle file change.
|
||||
* @param event The file change event.
|
||||
*/
|
||||
return (event: Event) => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
if (input.files && input.files.length > 0) {
|
||||
fileData.value = input.files[0];
|
||||
statusMessage.value = "File selected: " + input.files[0].name;
|
||||
statusMessage.value = `File selected: ${input.files[0].name}`;
|
||||
} else {
|
||||
fileData.value = null;
|
||||
statusMessage.value = "No file selected";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const confirmUpload = () => {
|
||||
/**
|
||||
* Create a new handler that sends data file to server.
|
||||
* @param statusMessage The status message signal.
|
||||
* @param fileData The file data signal.
|
||||
* @returns The file confirmation handler.
|
||||
*/
|
||||
function getUploadConfirmationFunction(
|
||||
statusMessage: Signal<string>,
|
||||
fileData: Signal<File | null>,
|
||||
): () => void {
|
||||
/**
|
||||
* Add students to database.
|
||||
* @returns Confirm upload of students.
|
||||
*/
|
||||
return () => {
|
||||
if (!fileData.value) {
|
||||
statusMessage.value = "Please select a file before confirming upload.";
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onload = async (e) => {
|
||||
const arrayBuffer = e.target?.result as ArrayBuffer;
|
||||
/**
|
||||
* Send all data to the server.
|
||||
* @param event The finished progress event.
|
||||
*/
|
||||
reader.onload = async (event: ProgressEvent<FileReader>) => {
|
||||
const arrayBuffer = event.target!.result as ArrayBuffer;
|
||||
const workbook = XLSX.read(arrayBuffer, { type: "array" });
|
||||
let allOK = true;
|
||||
|
||||
for (const sheetName of workbook.SheetNames) {
|
||||
const sheet = workbook.Sheets[sheetName];
|
||||
const data = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: ["Identifiant", "Nom", "Prénom", "Mail"],
|
||||
range: 1, // Ignorer les en-têtes
|
||||
header: ["userId", "lastName", "firstName", "mail"],
|
||||
range: 1,
|
||||
});
|
||||
|
||||
console.log(`Data from sheet ${sheetName}:`, data);
|
||||
|
||||
const response = await fetch("/students/api/insert_students", {
|
||||
const response = await fetch("/students/api/students", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ promoName: sheetName, data }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to insert data for promotion ${sheetName}`);
|
||||
allOK = false;
|
||||
}
|
||||
}
|
||||
|
||||
statusMessage.value = "Data uploaded and inserted successfully!";
|
||||
statusMessage.value = allOK
|
||||
? "Failed to insert all data."
|
||||
: "Data uploaded and inserted successfully!";
|
||||
};
|
||||
|
||||
/**
|
||||
* Display error message if any.
|
||||
*/
|
||||
reader.onerror = () => {
|
||||
statusMessage.value = "Error reading the file.";
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(fileData.value);
|
||||
} catch (error) {
|
||||
console.error("Error uploading file:", error);
|
||||
statusMessage.value = "An unexpected error occurred during upload.";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
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 (
|
||||
<div>
|
||||
<h2>Upload Students</h2>
|
||||
<>
|
||||
<input type="file" accept=".xlsx, .xls" onChange={handleFileChange} />
|
||||
<button onClick={confirmUpload}>Confirm Upload</button>
|
||||
<button type="button" onClick={confirmUpload}>Confirm Upload</button>
|
||||
<p>{statusMessage.value}</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ const properties: AppProperties = {
|
||||
icon: "badge",
|
||||
pages: {
|
||||
index: "Homepage",
|
||||
overview: "Students overview",
|
||||
upload: "Upload students",
|
||||
consult: "Consult students",
|
||||
},
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
// import { Database } from "@db/sqlite";
|
||||
import connect from "$root/databases/connect.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
// deno-lint-ignore require-await
|
||||
async GET() {
|
||||
try {
|
||||
using connection = connect("students");
|
||||
|
||||
const promotions = connection.database.prepare(
|
||||
"select id, name from promotions",
|
||||
).all();
|
||||
|
||||
const students = connection.database
|
||||
.prepare(
|
||||
`select userId, firstName, lastName, mail, promotionId from students`,
|
||||
)
|
||||
.all();
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ promotions, students }),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
return new Response("Failed to fetch data", { status: 500 });
|
||||
}
|
||||
},
|
||||
|
||||
async POST(request) {
|
||||
console.log("API /students/api/insert_students called");
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { data, promoName } = body;
|
||||
|
||||
console.log("Received data:", { promoName, data });
|
||||
|
||||
if (!promoName || !Array.isArray(data)) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
|
||||
using connection = connect("students");
|
||||
|
||||
connection.database.prepare(
|
||||
"INSERT OR IGNORE INTO promotions (name) VALUES (?)",
|
||||
).run(promoName);
|
||||
|
||||
const promoIdRow: { id: number } = connection.database
|
||||
.prepare("SELECT id FROM promotions WHERE name = ?")
|
||||
.get(promoName)!;
|
||||
const promoId = promoIdRow.id;
|
||||
|
||||
console.log(`Promotion ID for "${promoName}":`, promoId);
|
||||
|
||||
const insertQuery = connection.database.prepare(
|
||||
`INSERT INTO students
|
||||
(userId, firstName, lastName, mail, promotionId)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
);
|
||||
|
||||
for (const student of data) {
|
||||
console.log("Inserting student:", student);
|
||||
insertQuery.run(
|
||||
student.Identifiant,
|
||||
student.Nom,
|
||||
student["Prénom"],
|
||||
student.Mail,
|
||||
promoId,
|
||||
);
|
||||
}
|
||||
|
||||
console.log("All data inserted successfully");
|
||||
return new Response("Data inserted successfully", { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("Error inserting data:", error);
|
||||
return new Response("Failed to insert data", { status: 500 });
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,151 @@
|
||||
import { FreshContext, Handlers } from "$fresh/server.ts";
|
||||
import connect from "$root/databases/connect.ts";
|
||||
import { AuthenticatedState } from "$root/defaults/interfaces.ts";
|
||||
import { Database } from "@db/sqlite";
|
||||
|
||||
/**
|
||||
* Gets itself from the database.
|
||||
* @param database The database connection
|
||||
* @param userId The user ID.
|
||||
* @returns Itself from the database.
|
||||
*/
|
||||
function getItself(
|
||||
database: Database,
|
||||
userId: string,
|
||||
): { student: Student | null; promo: Promotion | null } {
|
||||
const studentQuery = "select * from students where userId = ?";
|
||||
const student: Student | undefined = database.prepare(studentQuery).get(
|
||||
userId,
|
||||
);
|
||||
|
||||
if (!student) {
|
||||
return { student: null, promo: null };
|
||||
}
|
||||
|
||||
const promoQuery = "select * from promotions where id = ?";
|
||||
const promo: Promotion | undefined = database.prepare(promoQuery).get(
|
||||
student.promotionId,
|
||||
);
|
||||
|
||||
return { student, promo: promo ?? null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets itself from the database.
|
||||
* @param database The database connexion
|
||||
* @param userId The user ID.
|
||||
* @returns Itself from the database.
|
||||
*/
|
||||
function getAll(
|
||||
database: Database,
|
||||
): { students: Student[]; promos: Promotion[] } {
|
||||
const studentsQuery = `
|
||||
select userId, firstName, lastName, mail, promotionId
|
||||
from students inner join promotions
|
||||
on students.promotionId = promotions.id
|
||||
where promotions.current < 6`;
|
||||
const students: Student[] = database.prepare(studentsQuery).all();
|
||||
|
||||
const promosQuery = "select * from promotions where promotions.current < 6";
|
||||
const promos: Promotion[] | undefined = database.prepare(promosQuery).all();
|
||||
|
||||
return { students, promos };
|
||||
}
|
||||
|
||||
/**
|
||||
* Add users to the database.
|
||||
* @param database The database connexion
|
||||
* @param students The students to add
|
||||
* @param promoId The promotion id.
|
||||
*/
|
||||
function addStudents(database: Database, students: Student[], promoId: string) {
|
||||
const query = `
|
||||
INSERT INTO students
|
||||
(userId, firstName, lastName, mail, promotionId)
|
||||
VALUES (?, ?, ?, ?, ?)`;
|
||||
|
||||
const statement = database.prepare(query);
|
||||
|
||||
for (const student of students) {
|
||||
statement.run(
|
||||
student.userId,
|
||||
student.firstName,
|
||||
student.lastName,
|
||||
student.mail,
|
||||
promoId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const handler: Handlers<null, AuthenticatedState> = {
|
||||
/**
|
||||
* The students the user can see.
|
||||
* @param _request The HTTP request.
|
||||
* @param _context The context with authenticated state.
|
||||
* @returns All students our user can see.
|
||||
*/
|
||||
// deno-lint-ignore require-await
|
||||
async GET(
|
||||
_request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
using connection = connect("students");
|
||||
const database = connection.database;
|
||||
|
||||
if (context.state.session.eduPersonPrimaryAffiliation == "student") {
|
||||
return new Response(
|
||||
JSON.stringify(getItself(database, context.state.session.uid)),
|
||||
{
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify(getAll(database)),
|
||||
{
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
/**
|
||||
* Add students in the database.
|
||||
* @param request The HTTP request.
|
||||
* @param _context The Fresh context.
|
||||
* @returns HTTP 201 on successful insert.
|
||||
*/
|
||||
async POST(
|
||||
request: Request,
|
||||
_context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
const { students, promo }: { students: Student[]; promo: string } =
|
||||
await request.json();
|
||||
|
||||
if (!promo || !promo.match(/^\d{4}-\dA$/) || !Array.isArray(students)) {
|
||||
return new Response(null, { status: 400 });
|
||||
}
|
||||
|
||||
using connection = connect("students");
|
||||
const database = connection.database;
|
||||
|
||||
const { endyear, current } = promo.match(
|
||||
/^(?<endyear>\d{4})-(?<current>\d)A$/,
|
||||
)?.groups!;
|
||||
|
||||
database.prepare(
|
||||
"insert or ignore into promotions (endyear, current) values (?, ?)",
|
||||
).run(endyear, current);
|
||||
|
||||
const { id: promoId }: { id: string } = database
|
||||
.prepare("select id from promotions where endyear = ? and current = ?")
|
||||
.get(endyear, current)!;
|
||||
|
||||
addStudents(database, students, promoId);
|
||||
|
||||
return new Response(null, { status: 201 });
|
||||
},
|
||||
};
|
||||
@@ -1,17 +1,16 @@
|
||||
import ConsultStudents from "$root/routes/(apps)/students/(_islands)/ConsultStudents.tsx";
|
||||
import ConsultStudents from "../../(_islands)/ConsultStudents.tsx";
|
||||
import {
|
||||
getPartialsConfig,
|
||||
makePartials,
|
||||
} from "$root/defaults/makePartials.tsx";
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { State } from "$root/routes/_middleware.ts";
|
||||
//import EditStudents from "../(_islands)/EditStudents.tsx";
|
||||
import { State } from "$root/defaults/interfaces.ts";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async function Students(_request: Request, _context: FreshContext<State>) {
|
||||
return (
|
||||
<>
|
||||
<h1>Manage Promotions</h1>
|
||||
<h2>Consult students</h2>
|
||||
<ConsultStudents />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import UploadStudents from "$root/routes/(apps)/students/(_islands)/UploadStudents.tsx";
|
||||
import UploadStudents from "../../(_islands)/UploadStudents.tsx";
|
||||
import {
|
||||
getPartialsConfig,
|
||||
makePartials,
|
||||
} from "$root/defaults/makePartials.tsx";
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { State } from "$root/routes/_middleware.ts";
|
||||
//import EditStudents from "../(_islands)/EditStudents.tsx";
|
||||
import { State } from "$root/defaults/interfaces.ts";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async function Students(_request: Request, _context: FreshContext<State>) {
|
||||
return (
|
||||
<>
|
||||
<h1>Manage Promotions</h1>
|
||||
<h2>Upload Students</h2>
|
||||
<UploadStudents />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -3,11 +3,18 @@ import {
|
||||
makePartials,
|
||||
} from "$root/defaults/makePartials.tsx";
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { State } from "$root/routes/_middleware.ts";
|
||||
import { State } from "$root/defaults/interfaces.ts";
|
||||
import SelfPortrait from "$root/routes/(apps)/students/(_components)/SelfPortrait.tsx";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
export async function Index(_request: Request, context: FreshContext<State>) {
|
||||
return <h2>Welcome to {context.state.session?.displayName}.</h2>;
|
||||
return (
|
||||
<>
|
||||
<h2>Welcome {context.state.session?.givenName}!</h2>
|
||||
<h3>Your amU identity</h3>
|
||||
<SelfPortrait self={context.state.session!} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const config = getPartialsConfig();
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Partial } from "$fresh/runtime.ts";
|
||||
import { RouteConfig } from "$fresh/server.ts";
|
||||
|
||||
type ModulesProps = Record<string | number | symbol, never>;
|
||||
|
||||
export const config: RouteConfig = {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
};
|
||||
|
||||
export default function Modules(_props: ModulesProps) {
|
||||
return (
|
||||
<Partial name="body">
|
||||
<a href="students" f-partial={"notes/partials"}>students</a>
|
||||
</Partial>
|
||||
);
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
interface Student {
|
||||
userId: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
mail: string;
|
||||
promotionId: number;
|
||||
}
|
||||
|
||||
interface Promotion {
|
||||
id: number;
|
||||
endyear: number;
|
||||
current: number;
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export default async function App(
|
||||
<link rel="stylesheet" href="/styles/main.css" />
|
||||
<link rel="stylesheet" href="/styles/app.css" />
|
||||
<link rel="stylesheet" href="styles/app-cards.css" />
|
||||
<link rel="stylesheet" href="styles/students.css" />
|
||||
</head>
|
||||
<body f-client-nav>
|
||||
<Header link={link} />
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
padding: 1em 0;
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 1em;
|
||||
gap: 4em;
|
||||
}
|
||||
|
||||
#app > #app-body {
|
||||
@@ -16,7 +16,7 @@
|
||||
}
|
||||
|
||||
#app > nav > a {
|
||||
padding: 0.25em 0.5em;
|
||||
padding: 0.5em 4em 0.5em 1em;
|
||||
color: light-dark(var(--light-foreground), var(--dark-foreground));
|
||||
}
|
||||
|
||||
@@ -57,5 +57,10 @@
|
||||
#app {
|
||||
grid-template-rows: auto 1fr;
|
||||
grid-template-columns: none;
|
||||
gap: 1em;
|
||||
}
|
||||
|
||||
#app > nav > a {
|
||||
padding: 0.5em 1em;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#self-portrait {
|
||||
display: grid;
|
||||
gap: 1em;
|
||||
grid-template-columns: auto 1fr;
|
||||
}
|
||||
|
||||
#self-portrait > div:nth-child(2n+1) {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
@media screen and (max-width: 1024px) {
|
||||
#self-portrait {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Mock de fetch() pour les tests — supporte méthodes HTTP et status codes
|
||||
|
||||
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
|
||||
|
||||
export interface MockRoute {
|
||||
method?: HttpMethod;
|
||||
status?: number;
|
||||
body?: unknown;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
let _originalFetch: ((input: any, init?: any) => Promise<Response>) | null =
|
||||
null;
|
||||
let _calls: { url: string; method: string; body?: unknown }[] = [];
|
||||
|
||||
/**
|
||||
* Remplace globalThis.fetch par un mock configurable.
|
||||
*
|
||||
* Usage simple (GET 200 par défaut) :
|
||||
* mockFetch({ "/students": studentsData })
|
||||
*
|
||||
* Usage avancé (méthode + status) :
|
||||
* mockFetch({ "/students": { method: "POST", status: 201, body: newStudent } })
|
||||
*/
|
||||
export function mockFetch(
|
||||
routes: Record<string, unknown | MockRoute>,
|
||||
): void {
|
||||
_originalFetch = globalThis.fetch;
|
||||
_calls = [];
|
||||
|
||||
globalThis.fetch = (
|
||||
input: string | URL | Request,
|
||||
init?: RequestInit,
|
||||
): Promise<Response> => {
|
||||
const url = typeof input === "string"
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.toString()
|
||||
: input.url;
|
||||
const method = (init?.method ?? "GET").toUpperCase();
|
||||
|
||||
// Parse le body si présent
|
||||
let reqBody: unknown = undefined;
|
||||
if (init?.body) {
|
||||
try {
|
||||
reqBody = JSON.parse(init.body as string);
|
||||
} catch {
|
||||
reqBody = init.body;
|
||||
}
|
||||
}
|
||||
|
||||
_calls.push({ url, method, body: reqBody });
|
||||
|
||||
for (const [pattern, config] of Object.entries(routes)) {
|
||||
if (!url.includes(pattern)) continue;
|
||||
|
||||
// Config simple : la valeur est directement le body de réponse (GET 200)
|
||||
if (!isRouteConfig(config)) {
|
||||
return new Response(JSON.stringify(config), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
// Config avancée : vérifier la méthode si spécifiée
|
||||
if (config.method && config.method !== method) continue;
|
||||
|
||||
const status = config.status ?? 200;
|
||||
|
||||
// 204 : pas de body
|
||||
if (status === 204) {
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
return new Response(
|
||||
config.body !== undefined ? JSON.stringify(config.body) : null,
|
||||
{
|
||||
status,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...config.headers,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ error: "Not Found" }), {
|
||||
status: 404,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Restaure le fetch original.
|
||||
*/
|
||||
export function restoreFetch(): void {
|
||||
if (_originalFetch) {
|
||||
globalThis.fetch = _originalFetch;
|
||||
_originalFetch = null;
|
||||
}
|
||||
_calls = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourne la liste des appels fetch interceptés.
|
||||
*/
|
||||
export function getFetchCalls(): {
|
||||
url: string;
|
||||
method: string;
|
||||
body?: unknown;
|
||||
}[] {
|
||||
return [..._calls];
|
||||
}
|
||||
|
||||
function isRouteConfig(value: unknown): value is MockRoute {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
||||
return false;
|
||||
}
|
||||
const v = value as Record<string, unknown>;
|
||||
return "status" in v || "method" in v || "body" in v;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// Mock de la couche Drizzle pour les tests unitaires/intégration
|
||||
// Permet de tester les handlers sans connexion PostgreSQL
|
||||
|
||||
export interface MockQueryResult<T> {
|
||||
rows: T[];
|
||||
}
|
||||
|
||||
export interface MockDbConfig {
|
||||
// Table name → array of rows
|
||||
// deno-lint-ignore no-explicit-any
|
||||
tables: Record<string, Record<string, any>[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée un mock de la DB Drizzle.
|
||||
* Simule select/insert/update/delete avec un store en mémoire.
|
||||
*
|
||||
* Usage :
|
||||
* ```ts
|
||||
* const db = createMockDb({
|
||||
* tables: {
|
||||
* students: [{ numEtud: 21212006, nom: "Dupont", ... }],
|
||||
* notes: [],
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // Lire toutes les lignes d'une table
|
||||
* const rows = db.getTable("students");
|
||||
*
|
||||
* // Insérer
|
||||
* db.insert("students", { numEtud: 21212009, nom: "Test", ... });
|
||||
*
|
||||
* // Trouver par clé
|
||||
* const student = db.findOne("students", (r) => r.numEtud === 21212006);
|
||||
*
|
||||
* // Supprimer
|
||||
* db.deleteWhere("students", (r) => r.numEtud === 21212006);
|
||||
* ```
|
||||
*/
|
||||
export function createMockDb(config: MockDbConfig) {
|
||||
// Deep clone pour éviter les mutations entre tests
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const tables: Record<string, Record<string, any>[]> = {};
|
||||
for (const [name, rows] of Object.entries(config.tables)) {
|
||||
tables[name] = rows.map((r) => ({ ...r }));
|
||||
}
|
||||
|
||||
return {
|
||||
/** Retourne toutes les lignes d'une table */
|
||||
getTable<T = Record<string, unknown>>(name: string): T[] {
|
||||
return (tables[name] ?? []) as T[];
|
||||
},
|
||||
|
||||
/** Retourne les lignes qui matchent le filtre */
|
||||
findMany<T = Record<string, unknown>>(
|
||||
name: string,
|
||||
predicate: (row: T) => boolean,
|
||||
): T[] {
|
||||
return (this.getTable<T>(name)).filter(predicate);
|
||||
},
|
||||
|
||||
/** Retourne la première ligne qui matche, ou undefined */
|
||||
findOne<T = Record<string, unknown>>(
|
||||
name: string,
|
||||
predicate: (row: T) => boolean,
|
||||
): T | undefined {
|
||||
return (this.getTable<T>(name)).find(predicate);
|
||||
},
|
||||
|
||||
/** Insère une ligne dans la table */
|
||||
insert<T = Record<string, unknown>>(name: string, row: T): T {
|
||||
if (!tables[name]) tables[name] = [];
|
||||
const copy = { ...row } as T;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
tables[name].push(copy as any);
|
||||
return copy;
|
||||
},
|
||||
|
||||
/** Met à jour les lignes qui matchent le prédicat */
|
||||
updateWhere<T = Record<string, unknown>>(
|
||||
name: string,
|
||||
predicate: (row: T) => boolean,
|
||||
updates: Partial<T>,
|
||||
): number {
|
||||
const rows = this.getTable<T>(name);
|
||||
let count = 0;
|
||||
for (const row of rows) {
|
||||
if (predicate(row)) {
|
||||
Object.assign(row as Record<string, unknown>, updates);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
},
|
||||
|
||||
/** Supprime les lignes qui matchent le prédicat */
|
||||
deleteWhere<T = Record<string, unknown>>(
|
||||
name: string,
|
||||
predicate: (row: T) => boolean,
|
||||
): number {
|
||||
const before = (tables[name] ?? []).length;
|
||||
tables[name] = (tables[name] ?? []).filter(
|
||||
(r) => !predicate(r as unknown as T),
|
||||
);
|
||||
return before - tables[name].length;
|
||||
},
|
||||
|
||||
/** Vide une table */
|
||||
clear(name: string): void {
|
||||
tables[name] = [];
|
||||
},
|
||||
|
||||
/** Vide toutes les tables */
|
||||
reset(): void {
|
||||
for (const name of Object.keys(tables)) {
|
||||
tables[name] = [];
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type MockDb = ReturnType<typeof createMockDb>;
|
||||
@@ -0,0 +1,137 @@
|
||||
// Types et données de test alignés sur l'API REST PolyMPR
|
||||
|
||||
// --- Types ---
|
||||
|
||||
export interface Student {
|
||||
numEtud: number;
|
||||
nom: string;
|
||||
prenom: string;
|
||||
idPromo: string;
|
||||
}
|
||||
|
||||
export interface Promotion {
|
||||
idPromo: string;
|
||||
annee: string;
|
||||
}
|
||||
|
||||
export interface Prof {
|
||||
id: number;
|
||||
nom: string;
|
||||
prenom: string;
|
||||
}
|
||||
|
||||
export interface Module {
|
||||
id: string;
|
||||
nom: string;
|
||||
}
|
||||
|
||||
export interface Note {
|
||||
note: number;
|
||||
numEtud: number;
|
||||
idModule: string;
|
||||
}
|
||||
|
||||
export interface UE {
|
||||
id: number;
|
||||
nom: string;
|
||||
}
|
||||
|
||||
export interface UeModule {
|
||||
idModule: string;
|
||||
idUE: number;
|
||||
idPromo: string;
|
||||
coeff: number;
|
||||
}
|
||||
|
||||
export interface Enseignement {
|
||||
idProf: number;
|
||||
idModule: string;
|
||||
idPromo: string;
|
||||
}
|
||||
|
||||
export interface Ajustement {
|
||||
numEtud: number;
|
||||
idUE: number;
|
||||
valeur: number;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
imported: number;
|
||||
errors: { line: number; message: string }[];
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
error: string;
|
||||
}
|
||||
|
||||
// --- Fixtures ---
|
||||
|
||||
export const students: Student[] = [
|
||||
{ numEtud: 21212006, nom: "Dupont", prenom: "Jean", idPromo: "4AFISE25/26" },
|
||||
{
|
||||
numEtud: 21212007,
|
||||
nom: "Martin",
|
||||
prenom: "Alice",
|
||||
idPromo: "4AFISE25/26",
|
||||
},
|
||||
{
|
||||
numEtud: 21212008,
|
||||
nom: "Durand",
|
||||
prenom: "Claire",
|
||||
idPromo: "3AFISE25/26",
|
||||
},
|
||||
];
|
||||
|
||||
export const promotions: Promotion[] = [
|
||||
{ idPromo: "4AFISE25/26", annee: "2025" },
|
||||
{ idPromo: "3AFISE25/26", annee: "2025" },
|
||||
{ idPromo: "JIA4A2526", annee: "2025" },
|
||||
];
|
||||
|
||||
export const profs: Prof[] = [
|
||||
{ id: 1, nom: "Leclerc", prenom: "Jean" },
|
||||
{ id: 2, nom: "Moreau", prenom: "Sophie" },
|
||||
];
|
||||
|
||||
export const modules: Module[] = [
|
||||
{ id: "JIN702C", nom: "Optimisation" },
|
||||
{ id: "JIN703C", nom: "Informatique" },
|
||||
{ id: "JIN704C", nom: "Physique" },
|
||||
];
|
||||
|
||||
export const notes: Note[] = [
|
||||
{ note: 15.5, numEtud: 21212006, idModule: "JIN702C" },
|
||||
{ note: 12.0, numEtud: 21212006, idModule: "JIN703C" },
|
||||
{ note: 18.0, numEtud: 21212007, idModule: "JIN702C" },
|
||||
{ note: 9.0, numEtud: 21212008, idModule: "JIN704C" },
|
||||
];
|
||||
|
||||
export const ues: UE[] = [
|
||||
{ id: 1, nom: "UE Informatique" },
|
||||
{ id: 2, nom: "UE Mathématiques" },
|
||||
];
|
||||
|
||||
export const ueModules: UeModule[] = [
|
||||
{ idModule: "JIN702C", idUE: 1, idPromo: "4AFISE25/26", coeff: 3.0 },
|
||||
{ idModule: "JIN703C", idUE: 2, idPromo: "4AFISE25/26", coeff: 4.0 },
|
||||
{ idModule: "JIN704C", idUE: 1, idPromo: "3AFISE25/26", coeff: 2.0 },
|
||||
];
|
||||
|
||||
export const enseignements: Enseignement[] = [
|
||||
{ idProf: 1, idModule: "JIN702C", idPromo: "4AFISE25/26" },
|
||||
{ idProf: 2, idModule: "JIN703C", idPromo: "4AFISE25/26" },
|
||||
{ idProf: 1, idModule: "JIN704C", idPromo: "3AFISE25/26" },
|
||||
];
|
||||
|
||||
export const ajustements: Ajustement[] = [
|
||||
{ numEtud: 21212006, idUE: 1, valeur: 13.25 },
|
||||
{ numEtud: 21212008, idUE: 1, valeur: 11.0 },
|
||||
];
|
||||
|
||||
// --- Réponses d'erreur standard ---
|
||||
|
||||
export const ERROR_NOT_FOUND: ApiError = { error: "Ressource introuvable" };
|
||||
export const ERROR_CONFLICT: ApiError = { error: "Ressource déjà existante" };
|
||||
export const ERROR_BAD_REQUEST: ApiError = { error: "Requête invalide" };
|
||||
export const ERROR_UNAUTHORIZED: ApiError = { error: "Non authentifié" };
|
||||
export const ERROR_FORBIDDEN: ApiError = { error: "Accès interdit" };
|
||||
@@ -0,0 +1,55 @@
|
||||
// Setup happy-dom + wrapper render pour les tests de composants Preact
|
||||
|
||||
import { Window } from "happy-dom";
|
||||
|
||||
let _window: Window | null = null;
|
||||
|
||||
/**
|
||||
* Initialise un environnement DOM virtuel via happy-dom.
|
||||
* À appeler avant de rendre des composants Preact dans les tests.
|
||||
*/
|
||||
export function setupDOM(): void {
|
||||
_window = new Window({ url: "http://localhost" });
|
||||
|
||||
// Expose les globals DOM nécessaires à Preact
|
||||
const globals = _window as unknown as Record<string, unknown>;
|
||||
const target = globalThis as unknown as Record<string, unknown>;
|
||||
|
||||
for (
|
||||
const key of [
|
||||
"document",
|
||||
"navigator",
|
||||
"location",
|
||||
"HTMLElement",
|
||||
"HTMLInputElement",
|
||||
"HTMLTextAreaElement",
|
||||
"HTMLSelectElement",
|
||||
"Event",
|
||||
"CustomEvent",
|
||||
"KeyboardEvent",
|
||||
"MouseEvent",
|
||||
"InputEvent",
|
||||
"MutationObserver",
|
||||
"requestAnimationFrame",
|
||||
"cancelAnimationFrame",
|
||||
]
|
||||
) {
|
||||
target[key] = globals[key];
|
||||
}
|
||||
|
||||
target["window"] = _window;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoie l'environnement DOM.
|
||||
* À appeler dans un afterEach ou à la fin d'un test.
|
||||
*/
|
||||
export function cleanupDOM(): void {
|
||||
if (_window) {
|
||||
const doc = _window.document;
|
||||
doc.body.innerHTML = "";
|
||||
doc.head.innerHTML = "";
|
||||
_window.close();
|
||||
_window = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import { assertEquals, assertExists } from "@std/assert";
|
||||
import { getFetchCalls, mockFetch, restoreFetch } from "../helpers/api_mock.ts";
|
||||
import { createMockDb } from "../helpers/db_mock.ts";
|
||||
import {
|
||||
ERROR_CONFLICT,
|
||||
ERROR_NOT_FOUND,
|
||||
modules,
|
||||
notes,
|
||||
type Student,
|
||||
students,
|
||||
} from "../helpers/fixtures.ts";
|
||||
import { cleanupDOM, setupDOM } from "../helpers/render.ts";
|
||||
|
||||
// --- Fixtures ---
|
||||
|
||||
Deno.test("fixtures - students match API shape", () => {
|
||||
assertEquals(students.length, 3);
|
||||
assertEquals(students[0].numEtud, 21212006);
|
||||
assertEquals(students[0].idPromo, "4AFISE25/26");
|
||||
assertEquals(typeof students[0].idPromo, "string");
|
||||
});
|
||||
|
||||
Deno.test("fixtures - modules have string ids", () => {
|
||||
assertEquals(modules[0].id, "JIN702C");
|
||||
assertEquals(typeof modules[0].id, "string");
|
||||
});
|
||||
|
||||
Deno.test("fixtures - notes use decimal values", () => {
|
||||
assertEquals(notes[0].note, 15.5);
|
||||
assertEquals(notes[0].idModule, "JIN702C");
|
||||
});
|
||||
|
||||
// --- Mock fetch simple (GET 200) ---
|
||||
|
||||
Deno.test("mockFetch - GET returns mocked data", async () => {
|
||||
mockFetch({ "/students": students });
|
||||
try {
|
||||
const res = await fetch("http://localhost/api/students");
|
||||
assertEquals(res.status, 200);
|
||||
const data = await res.json();
|
||||
assertEquals(data.length, 3);
|
||||
assertEquals(data[0].nom, "Dupont");
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("mockFetch - returns 404 for unknown routes", async () => {
|
||||
mockFetch({});
|
||||
try {
|
||||
const res = await fetch("http://localhost/api/unknown");
|
||||
assertEquals(res.status, 404);
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
// --- Mock fetch avancé (méthodes + status codes) ---
|
||||
|
||||
Deno.test("mockFetch - POST 201 created", async () => {
|
||||
const newStudent = students[0];
|
||||
mockFetch({
|
||||
"/students": { method: "POST", status: 201, body: newStudent },
|
||||
});
|
||||
try {
|
||||
const res = await fetch("http://localhost/api/students", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(newStudent),
|
||||
});
|
||||
assertEquals(res.status, 201);
|
||||
const data = await res.json();
|
||||
assertEquals(data.numEtud, 21212006);
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("mockFetch - DELETE 204 no content", async () => {
|
||||
mockFetch({
|
||||
"/students/21212006": { method: "DELETE", status: 204 },
|
||||
});
|
||||
try {
|
||||
const res = await fetch("http://localhost/api/students/21212006", {
|
||||
method: "DELETE",
|
||||
});
|
||||
assertEquals(res.status, 204);
|
||||
assertEquals(res.body, null);
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("mockFetch - 404 error response", async () => {
|
||||
mockFetch({
|
||||
"/students/99999": { status: 404, body: ERROR_NOT_FOUND },
|
||||
});
|
||||
try {
|
||||
const res = await fetch("http://localhost/api/students/99999");
|
||||
assertEquals(res.status, 404);
|
||||
const data = await res.json();
|
||||
assertEquals(data.error, "Ressource introuvable");
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("mockFetch - 409 conflict", async () => {
|
||||
mockFetch({
|
||||
"/enseignements": { method: "POST", status: 409, body: ERROR_CONFLICT },
|
||||
});
|
||||
try {
|
||||
const res = await fetch("http://localhost/api/enseignements", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
idProf: 1,
|
||||
idModule: "JIN702C",
|
||||
idPromo: "4AFISE25/26",
|
||||
}),
|
||||
});
|
||||
assertEquals(res.status, 409);
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
// --- getFetchCalls ---
|
||||
|
||||
Deno.test("getFetchCalls - tracks all intercepted calls", async () => {
|
||||
mockFetch({ "/notes": notes });
|
||||
try {
|
||||
await fetch("http://localhost/api/notes");
|
||||
await fetch("http://localhost/api/notes?numEtud=21212006");
|
||||
const calls = getFetchCalls();
|
||||
assertEquals(calls.length, 2);
|
||||
assertEquals(calls[0].method, "GET");
|
||||
assertEquals(calls[1].url, "http://localhost/api/notes?numEtud=21212006");
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("getFetchCalls - captures POST body", async () => {
|
||||
mockFetch({ "/notes": { method: "POST", status: 201, body: notes[0] } });
|
||||
try {
|
||||
await fetch("http://localhost/api/notes", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(notes[0]),
|
||||
});
|
||||
const calls = getFetchCalls();
|
||||
assertEquals(calls.length, 1);
|
||||
assertEquals(calls[0].method, "POST");
|
||||
assertEquals((calls[0].body as { note: number }).note, 15.5);
|
||||
} finally {
|
||||
restoreFetch();
|
||||
}
|
||||
});
|
||||
|
||||
// --- Mock DB ---
|
||||
|
||||
Deno.test("mockDb - getTable returns seeded rows", () => {
|
||||
const db = createMockDb({ tables: { students: [...students] } });
|
||||
assertEquals(db.getTable("students").length, 3);
|
||||
});
|
||||
|
||||
Deno.test("mockDb - findOne by key", () => {
|
||||
const db = createMockDb({ tables: { students: [...students] } });
|
||||
const found = db.findOne<Student>("students", (r) => r.numEtud === 21212006);
|
||||
assertExists(found);
|
||||
assertEquals(found.nom, "Dupont");
|
||||
});
|
||||
|
||||
Deno.test("mockDb - findOne returns undefined for missing", () => {
|
||||
const db = createMockDb({ tables: { students: [...students] } });
|
||||
const found = db.findOne<Student>("students", (r) => r.numEtud === 99999);
|
||||
assertEquals(found, undefined);
|
||||
});
|
||||
|
||||
Deno.test("mockDb - insert adds a row", () => {
|
||||
const db = createMockDb({ tables: { students: [] } });
|
||||
const newStudent: Student = {
|
||||
numEtud: 21212099,
|
||||
nom: "Test",
|
||||
prenom: "User",
|
||||
idPromo: "4AFISE25/26",
|
||||
};
|
||||
db.insert("students", newStudent);
|
||||
assertEquals(db.getTable("students").length, 1);
|
||||
assertEquals(
|
||||
db.findOne<Student>("students", (r) => r.numEtud === 21212099)?.nom,
|
||||
"Test",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("mockDb - updateWhere modifies matching rows", () => {
|
||||
const db = createMockDb({ tables: { students: [...students] } });
|
||||
const updated = db.updateWhere<Student>(
|
||||
"students",
|
||||
(r) => r.numEtud === 21212006,
|
||||
{ prenom: "Marie" },
|
||||
);
|
||||
assertEquals(updated, 1);
|
||||
assertEquals(
|
||||
db.findOne<Student>("students", (r) => r.numEtud === 21212006)?.prenom,
|
||||
"Marie",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("mockDb - deleteWhere removes matching rows", () => {
|
||||
const db = createMockDb({ tables: { students: [...students] } });
|
||||
const deleted = db.deleteWhere<Student>(
|
||||
"students",
|
||||
(r) => r.numEtud === 21212006,
|
||||
);
|
||||
assertEquals(deleted, 1);
|
||||
assertEquals(db.getTable("students").length, 2);
|
||||
});
|
||||
|
||||
Deno.test("mockDb - findMany with filter", () => {
|
||||
const db = createMockDb({ tables: { students: [...students] } });
|
||||
const promo4 = db.findMany<Student>(
|
||||
"students",
|
||||
(r) => r.idPromo === "4AFISE25/26",
|
||||
);
|
||||
assertEquals(promo4.length, 2);
|
||||
});
|
||||
|
||||
Deno.test("mockDb - reset clears all tables", () => {
|
||||
const db = createMockDb({
|
||||
tables: { students: [...students], notes: [...notes] },
|
||||
});
|
||||
db.reset();
|
||||
assertEquals(db.getTable("students").length, 0);
|
||||
assertEquals(db.getTable("notes").length, 0);
|
||||
});
|
||||
|
||||
Deno.test("mockDb - isolated between instances", () => {
|
||||
const db1 = createMockDb({ tables: { students: [...students] } });
|
||||
const db2 = createMockDb({ tables: { students: [...students] } });
|
||||
db1.deleteWhere<Student>("students", () => true);
|
||||
assertEquals(db1.getTable("students").length, 0);
|
||||
assertEquals(db2.getTable("students").length, 3);
|
||||
});
|
||||
|
||||
// --- happy-dom ---
|
||||
|
||||
Deno.test({
|
||||
name: "happy-dom - document is available after setup",
|
||||
sanitizeResources: false,
|
||||
sanitizeOps: false,
|
||||
fn() {
|
||||
setupDOM();
|
||||
try {
|
||||
const doc = globalThis.document;
|
||||
assertExists(doc);
|
||||
|
||||
const div = doc.createElement("div");
|
||||
div.textContent = "hello";
|
||||
doc.body.appendChild(div);
|
||||
|
||||
assertEquals(doc.body.textContent, "hello");
|
||||
} finally {
|
||||
cleanupDOM();
|
||||
}
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user