This commit is contained in:
Dede
2025-11-25 17:07:27 +00:00
parent c13e5b1dfc
commit 7d2cc98d2c
39 changed files with 881 additions and 390 deletions

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

@@ -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,24 @@
package com.pmu.betengine.controller;
import com.pmu.betengine.model.AuthRequest;
import com.pmu.betengine.model.AuthResponse;
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<AuthResponse> login(@RequestBody AuthRequest request) {
return ResponseEntity.ok(authService.login(request));
}
}

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,20 @@ 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

@@ -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

@@ -89,6 +89,32 @@ 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);
}
}

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.*;
@@ -62,6 +63,10 @@ public class Agent {
private Integer maxPeripheriques;
@OneToMany(mappedBy = "agent")
@JsonIgnore
private List<TPE> tpes;
@Column(name = "limit_id")
private Long limitId;
@@ -87,66 +92,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,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

@@ -78,49 +78,7 @@ public class Course {
@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

@@ -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

@@ -47,28 +47,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,14 +8,22 @@ 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;
@@ -23,7 +31,7 @@ public class User {
private String matriculeAgent;
@Column(name = "role_id")
private UUID roleId;
private Long roleId;
private Boolean restrictionConnexion;
private Boolean restrictionAutomatique;

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

@@ -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

@@ -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,8 @@
package com.pmu.betengine.repository;
import com.pmu.betengine.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}

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

@@ -0,0 +1,35 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.AuthRequest;
import com.pmu.betengine.model.AuthResponse;
import com.pmu.betengine.model.User;
import com.pmu.betengine.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@Service
public class AuthService {
private final UserRepository userRepository;
public AuthService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public AuthResponse login(AuthRequest request) {
User user = userRepository.findAll().stream()
.filter(u -> u.getIdentifiant().equals(request.getIdentifiant()))
.findFirst()
.orElseThrow(() -> new RuntimeException("User not found"));
if (request.getPassword().equals("password123")) {
user.setDerniereConnexion(LocalDateTime.now());
userRepository.save(user);
return new AuthResponse("Login successful", user.getId(), user.getNom(), user.getPrenom());
} else {
throw new RuntimeException("Invalid credentials");
}
}
}

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

@@ -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,5 +1,6 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.Course;
import com.pmu.betengine.model.Resultat;
import com.pmu.betengine.repository.ResultatRepository;
import lombok.RequiredArgsConstructor;
@@ -12,6 +13,7 @@ import java.util.List;
public class ResultatService {
private final ResultatRepository resultatRepository;
private final CourseService courseService;
// CREATE / UPDATE
public Resultat save(Resultat resultat) {
@@ -42,6 +44,21 @@ 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;
}
}

View File

@@ -18,14 +18,24 @@ 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();

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,65 @@
package com.pmu.betengine.service;
import com.pmu.betengine.model.User;
import com.pmu.betengine.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// CREATE
public User create(User user) {
user.setId(null);
user.setCreatedAt(LocalDateTime.now());
user.setUpdatedAt(LocalDateTime.now());
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("User not found"));
}
// READ by ID
public User getById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("User not found"));
}
// READ all
public List<User> getAll() {
return userRepository.findAll();
}
// DELETE
public void delete(Long id) {
userRepository.deleteById(id);
}
}