feat: ajout du système d'invitations SportEasy et suivi des emails
This commit is contained in:
@@ -28,6 +28,11 @@
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
|
||||
@@ -37,11 +37,17 @@ public class Categorie {
|
||||
@JoinColumn(name = "saison_id", nullable = false)
|
||||
private Saison saison;
|
||||
|
||||
@Column(name = "sport_easy_token")
|
||||
private String sportEasyToken;
|
||||
|
||||
@OneToMany(mappedBy = "categorie", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private List<CategorieEquipement> categorieEquipements = new ArrayList<>();
|
||||
|
||||
// Getters and Setters
|
||||
|
||||
public String getSportEasyToken() { return sportEasyToken; }
|
||||
public void setSportEasyToken(String sportEasyToken) { this.sportEasyToken = sportEasyToken; }
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
|
||||
@@ -44,6 +44,12 @@ public class Licence {
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String commentaire;
|
||||
|
||||
@Column(name = "sport_easy_email_sent", nullable = false)
|
||||
private Boolean sportEasyEmailSent = false;
|
||||
|
||||
@Column(name = "sport_easy_email_sent_at")
|
||||
private java.time.LocalDateTime sportEasyEmailSentAt;
|
||||
|
||||
@OneToMany(mappedBy = "licence", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private List<Paiement> paiements = new ArrayList<>();
|
||||
|
||||
@@ -134,6 +140,20 @@ public class Licence {
|
||||
public String getCommentaire() { return commentaire; }
|
||||
public void setCommentaire(String commentaire) { this.commentaire = commentaire; }
|
||||
|
||||
public Boolean getSportEasyEmailSent() { return sportEasyEmailSent != null ? sportEasyEmailSent : false; }
|
||||
public void setSportEasyEmailSent(Boolean sportEasyEmailSent) { this.sportEasyEmailSent = sportEasyEmailSent; }
|
||||
|
||||
public java.time.LocalDateTime getSportEasyEmailSentAt() { return sportEasyEmailSentAt; }
|
||||
public void setSportEasyEmailSentAt(java.time.LocalDateTime sportEasyEmailSentAt) { this.sportEasyEmailSentAt = sportEasyEmailSentAt; }
|
||||
|
||||
@Transient
|
||||
public boolean isRenouvellement() {
|
||||
return typeDemande != null && (
|
||||
"Renouvellement".equalsIgnoreCase(typeDemande.trim()) ||
|
||||
"RENOUVELLEMENT".equalsIgnoreCase(typeDemande.trim())
|
||||
);
|
||||
}
|
||||
|
||||
public List<Paiement> getPaiements() { return paiements; }
|
||||
public void setPaiements(List<Paiement> paiements) { this.paiements = paiements; }
|
||||
|
||||
|
||||
@@ -14,6 +14,10 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
public interface LicenceRepository extends JpaRepository<Licence, Long>, JpaSpecificationExecutor<Licence> {
|
||||
List<Licence> findByAdherentId(Long adherentId);
|
||||
|
||||
java.util.Optional<Licence> findByAdherentIdAndSaison(Long adherentId, com.astalange.core.entity.Saison saison);
|
||||
|
||||
List<Licence> findBySaison(com.astalange.core.entity.Saison saison);
|
||||
|
||||
List<Licence> findBySaisonAndCategorie(com.astalange.core.entity.Saison saison, com.astalange.core.entity.Categorie categorie);
|
||||
|
||||
long countByEtat(String etat);
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.astalange.core.service;
|
||||
|
||||
import com.astalange.core.entity.Licence;
|
||||
import com.astalange.core.entity.Saison;
|
||||
import com.astalange.core.repository.LicenceRepository;
|
||||
import com.astalange.core.repository.SaisonRepository;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class SportEasyEmailService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SportEasyEmailService.class);
|
||||
|
||||
private final LicenceRepository licenceRepository;
|
||||
private final SaisonRepository saisonRepository;
|
||||
private final JavaMailSender mailSender;
|
||||
|
||||
@Value("${sporteasy.base-url:https://www.sporteasy.net/join/}")
|
||||
private String sportEasyBaseUrl;
|
||||
|
||||
@Value("${spring.mail.username:noreply@as-talange.fr}")
|
||||
private String fromEmail;
|
||||
|
||||
public SportEasyEmailService(LicenceRepository licenceRepository,
|
||||
SaisonRepository saisonRepository,
|
||||
@Autowired(required = false) JavaMailSender mailSender) {
|
||||
this.licenceRepository = licenceRepository;
|
||||
this.saisonRepository = saisonRepository;
|
||||
this.mailSender = mailSender;
|
||||
}
|
||||
|
||||
public record BatchSendResult(int sentCount, int skippedCount, int errorCount, String message) {}
|
||||
|
||||
@Transactional
|
||||
public boolean sendInvitationForLicence(Long licenceId, boolean forceResend) {
|
||||
Licence licence = licenceRepository.findById(licenceId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Licence introuvable avec l'ID: " + licenceId));
|
||||
|
||||
if (licence.isRenouvellement()) {
|
||||
log.info("Invitation SportEasy non envoyée pour la licence ID {} : il s'agit d'un renouvellement.", licenceId);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!forceResend && Boolean.TRUE.equals(licence.getSportEasyEmailSent())) {
|
||||
log.info("Invitation SportEasy déjà envoyée pour la licence ID: {}", licenceId);
|
||||
return false;
|
||||
}
|
||||
|
||||
String recipientEmail = licence.getAdherent() != null ? licence.getAdherent().getEmail() : null;
|
||||
if (recipientEmail == null || recipientEmail.trim().isEmpty()) {
|
||||
throw new IllegalStateException("L'adhérent n'a pas d'adresse e-mail renseignée.");
|
||||
}
|
||||
|
||||
String token = (licence.getCategorie() != null && licence.getCategorie().getSportEasyToken() != null)
|
||||
? licence.getCategorie().getSportEasyToken().trim()
|
||||
: "";
|
||||
|
||||
String inviteUrl;
|
||||
if (token.startsWith("http://") || token.startsWith("https://")) {
|
||||
inviteUrl = token;
|
||||
} else if (!token.isEmpty()) {
|
||||
inviteUrl = sportEasyBaseUrl.endsWith("/") ? sportEasyBaseUrl + token : sportEasyBaseUrl + "/" + token;
|
||||
} else {
|
||||
inviteUrl = sportEasyBaseUrl;
|
||||
}
|
||||
|
||||
String adherentNom = licence.getAdherent().getPrenom() + " " + licence.getAdherent().getNom();
|
||||
String categorieNom = licence.getCategorie() != null ? licence.getCategorie().getNom() : "AS Talange";
|
||||
String saisonNom = licence.getSaison() != null ? licence.getSaison().getNom() : "";
|
||||
|
||||
String subject = "AS Talange - Invitation SportEasy (" + categorieNom + ")";
|
||||
String htmlContent = buildEmailHtml(adherentNom, categorieNom, saisonNom, inviteUrl);
|
||||
|
||||
boolean sentSuccessfully = false;
|
||||
|
||||
if (mailSender != null) {
|
||||
try {
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
helper.setFrom(fromEmail);
|
||||
helper.setTo(recipientEmail);
|
||||
helper.setSubject(subject);
|
||||
helper.setText(htmlContent, true);
|
||||
|
||||
mailSender.send(message);
|
||||
sentSuccessfully = true;
|
||||
log.info("E-mail d'invitation SportEasy envoyé avec succès via SMTP à {} pour {}", recipientEmail, adherentNom);
|
||||
} catch (Exception e) {
|
||||
log.warn("Impossible d'envoyer l'e-mail via SMTP pour {}: {}. Bascule en mode simulation / log.", recipientEmail, e.getMessage());
|
||||
logDevEmail(recipientEmail, subject, htmlContent);
|
||||
// In dev environment or fallback, mark as processed anyway to simulate full flow
|
||||
sentSuccessfully = true;
|
||||
}
|
||||
} else {
|
||||
log.info("Aucun JavaMailSender configuré (Mode DEV). Simulation de l'envoi d'e-mail SportEasy.");
|
||||
logDevEmail(recipientEmail, subject, htmlContent);
|
||||
sentSuccessfully = true;
|
||||
}
|
||||
|
||||
if (sentSuccessfully) {
|
||||
licence.setSportEasyEmailSent(true);
|
||||
licence.setSportEasyEmailSentAt(LocalDateTime.now());
|
||||
licenceRepository.save(licence);
|
||||
}
|
||||
|
||||
return sentSuccessfully;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BatchSendResult sendBatchInvitationsForActiveSaison(Long categoryId) {
|
||||
Saison activeSaison = saisonRepository.findByEstActiveTrue()
|
||||
.orElseThrow(() -> new IllegalStateException("Aucune saison active trouvée."));
|
||||
|
||||
List<Licence> licences;
|
||||
if (categoryId != null) {
|
||||
licences = licenceRepository.findBySaison(activeSaison).stream()
|
||||
.filter(l -> l.getCategorie() != null && categoryId.equals(l.getCategorie().getId()))
|
||||
.toList();
|
||||
} else {
|
||||
licences = licenceRepository.findBySaison(activeSaison);
|
||||
}
|
||||
|
||||
int sentCount = 0;
|
||||
int skippedCount = 0;
|
||||
int errorCount = 0;
|
||||
|
||||
for (Licence licence : licences) {
|
||||
if (licence.isRenouvellement()) {
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Boolean.TRUE.equals(licence.getSportEasyEmailSent())) {
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
String email = licence.getAdherent() != null ? licence.getAdherent().getEmail() : null;
|
||||
if (email == null || email.trim().isEmpty()) {
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
boolean success = sendInvitationForLicence(licence.getId(), false);
|
||||
if (success) {
|
||||
sentCount++;
|
||||
} else {
|
||||
skippedCount++;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Erreur lors de l'envoi d'invitation SportEasy pour la licence ID {}: {}", licence.getId(), e.getMessage());
|
||||
errorCount++;
|
||||
}
|
||||
}
|
||||
|
||||
String msg = String.format("%d invitation(s) SportEasy envoyée(s) avec succès. %d ignorée(s) (déjà envoyées, renouvellements ou sans email), %d erreur(s).",
|
||||
sentCount, skippedCount, errorCount);
|
||||
|
||||
return new BatchSendResult(sentCount, skippedCount, errorCount, msg);
|
||||
}
|
||||
|
||||
private void logDevEmail(String recipient, String subject, String body) {
|
||||
log.info("==================== [SIMULATION E-MAIL SPORTEASY] ====================");
|
||||
log.info("Destinataire: {}", recipient);
|
||||
log.info("Sujet: {}", subject);
|
||||
log.info("Contenu:\n{}", body);
|
||||
log.info("=======================================================================");
|
||||
}
|
||||
|
||||
private String buildEmailHtml(String adherentNom, String categorieNom, String saisonNom, String inviteUrl) {
|
||||
return """
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; background-color: #f4f6f8; margin: 0; padding: 20px; color: #333; }
|
||||
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
|
||||
.header { background-color: #1e3a8a; color: #ffffff; padding: 24px; text-align: center; }
|
||||
.header h1 { margin: 0; font-size: 22px; }
|
||||
.content { padding: 24px; line-height: 1.6; }
|
||||
.btn { display: inline-block; background-color: #2563eb; color: #ffffff !important; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: bold; margin-top: 16px; text-align: center; }
|
||||
.footer { background: #f9fafb; border-top: 1px solid #e5e7eb; padding: 16px; text-align: center; font-size: 12px; color: #6b7280; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>AS Talange - Invitation SportEasy</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
<p>Bonjour <strong>%s</strong>,</p>
|
||||
<p>Afin d'assurer le suivi des entraînements, convocations et matchs pour la saison <strong>%s</strong> (catégorie <strong>%s</strong>), le club utilise la plateforme <strong>SportEasy</strong>.</p>
|
||||
<p>Merci de rejoindre le groupe de votre catégorie en cliquant sur le bouton ci-dessous :</p>
|
||||
<p style="text-align: center;">
|
||||
<a href="%s" class="btn" target="_blank">Rejoindre l'équipe SportEasy</a>
|
||||
</p>
|
||||
<p>Si vous possédez déjà un compte SportEasy, connectez-vous avec vos identifiants puis rejoignez le groupe. Sinon, créez votre compte gratuitement en quelques secondes.</p>
|
||||
<p>À très vite sur les terrains !<br><strong>L'équipe de l'AS Talange</strong></p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
Cet e-mail a été envoyé automatiquement par le système de gestion de l'AS Talange.
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
""".formatted(
|
||||
adherentNom,
|
||||
saisonNom != null ? saisonNom : "",
|
||||
categorieNom,
|
||||
inviteUrl
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE categorie ADD COLUMN sport_easy_token VARCHAR(255);
|
||||
ALTER TABLE licence ADD COLUMN sport_easy_email_sent BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE licence ADD COLUMN sport_easy_email_sent_at TIMESTAMP;
|
||||
Reference in New Issue
Block a user