feat(mail): ajout du service de relances par e-mail et intégration HTMX dans l'admin

This commit is contained in:
2026-08-07 23:30:18 +02:00
parent 5f372254f0
commit 1bd6407c39
7 changed files with 586 additions and 5 deletions
@@ -0,0 +1,309 @@
package com.astalange.core.service;
import com.astalange.core.entity.Adherent;
import com.astalange.core.entity.Licence;
import com.astalange.core.entity.PreInscription;
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 java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Period;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
@Service
public class RelanceEmailService {
private static final Logger log = LoggerFactory.getLogger(RelanceEmailService.class);
private final JavaMailSender mailSender;
@Value("${app.mail.from:${spring.mail.username:astalange1933@gmail.com}}")
private String fromEmail = "astalange1933@gmail.com";
public RelanceEmailService(@Autowired(required = false) JavaMailSender mailSender) {
this.mailSender = mailSender;
}
private String getEffectiveFromEmail() {
if (fromEmail != null && !fromEmail.trim().isEmpty() && fromEmail.contains("@")) {
return fromEmail.trim();
}
return "astalange1933@gmail.com";
}
public boolean isMineur(LocalDate dateNaissance) {
if (dateNaissance == null) return false;
return Period.between(dateNaissance, LocalDate.now()).getYears() < 18;
}
/**
* Envoie une relance aux personnes pré-inscrites pour leur demander de se présenter au club.
*/
public boolean sendRelancePreInscription(PreInscription preInscription) {
if (preInscription == null) {
log.warn("Impossible d'envoyer l'e-mail de relance : la pré-inscription est nulle.");
return false;
}
String recipientEmail = preInscription.getEmail();
if (recipientEmail == null || recipientEmail.trim().isEmpty()) {
log.warn("Pré-inscription ID {}: aucun e-mail renseigné. Relance non envoyée.", preInscription.getId());
return false;
}
boolean estMineur = isMineur(preInscription.getDateNaissance());
String adherentNomComplet = preInscription.getPrenom() + " " + preInscription.getNom();
String greeting;
String subject;
if (estMineur) {
String rep = preInscription.getRepresentantLegal();
if (rep != null && !rep.trim().isEmpty()) {
greeting = "Bonjour " + rep.trim() + " (Représentant légal de " + adherentNomComplet + ")";
} else {
greeting = "Bonjour (Représentant légal de " + adherentNomComplet + ")";
}
subject = "AS Talange - Relance demande d'inscription pour " + adherentNomComplet;
} else {
greeting = "Bonjour " + adherentNomComplet;
subject = "AS Talange - Relance concernant votre demande d'inscription";
}
String htmlContent = buildRelancePreInscriptionHtml(preInscription, greeting, adherentNomComplet, estMineur);
CompletableFuture.runAsync(() -> {
if (mailSender != null) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(getEffectiveFromEmail());
helper.setTo(recipientEmail.trim());
helper.setSubject(subject);
helper.setText(htmlContent, true);
mailSender.send(message);
log.info("E-mail de relance pré-inscription envoyé avec succès à {} pour {}", recipientEmail, adherentNomComplet);
} catch (Exception e) {
log.warn("Erreur envoi SMTP relance pré-inscription à {}: {}. Log en mode simulation.", recipientEmail, e.getMessage());
logDevEmail(recipientEmail, subject, htmlContent);
}
} else {
log.info("Mode DEV (MailSender non configuré) : simulation relance pré-inscription.");
logDevEmail(recipientEmail, subject, htmlContent);
}
});
return true;
}
/**
* Envoie une relance pour les paiements de cotisation incomplets.
*/
public boolean sendRelancePaiementCotisation(Licence licence) {
if (licence == null || licence.getAdherent() == null) {
log.warn("Impossible d'envoyer l'e-mail de relance paiement : licence ou adhérent nul.");
return false;
}
Adherent adherent = licence.getAdherent();
String recipientEmail = adherent.getEmail();
if (recipientEmail == null || recipientEmail.trim().isEmpty()) {
log.warn("Adhérent ID {}: aucun e-mail renseigné. Relance paiement non envoyée.", adherent.getId());
return false;
}
BigDecimal resteAPayer = licence.getResteAPayer();
if (resteAPayer.compareTo(BigDecimal.ZERO) <= 0) {
log.info("Licence ID {}: aucun solde restant à payer (Reste = 0 €). Relance non nécessaire.", licence.getId());
return false;
}
boolean estMineur = isMineur(adherent.getDateNaissance());
String adherentNomComplet = adherent.getPrenom() + " " + adherent.getNom();
String greeting;
String subject;
if (estMineur) {
String rep = adherent.getRepresentantLegal();
if (rep != null && !rep.trim().isEmpty()) {
greeting = "Bonjour " + rep.trim() + " (Représentant légal de " + adherentNomComplet + ")";
} else {
greeting = "Bonjour (Représentant légal de " + adherentNomComplet + ")";
}
subject = "AS Talange - Rappel solde de cotisation pour " + adherentNomComplet;
} else {
greeting = "Bonjour " + adherentNomComplet;
subject = "AS Talange - Rappel important : Solde de cotisation impayé";
}
String htmlContent = buildRelancePaiementHtml(licence, greeting, adherentNomComplet, estMineur, resteAPayer);
CompletableFuture.runAsync(() -> {
if (mailSender != null) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(getEffectiveFromEmail());
helper.setTo(recipientEmail.trim());
helper.setSubject(subject);
helper.setText(htmlContent, true);
mailSender.send(message);
log.info("E-mail de relance paiement envoyé avec succès à {} (Reste: {} €)", recipientEmail, resteAPayer);
} catch (Exception e) {
log.warn("Erreur envoi SMTP relance paiement à {}: {}. Log en mode simulation.", recipientEmail, e.getMessage());
logDevEmail(recipientEmail, subject, htmlContent);
}
} else {
log.info("Mode DEV (MailSender non configuré) : simulation relance paiement.");
logDevEmail(recipientEmail, subject, htmlContent);
}
});
return true;
}
private void logDevEmail(String recipient, String subject, String body) {
log.info("==================== [SIMULATION E-MAIL RELANCE] ====================");
log.info("Destinataire: {}", recipient);
log.info("Sujet: {}", subject);
log.info("Contenu:\n{}", body);
log.info("======================================================================");
}
private String buildRelancePreInscriptionHtml(PreInscription pre, String greeting, String adherentNomComplet, boolean estMineur) {
String saisonNom = pre.getSaison() != null ? pre.getSaison().getNom() : "";
String termeSujet = estMineur ? "la demande d'inscription pour votre enfant <strong>" + adherentNomComplet + "</strong>" : "votre demande d'inscription";
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; }
.alert-info { background-color: #e0f2fe; border-left: 4px solid #0284c7; color: #075985; padding: 16px; border-radius: 6px; margin: 20px 0; }
.info-box { background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px; padding: 16px; margin-top: 20px; }
.info-box h3 { margin-top: 0; font-size: 16px; color: #1e3a8a; }
.btn { display: inline-block; background-color: #1e3a8a; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; margin-top: 15px; }
.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 - Finalisation de votre inscription</h1>
</div>
<div class="content">
<p>%s,</p>
<p>Sauf erreur de notre part, nous avons bien reçu %s pour la saison <strong>%s</strong>, mais celle-ci n'a pas encore été finalisée au sein de notre club.</p>
<div class="alert-info">
<strong>Pour finaliser l'inscription :</strong> Nous vous invitons à vous présenter directement au secrétariat de l'AS Talange lors de nos permanences pour valider l'inscription.
</div>
<p style="margin-top: 24px;">Nous restant à votre entière disposition pour tout renseignement complémentaire.<br><br>Sportivement,<br><strong>L'équipe de l'AS Talange</strong></p>
</div>
<div class="footer">
Cet e-mail automatique a été envoyé par le système de gestion de l'AS Talange.
</div>
</div>
</body>
</html>
""".formatted(greeting, termeSujet, saisonNom);
}
private String buildRelancePaiementHtml(Licence licence, String greeting, String adherentNomComplet, boolean estMineur, BigDecimal resteAPayer) {
String saisonNom = licence.getSaison() != null ? licence.getSaison().getNom() : "";
String categorieNom = licence.getCategorie() != null ? licence.getCategorie().getNom() : "";
String termeSujet = estMineur ? "la cotisation de votre enfant <strong>" + adherentNomComplet + "</strong>" : "votre cotisation";
String prixTotalStr = String.format(Locale.FRANCE, "%.2f €", licence.getPrixTotal());
String totalPayeStr = String.format(Locale.FRANCE, "%.2f €", licence.getSommePayee());
String resteStr = String.format(Locale.FRANCE, "%.2f €", resteAPayer);
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; }
.alert-danger { background-color: #fef2f2; border-left: 4px solid #ef4444; color: #991b1b; padding: 16px; border-radius: 6px; margin: 20px 0; }
.receipt-box { background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px; padding: 16px; margin-top: 20px; }
.receipt-box h3 { margin-top: 0; margin-bottom: 12px; font-size: 16px; color: #1e3a8a; border-bottom: 1px solid #e5e7eb; padding-bottom: 8px; }
.receipt-table { width: 100%%; border-collapse: collapse; font-size: 14px; }
.receipt-table td { padding: 6px 0; }
.receipt-table td.label { color: #6b7280; width: 50%%; }
.receipt-table td.value { font-weight: bold; text-align: right; }
.badge-danger { display: inline-block; padding: 4px 10px; border-radius: 12px; font-weight: bold; font-size: 14px; background-color: #fef2f2; color: #991b1b; border: 1px solid #fca5a5; }
.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 - Rappel de solde de cotisation</h1>
</div>
<div class="content">
<p>%s,</p>
<p>Nous vous contactons concernant %s (saison <strong>%s</strong>, catégorie <strong>%s</strong>) pour laquelle un solde reste actuellement à régler.</p>
<div class="receipt-box">
<h3>Situation Financière</h3>
<table class="receipt-table">
<tr>
<td class="label">Adhérent :</td>
<td class="value">%s</td>
</tr>
<tr>
<td class="label">Montant total cotisation :</td>
<td class="value">%s</td>
</tr>
<tr>
<td class="label">Total versé à ce jour :</td>
<td class="value">%s</td>
</tr>
<tr>
<td class="label">Solde restant à régler :</td>
<td class="value"><span class="badge-danger">%s</span></td>
</tr>
</table>
</div>
<div class="alert-danger">
<strong>Important :</strong><br>
Conformément aux statuts et au règlement intérieur de l'AS Talange, <strong>tant que le paiement de la cotisation n'est pas intégralement finalisé, l'inscription et la licence ne seront pas valides</strong>. L'accès aux entraînements et aux rencontres officielles pourra être suspendu.
</div>
<p>Nous vous demandons de bien vouloir vous présenter au secrétariat du club lors des permanences afin d'effectuer le règlement du solde restant (%s).</p>
<p style="margin-top: 24px;">Comptant sur votre prompt réajustement,<br>Sportivement,<br><strong>Le Bureau de l'AS Talange</strong></p>
</div>
<div class="footer">
Cet e-mail automatique a été envoyé par le système de gestion de l'AS Talange.
</div>
</div>
</body>
</html>
""".formatted(greeting, termeSujet, saisonNom, categorieNom, adherentNomComplet, prixTotalStr, totalPayeStr, resteStr, resteStr);
}
}
@@ -0,0 +1,151 @@
package com.astalange.core.service;
import com.astalange.core.entity.Adherent;
import com.astalange.core.entity.Categorie;
import com.astalange.core.entity.Licence;
import com.astalange.core.entity.PreInscription;
import com.astalange.core.entity.Saison;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.mail.javamail.JavaMailSender;
import java.math.BigDecimal;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class RelanceEmailServiceTest {
private RelanceEmailService relanceEmailService;
private JavaMailSender mailSenderMock;
@BeforeEach
void setUp() {
mailSenderMock = mock(JavaMailSender.class);
MimeMessage mimeMessage = new MimeMessage((jakarta.mail.Session) null);
when(mailSenderMock.createMimeMessage()).thenReturn(mimeMessage);
relanceEmailService = new RelanceEmailService(mailSenderMock);
}
@Test
void testIsMineur() {
LocalDate minorDob = LocalDate.now().minusYears(10);
LocalDate adultDob = LocalDate.now().minusYears(20);
assertTrue(relanceEmailService.isMineur(minorDob));
assertFalse(relanceEmailService.isMineur(adultDob));
assertFalse(relanceEmailService.isMineur(null));
}
@Test
void testSendRelancePreInscription_Mineur() {
PreInscription pre = new PreInscription();
pre.setId(1L);
pre.setNom("MARTIN");
pre.setPrenom("Lucas");
pre.setEmail("parent.martin@example.com");
pre.setDateNaissance(LocalDate.now().minusYears(12));
pre.setRepresentantLegal("Marc MARTIN");
Saison saison = new Saison();
saison.setNom("2026/2027");
pre.setSaison(saison);
boolean sent = relanceEmailService.sendRelancePreInscription(pre);
assertTrue(sent);
verify(mailSenderMock, timeout(2000).times(1)).send(any(MimeMessage.class));
}
@Test
void testSendRelancePreInscription_Majeur() {
PreInscription pre = new PreInscription();
pre.setId(2L);
pre.setNom("DUBOIS");
pre.setPrenom("Alexandre");
pre.setEmail("alex.dubois@example.com");
pre.setDateNaissance(LocalDate.now().minusYears(25));
Saison saison = new Saison();
saison.setNom("2026/2027");
pre.setSaison(saison);
boolean sent = relanceEmailService.sendRelancePreInscription(pre);
assertTrue(sent);
verify(mailSenderMock, timeout(2000).times(1)).send(any(MimeMessage.class));
}
@Test
void testSendRelancePreInscription_SansEmail() {
PreInscription pre = new PreInscription();
pre.setId(3L);
pre.setEmail(null);
boolean sent = relanceEmailService.sendRelancePreInscription(pre);
assertFalse(sent);
verify(mailSenderMock, never()).send(any(MimeMessage.class));
}
@Test
void testSendRelancePaiementCotisation_MineurAvecReste() {
Adherent adherent = new Adherent();
adherent.setId(10L);
adherent.setNom("GARCIA");
adherent.setPrenom("Leo");
adherent.setEmail("parent.garcia@example.com");
adherent.setDateNaissance(LocalDate.now().minusYears(14));
adherent.setRepresentantLegal("Sophie GARCIA");
Categorie cat = new Categorie();
cat.setNom("U15");
cat.setTarifBase(new BigDecimal("180.00"));
cat.setTarifExterieur(new BigDecimal("180.00"));
Saison saison = new Saison();
saison.setNom("2026/2027");
Licence licence = new Licence();
licence.setId(100L);
licence.setAdherent(adherent);
licence.setCategorie(cat);
licence.setSaison(saison);
boolean sent = relanceEmailService.sendRelancePaiementCotisation(licence);
assertTrue(sent);
verify(mailSenderMock, timeout(2000).times(1)).send(any(MimeMessage.class));
}
@Test
void testSendRelancePaiementCotisation_SoldeZero() {
Adherent adherent = new Adherent();
adherent.setId(11L);
adherent.setNom("ROUX");
adherent.setPrenom("Thomas");
adherent.setEmail("thomas.roux@example.com");
adherent.setDateNaissance(LocalDate.now().minusYears(22));
Categorie cat = new Categorie();
cat.setNom("Senior");
cat.setTarifBase(new BigDecimal("200.00"));
cat.setTarifExterieur(new BigDecimal("200.00"));
Licence licence = new Licence();
licence.setId(101L);
licence.setAdherent(adherent);
licence.setCategorie(cat);
// Simulation d'un paiement intégral
com.astalange.core.entity.Paiement p = new com.astalange.core.entity.Paiement();
p.setMontant(new BigDecimal("200.00"));
licence.addPaiement(p);
boolean sent = relanceEmailService.sendRelancePaiementCotisation(licence);
assertFalse(sent, "Aucune relance ne doit être envoyée si le reste à payer est égal à 0");
verify(mailSenderMock, never()).send(any(MimeMessage.class));
}
}