contructeur classes, type DTO dans TS, clean hard code

This commit is contained in:
trochas
2026-01-08 15:42:11 +01:00
parent 78b82fcfee
commit f2a0f8ca86
7 changed files with 207 additions and 97 deletions

View File

@@ -1,15 +1,7 @@
export type Groupe = "Entrainement" | "Competition" | "Loisir"| "";
export type Role = "admin" | "athlete" | "coach";
import { ActiviteDTO, AdminDTO, AthleteDTO, CoachDTO, SessionDTO } from "./classesDTO";
export type Groupe = "Entrainement" | "Competition" | "Loisir"| "";
export class User{
id!: number;
keycloakId!: String;
nom!: string;
prenom!:string;
sessions: Session[] = []; //nb: Admin liaison non symétrique /!\
email!: string;
role!: Role;
}
export class Ligne{
id!: number;
@@ -18,32 +10,103 @@ export class Ligne{
tempsDeJeu!: number; // en minutes
}
export class User{
id!: number;
keycloakId!: String;
nom!: string;
prenom!:string;
email!: string;
}
export class Admin extends User{
role!: Role;
constructor(dto:AdminDTO);
constructor();
constructor(dto?:AdminDTO){
super();
this.id = dto?.id ?? 0;
this.keycloakId = dto?.id_keycloak ?? "";
this.nom = dto?.name ?? "";
this.prenom = dto?.prenom ?? "";
this.email = ""; //TODO
}
}
export class Athlete extends User{
nom!: string;
groupe!: Groupe;
role!: Role;
groupes!: Groupe[];
sessionsID!: number[];
sessions: Session[] = [];
constructor(dto:AthleteDTO);
constructor();
constructor(dto?:AthleteDTO){
super();
this.id = dto?.id ?? 0;
this.keycloakId = dto?.id_keycloak ?? "";
this.nom = dto?.name ?? "";
this.prenom = dto?.prenom ?? "" ;
this.email = ""; //TODO
this.groupes = dto?.groupes ?? [];
this.sessionsID = dto?.sessionIds ?? [];
this.sessions = [];
}
}
export class Coach extends User{
nom!: string;
role!: Role;
sessionsID!: number[];
sessions: Session[] = [];
constructor(dto:CoachDTO);
constructor();
constructor(dto?:CoachDTO){
super();
this.id = dto?.id ?? 0;
this.keycloakId = dto?.id_keycloak ?? "";
this.nom = dto?.name ?? "";
this.prenom = dto?.prenom ?? "";
this.email = ""; //TODO
this.sessionsID = dto?.sessionIds ?? [];
this.sessions = [];
}
}
export class Session{
id!: number;
name!: string;
activitesID: number[] = [];
activites: Activite[] = [];
isRecurrent! : Boolean;
creneau!: Date;
coach!: Coach;
athletesID!: number[]
athletes!: Athlete[]
duree! : number;
groupe! : Groupe;
ligne! : Ligne[];
constructor(dto:SessionDTO);
constructor();
constructor(dto?:SessionDTO){
this.id = dto?.id?? 0;
this.name = dto?.name?? "";
this.activitesID = dto?.activiteIds?? [];
this.activites = [];
this.isRecurrent = dto?.isRecurrent?? false;
this.creneau = dto? new Date(dto.creneau) : new Date();
//this.coach = new Coach(); //dto.coachId; //TODO
this.athletesID = dto?.athleteIds ?? [];
this.athletes = [];
this.duree = dto?.duree ?? 0;
this.groupe = dto?.groupe ?? "";
this.ligne = []; //TODO
}
}
export class Activite{
@@ -54,10 +117,23 @@ export class Activite{
data!: Map<string,string>;
duree!: number;
}
constructor(dto:ActiviteDTO);
constructor();
constructor(dto?:ActiviteDTO){
this.id = dto?.id ?? 0;
this.nom = dto?.name ?? "";
//this.session = dto.sessionId; //TODO
this.theme = dto?.theme ?? "";
//this.data = //TODO
this.duree = dto?.duree ?? 0;
}
}
/*
export function getUserTest():User{
const user = new User();
const user = new Athlete();
const s1 = new Session();
const s2 = new Session();
const s3 = new Session();
@@ -65,17 +141,17 @@ export function getUserTest():User{
athlete1.id = 1;
athlete1.nom = "Alice Dupont";
athlete1.email = "alice@nootnoot.yee";
athlete1.groupe = "Entrainement";
athlete1.groupes = ["Entrainement"];
const athlete2 = new Athlete();
athlete2.id = 2;
athlete2.nom = "Bob Martin";
athlete2.groupe = "Competition";
athlete2.groupes = ["Competition"];
const athlete3 = new Athlete();
athlete3.id = 3;
athlete3.nom = "Clara Lopez";
athlete3.groupe = "Loisir";
athlete3.groupes = ["Loisir"];
const ligne1 = new Ligne();
ligne1.id = 1;
@@ -99,7 +175,6 @@ export function getUserTest():User{
user.id = 0;
user.nom = "Emilien-Yee NootNoot";
user.role = "coach"
user.email = "emilien@nootnoot.yee";
s1.creneau = new Date();
s1.id = 1;
@@ -187,9 +262,7 @@ export function getUserTest():User{
user.sessions.push(s2);
user.sessions.push(s3);
athlete1.role = "athlete";
athlete2.role = "athlete";
athlete3.role = "athlete";
return user;
}
*/

View File

@@ -0,0 +1,50 @@
import { Groupe } from "./classes";
export type ActiviteDTO = {
id: number;
name: string;
theme: string;
duree: number;
dataActivite: string[];
sessionId: number;
}
export type AdminDTO = {
id: number;
id_keycloak: string;
name: string;
prenom: string;
}
export type AthleteDTO = {
id:number;
id_keycloak: string;
name: string;
prenom: string;
categorie: string;
niveau: string;
groupes: Groupe[];
sessionIds: number[];
};
export type CoachDTO = {
id: number;
id_keycloak: string;
name: string;
prenom: string;
sessionIds: number[];
};
export type SessionDTO = {
id: number;
name: string;
isRecurrent: boolean;
creneau: string; // LocalDateTime → ISO string
duree: number;
groupe: Groupe;
coachId: number;
athleteIds: number[];
activiteIds: number[];
};

View File

@@ -1,42 +1,51 @@
import { useKeycloak } from '@react-keycloak/web'
import { useEffect } from 'react';
import { getUserTest, User } from '../classes';
import { Athlete, User } from '../classes';
import { useLocalData } from '../context/useLocalData';
import { postAthlete } from '../requetes';
export const Login =() =>{
const {user,setUser} = useLocalData()
const { keycloak } = useKeycloak();
useEffect(() => {
const syncAndLoadUser = async () => {
if (keycloak.authenticated && keycloak.token) {
const tokenParsed = keycloak.tokenParsed;
setUser({
id: 0,
keycloakId: tokenParsed!.sub!,
email: tokenParsed?.email || "",
nom: tokenParsed?.family_name || "",
prenom: tokenParsed?.given_name || "",
role: "athlete",
sessions: []
});
try {
const response = await fetch("http://localhost:8081/api/users/sync", {
method: "POST",
headers: {
"Authorization": `Bearer ${keycloak.token}`,
"Content-Type": "application/json"
},
});
console.log("Sync status:", response.status);
} catch (error) {
console.error("Sync fetch failed:", error);
}
}
};
const syncAndLoadUser = async () => {
const newAthlete:Athlete = new Athlete()
syncAndLoadUser();
}, [keycloak.authenticated, keycloak.token, setUser]);
const athlete:Athlete = await postAthlete(newAthlete)
setUser(athlete);
/*postAthlete
if (keycloak.authenticated && keycloak.token) {
const tokenParsed = keycloak.tokenParsed;
setUser(
{
id: 0,
keycloakId: tokenParsed!.sub!,
email: tokenParsed?.email || "",
nom: tokenParsed?.family_name || "",
prenom: tokenParsed?.given_name || "",
sessions: []
}
);
try {
const response = await fetch("http://localhost:8081/api/users/sync", {
method: "POST",
headers: {
"Authorization": `Bearer ${keycloak.token}`,
"Content-Type": "application/json"
},
});
console.log("Sync status:", response.status);
} catch (error) {
console.error("Sync fetch failed:", error);
}
}*/
};
syncAndLoadUser();
}, [keycloak.authenticated, keycloak.token, setUser]);
function handleLogin(): void {
@@ -61,9 +70,6 @@ export const Login =() =>{
<div>
User nom : { user.nom}
</div>
<div>
User role : { user.role}
</div>
</div>
}

View File

@@ -101,20 +101,18 @@ function ObjectUser({admin=null,athlete=null,coach=null}:Props){
return(
<div>
<div className="object" onClick={() => handleOpen()}>
<div>{user2.nom} ({user2.role})</div>
<div>{user2.nom}</div>
{/* <div>{user2.role}</div> */}
</div>
{open &&
<Modal isOpen={open} onClose={() => setOpen(false)}>
<div className="object_modal">
<div>{user2.nom} ({user2.role})</div>
<div>{user2.nom}</div>
<div>{user2.email}</div>
<div className='list_object'>
<div>Sessions :</div>
{user.sessions.map((session,index)=>(
<ObjectSession session={session}/>
))}
{/* TODO */}
</div>
</div>

View File

@@ -72,7 +72,7 @@ function AthleteList({ athletes, sessions }: AthleteListProps) {
return (
<li key={a.id}>
<div><strong>Nom:</strong> {a.nom}</div>
<div><strong>Groupe:</strong> {a.groupe}</div>
<div><strong>Groupe:</strong> {a.groupes}</div>
<div><strong>Nombre de sessions:</strong> {stats.nbSessions}</div>
<div><strong>Sessions/semaine:</strong> {stats.nbSessionsPerWeek.toFixed(2)}</div>
<div><strong>Alerte:</strong> {alerte}</div>

View File

@@ -1,6 +1,6 @@
import { useState } from "react";
import { useLocalData } from "../context/useLocalData";
import { Activite, Athlete, Coach , Session, Ligne, getUserTest } from "../classes";
import { Activite, Athlete, Coach , Session, Ligne, Admin } from "../classes";
import {calculTempsDeJeuParLigne} from "../utils/ligneUtils";
import { keyboard } from "@testing-library/user-event/dist/keyboard";
import ObjectSession from "./object/session";
@@ -10,14 +10,11 @@ import ObjectUser from "./object/user";
export type keyWord = "athletes" | "activites" | "coachs" | "sessions"| "lignes";
export default function RessourcePanel() {
//const { user } = useLocalData();
const user = getUserTest(); //TODO
const { user } = useLocalData();
//const user = getUserTest(); //TODO
const [value,setValue] = useState<keyWord>("athletes");
console.log("Rôle utilisateur:", user.role);
console.log(user.nom);
console.log(user.prenom);
console.log(user.email);
if (user.role === "athlete") return null;
if (user instanceof Athlete) return null;
const allAthletes: Athlete[] = [];
@@ -28,26 +25,8 @@ import ObjectUser from "./object/user";
const allSessions: Session[] = [];
const ligneMap: Map<number, Ligne> = new Map();
user.sessions.forEach(session => {
if (session.ligne) {
const allLignes: Ligne[] = [];
session.ligne.forEach(ligne => {
ligneMap.set(ligne.id, ligne);
});
}
});
const allLignes: Ligne[] = Array.from(ligneMap.values());
// Calculer le temps de jeu pour chaque ligne
const tempsDeJeuParLigne: Map<number, number> = new Map();
allLignes.forEach(ligne => {
const tempsTotal = calculTempsDeJeuParLigne(allSessions, ligne);
tempsDeJeuParLigne.set(ligne.id, tempsTotal);
ligne.tempsDeJeu = tempsTotal;
});
@@ -63,7 +42,7 @@ import ObjectUser from "./object/user";
}}>
<option value="athletes">Athlètes</option>
<option value="activites">Activités</option>
{user.role === "admin" && <option value="coachs"> Coachs</option>}
{user instanceof Admin && <option value="coachs"> Coachs</option>}
<option value="sessions"> Sessions</option>
<option value="lignes"> Lignes</option>

View File

@@ -1,6 +1,7 @@
import api, { activiteService, sessionService } from "./api";
import { Activite, Admin, Athlete, Coach, Session, User } from "./classes";
import Keycloak from 'keycloak-js'
import { AdminDTO, AthleteDTO, CoachDTO } from "./classesDTO";
//debug:
export function delay(ms: number): Promise<void> {
@@ -19,16 +20,19 @@ export async function getUser(keycloak:Keycloak): Promise<User|null>{
const roles = keycloak.tokenParsed?.realm_access?.roles
if(roles!=null){
if(roles.includes("admin")){
const response = await api.get<any>(`/TODO`);
return response.data;
const response = await api.get<AdminDTO>(`/TODO`);
const admin = new Admin(response.data);
return admin;
}
else if(roles.includes("coach")){
const response = await api.get<any>(`/TODO`);
return response.data;
const response = await api.get<CoachDTO>(`/TODO`);
const coach = new Coach(response.data);
return coach;
}
else if(roles.includes("athletes")){
const response = await api.get<any>(`/TODO`);
return response.data;
const response = await api.get<AthleteDTO>(`/TODO`);
const athlete = new Athlete(response.data);
return athlete;
}
console.error("Error roles inconnu");
}