This commit is contained in:
trochas
2026-01-08 13:17:57 +01:00
26 changed files with 474 additions and 100 deletions

6
back_end/package-lock.json generated Normal file
View File

@@ -0,0 +1,6 @@
{
"name": "back_end",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

View File

@@ -6,11 +6,15 @@ import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity
@@ -19,9 +23,16 @@ public class WebSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/public", "/coach/**").permitAll() // allow coach endpoints
// TODO //TODO // T O D O
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 2. Allow public endpoints BEFORE any authenticated() calls
.requestMatchers("/athlete/create", "/", "/public").permitAll()
.requestMatchers("/coach/**").permitAll()
// 3. Authenticated endpoints
.requestMatchers("/users/sync").authenticated()
.requestMatchers("/admin/**").hasRole("admin")
.requestMatchers("/user/**").hasRole("user")
.anyRequest().authenticated())
@@ -29,6 +40,7 @@ public class WebSecurityConfig {
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtToken -> {
Map<String, Collection<String>> realmAccess = jwtToken.getClaim("realm_access");
Collection<String> roles = realmAccess.get("roles");
System.out.println("ROLES FROM TOKEN " + roles);
List<SimpleGrantedAuthority> authorities = roles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.toList();
@@ -37,4 +49,18 @@ public class WebSecurityConfig {
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("http://localhost:3000"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowCredentials(true);
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}

View File

@@ -7,7 +7,7 @@ import java.util.List;
@Data
public class SessionDTO {
private Integer id;
private String name;
private Boolean isRecurrent;
private LocalDateTime creneau;

View File

@@ -14,11 +14,37 @@ import jakarta.persistence.Entity;
public class Admin extends User{
public Admin(String id_keycloak, String name, String prenom){
super(name, id_keycloak, prenom, Role.ADMIN );
super(name, id_keycloak, prenom, Role.admin );
}
@Override
public String toString() {
return "Admin [id=" + super.getId() + " , name=" + super.getName() + "]";
}
@Override
public void setName(String name) {
super.setName(name);
}
@Override
public String getName() {
return super.getName();
}
@Override
public String getPrenom() {
return super.getPrenom();
}
@Override
public void setPrenom(String prenom) {
super.setPrenom(prenom);
}
@Override
public Role getRole() {
return super.getRole();
}
}

View File

@@ -28,11 +28,36 @@ public class Athlete extends User{
private List<Session> sessions = new ArrayList<>(); // plusieurs sessions sont possibles
public Athlete(String name, String id_keycloak, String prenom){
super(name, id_keycloak, prenom, Role.ATHLETE);
super(name, id_keycloak, prenom, Role.athlete);
}
@Override
public String toString() {
return "Athlete [id=" + super.getId() + " , name=" + super.getName() + "]";
}
@Override
public void setName(String name) {
super.setName(name);
}
@Override
public String getName() {
return super.getName();
}
@Override
public String getPrenom() {
return super.getPrenom();
}
@Override
public void setPrenom(String prenom) {
super.setPrenom(prenom);
}
@Override
public Role getRole() {
return super.getRole();
}
}

View File

@@ -20,11 +20,37 @@ public class Coach extends User{
private List<Session> sessions = new ArrayList<>(); // Un coach peut avoir plusieurs sessions
public Coach(String name, String id_keycloak, String prenom){
super(name, id_keycloak, prenom, Role.COACH );
super(name, id_keycloak, prenom, Role.coach );
}
@Override
public String toString() {
return "Coach [id=" + super.getId() + " , name=" + super.getName() + "]";
}
@Override
public void setName(String name) {
super.setName(name);
}
@Override
public String getName() {
return super.getName();
}
@Override
public String getPrenom() {
return super.getPrenom();
}
@Override
public void setPrenom(String prenom) {
super.setPrenom(prenom);
}
@Override
public Role getRole() {
return super.getRole();
}
}

View File

@@ -1,7 +1,7 @@
package hackathon.FrisbYEE.jpa.metier;
public enum Role {
ADMIN,
COACH,
ATHLETE
admin,
coach,
athlete
}

View File

@@ -58,7 +58,7 @@ public class Session {
}
public void setCoach(Coach coach) {
if (coach.getRole() != Role.COACH) {
if (coach.getRole() != Role.coach) {
throw new IllegalArgumentException("L'utilisateur n'est pas un coach");
}
this.coach = coach;
@@ -66,7 +66,7 @@ public class Session {
public void setAthletes(List<Athlete> athletes) {
for (Athlete athlete : athletes) {
if (athlete.getRole() != Role.ATHLETE) {
if (athlete.getRole() != Role.athlete) {
throw new IllegalArgumentException("L'utilisateur n'est pas un athlète");
}
}

View File

@@ -26,8 +26,8 @@ public class User implements Serializable {
@GeneratedValue
@Column(unique = true, nullable = false)
private Integer id;
@Column(nullable = false, unique = true)
private String id_keycloak;
@Column(name = "id_keycloak", unique = true, nullable = false)
private String keycloakId;
private String name;
private String prenom;
@@ -38,7 +38,7 @@ public class User implements Serializable {
public User(String name, String id_keycloak, String prenom, Role role) {
this.name = name;
this.id_keycloak = id_keycloak;
this.keycloakId = id_keycloak;
this.prenom = prenom;
this.role = role;
}

View File

@@ -1,11 +1,12 @@
package hackathon.FrisbYEE.jpa.service;
import hackathon.FrisbYEE.jpa.metier.Athlete;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AthleteDAO extends JpaRepository<Athlete, Integer> {
boolean existsByKeycloakId(String keycloakId);
Optional<Athlete> findByKeycloakId(String keycloakId);
}

View File

@@ -20,6 +20,7 @@ import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@CrossOrigin(origins = "http://localhost:3000")
@Controller
@RequestMapping("/activite")
@@ -45,10 +46,11 @@ public class ActiviteResource {
})
@PostMapping("/create")
@ResponseBody
@PreAuthorize("hasRole('Coach')")
@PreAuthorize("hasRole('coach')")
public ResponseEntity<String> create(@RequestBody ActiviteDTO dto) {
try {
System.out.println("ROLE TEST " + hackathon.FrisbYEE.jpa.metier.Role.coach);
Session session = sessionDAO.findById(dto.getSessionId()).get();
Activite activite = mapToEntity(dto);
activite.setSession(session);
@@ -67,7 +69,7 @@ public class ActiviteResource {
})
@DeleteMapping("/delete/{id}")
@ResponseBody
@PreAuthorize("hasRole('Coach')")
@PreAuthorize("hasRole('coach')")
public ResponseEntity<String> delete(@PathVariable("id") int id) {
try {
Activite activite = activiteDAO.findById(id).get();
@@ -87,7 +89,7 @@ public class ActiviteResource {
})
@PostMapping("/update/{id}")
@ResponseBody
@PreAuthorize("hasRole('Coach')")
@PreAuthorize("hasRole('coach')")
public ResponseEntity<String> modifyById(@PathVariable("id") int id, @RequestBody ActiviteDTO dto) {
try {
Session session = sessionDAO.findById(dto.getSessionId()).get();
@@ -112,7 +114,7 @@ public class ActiviteResource {
schema = @Schema(implementation = ActiviteDTO.class)))
})
@GetMapping("/{id}")
@PreAuthorize("hasRole('Coach') or hasRole('Athlete')")
@PreAuthorize("hasRole('coach') or hasRole('athlete')")
@ResponseBody
public ResponseEntity<ActiviteDTO> getActivityById(@PathVariable("id") int id) {
try {
@@ -131,7 +133,7 @@ public class ActiviteResource {
schema = @Schema(implementation = ActiviteDTO.class)))
})
@GetMapping("/all")
@PreAuthorize("hasRole('Coach') or hasRole('Athlete')")
@PreAuthorize("hasRole('coach') or hasRole('athlete')")
@ResponseBody
public ResponseEntity<List<ActiviteDTO>> getAllActivity() {
try {
@@ -151,7 +153,7 @@ public class ActiviteResource {
schema = @Schema(implementation = ActiviteDTO.class)))
})
@GetMapping("/theme/{theme}")
@PreAuthorize("hasRole('Coach') or hasRole('Athlete')")
@PreAuthorize("hasRole('coach') or hasRole('athlete')")
@ResponseBody
public ResponseEntity<List<ActiviteDTO>> getActivityByTheme(@PathVariable("theme") String theme) {
try {

View File

@@ -10,6 +10,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -18,6 +19,8 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import hackathon.FrisbYEE.jpa.dto.ActiviteDTO;
import hackathon.FrisbYEE.jpa.dto.AthleteDTO;
import hackathon.FrisbYEE.jpa.dto.SessionDTO;
@@ -32,9 +35,9 @@ import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
@Controller
@RestController
@RequestMapping("/athlete")
@CrossOrigin(origins = "http://localhost:3000")
public class AthleteResource {
@Autowired
private AthleteDAO athleteDAO;
@@ -45,7 +48,7 @@ public class AthleteResource {
@ApiResponse(responseCode = "200", description = "Renvoie l'athlète créé", content = @Content(mediaType = "application/json", schema = @Schema(implementation = AthleteDTO.class)))
})
@PostMapping("/create")
@PreAuthorize("hasRole('Admin')") // Only admin can create??
@PreAuthorize("hasRole('admin') or hasRole('coach') or hasRole('Athlete')")
public ResponseEntity<AthleteDTO> create(@RequestBody AthleteDTO dto) {
Athlete athlete = mapToEntity(dto);
athleteDAO.save(athlete);
@@ -57,7 +60,7 @@ public class AthleteResource {
@ApiResponse(responseCode = "200", description = "Récupère tous les athlètes", content = @Content(mediaType = "application/json", schema = @Schema(implementation = List.class)))
})
@GetMapping("/all")
@PreAuthorize("hasRole('Admin') or hasRole('Coach') or hasRole('Athlete')")
@PreAuthorize("hasRole('admin') or hasRole('coach') or hasRole('athlete')")
public ResponseEntity<List<AthleteDTO>> all() {
List<Athlete> athletes = athleteDAO.findAll();
List<AthleteDTO> dtos = new ArrayList<>();
@@ -72,7 +75,7 @@ public class AthleteResource {
@ApiResponse(responseCode = "200", description = "Récupération effectuée", content = @Content(mediaType = "application/json", schema = @Schema(implementation = AthleteDTO.class)))
})
@GetMapping("/{id}")
@PreAuthorize("hasRole('Admin') or hasRole('Coach') or hasRole('Athlete')")
@PreAuthorize("hasRole('admin') or hasRole('coach') or hasRole('athlete')")
public ResponseEntity<AthleteDTO> getById(@PathVariable Integer id) {
return athleteDAO.findById(id)
.map(athlete -> ResponseEntity.ok(mapToDTO(athlete)))
@@ -84,7 +87,7 @@ public class AthleteResource {
@ApiResponse(responseCode = "200", description = "Mise à jour effectuée", content = @Content(mediaType = "application/json", schema = @Schema(implementation = AthleteDTO.class)))
})
@PutMapping("/{id}")
@PreAuthorize("hasRole('ADMIN') or #id == principal.id")
@PreAuthorize("hasRole('admin') or #id == principal.id")
public ResponseEntity<AthleteDTO> update(@PathVariable Integer id, @RequestBody AthleteDTO dto) {
try {
Athlete athlete = athleteDAO.findById(id).get();
@@ -115,7 +118,7 @@ public class AthleteResource {
@ApiResponse(responseCode = "200", description = "Suppression effectuée", content = @Content(mediaType = "application/json", schema = @Schema(implementation = AthleteDTO.class)))
})
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('Admin')")
@PreAuthorize("hasRole('admin')")
public ResponseEntity<Void> delete(@PathVariable Integer id) {
if (!athleteDAO.existsById(id)) {
return ResponseEntity.notFound().build();
@@ -126,8 +129,9 @@ public class AthleteResource {
private AthleteDTO mapToDTO(Athlete athlete) {
AthleteDTO dto = new AthleteDTO();
dto.setId_keycloak(athlete.getId_keycloak());
dto.setId_keycloak(athlete.getKeycloakId());
dto.setName(athlete.getName());
dto.setPrenom(athlete.getPrenom());
dto.setCategorie(athlete.getCategorie());
dto.setNiveau(athlete.getNiveau());
return dto;
@@ -135,6 +139,12 @@ public class AthleteResource {
private Athlete mapToEntity(AthleteDTO dto) {
Athlete athlete = new Athlete();
athlete.setName(dto.getName());
athlete.setPrenom(dto.getPrenom());
athlete.setKeycloakId(dto.getId_keycloak());
athlete.setCategorie(dto.getCategorie());
athlete.setNiveau(dto.getNiveau());
athlete.setRole(hackathon.FrisbYEE.jpa.metier.Role.athlete);
return athlete;
}

View File

@@ -70,14 +70,14 @@ public class CoachResource {
private CoachDTO mapToDTO(Coach coach) {
CoachDTO dto = new CoachDTO();
dto.setId_keycloak(coach.getId_keycloak());
dto.setId_keycloak(coach.getKeycloakId());
dto.setName(coach.getName());
return dto;
}
private Coach mapToEntity(CoachDTO dto) {
Coach coach = new Coach();
coach.setId_keycloak(dto.getId_keycloak());
coach.setKeycloakId(dto.getId_keycloak());
coach.setName(dto.getName());
return coach;
}

View File

@@ -40,7 +40,7 @@ public class SessionResource {
@PostMapping("/create")
@ResponseBody
@PreAuthorize("hasRole('Coach')")
@PreAuthorize("hasRole('coach')")
public ResponseEntity<?> create(@RequestBody SessionDTO dto) {
try {
Session session = maptoEntity(dto);
@@ -53,7 +53,7 @@ public class SessionResource {
}
@GetMapping("/all")
@PreAuthorize("hasRole('Coach') or hasRole('Athlete')")
@PreAuthorize("hasRole('coach') or hasRole('athlete')")
public ResponseEntity<List<SessionDTO>> getAll() {
List<Session> sessions = sessionDAO.findAll();
List<SessionDTO> dtos = new ArrayList<>();
@@ -64,7 +64,7 @@ public class SessionResource {
}
@GetMapping("/{id}")
@PreAuthorize("hasRole('Coach') or hasRole('Athlete')")
@PreAuthorize("hasRole('coach') or hasRole('athlete')")
public ResponseEntity<?> getById(@PathVariable Integer id) {
try {
Session session = sessionDAO.findById(id).orElseThrow();
@@ -76,7 +76,7 @@ public class SessionResource {
@DeleteMapping("/delete/{id}")
@ResponseBody
@PreAuthorize("hasRole('Coach')")
@PreAuthorize("hasRole('coach')")
public ResponseEntity<String> delete(@PathVariable("id") int id) {
try {
Session session = sessionDAO.findById(id).get();
@@ -88,7 +88,7 @@ public class SessionResource {
}
@PutMapping("/update/{id}")
@PreAuthorize("hasRole('Coach')")
@PreAuthorize("hasRole('coach')")
public ResponseEntity<Void> updateSession(@PathVariable Integer id, @RequestBody SessionDTO dto) {
Session session = sessionDAO.findById(id).orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND, "Session not found with id " + id));

View File

@@ -8,6 +8,5 @@ spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
server.port=8081
server.servlet.context-path=/api
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/Frisbyee_realm
spring.security.oauth2.resourceserver.jwt.jwk-set-uri: http://localhost:8080/realms/Frisbyee_realm/protocol/openid-connect/certs

View File

@@ -1,6 +1,7 @@
{
"realm": "Frisbyee_realm",
"resource": "Frisbyee_client",
"clientId": "Frisbyee_client",
"auth-server-url": "http://localhost:8080",
"public-client": true
}

View File

@@ -11,7 +11,7 @@ import EdtCoach from './components/edt_coach'
import { Coach } from "./classes";
import RessourcePanel from './components/ressourcePanel';
import TestAPI from './components/test_api';
import EdtAthlete from './components/edt_athlete';
// Test
const testCoach = new Coach();
testCoach.id = 1;
@@ -36,7 +36,7 @@ function App() {
<RessourcePanel/>
<EDT/>
<CreateSession/>
<EdtAthlete/>
<TestAPI/>
</div>
</LocalDataProvider>

View File

@@ -6,6 +6,7 @@ const api = axios.create({
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
});
api.interceptors.request.use((config) => {

View File

@@ -1,43 +1,41 @@
export type Groupe = "Entrainement" | "Competition" | "Loisir"| "";
export type Role = "Admin" | "Athlete" | "Coach";
export type Role = "admin" | "athlete" | "coach";
export class User{
id!: number;
nom!: String;
keycloakId!: String;
nom!: string;
prenom!:string;
sessions: Session[] = []; //nb: Admin liaison non symétrique /!\
email!: String;
email!: string;
role!: Role;
}
export class Ligne{
id!: number;
nom!: String;
nom!: string;
composition!: Athlete[] //les joueurs compososant la ligne
tempsDeJeu!: number; // en minutes
}
export class Admin extends User{
role!: Role;
}
export class Athlete extends User{
nom!: String;
nom!: string;
groupe!: Groupe;
role!: Role;
}
export class Coach extends User{
nom!: String;
nom!: string;
role!: Role;
}
export class Session{
id!: number;
name!: String;
name!: string;
activites: Activite[] = [];
isRecurrent! : Boolean;
creneau!: Date;
@@ -50,10 +48,10 @@ export class Session{
export class Activite{
id!: number;
nom!: String;
nom!: string;
session!: Session;
theme!: String;
data!: Map<String,String>;
theme!: string;
data!: Map<string,string>;
duree!: number;
}
@@ -101,13 +99,15 @@ export function getUserTest():User{
user.id = 0;
user.nom = "Emilien-Yee NootNoot";
user.role = "coach"
user.email = "emilien@nootnoot.yee";
user.role = "Coach"
s1.creneau = new Date();
s1.id = 1;
s1.name = "Entrainement Frisbee"
s1.isRecurrent = true;
s1.ligne = [ligne1];
s1.duree= 90;
s1.athletes = [athlete1,athlete2];
var date2 = new Date();
date2.setDate(date2.getDate() + 2);
s2.creneau = date2;
@@ -115,18 +115,16 @@ export function getUserTest():User{
s2.isRecurrent = false;
s2.name = "entraintement 2"
s2.ligne = [ligne2];
s2.duree= 120;
s2.athletes = [athlete1,athlete2, athlete3];
s3.creneau = date2;
s3.id = 3;
s3.isRecurrent = false;
s3.name = "entraintement 3"
s3.ligne = [ligne3];
s1.athletes = [athlete1, athlete2];
s2.athletes = [athlete2, athlete3];
s3.athletes = [athlete1, athlete3];
s3.ligne = [ligne3, ligne1];
s3.duree= 120;
s3.athletes = [athlete2, athlete3];
const act1 = new Activite();
act1.id = 1;
@@ -189,9 +187,9 @@ export function getUserTest():User{
user.sessions.push(s2);
user.sessions.push(s3);
athlete1.role = "Athlete";
athlete2.role = "Athlete";
athlete3.role = "Athlete";
athlete1.role = "athlete";
athlete2.role = "athlete";
athlete3.role = "athlete";
return user;
}

View File

@@ -1,7 +1,7 @@
import { useState, useEffect } from "react";
import { Session, User, Coach, Activite, Groupe } from "../classes";
import { useLocalData } from "../context/useLocalData";
import { sessionService } from "../api";
import { activiteService, sessionService } from "../api";
import { postSession } from "../requetes";
export const CreateSession = () => {

View File

@@ -0,0 +1,65 @@
import React, { useState } from 'react';
export const EdtAthlete = () => {
const [formData, setFormData] = useState({
name: '',
prenom: '',
id_keycloak: '',
categorie: '',
niveau: ''
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch("http://localhost:8081/api/athlete/create", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
if (response.ok) {
alert("Athlete created successfully in PostgreSQL!");
setFormData({ name: '', prenom: '', id_keycloak: '', categorie: '', niveau: '' });
} else {
alert("Failed to create athlete. Status: " + response.status);
}
} catch (error) {
console.error("Error creating athlete:", error);
alert("Error: Check console");
}
};
return (
<div style={{ padding: '20px', border: '1px solid #ccc', margin: '10px' }}>
<h3>Test Create Athlete (PostgreSQL)</h3>
<form onSubmit={handleSubmit}>
<div>
<label>Nom: </label>
<input type="text" value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} />
</div>
<div>
<label>Prénom: </label>
<input type="text" value={formData.prenom} onChange={(e) => setFormData({...formData, prenom: e.target.value})} />
</div>
<div>
<label>Keycloak ID: </label>
<input type="text" value={formData.id_keycloak} onChange={(e) => setFormData({...formData, id_keycloak: e.target.value})} />
</div>
<div>
<label>Catégorie: </label>
<input type="text" value={formData.categorie} onChange={(e) => setFormData({...formData, categorie: e.target.value})} />
</div>
<div>
<label>Niveau: </label>
<input type="text" value={formData.niveau} onChange={(e) => setFormData({...formData, niveau: e.target.value})} />
</div>
<button type="submit" style={{ marginTop: '10px' }}>Créer l'athlète</button>
</form>
</div>
);
};
export default EdtAthlete;

View File

@@ -3,20 +3,63 @@ import { useEffect } from 'react';
import { getUserTest, User } from '../classes';
import { useLocalData } from '../context/useLocalData';
export const Login =() =>{
const {user,setUser} = useLocalData()
const { keycloak } = useKeycloak();
useEffect(() => {
const syncUser = async () => {
if (keycloak.authenticated && keycloak.token) {
console.log("Attempting to sync user with backend...");
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);
}
}
};
useEffect(() => { //TODO à supprimer
setUser(getUserTest())
},[]);
syncUser();
}, [keycloak.authenticated, keycloak.token]);
useEffect(() => {
if (keycloak.authenticated && keycloak.token) {
fetch("http://localhost:8081/api/users/sync", {
method: "POST",
headers: {
Authorization: `Bearer ${keycloak.token}`,
},
})
.then(res => console.log("Sync response status:", res.status))
.catch(err => console.error("Sync error:", err));;
}
}, [keycloak.authenticated]);
useEffect(() => {
if (keycloak.authenticated) {
const tokenParsed = keycloak.tokenParsed;
setUser({
id: 0,
keycloakId: tokenParsed!.sub!,
email: tokenParsed?.email,
nom: tokenParsed?.family_name,
prenom: tokenParsed?.given_name,
role: "athlete",
sessions: []
});
}
}, [keycloak.authenticated]);
function handleLogin(): void {
keycloak.login()
keycloak.login();
//TODO setUser
}
@@ -24,8 +67,6 @@ export const Login =() =>{
keycloak.logout()
setUser(new User());
}
const { keycloak } = useKeycloak()
return(
<div>
<div>
@@ -39,6 +80,9 @@ export const Login =() =>{
<div>
User nom : { user.nom}
</div>
<div>
User role : { user.role}
</div>
</div>
}

View File

@@ -1,25 +1,87 @@
import React from "react";
import { Athlete, Activite, Coach, Session, Ligne } from "../classes";
import ObjectSession from "./object/session";
import {calculStatsAthlete, niveauAlerte} from "../utils/athleteUtils";
import {calculTempsDeJeuParLigne} from "../utils/ligneUtils";
type AthleteListProps = { athletes: Athlete[] };
type AthleteListProps = { athletes: Athlete[], sessions: Session[]};
type ActiviteListProps = { activites: Activite[] };
type CoachListProps = { coachs: Coach[] };
type SessionListProps = { sessions: Session[]};
type LigneListProps = { lignes: Ligne[]};
type LigneListProps = { lignes: Ligne[], tempsDeJeuParLigne: Map<number, number> };
function AthleteList({ athletes }: AthleteListProps) {
function AthleteList({ athletes, sessions }: AthleteListProps) {
const [dateDebut, setDateDebut] = React.useState(new Date());
const [dateFin, setDateFin] = React.useState(new Date());
const [seuilCritique, setSeuilCritique] = React.useState(0);
const [seuilMax, setSeuilMax] = React.useState(0);
const dateToDatetimeLocal = (date: Date) => {
const pad = (n: number) => n.toString().padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
};
return (
<ul className="AthleteList">
{athletes.map((athlete) => (
<li key={athlete.id}>
<div><strong>Nom:</strong> {athlete.nom}</div>
<div><strong>Groupe:</strong> {athlete.groupe}</div>
</li>
))}
</ul>
<>
<div className="creneau-stats">
<label>
Début :
<input
type="datetime-local"
value={dateToDatetimeLocal(dateDebut)}
onChange={e => setDateDebut(new Date(e.target.value))}
/>
</label>
<label>
Fin :
<input
type="datetime-local"
value={dateToDatetimeLocal(dateFin)}
onChange={e => setDateFin(new Date(e.target.value))}
/>
</label>
<label>
Seuil critique :
<input
type="number"
value={seuilCritique}
min={1}
onChange={e => setSeuilCritique(Number(e.target.value))}
/>
</label>
<label>Seuil max :
<input
type="number"
value={seuilMax}
min={1}
onChange={e => setSeuilMax(Number(e.target.value))}
/>
</label>
</div>
<ul className="AthleteList">
{athletes.map(a => {
const stats = calculStatsAthlete(sessions, a, dateDebut, dateFin);
const alerte = niveauAlerte(stats, seuilCritique, seuilMax);
return (
<li key={a.id}>
<div><strong>Nom:</strong> {a.nom}</div>
<div><strong>Groupe:</strong> {a.groupe}</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>
<div><strong>Distribuion des activités:</strong> {stats.distributions}</div>
</li>
);
})}
</ul>
</>
);
}
@@ -69,7 +131,7 @@ function SessionList({ sessions }: SessionListProps) {
);
}
function LigneList({ lignes }: LigneListProps) {
function LigneList({ lignes, tempsDeJeuParLigne }: LigneListProps) {
return (
<ul className="LigneList">
{lignes.map((lignes) => (
@@ -90,7 +152,8 @@ function LigneList({ lignes }: LigneListProps) {
</div>
</div>
<div>
<strong>Temps de jeu: {lignes.tempsDeJeu}</strong>
<strong>Temps de jeu total :</strong>{" "}
{tempsDeJeuParLigne.get(lignes.id) ?? 0} min
</div>
</li>
))}

View File

@@ -1,7 +1,7 @@
import { useState } from "react";
import { useLocalData } from "../context/useLocalData";
import { AthleteList, ActiviteList, CoachList, SessionList, LigneList} from "./ressourceList";
import { Activite, Athlete, Coach , Session, Ligne } from "../classes";
import { useState } from "react";
import { useLocalData } from "../context/useLocalData";
import { Activite, Athlete, Coach , Session, Ligne, getUserTest } from "../classes";
import {calculTempsDeJeuParLigne} from "../utils/ligneUtils";
import { keyboard } from "@testing-library/user-event/dist/keyboard";
import ObjectSession from "./object/session";
import ObjectUser from "./object/user";
@@ -10,21 +10,25 @@ import ObjectUser from "./object/user";
export type keyWord = "athletes" | "activites" | "coachs" | "sessions"| "lignes";
export default function RessourcePanel() {
const { user } = useLocalData();
//const { user } = useLocalData();
const user = getUserTest(); //TODO
const [value,setValue] = useState<keyWord>("athletes");
console.log("Rôle utilisateur:", user.role);
if (user.role === "Athlete") return null;
console.log(user.nom);
console.log(user.prenom);
console.log(user.email);
if (user.role === "athlete") return null;
const athleteMap: Map<number, Athlete> = new Map();
const athleteMap: Map<number, Athlete> = new Map();//TODO
user.sessions.forEach(session => {
session.athletes?.forEach(a => athleteMap.set(a.id, a));
session.athletes?.forEach(a => athleteMap.set(a.id, a));
});
const allAthletes: Athlete[] = Array.from(athleteMap.values());
const activiteMap: Map<number, Activite> = new Map();
user.sessions.forEach(session => {
session.activites?.forEach(act => activiteMap.set(act.id, act));
session.activites?.forEach(act => activiteMap.set(act.id, act));
});
const allActivites: Activite[] = Array.from(activiteMap.values());
@@ -54,7 +58,18 @@ import ObjectUser from "./object/user";
}
});
const allLignes: Ligne[] = Array.from(ligneMap.values());
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;
});
return (
<div className="ressource_panel">
@@ -68,7 +83,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.role === "admin" && <option value="coachs"> Coachs</option>}
<option value="sessions"> Sessions</option>
<option value="lignes"> Lignes</option>
@@ -78,7 +93,7 @@ import ObjectUser from "./object/user";
<h3>Liste des {value}</h3>
<div className="list_object">
{value==="athletes" && (
allAthletes.map((athlete) => ( //TODO
allAthletes.map((athlete) => (
<ObjectUser athlete={athlete}/>
))
)}

View File

@@ -0,0 +1,50 @@
import { Athlete, Session , Activite} from '../classes';
export interface StatsAthlete {
nbSessions: number;
nbSessionsPerWeek: number;
isAlerte: boolean;
distributions: Map<String, number>; //le nom de l'activité et son nombre
}
export function niveauAlerte(stats: StatsAthlete, seuilCritique = 0, seuilMax = 0) {
if (stats.nbSessionsPerWeek > seuilMax) return "Alerte ! Niveau maximal atteint.";
if (stats.nbSessionsPerWeek > seuilCritique) return "Attention! Niveau critique atteint.";
return "Normal";
}
export function calculStatsAthlete(sessions: Session[], athlete: Athlete, debut: Date, fin: Date): StatsAthlete {
let nb_sessions = 0;
let nb_semaine = 1; //forcément une semaine
const distributions: Map<string, number> = new Map();
const timeDiff = Math.abs(fin.getTime() - debut.getTime());
nb_semaine = Math.ceil(timeDiff / (1000 * 3600 * 24 * 7));
sessions.forEach(session => {
// verification session dans l'intervalle
if (session.creneau < debut || session.creneau > fin) return;
// verification athlete dans session
if (!session.athletes.some(a => a.id === athlete.id)) return;
//incrementation (verifie si recurent ou non)
const increment = session.isRecurrent ? nb_semaine : 1;
nb_sessions += increment;
//distribution des activités
session.activites.forEach(activite => {
const currentCount = distributions.get(activite.nom) || 0;
distributions.set(activite.nom, currentCount + increment);
});
});
const nbSessionsPerWeek = nb_sessions / nb_semaine;
const isAlerte = nbSessionsPerWeek > 8;
return {
nbSessions: nb_sessions,
nbSessionsPerWeek: nbSessionsPerWeek,
isAlerte: isAlerte,
distributions: distributions
};
}

View File

@@ -0,0 +1,16 @@
import {Ligne, Session} from '../classes';
//Temps de jeu cumulé par ligne
export function calculTempsDeJeuParLigne(sessions: Session[], ligne : Ligne): number {
let tempsDeJeuTotal = 0;
sessions.forEach(session => {
// Vérifier si la ligne est présente dans la session
if (session.ligne && session.ligne.some(l => l.id === ligne.id)) {
tempsDeJeuTotal += session.duree;
}
});
return tempsDeJeuTotal;
}