Compare commits

...

4 Commits

Author SHA1 Message Date
Dede
4873abe865 splitting the services 2025-12-04 12:21:53 +00:00
Dede
f03e876e08 mises gestion done 2025-12-02 13:31:22 +00:00
Dede
65c5fd5c6e mise gestion 2025-12-02 08:40:58 +00:00
Dede
7d2cc98d2c 70% 2025-11-25 17:07:27 +00:00
59 changed files with 1372 additions and 455 deletions

View File

@@ -41,6 +41,7 @@ dependencies {
implementation('io.jsonwebtoken:jjwt-jackson:0.11.5')
implementation('org.modelmapper:modelmapper:3.2.0')
implementation 'org.springframework.boot:spring-boot-starter-security'
}
tasks.named('test') {

View File

@@ -26,4 +26,19 @@ public class CorsConfig {
}
};
}
// @Bean
// public WebMvcConfigurer corsConfigurer() {
// return new WebMvcConfigurer() {
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOrigins("*") // Same as configuration.addAllowedOrigin("*")
// .allowedHeaders("*") // Same as configuration.addAllowedHeader("*")
// .allowedMethods("*") // Same as configuration.addAllowedMethod("*")
// .maxAge(3600);
// }
// };
// }
}

View File

@@ -7,6 +7,8 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@@ -29,5 +31,10 @@ public class SecurityConfig {
.addFilterBefore(apiKeyFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@@ -47,11 +47,23 @@ public class AgentController {
}
@DeleteMapping("/{id}")
@Operation(summary = "Supprimer un Agent")
@Operation(summary = "Désactiver un Agent")
public ResponseEntity<String> deleteAgent(@PathVariable Long id) {
return ResponseEntity.ok(agentService.deleteAgent(id));
}
@PutMapping("/toggle-status/{id}")
@Operation(summary = "Activer ou désactiver un Agent")
public ResponseEntity<Agent> toggleAgentStatus(@PathVariable Long id) {
return ResponseEntity.ok(agentService.toggleAgentStatus(id));
}
@PutMapping("/restore/{id}")
public ResponseEntity<Agent> restoreAgent(@PathVariable Long id) {
return ResponseEntity.ok(agentService.restoreAgent(id));
}
@GetMapping("/code/{code}")
@Operation(summary = "Obtenir un Agent par code")
public ResponseEntity<Agent> getAgentByCode(@PathVariable String code) {

View File

@@ -53,15 +53,26 @@ public class AgentLimitController {
return ResponseEntity.ok(service.deleteAgentLimit(id));
}
@GetMapping("/actif/{actif}")
@Operation(summary = "Lister les limites actives ou inactives")
public ResponseEntity<List<AgentLimit>> getAgentLimitsByActif(@PathVariable boolean actif) {
return ResponseEntity.ok(service.getAgentLimitsByActif(actif));
@GetMapping("/actif")
@Operation(summary = "Lister les limites actives")
public ResponseEntity<List<AgentLimit>> getAgentLimitsByActif() {
return ResponseEntity.ok(service.getAgentLimitsByActif(true));
}
@GetMapping("/search")
@Operation(summary = "Rechercher les limites par nom")
public ResponseEntity<List<AgentLimit>> searchAgentLimitsByNom(@RequestParam String nom) {
@GetMapping("/inactif")
@Operation(summary = "Lister les limites inactives")
public ResponseEntity<List<AgentLimit>> getAgentLimitsByInactif() {
return ResponseEntity.ok(service.getAgentLimitsByActif(false));
}
// @GetMapping("/search")
// @Operation(summary = "Rechercher les limites par nom")
// public ResponseEntity<List<AgentLimit>> searchAgentLimitsByNom(@RequestParam String nom) {
// return ResponseEntity.ok(service.searchAgentLimitsByNom(nom));
// }
@GetMapping("/search/{nom}")
public ResponseEntity<List<AgentLimit>> searchAgentLimitsByNom(@PathVariable String nom) {
return ResponseEntity.ok(service.searchAgentLimitsByNom(nom));
}
}

View File

@@ -0,0 +1,35 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.Agent;
import com.pmu.betengine.model.AuthRequest;
import com.pmu.betengine.model.AuthRequestAgent;
import com.pmu.betengine.model.AuthResponse;
import com.pmu.betengine.model.User;
import com.pmu.betengine.service.AuthService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/auth")
@CrossOrigin
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping("/login")
public ResponseEntity<User> login(@RequestBody AuthRequest request) {
User loggedUser = authService.login(request);
return ResponseEntity.ok(loggedUser);
}
// AGENT LOGIN via TPE
@PostMapping("/agent/login")
public ResponseEntity<Agent> loginAgent(@RequestBody AuthRequestAgent request) {
Agent loggedAgent = authService.loginAgentWithPin(request);
return ResponseEntity.ok(loggedAgent);
}
}

View File

@@ -1,9 +1,13 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.Course;
import com.pmu.betengine.model.NonPartant;
import com.pmu.betengine.model.SearchParam;
import com.pmu.betengine.service.CourseService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@@ -35,6 +39,20 @@ public class CourseController {
return ResponseEntity.ok(courseService.getCourseById(id));
}
// @GetMapping("/reunion/{reunionId}")
// @Operation(summary = "Lister les Courses d'une réunion")
// public ResponseEntity<List<Course>> getCoursesByReunion(@PathVariable Long reunionId) {
// return ResponseEntity.ok(courseService.getCoursesByReunionId(reunionId));
// }
@GetMapping("/reunion/{reunionId}")
@Operation(summary = "Lister les Courses VALIDATED d'une réunion")
public ResponseEntity<List<Course>> getValidatedCoursesByReunion(@PathVariable Long reunionId) {
return ResponseEntity.ok(courseService.getCoursesByReunionIdAndStatut(reunionId, "VALIDATED"));
}
@PostMapping
@Operation(summary = "Créer une Course")
public ResponseEntity<Course> createCourse(@RequestBody Course course) {
@@ -66,4 +84,21 @@ public class CourseController {
String statut = request.get("statut");
return ResponseEntity.ok(courseService.updateStatut(id, statut));
}
@PutMapping("/{courseId}/non-partants")
@Operation(summary = "Remplacer la liste des non-partants d'une course")
public ResponseEntity<List<String>> replaceCourseNonPartants(
@PathVariable Long courseId,
@RequestBody List<String> nonPartants) {
return ResponseEntity.ok(courseService.replaceCourseNonPartants(courseId, nonPartants));
}
@PostMapping("/searchByParams")
@Operation(summary = "Rechercher des Courses avec critères")
public ResponseEntity<List<Course>> searchCourses(@RequestBody SearchParam searchParam) {
return ResponseEntity.ok(courseService.search(searchParam));
}
}

View File

@@ -46,13 +46,28 @@ public class HippodromeController {
return ResponseEntity.ok(hippodromeService.updateHippodrome(id, hippodrome));
}
@DeleteMapping("/{id}")
@DeleteMapping("/delete/{id}")
@Operation(summary = "Supprimer un Hippodrome")
public ResponseEntity<Void> deleteHippodrome(@PathVariable Long id) {
hippodromeService.deleteHippodrome(id);
return ResponseEntity.noContent().build();
}
@PutMapping("/restore/{id}")
public ResponseEntity<Hippodrome> restoreHippodrome(@PathVariable Long id) {
return ResponseEntity.ok(hippodromeService.restoreHippodrome(id));
}
@DeleteMapping("/{id}")
@Operation(summary = "Desactiver un Hippodrome")
public ResponseEntity<Void> deleteHippodrome2(@PathVariable Long id) {
hippodromeService.deleteHippodrome2(id);
return ResponseEntity.noContent().build();
}
@GetMapping("/ville/{ville}")
@Operation(summary = "Lister les Hippodromes par ville")
public ResponseEntity<List<Hippodrome>> getHippodromesByVille(@PathVariable String ville) {

View File

@@ -0,0 +1,55 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.Mise;
import com.pmu.betengine.service.MiseService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1")
@CrossOrigin(origins = "*")
@Tag(name = "Gestion des Mises", description = "Endpoints relatifs aux Mises")
public class MiseController {
private final MiseService miseService;
public MiseController(MiseService miseService) {
this.miseService = miseService;
}
@GetMapping
@Operation(summary = "Lister toutes les Mises")
public ResponseEntity<List<Mise>> getAllMises() {
return ResponseEntity.ok(miseService.getAll());
}
@GetMapping("/{id}")
@Operation(summary = "Obtenir une Mise par ID")
public ResponseEntity<Mise> getMiseById(@PathVariable Long id) {
return ResponseEntity.ok(miseService.getById(id));
}
@PostMapping
@Operation(summary = "Créer une Mise")
public ResponseEntity<Mise> createMise(@RequestBody Mise mise) {
return new ResponseEntity<>(miseService.create(mise), HttpStatus.CREATED);
}
@PutMapping("/{id}")
@Operation(summary = "Modifier une Mise")
public ResponseEntity<Mise> updateMise(@PathVariable Long id, @RequestBody Mise mise) {
return ResponseEntity.ok(miseService.update(id, mise));
}
@DeleteMapping("/{id}")
@Operation(summary = "Supprimer une Mise")
public ResponseEntity<Void> deleteMise(@PathVariable Long id) {
miseService.delete(id);
return ResponseEntity.noContent().build();
}
}

View File

@@ -0,0 +1,46 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.Permission;
import com.pmu.betengine.service.PermissionService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/permissions")
@CrossOrigin
public class PermissionController {
private final PermissionService permissionService;
public PermissionController(PermissionService permissionService) {
this.permissionService = permissionService;
}
@PostMapping
public ResponseEntity<Permission> create(@RequestBody Permission permission) {
return ResponseEntity.ok(permissionService.create(permission));
}
@PutMapping("/{id}")
public ResponseEntity<Permission> update(@PathVariable Long id, @RequestBody Permission permission) {
return ResponseEntity.ok(permissionService.update(id, permission));
}
@GetMapping("/{id}")
public ResponseEntity<Permission> getById(@PathVariable Long id) {
return ResponseEntity.ok(permissionService.getById(id));
}
@GetMapping
public ResponseEntity<List<Permission>> getAll() {
return ResponseEntity.ok(permissionService.getAll());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
permissionService.delete(id);
return ResponseEntity.noContent().build();
}
}

View File

@@ -3,12 +3,18 @@ package com.pmu.betengine.controller;
import com.pmu.betengine.model.Cheval;
import com.pmu.betengine.model.Course;
import com.pmu.betengine.model.Resultat;
import com.pmu.betengine.model.SearchParam;
import com.pmu.betengine.service.CourseService;
import com.pmu.betengine.service.ResultatService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/resultat")
@@ -58,9 +64,15 @@ public class ResultatController {
// GET BY COURSE
@GetMapping("/course/{courseId}")
public ResponseEntity<Resultat> getByCourse(@PathVariable Long courseId) {
public ResponseEntity<?> getByCourse(@PathVariable Long courseId) {
Resultat r = resultatService.getByCourseId(courseId);
return r != null ? ResponseEntity.ok(r) : ResponseEntity.notFound().build();
if (r != null) {
return ResponseEntity.ok(r);
} else {
Map<String, String> response = new HashMap<>();
response.put("message", "Aucun résultat disponible pour cette course");
return ResponseEntity.ok(response);
}
}
// UPDATE
@@ -89,6 +101,39 @@ public class ResultatController {
resultatService.deleteByCourseId(courseId);
return ResponseEntity.noContent().build();
}
@PostMapping("/publish")
public ResponseEntity<Resultat> publishResultat(@RequestBody Resultat dto) {
// Fetch the course
Course course = courseService.getCourseById(dto.getCourse().getId());
// Build the resultat object
Resultat resultat = Resultat.builder()
.course(course)
.ordreArrivee(dto.getOrdreArrivee() != null ? dto.getOrdreArrivee() : List.of())
.chevauxDeadHeat(dto.getChevauxDeadHeat())
.aDeadHeat(dto.isADeadHeat())
.totalMises(dto.getTotalMises())
.masseAPartager(dto.getMasseAPartager())
.prelevementsLegaux(dto.getPrelevementsLegaux())
.montantRembourse(dto.getMontantRembourse())
.montantCagnotte(dto.getMontantCagnotte())
.build();
// Save resultat and update course statut
Resultat saved = resultatService.saveAndUpdateCourse(resultat);
return ResponseEntity.ok(saved);
}
@PostMapping("/searchByParams")
@Operation(summary = "Rechercher des résultats avec critères")
public ResponseEntity<List<Resultat>> searchResultats(@RequestBody SearchParam searchParam) {
return ResponseEntity.ok(resultatService.search(searchParam));
}
}

View File

@@ -46,12 +46,25 @@ public class ReunionController {
return ResponseEntity.ok(reunionService.updateReunion(id, reunion));
}
// @DeleteMapping("/{id}")
// @Operation(summary = "Supprimer une Réunion")
// public ResponseEntity<String> deleteReunion(@PathVariable Long id) {
// return ResponseEntity.ok(reunionService.deleteReunion(id));
// }
@DeleteMapping("/{id}")
@Operation(summary = "Supprimer une Réunion")
@Operation(summary = "Désactiver une Réunion")
public ResponseEntity<String> deleteReunion(@PathVariable Long id) {
return ResponseEntity.ok(reunionService.deleteReunion(id));
}
@PutMapping("/restore/{id}")
@Operation(summary = "Restaurer une Réunion désactivée")
public ResponseEntity<Reunion> restoreReunion(@PathVariable Long id) {
return ResponseEntity.ok(reunionService.restoreReunion(id));
}
@GetMapping("/code/{code}")
@Operation(summary = "Obtenir une Réunion par code")
public ResponseEntity<Reunion> getReunionByCode(@PathVariable String code) {

View File

@@ -0,0 +1,46 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.Role;
import com.pmu.betengine.service.RoleService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/roles")
@CrossOrigin
public class RoleController {
private final RoleService roleService;
public RoleController(RoleService roleService) {
this.roleService = roleService;
}
@PostMapping
public ResponseEntity<Role> create(@RequestBody Role role) {
return ResponseEntity.ok(roleService.create(role));
}
@PutMapping("/{id}")
public ResponseEntity<Role> update(@PathVariable Long id, @RequestBody Role role) {
return ResponseEntity.ok(roleService.update(id, role));
}
@GetMapping("/{id}")
public ResponseEntity<Role> getById(@PathVariable Long id) {
return ResponseEntity.ok(roleService.getById(id));
}
@GetMapping
public ResponseEntity<List<Role>> getAll() {
return ResponseEntity.ok(roleService.getAll());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
roleService.delete(id);
return ResponseEntity.noContent().build();
}
}

View File

@@ -1,5 +1,6 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.TPE;
import com.pmu.betengine.model.dto.TPEDTO;
import com.pmu.betengine.model.dto.TPERequestDTO;
import com.pmu.betengine.model.statut.StatutTPE;
@@ -18,6 +19,7 @@ import java.util.Map;
@RequestMapping("/api/v1/tpes")
@CrossOrigin(origins = "*")
@Tag(name = "Gestion des TPE", description = "Endpoints relatifs à l'objet TPE")
public class TPEController {
private final TPEService tpeService;
@@ -27,94 +29,84 @@ public class TPEController {
}
@GetMapping
public ResponseEntity<List<TPEDTO>> getAllTPEs() {
public ResponseEntity<List<TPE>> getAllTPEs() {
return ResponseEntity.ok(tpeService.getAllTPEs());
}
@GetMapping("/{id}")
public ResponseEntity<TPEDTO> getTPEById(@PathVariable Long id) {
public ResponseEntity<TPE> getTPEById(@PathVariable Long id) {
return ResponseEntity.ok(tpeService.getTPEById(id));
}
@PostMapping
@Operation(summary = "Enregistrer Un TPE",
description = "Méthode permettant d'enregistrer un TPE")
public ResponseEntity<TPEDTO> createTPE(@Valid @RequestBody TPERequestDTO requestDTO) {
return new ResponseEntity<>(tpeService.createTPE(requestDTO), HttpStatus.CREATED);
public ResponseEntity<TPE> createTPE(@RequestBody TPE tpe) {
return new ResponseEntity<>(tpeService.createTPE(tpe), HttpStatus.CREATED);
}
@PutMapping("/{id}")
@Operation(summary = "Modifier Un TPE",
description = "Méthode permettant de modifier un TPE")
public ResponseEntity<TPEDTO> updateTPE(@PathVariable Long id, @Valid @RequestBody TPERequestDTO requestDTO) {
return ResponseEntity.ok(tpeService.updateTPE(id, requestDTO));
public ResponseEntity<TPE> updateTPE(@PathVariable Long id, @RequestBody TPE tpe) {
return ResponseEntity.ok(tpeService.updateTPE(id, tpe));
}
@DeleteMapping("/{id}")
@Operation(summary = "Supprimer Un TPE",
description = "Méthode permettant de supprimer un TPE")
public ResponseEntity<Void> deleteTPE(@PathVariable Long id) {
tpeService.deleteTPE(id);
return ResponseEntity.noContent().build();
}
@PatchMapping("/{id}/statut")
@Operation(summary = "Modifier le Statut d'un TPE",
description = "Méthode permettant de modifier le statut d'un TPE")
public ResponseEntity<TPEDTO> updateStatut(@PathVariable Long id, @RequestBody Map<String, String> request) {
public ResponseEntity<TPE> updateStatut(@PathVariable Long id, @RequestBody Map<String, String> request) {
String statutStr = request.get("statut");
try {
StatutTPE statut = StatutTPE.valueOf(statutStr.toUpperCase());
return ResponseEntity.ok(tpeService.updateStatut(id, statut));
} catch (IllegalArgumentException e) {
throw new RuntimeException("Statut invalide: " + statutStr);
}
}
@PatchMapping("/{id}/assigner")
@Operation(summary = "Assigner Un TPE",
description = "Méthode permettant d'd'assigner un TPE")
public ResponseEntity<TPEDTO> assignerTPE(@PathVariable Long id) {
return ResponseEntity.ok(tpeService.assignerTPE(id));
// @PatchMapping("/{id}/assigner")
// public ResponseEntity<TPE> assignerTPE(@PathVariable Long id, @RequestParam Long agentId) {
// return ResponseEntity.ok(tpeService.assignerTPE(id, agentId));
// }
@PatchMapping("/assigner")
@Operation(summary = "Assigner Un TPE", description = "Assigner un TPE à un Agent")
public ResponseEntity<TPE> assignerTPE(@RequestBody Map<String, Long> request) {
Long tpeId = request.get("tpeId");
Long agentId = request.get("agentId");
return ResponseEntity.ok(tpeService.assignerTPE(tpeId, agentId));
}
@PatchMapping("/{id}/liberer")
@Operation(summary = "Libérer Un TPE",
description = "Méthode permettant de libérer un TPE")
public ResponseEntity<TPEDTO> libererTPE(@PathVariable Long id) {
@PatchMapping("/liberer/{id}")
public ResponseEntity<TPE> libererTPE(@PathVariable Long id) {
return ResponseEntity.ok(tpeService.libererTPE(id));
}
@GetMapping("/statut/{statut}")
@Operation(summary = "Lister les TPE par statut",
description = "Méthode permettant d'obtenir les TPE du statut en parametre")
public ResponseEntity<List<TPEDTO>> getTPEsByStatut(@PathVariable StatutTPE statut) {
public ResponseEntity<List<TPE>> getTPEsByStatut(@PathVariable StatutTPE statut) {
return ResponseEntity.ok(tpeService.getTPEsByStatut(statut));
}
@GetMapping("/disponibles")
@Operation(summary = "Lister les TPE Disponibles",
description = "Méthode permettant de lister les TPE disponibles")
public ResponseEntity<List<TPEDTO>> getTPEsDisponibles() {
public ResponseEntity<List<TPE>> getTPEsDisponibles() {
return ResponseEntity.ok(tpeService.getTPEsDisponibles());
}
@GetMapping("/search")
public ResponseEntity<List<TPEDTO>> searchTPEs(@RequestParam String q) {
public ResponseEntity<List<TPE>> searchTPEs(@RequestParam String q) {
return ResponseEntity.ok(tpeService.searchTPEs(q));
}
@GetMapping("/stats/count-by-statut")
public ResponseEntity<Map<StatutTPE, Long>> getCountByStatut() {
Map<StatutTPE, Long> stats = Map.of(
return ResponseEntity.ok(Map.of(
StatutTPE.VALIDE, tpeService.countTPEsByStatut(StatutTPE.VALIDE),
StatutTPE.INVALIDE, tpeService.countTPEsByStatut(StatutTPE.INVALIDE),
StatutTPE.EN_PANNE, tpeService.countTPEsByStatut(StatutTPE.EN_PANNE),
StatutTPE.BLOQUE, tpeService.countTPEsByStatut(StatutTPE.BLOQUE),
StatutTPE.DISPONIBLE, tpeService.countTPEsByStatut(StatutTPE.DISPONIBLE),
StatutTPE.AFFECTE, tpeService.countTPEsByStatut(StatutTPE.AFFECTE),
StatutTPE.EN_PANNE, tpeService.countTPEsByStatut(StatutTPE.EN_PANNE),
StatutTPE.EN_MAINTENANCE, tpeService.countTPEsByStatut(StatutTPE.EN_MAINTENANCE),
StatutTPE.HORS_SERVICE, tpeService.countTPEsByStatut(StatutTPE.HORS_SERVICE),
StatutTPE.VOLE, tpeService.countTPEsByStatut(StatutTPE.VOLE)
);
return ResponseEntity.ok(stats);
));
}
@GetMapping("/stats/assignes")
@@ -122,3 +114,4 @@ public class TPEController {
return ResponseEntity.ok(tpeService.countTPEsAssignes());
}
}

View File

@@ -0,0 +1,46 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.User;
import com.pmu.betengine.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/users")
@CrossOrigin
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping
public ResponseEntity<User> create(@RequestBody User user) {
return ResponseEntity.ok(userService.create(user));
}
@PutMapping("/{id}")
public ResponseEntity<User> update(@PathVariable Long id, @RequestBody User user) {
return ResponseEntity.ok(userService.update(id, user));
}
@GetMapping("/{id}")
public ResponseEntity<User> getById(@PathVariable Long id) {
return ResponseEntity.ok(userService.getById(id));
}
@GetMapping
public ResponseEntity<List<User>> getAll() {
return ResponseEntity.ok(userService.getAll());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
}

View File

@@ -1,5 +1,6 @@
package com.pmu.betengine.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.pmu.betengine.model.statut.StatutAgent;
import jakarta.persistence.*;
@@ -32,7 +33,10 @@ public class Agent {
private String profile;
private String principalCode;
private String caisseProfile;
private String statut;
@Enumerated(EnumType.STRING)
private StatutAgent statut = StatutAgent.ACTIF;
private String zone;
private String kiosk;
private String fonction;
@@ -40,6 +44,10 @@ public class Agent {
@Column(name = "date_embauche")
private LocalDateTime dateEmbauche;
@Column(name = "derniere_connexion")
private LocalDateTime derniereConnexion;
private String nom;
private String prenom;
private String autresNoms;
@@ -61,10 +69,11 @@ public class Agent {
private Double limiteMaxAirtime;
private Integer maxPeripheriques;
@OneToMany(mappedBy = "agent")
@JsonIgnore
private List<TPE> tpes;
@Column(name = "limit_id")
private Long limitId;
private String nationalite;
private String cni;
@@ -87,66 +96,3 @@ public class Agent {
@Column(name = "created_by")
private String createdBy;
}
// @Table(name = "agent")
// public class Agent {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String code;
// private String profile;
// private String principalCode;
// private String caisseProfile;
// private StatutAgent statut;
// private String zone;
// private String kiosk;
// private String fonction;
// @Pattern(regexp = "^\\d{2}/\\d{2}/\\d{4}$", message = "La date doit être au format dd/MM/yyyy")
// @JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
// private LocalDate dateEmbauche;
// @NotBlank(message = "Le nom est obligatoire")
// private String nom;
// private String prenom;
// private String autresNoms;
// @Pattern(regexp = "^\\d{2}/\\d{2}/\\d{4}$", message = "La date de naissance doit être au format dd/MM/yyyy")
// @Column(name = "date_naissance", nullable = false)
// @JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
// private LocalDate dateNaissance;
// private String lieuNaissance;
// private String ville;
// private String adresse;
// private Boolean autoriserAides;
// private String phone;
// private String pin;
// private Double limiteInferieure;
// private Double limiteSuperieure;
// private Double limiteParTransaction;
// private Double limiteMinAirtime;
// private Double limiteMaxAirtime;
// private Integer maxPeripheriques;
// private String limitId;
// // Légales
// private String nationalite;
// private String cni;
// private String cniDelivreeLe;
// private String cniDelivreeA;
// private String residence;
// private String autreAdresse1;
// private String statutMarital;
// private String epoux;
// private String autreTelephone;
// // Situation familiale
// @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
// @JoinTable(name = "agent_famille",
// joinColumns = @JoinColumn(name = "agent_id"),
// inverseJoinColumns = @JoinColumn(name = "famille_id"))
// private List<AgentFamilyMember> famille;
// // TPE assignés
// private String [] assignedTpeIds;
// @CreationTimestamp
// private LocalDateTime createdAt;
// @UpdateTimestamp
// private LocalDateTime updatedAt;
// private String createdBy;
// }

View File

@@ -25,7 +25,7 @@ public class AgentLimit {
public String nom;
public boolean isDefault;
public boolean actif;
// Bet limits (Double for nullable number fields)
// Bet limits
public Double betMin;
public Double betMax;
public Double maxBet;

View File

@@ -0,0 +1,23 @@
package com.pmu.betengine.model;
public class AuthRequest {
private String identifiant;
private String password;
public String getIdentifiant() {
return identifiant;
}
public void setIdentifiant(String identifiant) {
this.identifiant = identifiant;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@@ -0,0 +1,9 @@
package com.pmu.betengine.model;
public class AuthRequestAgent {
private String pin;
// Getter and Setter
public String getPin() { return pin; }
public void setPin(String pin) { this.pin = pin; }
}

View File

@@ -0,0 +1,32 @@
package com.pmu.betengine.model;
public class AuthResponse {
private String message;
private Long userId;
private String nom;
private String prenom;
public AuthResponse(String message, Long userId, String nom, String prenom) {
this.message = message;
this.userId = userId;
this.nom = nom;
this.prenom = prenom;
}
public String getMessage() {
return message;
}
public Long getUserId() {
return userId;
}
public String getNom() {
return nom;
}
public String getPrenom() {
return prenom;
}
}

View File

@@ -25,102 +25,39 @@ public class Course {
@Id
@GeneratedValue
private Long id;
private String type;
private Integer numero;
private String nom;
@Column(name = "date_depart_course")
private LocalDateTime dateDepartCourse;
@Column(name = "date_debut_paris")
private LocalDateTime dateDebutParis;
@Column(name = "date_fin_paris")
private LocalDateTime dateFinParis;
@Column(name = "reunion_id")
private Long reunionId;
@Column(name = "reunion_course")
private Integer reunionCourse;
private String particularite;
private Integer partants;
private Integer distance;
private String condition;
private boolean estTerminee;
private boolean estAnnulee;
private boolean aDeadHeat;
private String statut;
private int nombreChevauxInscrits;
@Column(name = "resultat_statut")
private String resultatStatut;
@Column(name = "created_by")
private String createdBy;
@Column(name = "validated_by")
private String validatedBy;
@Column(name = "created_at")
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private List<NonPartant> nonPartants;
@Column(name = "nom_partants")
private List<String> nonPartants;
}
// public class Course {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String numero;
// // FIX 1: Changement de @OneToOne à @ManyToOne (Une course appartient à une seule réunion)
// @ManyToOne
// @JoinColumn(name = "reunion_id", nullable = false)
// private Reunion reunion;
// @JsonFormat(pattern = "dd/MM/yyyy HH:mm:ss", shape = JsonFormat.Shape.STRING)
// @Column(name = "heure_course")
// private LocalDateTime heureCourse;
// private String lieu;
// private int nombreChevauxInscrits;
// private boolean estTerminee;
// private boolean estAnnulee;
// private boolean aDeadHeat;
// @Enumerated(EnumType.STRING)
// private StatutCourse statut;
// @OneToOne(mappedBy = "course")
// private Resultat resultat;
// @OneToMany(fetch = FetchType.LAZY)
// @JoinTable(name = "course_chevaux",
// joinColumns = @JoinColumn(name = "course_id"),
// inverseJoinColumns = @JoinColumn(name = "cheval_id"))
// private List<Cheval> chevaux;
// @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL,mappedBy = "course")
// private List<Pari> paris;
// public boolean estEligiblePourTrioOrdre() {
// return chevaux != null && chevaux.size() >= 3 && chevaux.size() <= 7;
// }
// }

View File

@@ -33,11 +33,14 @@ public class Hippodrome {
private String description;
@Column(name = "created_at")
@CreationTimestamp
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updated_at")
private LocalDateTime updatedAt;
}
// @Table(name = "hippodrome")

View File

@@ -0,0 +1,25 @@
package com.pmu.betengine.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "mises")
public class Mise {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
String typePari;
Double montantMise;
}

View File

@@ -20,21 +20,15 @@ public class NonPartant {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
private Integer numero;
@Column(name = "nom_cheval")
private String nomCheval;
private String motif;
@Column(name = "declare_par")
private String declarePar;
@Column(name = "date_declaration")
private LocalDateTime dateDeclaration;
}

View File

@@ -38,7 +38,7 @@ public class Pari {
private double mise = 500.0;
@JsonFormat(pattern = "dd/MM/yyyy HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private LocalDateTime datePari;
private boolean estPaye;
@@ -47,11 +47,11 @@ public class Pari {
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
// LIST OF SELECTED CHEVAL NUMBERS (Integer list)
// LIST OF SELECTED CHEVAL NUMBERS
@ElementCollection
private List<Integer> chevauxSelectionnes;
private List<String> chevauxSelectionnes;
@ElementCollection
private List<Integer> ordrePredit;
private List<String> ordrePredit;
private Boolean validationOrdreExact;
@Enumerated(EnumType.STRING)
private TypeMulti typeMulti;

View File

@@ -0,0 +1,23 @@
package com.pmu.betengine.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "permissions")
public class Permission {
@Id
@GeneratedValue
private Long id;
private String name;
private String description;
}

View File

@@ -15,6 +15,7 @@ import java.util.List;
@AllArgsConstructor
@Table(name = "resultat")
public class Resultat {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@@ -23,105 +24,37 @@ public class Resultat {
@JoinColumn(name = "course_id")
private Course course;
@ManyToMany
@CollectionTable(name = "resultat_ordre_arrivee")
@ElementCollection
@CollectionTable(
name = "resultat_ordre_arrivee",
joinColumns = @JoinColumn(name = "resultat_id")
)
@OrderColumn(name = "ordre_position")
private List<Cheval> ordreArrivee;
@Column(name = "cheval_nom")
private List<String> ordreArrivee;
@ElementCollection
private List<Long> chevauxDeadHeat;
@CollectionTable(
name = "resultat_chevaux_deadheat",
joinColumns = @JoinColumn(name = "resultat_id")
)
@Column(name = "cheval_nom")
private List<String> chevauxDeadHeat;
private boolean aDeadHeat;
@Column(name = "total_mises")
private double totalMises;
@Column(name = "masse_apartager")
private double masseAPartager;
@Column(name = "prelevements_legaux")
private double prelevementsLegaux;
@Column(name = "montant_rembourse")
private double montantRembourse;
@Column(name = "montant_cagnotte")
private double montantCagnotte;
}
// package com.pmu.betengine.model;
// import jakarta.persistence.*;
// import lombok.AllArgsConstructor;
// import lombok.Builder;
// import lombok.Data;
// import lombok.NoArgsConstructor;
// import java.util.List;
// @Entity
// @Data
// @Builder
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "resultat")
// public class Resultat {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// @OneToOne
// @JoinColumn(name = "course_id")
// private Course course;
// @ManyToMany
// @CollectionTable(name = "resultat_ordre_arrivee")
// @OrderColumn(name = "ordre_position")
// private List<Cheval> ordreArrivee;
// @ManyToMany(fetch = FetchType.LAZY)
// @JoinTable(name = "resultat_premiers",
// joinColumns = @JoinColumn(name = "resultat_id"),
// inverseJoinColumns = @JoinColumn(name = "cheval_id"))
// private List<Cheval> premiers;
// @ManyToMany(fetch = FetchType.LAZY)
// @JoinTable(name = "resultat_seconds",
// joinColumns = @JoinColumn(name = "resultat_id"),
// inverseJoinColumns = @JoinColumn(name = "cheval_id"))
// private List<Cheval> seconds;
// @ManyToMany(fetch = FetchType.LAZY)
// @JoinTable(name = "resultat_troisiemes",
// joinColumns = @JoinColumn(name = "resultat_id"),
// inverseJoinColumns = @JoinColumn(name = "cheval_id"))
// private List<Cheval> troisiemes;
// @ManyToMany(fetch = FetchType.LAZY)
// @JoinTable(name = "resultat_quatriemes",
// joinColumns = @JoinColumn(name = "resultat_id"),
// inverseJoinColumns = @JoinColumn(name = "cheval_id"))
// private List<Cheval> quatriemes;
// @ManyToMany(fetch = FetchType.LAZY)
// @JoinTable(name = "resultat_cinquiemes",
// joinColumns = @JoinColumn(name = "resultat_id"),
// inverseJoinColumns = @JoinColumn(name = "cheval_id"))
// private List<Cheval> cinquiemes;
// @ElementCollection
// private List<Long> chevauxDeadHeat;
// private boolean aDeadHeat;
// @Column(name = "total_mises")
// private double totalMises;
// @Column(name = "masse_apartager")
// private double masseAPartager;
// @Column(name = "prelevements_legaux")
// private double prelevementsLegaux;
// @Column(name = "montant_rembourse")
// private double montantRembourse;
// @Column(name = "montant_cagnotte")
// private double montantCagnotte;
// }

View File

@@ -33,7 +33,9 @@ public class Reunion {
private Integer numero;
private String statut;
@Column(name = "statut", nullable = false)
@Builder.Default
private String statut = "ACTIF";
@Column(name = "hippodrome_id")
private Long hippodromeId;
@@ -47,28 +49,3 @@ public class Reunion {
@Column(name = "updated_at")
private LocalDateTime updatedAt;
}
// public class Reunion {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// public String code;
// public String nom;
// @JsonFormat(pattern = "dd/MM/yyyy HH:mm", shape = JsonFormat.Shape.STRING)
// private LocalDateTime date;
// public int numero;
// public StatutReunion statut;
// @ManyToOne
// @JoinColumn(name = "hippodrome_id")
// public Hippodrome hippodrome;
// @OneToMany(fetch = FetchType.LAZY, mappedBy = "reunion", cascade = CascadeType.ALL)
// private List<Course> courses;
// public Integer totalCourses;
// @CreationTimestamp
// private LocalDateTime createdAt;
// @UpdateTimestamp
// private LocalDateTime updatedAt;
// }

View File

@@ -0,0 +1,33 @@
package com.pmu.betengine.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue
private Long id;
private String name;
private String description;
@ManyToMany
@JoinTable(
name = "role_permissions",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "permission_id")
)
private List<Permission> permissions;
}

View File

@@ -0,0 +1,31 @@
package com.pmu.betengine.model;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate;
@Data
public class SearchParam implements Serializable {
private Long id;
private LocalDate date;
private LocalDate startDate;
private LocalDate endDate;
private Long userId;
private Long categoryId;
private String criteria;
private String query;
private String annee;
private String mois;
private String status;
private int page = 0;
private int pageSize = 10;
public SearchParam() {
}
}

View File

@@ -54,6 +54,11 @@ public class TPE {
@Column(nullable = false)
private StatutTPE statut = StatutTPE.DISPONIBLE;
@ManyToOne
@JoinColumn(name = "agent_id")
private Agent agent;
@Column(nullable = false)
private boolean assigne = false;

View File

@@ -8,22 +8,31 @@ import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private UUID id;
private Long id;
private String nom;
private String prenom;
private String identifiant;
private String password;
private String matriculeAgent;
@Column(name = "role_id")
private UUID roleId;
private Long roleId;
private Boolean restrictionConnexion;
private Boolean restrictionAutomatique;

View File

@@ -0,0 +1,7 @@
package com.pmu.betengine.model.statut;
public enum StatutUser {
ACTIF,
INACTIF,
SUSPENDU
}

View File

@@ -28,6 +28,4 @@ public enum TypeFormule {
CHAMP_TOTAL_1,
CHAMP_PARTIEL_1,
}

View File

@@ -10,9 +10,7 @@ public enum TypePaiement {
QUARTE_PLUS_ORDRE_INEXACT,
BONUS_3,
BONUS_3_BIS,
MULTI_4,
MULTI_5,
MULTI_6,
MULTI_7,

View File

@@ -1,5 +1,4 @@
package com.pmu.betengine.model.type;
public enum TypePari {
SIMPLE,
JUMELE_GAGNANT,
@@ -11,5 +10,11 @@ public enum TypePari {
QUATRO,
QUARTE_PLUS,
MULTI,
QUINTE_PLUS
QUINTE_PLUS,
TIERCE,
QUARTE,
QUINTE,
COUPLE_GAGNANT,
COUPLE_PLACE
}

View File

@@ -12,6 +12,8 @@ public interface AgentRepository extends JpaRepository<Agent, Long> {
Optional<Agent> findByCode(String code);
Optional<Agent> findByPin(String pin);
boolean existsByCode(String code);
List<Agent> findByStatut(String statut);

View File

@@ -2,8 +2,11 @@ package com.pmu.betengine.repository;
import com.pmu.betengine.model.Course;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@@ -15,4 +18,23 @@ public interface CourseRepository extends JpaRepository<Course, Long> {
// Search courses by name
List<Course> findByNomContainingIgnoreCase(String nom);
List<Course> findByReunionId(Long reunionId);
List<Course> findByReunionIdAndStatut(Long reunionId, String statut);
@Query("SELECT c FROM Course c " +
"WHERE c.dateDebutParis >= :startOfDay " +
"AND c.dateDebutParis < :endOfDay " +
"AND c.dateFinParis >= :now " +
"AND c.statut = 'VALIDATED'")
List<Course> findByDateDebutParisAndNotFinished(
@Param("startOfDay") LocalDateTime startOfDay,
@Param("endOfDay") LocalDateTime endOfDay,
@Param("now") LocalDateTime now
);
}

View File

@@ -10,12 +10,14 @@ import java.util.List;
public interface HippodromeRepository extends JpaRepository<Hippodrome, Long> {
boolean existsByNom(String nom);
List<Hippodrome> findByVille(String ville);
List<Hippodrome> findByPays(String pays);
List<Hippodrome> findByActif(boolean actif);
List<Hippodrome> findByNomContainingIgnoreCase(String nom);
List<Hippodrome> findByActifTrue();
List<Hippodrome> findByVilleAndActifTrue(String ville);
List<Hippodrome> findByPaysAndActifTrue(String pays);
List<Hippodrome> findByNomContainingIgnoreCaseAndActifTrue(String nom);
}

View File

@@ -0,0 +1,7 @@
package com.pmu.betengine.repository;
import com.pmu.betengine.model.Mise;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MiseRepository extends JpaRepository<Mise, Long> {
}

View File

@@ -5,7 +5,6 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.UUID;
@Repository
public interface NonPartantRepository extends JpaRepository<NonPartant, Long> {

View File

@@ -0,0 +1,7 @@
package com.pmu.betengine.repository;
import com.pmu.betengine.model.Permission;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PermissionRepository extends JpaRepository<Permission, Long> {
}

View File

@@ -8,24 +8,24 @@ import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Repository
public interface ResultatRepository extends JpaRepository<Resultat, Long> {
Optional<Resultat> findByCourseId(Long courseId);
@Query("SELECT r FROM Resultat r WHERE r.course.id = :courseId")
Optional<Resultat> findByCourse(@Param("courseId") Long courseId);
boolean existsByCourseId(Long courseId);
@Modifying
@Transactional
@Query("DELETE FROM Resultat r WHERE r.course.id = :courseId")
void deleteByCourseId(@Param("courseId") Long courseId);
}
@Query("SELECT r FROM Resultat r WHERE r.course.dateDebutParis >= :start AND r.course.dateDebutParis < :end")
List<Resultat> findByCourseDate(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
}
// package com.pmu.betengine.repository;

View File

@@ -0,0 +1,7 @@
package com.pmu.betengine.repository;
import com.pmu.betengine.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Long> {
}

View File

@@ -0,0 +1,20 @@
package com.pmu.betengine.repository;
import com.pmu.betengine.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// Récupérer un utilisateur par identifiant (connexion)
Optional<User> findByIdentifiant(String identifiant);
// Vérifier si un identifiant existe déjà (création)
boolean existsByIdentifiant(String identifiant);
// Vérifier si un matricule existe déjà (création)
boolean existsByMatriculeAgent(String matriculeAgent);
}

View File

@@ -22,6 +22,7 @@ public class AgentLimitService {
if (repository.existsByCode(agentLimit.getCode())) {
throw new RuntimeException("Un AgentLimit avec ce code existe déjà: " + agentLimit.getCode());
}
agentLimit.actif=true;
return repository.save(agentLimit);
}

View File

@@ -1,6 +1,7 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Agent;
import com.pmu.betengine.model.statut.StatutAgent;
import com.pmu.betengine.repository.AgentRepository;
import org.springframework.stereotype.Service;
@@ -27,7 +28,8 @@ public class AgentService {
// Get all
public List<Agent> getAllAgents() {
return agentRepository.findAll();
// return agentRepository.findAll();
return agentRepository.findByStatut(StatutAgent.ACTIF.name());
}
// Get by ID
@@ -82,13 +84,34 @@ public class AgentService {
// Delete
public String deleteAgent(Long id) {
if (!agentRepository.existsById(id)) {
throw new RuntimeException("Agent non trouvé avec l'id: " + id);
Agent agent = getAgentById(id);
if (agent.getStatut() == StatutAgent.INACTIF) {
throw new RuntimeException("Cet agent est déjà désactivé.");
}
agentRepository.deleteById(id);
return "Agent avec l'ID " + id + " supprimé avec succès.";
agent.setStatut(StatutAgent.INACTIF);
agent.setUpdatedAt(LocalDateTime.now());
agentRepository.save(agent);
return "Agent désactivé avec succès (soft delete).";
}
public Agent restoreAgent(Long id) {
Agent agent = getAgentById(id);
if (agent.getStatut() == StatutAgent.ACTIF) {
throw new RuntimeException("Cet agent est déjà actif.");
}
agent.setStatut(StatutAgent.ACTIF);
agent.setUpdatedAt(LocalDateTime.now());
return agentRepository.save(agent);
}
// Find by code
public Agent getAgentByCode(String code) {
return agentRepository.findByCode(code)
@@ -100,6 +123,20 @@ public class AgentService {
return agentRepository.findByStatut(statut);
}
public Agent toggleAgentStatus(Long id) {
Agent agent = getAgentById(id);
if (agent.getStatut() == StatutAgent.ACTIF) {
agent.setStatut(StatutAgent.INACTIF);
} else {
agent.setStatut(StatutAgent.ACTIF);
}
agent.setUpdatedAt(LocalDateTime.now());
return agentRepository.save(agent);
}
// Find by ville
public List<Agent> getAgentsByVille(String ville) {
return agentRepository.findByVille(ville);

View File

@@ -0,0 +1,54 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.AuthRequest;
import com.pmu.betengine.model.AuthRequestAgent;
import com.pmu.betengine.model.User;
import com.pmu.betengine.model.Agent;
import com.pmu.betengine.repository.UserRepository;
import com.pmu.betengine.repository.AgentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@Service
public class AuthService {
private final UserRepository userRepository;
private final AgentRepository agentRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public AuthService(UserRepository userRepository, AgentRepository agentRepository) {
this.userRepository = userRepository;
this.agentRepository = agentRepository;
}
// USER LOGIN
public User login(AuthRequest request) {
User user = userRepository.findByIdentifiant(request.getIdentifiant())
.orElseThrow(() -> new RuntimeException("User not found"));
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
throw new RuntimeException("Invalid credentials");
}
user.setDerniereConnexion(LocalDateTime.now());
return userRepository.save(user);
}
// AGENT ALR LOGIN
public Agent loginAgentWithPin(AuthRequestAgent request) {
Agent agent = agentRepository.findByPin(request.getPin())
.orElseThrow(() -> new RuntimeException("Invalid PIN"));
agent.setDerniereConnexion(LocalDateTime.now());
agentRepository.save(agent);
return agent;
}
}

View File

@@ -1,10 +1,18 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Course;
import com.pmu.betengine.model.NonPartant;
import com.pmu.betengine.model.SearchParam;
import com.pmu.betengine.repository.CourseRepository;
import com.pmu.betengine.repository.ReunionRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@@ -14,12 +22,21 @@ public class CourseService {
@Autowired
private CourseRepository courseRepository;
@Autowired
private ReunionRepository reunionRepository;
// Create
public Course createCourse(Course course) {
// Vérifie si la réunion existe
if (course.getReunionId() == null ||
!reunionRepository.existsById(course.getReunionId())) {
throw new IllegalArgumentException("Impossible de créer la course : réunion invalide");
}
LocalDateTime now = LocalDateTime.now();
course.setCreatedAt(now);
course.setUpdatedAt(now);
return courseRepository.save(course);
}
@@ -73,4 +90,69 @@ public class CourseService {
course.setStatut(statut);
return courseRepository.save(course);
}
public List<Course> getCoursesByReunionId(Long reunionId) {
return courseRepository.findByReunionId(reunionId);
}
public List<Course> getCoursesByReunionIdAndStatut(Long reunionId, String statut) {
return courseRepository.findByReunionIdAndStatut(reunionId, statut);
}
@Transactional
public List<String> replaceCourseNonPartants(Long courseId, List<String> newNonPartants) {
if (courseId == null) {
throw new IllegalArgumentException("L'identifiant de la course est obligatoire.");
}
Course course = courseRepository.findById(courseId)
.orElseThrow(() -> new RuntimeException("Aucune course trouvée avec l'ID : " + courseId));
if (newNonPartants == null) {
throw new IllegalArgumentException("La liste des non-partants ne peut pas être nulle.");
}
course.setNonPartants(newNonPartants);
course.setUpdatedAt(LocalDateTime.now());
courseRepository.save(course);
return course.getNonPartants();
}
public List<Course> search(SearchParam searchParam) {
System.out.println("******************** THE SEARCH PARAM " + searchParam);
if (searchParam.getCriteria() == null) {
throw new IllegalArgumentException("Le paramètre 'criteria' est obligatoire et ne peut pas être null");
}
try {
String criteria = searchParam.getCriteria();
if (criteria.equals("1")) {
return courseRepository.findAll();
} else if(criteria.equals("2") && searchParam.getDate() != null) {
LocalDate date = searchParam.getDate();
LocalDateTime startOfDay = date.atStartOfDay();
LocalDateTime endOfDay = startOfDay.plusDays(1);
return courseRepository.findByDateDebutParisAndNotFinished(
startOfDay,
endOfDay,
LocalDateTime.now()
);
}
// Cas par défaut
return courseRepository.findAll();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Erreur lors de la recherche des courses");
}
}
}

View File

@@ -59,6 +59,28 @@ public class HippodromeService {
hippodromeRepository.deleteById(id);
}
public void deleteHippodrome2(Long id) {
Hippodrome hippodrome = hippodromeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Hippodrome non trouvé"));
hippodrome.setActif(false);
hippodromeRepository.save(hippodrome);
}
public Hippodrome restoreHippodrome(Long id) {
Hippodrome hippodrome = hippodromeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Hippodrome non trouvé"));
if (hippodrome.getActif()) {
throw new RuntimeException("Hippodrome est déjà actif");
}
hippodrome.setActif(true);
return hippodromeRepository.save(hippodrome);
}
// Search by ville
public List<Hippodrome> getHippodromesByVille(String ville) {
return hippodromeRepository.findByVille(ville);

View File

@@ -0,0 +1,41 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Mise;
import com.pmu.betengine.repository.MiseRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MiseService {
private final MiseRepository repository;
public MiseService(MiseRepository repository) {
this.repository = repository;
}
public Mise create(Mise mise) {
return repository.save(mise);
}
public Mise getById(Long id) {
return repository.findById(id)
.orElseThrow(() -> new RuntimeException("Mise not found"));
}
public List<Mise> getAll() {
return repository.findAll();
}
public Mise update(Long id, Mise mise) {
Mise existing = getById(id);
existing.setTypePari(mise.getTypePari());
existing.setMontantMise(mise.getMontantMise());
return repository.save(existing);
}
public void delete(Long id) {
repository.deleteById(id);
}
}

View File

@@ -6,7 +6,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
// import java.util.Long;
@Service
@Transactional
@@ -33,12 +32,14 @@ public class NonPartantService {
public NonPartant updateNonPartant(Long id, NonPartant updated) {
NonPartant existing = getNonPartantById(id);
existing.setCourse(updated.getCourse());
existing.setNumero(updated.getNumero());
existing.setNomCheval(updated.getNomCheval());
existing.setMotif(updated.getMotif());
existing.setDeclarePar(updated.getDeclarePar());
existing.setDateDeclaration(updated.getDateDeclaration());
return repository.save(existing);
}

View File

@@ -28,11 +28,18 @@ public class PariService {
Course course = pari.getCourse();
// // Business rules
// if (pari.getTypeFormule() == TypeFormule.GAGNANT && course.getNombreChevauxInscrits() < 2) {
// throw new IllegalArgumentException("Pari GAGNANT impossible: moins de 2 chevaux.");
// }
// if (pari.getTypeFormule() == TypeFormule.PLACE && course.getNombreChevauxInscrits() < 3) {
// throw new IllegalArgumentException("Pari PLACE impossible: moins de 3 chevaux.");
// }
// Business rules
if (pari.getTypeFormule() == TypeFormule.GAGNANT && course.getNombreChevauxInscrits() < 2) {
if (pari.getTypeFormule() == TypeFormule.GAGNANT && course.getPartants() < 2) {
throw new IllegalArgumentException("Pari GAGNANT impossible: moins de 2 chevaux.");
}
if (pari.getTypeFormule() == TypeFormule.PLACE && course.getNombreChevauxInscrits() < 3) {
if (pari.getTypeFormule() == TypeFormule.PLACE && course.getPartants() < 3) {
throw new IllegalArgumentException("Pari PLACE impossible: moins de 3 chevaux.");
}

View File

@@ -0,0 +1,42 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Permission;
import com.pmu.betengine.repository.PermissionRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PermissionService {
private final PermissionRepository permissionRepository;
public PermissionService(PermissionRepository permissionRepository) {
this.permissionRepository = permissionRepository;
}
public Permission create(Permission permission) {
return permissionRepository.save(permission);
}
public Permission update(Long id, Permission updatedPermission) {
return permissionRepository.findById(id).map(permission -> {
permission.setName(updatedPermission.getName());
permission.setDescription(updatedPermission.getDescription());
return permissionRepository.save(permission);
}).orElseThrow(() -> new RuntimeException("Permission not found"));
}
public Permission getById(Long id) {
return permissionRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Permission not found"));
}
public List<Permission> getAll() {
return permissionRepository.findAll();
}
public void delete(Long id) {
permissionRepository.deleteById(id);
}
}

View File

@@ -1,10 +1,21 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Course;
import com.pmu.betengine.model.Resultat;
import com.pmu.betengine.model.SearchParam;
import com.pmu.betengine.repository.ResultatRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.Optional;
import java.util.Map;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
@Service
@@ -12,6 +23,7 @@ import java.util.List;
public class ResultatService {
private final ResultatRepository resultatRepository;
private final CourseService courseService;
// CREATE / UPDATE
public Resultat save(Resultat resultat) {
@@ -33,6 +45,7 @@ public class ResultatService {
return resultatRepository.findByCourseId(courseId).orElse(null);
}
// DELETE BY ID
public void delete(Long id) {
resultatRepository.deleteById(id);
@@ -42,6 +55,56 @@ public class ResultatService {
public void deleteByCourseId(Long courseId) {
resultatRepository.deleteByCourseId(courseId);
}
public Resultat saveAndUpdateCourse(Resultat resultat) {
// Save the resultat
Resultat savedResultat = resultatRepository.save(resultat);
// Update the course statut
Course course = savedResultat.getCourse();
if (course != null) {
course.setStatut("RESULT_PUBLISHED"); // or whatever statut you want
courseService.updateCourse(course.getId(), course);
}
return savedResultat;
}
public List<Resultat> search(SearchParam searchParam) {
System.out.println("******************** SEARCH PARAM: " + searchParam);
if (searchParam.getCriteria() == null) {
throw new IllegalArgumentException("Le paramètre 'criteria' est obligatoire et ne peut pas être null");
}
try {
String criteria = searchParam.getCriteria();
if ("1".equals(criteria)) {
// Retourne tous les résultats
return resultatRepository.findAll();
} else if ("2".equals(criteria) && searchParam.getDate() != null) {
LocalDate date = searchParam.getDate();
LocalDateTime startOfDay = date.atStartOfDay();
LocalDateTime endOfDay = startOfDay.plusDays(1);
return resultatRepository.findByCourseDate(startOfDay, endOfDay);
} else if ("3".equals(criteria) && searchParam.getId() != null) {
return resultatRepository.findByCourseId(searchParam.getId())
.map(List::of)
.orElse(List.of());
}
// Cas par défaut
return resultatRepository.findAll();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Erreur lors de la recherche des résultats");
}
}
}

View File

@@ -18,19 +18,65 @@ public class ReunionService {
// Create
public Reunion createReunion(Reunion reunion) {
// Check if hippodrome ID is missing
if (reunion.getHippodromeId() == null) {
throw new RuntimeException("Aucun hippodrome assigné à cette réunion.");
}
// Check if reunion code already exists
if (reunionRepository.existsByCode(reunion.getCode())) {
throw new RuntimeException("Code déjà existant: " + reunion.getCode());
}
reunion.setCreatedAt(LocalDateTime.now());
reunion.setUpdatedAt(LocalDateTime.now());
return reunionRepository.save(reunion);
}
// Get all
public List<Reunion> getAllReunions() {
return reunionRepository.findAll();
// public List<Reunion> getAllReunions() {
// return reunionRepository.findAll();
// }
// Soft delete
public String deleteReunion(Long id) {
Reunion reunion = getReunionById(id);
if ("INACTIF".equals(reunion.getStatut())) {
throw new RuntimeException("Cette réunion est déjà désactivée.");
}
reunion.setStatut("INACTIF");
reunion.setUpdatedAt(LocalDateTime.now());
reunionRepository.save(reunion);
return "Réunion désactivée avec succès.";
}
// Optional: restore
public Reunion restoreReunion(Long id) {
Reunion reunion = getReunionById(id);
if ("ACTIF".equals(reunion.getStatut())) {
throw new RuntimeException("Cette réunion est déjà active.");
}
reunion.setStatut("ACTIF");
reunion.setUpdatedAt(LocalDateTime.now());
return reunionRepository.save(reunion);
}
// Override getAll to return only active reunions
public List<Reunion> getAllReunions() {
return reunionRepository.findAll()
.stream()
.filter(r -> "ACTIF".equals(r.getStatut()))
.toList();
}
// Get by ID
public Reunion getReunionById(Long id) {
return reunionRepository.findById(id)
@@ -52,13 +98,13 @@ public class ReunionService {
}
// Delete
public String deleteReunion(Long id) {
if (!reunionRepository.existsById(id)) {
throw new RuntimeException("Réunion non trouvée avec l'id: " + id);
}
reunionRepository.deleteById(id);
return "Réunion avec l'ID " + id + " supprimée avec succès.";
}
// public String deleteReunion(Long id) {
// if (!reunionRepository.existsById(id)) {
// throw new RuntimeException("Réunion non trouvée avec l'id: " + id);
// }
// reunionRepository.deleteById(id);
// return "Réunion avec l'ID " + id + " supprimée avec succès.";
// }
// Find by code
public Reunion getReunionByCode(String code) {

View File

@@ -0,0 +1,43 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Role;
import com.pmu.betengine.repository.RoleRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RoleService {
private final RoleRepository roleRepository;
public RoleService(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
public Role create(Role role) {
return roleRepository.save(role);
}
public Role update(Long id, Role updatedRole) {
return roleRepository.findById(id).map(role -> {
role.setName(updatedRole.getName());
role.setDescription(updatedRole.getDescription());
role.setPermissions(updatedRole.getPermissions());
return roleRepository.save(role);
}).orElseThrow(() -> new RuntimeException("Role not found"));
}
public Role getById(Long id) {
return roleRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Role not found"));
}
public List<Role> getAll() {
return roleRepository.findAll();
}
public void delete(Long id) {
roleRepository.deleteById(id);
}
}

View File

@@ -1,79 +1,69 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Agent;
import com.pmu.betengine.model.TPE;
import com.pmu.betengine.model.dto.TPEDTO;
import com.pmu.betengine.model.dto.TPERequestDTO;
import com.pmu.betengine.model.statut.StatutTPE;
import com.pmu.betengine.repository.AgentRepository;
import com.pmu.betengine.repository.TPERepository;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
public class TPEService {
private final TPERepository tpeRepository;
private final ModelMapper modelMapper;
private final AgentRepository agentRepository;
public TPEService(TPERepository tpeRepository, ModelMapper modelMapper) {
public TPEService(TPERepository tpeRepository, AgentRepository agentRepository) {
this.tpeRepository = tpeRepository;
this.modelMapper = modelMapper;
this.agentRepository = agentRepository;
}
public List<TPEDTO> getAllTPEs() {
return tpeRepository.findAll()
.stream()
.map(this::convertToDTO)
.collect(Collectors.toList());
public List<TPE> getAllTPEs() {
return tpeRepository.findAll();
}
public TPEDTO getTPEById(Long id) {
TPE tpe = tpeRepository.findById(id)
public TPE getTPEById(Long id) {
return tpeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("TPE non trouvé avec l'id: " + id));
return convertToDTO(tpe);
}
public TPEDTO createTPE(TPERequestDTO requestDTO) {
// Vérifier l'unicité de l'IMEI
if (tpeRepository.existsByImei(requestDTO.getImei())) {
throw new RuntimeException("Un TPE avec cet IMEI existe déjà: " + requestDTO.getImei());
public TPE createTPE(TPE tpe) {
if (tpeRepository.existsByImei(tpe.getImei())) {
throw new RuntimeException("Un TPE avec cet IMEI existe déjà: " + tpe.getImei());
}
if (tpeRepository.existsBySerial(tpe.getSerial())) {
throw new RuntimeException("Un TPE avec ce numéro de série existe déjà: " + tpe.getSerial());
}
return tpeRepository.save(tpe);
}
// Vérifier l'unicité du numéro de série
if (tpeRepository.existsBySerial(requestDTO.getSerial())) {
throw new RuntimeException("Un TPE avec ce numéro de série existe déjà: " + requestDTO.getSerial());
}
TPE tpe = convertToEntity(requestDTO);
TPE saved = tpeRepository.save(tpe);
return convertToDTO(saved);
}
public TPEDTO updateTPE(Long id, TPERequestDTO requestDTO) {
public TPE updateTPE(Long id, TPE tpeDetails) {
TPE existing = tpeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("TPE non trouvé avec l'id: " + id));
// Vérifier l'unicité de l'IMEI si modifié
if (!existing.getImei().equals(requestDTO.getImei()) &&
tpeRepository.existsByImei(requestDTO.getImei())) {
throw new RuntimeException("Un TPE avec cet IMEI existe déjà: " + requestDTO.getImei());
if (!existing.getImei().equals(tpeDetails.getImei()) &&
tpeRepository.existsByImei(tpeDetails.getImei())) {
throw new RuntimeException("Un TPE avec cet IMEI existe déjà: " + tpeDetails.getImei());
}
// Vérifier l'unicité du numéro de série si modifié
if (!existing.getSerial().equals(requestDTO.getSerial()) &&
tpeRepository.existsBySerial(requestDTO.getSerial())) {
throw new RuntimeException("Un TPE avec ce numéro de série existe déjà: " + requestDTO.getSerial());
if (!existing.getSerial().equals(tpeDetails.getSerial()) &&
tpeRepository.existsBySerial(tpeDetails.getSerial())) {
throw new RuntimeException("Un TPE avec ce numéro de série existe déjà: " + tpeDetails.getSerial());
}
// Mise à jour des champs
modelMapper.map(requestDTO, existing);
// Update fields
existing.setImei(tpeDetails.getImei());
existing.setSerial(tpeDetails.getSerial());
existing.setType(tpeDetails.getType());
existing.setMarque(tpeDetails.getMarque());
existing.setModele(tpeDetails.getModele());
existing.setStatut(tpeDetails.getStatut());
return convertToDTO(tpeRepository.save(existing));
return tpeRepository.save(existing);
}
public void deleteTPE(Long id) {
@@ -83,69 +73,44 @@ public class TPEService {
tpeRepository.deleteById(id);
}
public TPEDTO updateStatut(Long id, StatutTPE statut) {
TPE tpe = tpeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("TPE non trouvé avec l'id: " + id));
public TPE updateStatut(Long id, StatutTPE statut) {
TPE tpe = getTPEById(id);
tpe.setStatut(statut);
tpe.setAssigne(statut == StatutTPE.AFFECTE);
if (statut == StatutTPE.DISPONIBLE) tpe.setAssigne(false);
return tpeRepository.save(tpe);
}
// Si le statut est AFFECTE, mettre à jour le champ assigne
if (statut == StatutTPE.AFFECTE) {
public TPE assignerTPE(Long tpeId, Long agentId) {
TPE tpe = getTPEById(tpeId);
Agent agent = agentRepository.findById(agentId)
.orElseThrow(() -> new RuntimeException("Agent not found"));
tpe.setAgent(agent);
tpe.setAssigne(true);
} else if (statut == StatutTPE.DISPONIBLE) {
tpe.setAssigne(false);
return tpeRepository.save(tpe);
}
return convertToDTO(tpeRepository.save(tpe));
}
public TPEDTO assignerTPE(Long id) {
TPE tpe = tpeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("TPE non trouvé avec l'id: " + id));
if (tpe.isAssigne()) {
throw new RuntimeException("Le TPE est déjà assigné");
}
tpe.setAssigne(true);
tpe.setStatut(StatutTPE.AFFECTE);
return convertToDTO(tpeRepository.save(tpe));
}
public TPEDTO libererTPE(Long id) {
TPE tpe = tpeRepository.findById(id)
.orElseThrow(() -> new RuntimeException("TPE non trouvé avec l'id: " + id));
public TPE libererTPE(Long id) {
TPE tpe = getTPEById(id);
if (!tpe.isAssigne()) {
throw new RuntimeException("Le TPE n'est pas assigné");
}
tpe.setAssigne(false);
tpe.setStatut(StatutTPE.DISPONIBLE);
return convertToDTO(tpeRepository.save(tpe));
tpe.setAgent(null);
return tpeRepository.save(tpe);
}
public List<TPEDTO> getTPEsByStatut(StatutTPE statut) {
return tpeRepository.findByStatut(statut)
.stream()
.map(this::convertToDTO)
.collect(Collectors.toList());
public List<TPE> getTPEsByStatut(StatutTPE statut) {
return tpeRepository.findByStatut(statut);
}
public List<TPEDTO> getTPEsDisponibles() {
return tpeRepository.findAvailableTPE()
.stream()
.map(this::convertToDTO)
.collect(Collectors.toList());
public List<TPE> getTPEsDisponibles() {
return tpeRepository.findAvailableTPE();
}
public List<TPEDTO> searchTPEs(String searchTerm) {
return tpeRepository.searchByTerm(searchTerm)
.stream()
.map(this::convertToDTO)
.collect(Collectors.toList());
public List<TPE> searchTPEs(String searchTerm) {
return tpeRepository.searchByTerm(searchTerm);
}
public long countTPEsByStatut(StatutTPE statut) {
@@ -156,22 +121,4 @@ public class TPEService {
return tpeRepository.countByAssigne(true);
}
private TPEDTO convertToDTO(TPE tpe) {
TPEDTO dto = modelMapper.map(tpe, TPEDTO.class);
// Formatage des dates
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
if (tpe.getCreatedAt() != null) {
dto.setCreatedAt(tpe.getCreatedAt().format(formatter));
}
if (tpe.getUpdatedAt() != null) {
dto.setUpdatedAt(tpe.getUpdatedAt().format(formatter));
}
return dto;
}
private TPE convertToEntity(TPERequestDTO dto) {
return modelMapper.map(dto, TPE.class);
}
}

View File

@@ -0,0 +1,102 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.User;
import com.pmu.betengine.model.statut.StatutUser;
import com.pmu.betengine.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// CREATE
public User create(User user) {
// 1. Vérification des champs obligatoires
if (!StringUtils.hasText(user.getNom())) {throw new RuntimeException("Le nom est obligatoire");}
if (!StringUtils.hasText(user.getPrenom())) {throw new RuntimeException("Le prénom est obligatoire");}
if (!StringUtils.hasText(user.getIdentifiant())) {throw new RuntimeException("L'identifiant est obligatoire");}
if (!StringUtils.hasText(user.getPassword())) {throw new RuntimeException("Le mot de passe est obligatoire");}
if (user.getRoleId() == null) {throw new RuntimeException("L'ID du rôle est obligatoire");}
// 2. Vérification de l'unicité
if (userRepository.existsByIdentifiant(user.getIdentifiant())) {throw new RuntimeException("Cet identifiant existe déjà");}
if (user.getMatriculeAgent() != null &&
userRepository.existsByMatriculeAgent(user.getMatriculeAgent())) {throw new RuntimeException("Ce matricule agent existe déjà");}
// 3. Validation du mot de passe
if (!user.getPassword().matches("^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$")) {throw new RuntimeException("Le mot de passe doit contenir au moins 8 caractères, incluant lettres et chiffres");}
// 4. Définition des valeurs par défaut et encodage du mot de passe
user.setId(null);
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setStatut(StatutUser.ACTIF.name());
user.setCreatedAt(LocalDateTime.now());
user.setUpdatedAt(LocalDateTime.now());
user.setDerniereConnexion(null);
// 5. Vérification des champs numériques
if (user.getNombreIpAutorise() == null || user.getNombreIpAutorise() < 0) {
user.setNombreIpAutorise(0);
}
if (user.getNombreIpAutoAutorise() == null || user.getNombreIpAutoAutorise() < 0) {
user.setNombreIpAutoAutorise(0);
}
// 6. Nettoyage des chaînes
user.setIdentifiant(user.getIdentifiant().trim().toLowerCase());
if (user.getMatriculeAgent() != null) {
user.setMatriculeAgent(user.getMatriculeAgent().trim().toUpperCase());
}
// 7. Enregistrement
return userRepository.save(user);
}
// UPDATE
public User update(Long id, User updatedUser) {
return userRepository.findById(id).map(user -> {
user.setNom(updatedUser.getNom());
user.setPrenom(updatedUser.getPrenom());
user.setIdentifiant(updatedUser.getIdentifiant());
user.setMatriculeAgent(updatedUser.getMatriculeAgent());
user.setRoleId(updatedUser.getRoleId());
user.setRestrictionConnexion(updatedUser.getRestrictionConnexion());
user.setRestrictionAutomatique(updatedUser.getRestrictionAutomatique());
user.setNombreIpAutorise(updatedUser.getNombreIpAutorise());
user.setNombreIpAutoAutorise(updatedUser.getNombreIpAutoAutorise());
user.setStatut(updatedUser.getStatut());
user.setDerniereConnexion(updatedUser.getDerniereConnexion());
user.setUpdatedAt(LocalDateTime.now());
return userRepository.save(user);
}).orElseThrow(() -> new RuntimeException("Utilisateur introuvable"));
}
// READ by ID
public User getById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Utilisateur introuvable"));
}
// READ all
public List<User> getAll() {
return userRepository.findAll();
}
// DELETE
public void delete(Long id) {
userRepository.deleteById(id);
}
}