54 Commits
Author SHA1 Message Date
ucef 86f87955cf Merge remote-tracking branch 'origin/main'
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m9s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m19s
2026-09-04 09:34:05 +02:00
ucef 7a9d45fb0c feat(ci): add automated DB backup, UAT RGPD restoration and Gitea CI SSH deployment 2026-09-04 09:33:19 +02:00
ucef 58d8a8d7fb fix(backup): handle SIGPIPE exit code 141 in pg_dump pipeline
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m11s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m9s
2026-09-04 09:19:13 +02:00
ucef 96c690dd79 fix(backup): purge pg_largeobject metadata prior to UAT schema reset
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m46s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m16s
2026-09-04 09:07:31 +02:00
ucef ccbcf5c6be fix(backup): clean UAT schema before restore and add --no-owner --no-privileges to pg_dump 2026-09-04 08:55:11 +02:00
ucef 645d07fdfc feat(backup): update DB UAT port
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m57s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m1s
2026-09-04 08:42:55 +02:00
ucef e1cffb8fc8 feat(backup): add automatic database restoration and RGPD anonymization for UAT environment (10.8.0.2) 2026-09-04 08:39:21 +02:00
ucef 3daef9b567 fix(ci): combine --net=host with Base64 payload transfer for key, script, and env to resolve VPN routing and file isolation
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m50s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m14s
2026-09-04 08:10:08 +02:00
ucef d987b9e46c fix(ci): execute deployment directly in runner step environment without nested container 2026-09-04 08:03:23 +02:00
ucef c5a4ae9498 fix(ci): use GITHUB_WORKSPACE for repository volume mount and absolute path /workspace/ for rsync 2026-09-04 07:26:53 +02:00
ucef 3354f3ee70 fix(ci): re-wrap PEM payload to 64 chars with explicit trailing newline 2026-09-04 07:18:12 +02:00
ucef dae97f15ba fix(ci): validate SSH key header format and provide explicit guidance for Gitea secret value 2026-09-04 07:04:21 +02:00
ucef 37611dc79f fix(ci): handle file paths in RAW_KEY and add key line count diagnostic logs 2026-09-03 15:55:13 +02:00
ucef ab63a8a913 fix(ci): pass SSH key as base64 environment variable to completely eliminate volume mount issues 2026-09-03 15:47:40 +02:00
ucef a4186ab4d3 fix(ci): strict regular file check and explicit error message when PROD_DB_SSH_KEY is missing 2026-09-03 15:39:35 +02:00
ucef 1231947e2b fix(ci): write secret key to runner file before docker run to preserve multi-line format 2026-09-03 15:26:22 +02:00
ucef 7450ea07ab fix(ci): use PROD_DB_SSH_KEY Gitea secret for reliable cross-runner authentication 2026-09-03 15:19:28 +02:00
ucef 22d8f5aea1 security: replace key header log with safe public ssh-keygen fingerprint display 2026-09-03 15:11:16 +02:00
ucef e70bf08fe9 ci: add comprehensive diagnostic logs and ssh -vv trace to step 2026-09-03 15:09:07 +02:00
ucef 748d86e71c fix(ci): mount /home/ucef/.ssh and prioritize gitea_ci_key over generic host keys 2026-09-03 15:02:09 +02:00
ucef 75611d147c fix(ci): copy key to /tmp/id_rsa instead of ~/.ssh/id_rsa to avoid read-only mount error 2026-09-03 14:56:31 +02:00
ucef e6de9836fc fix(ci): robust SSH key resolution supporting both file paths and Gitea secrets 2026-09-03 14:49:33 +02:00
ucef c198368c19 refactor(ci): simplify SSH step to directly copy and use /root/.ssh/gitea_ci_key with 600 permissions
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m51s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m7s
2026-09-03 14:40:44 +02:00
ucef 390c547920 fix(ci): prioritize /root/.ssh/gitea_ci_key mount
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m56s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m23s
2026-09-03 14:29:20 +02:00
ucef 2d390b553d fix(ci): mount /home/ubuntu/.ssh and auto-detect gitea_ci_key location 2026-09-03 14:26:53 +02:00
ucef 801fbd359d fix(ci): add UserKnownHostsFile=/dev/null and target gitea_ci_key to fix read-only ssh error
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m1s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m2s
2026-09-03 14:05:44 +02:00
ucef af47025893 refactor(ci): mount host .ssh directory directly in docker step container
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m48s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 1m53s
2026-09-03 13:16:03 +02:00
ucef b05a490040 fix(ci): strip carriage returns from SSH key and force IdentitiesOnly=yes to fix libcrypto unsupported error
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m11s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m3s
2026-09-03 12:59:24 +02:00
ucef ced7c9ce38 fix(ci): run rsync DB script deployment with host network (--net=host) to fix VPN timeout
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m8s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m13s
2026-09-03 12:51:10 +02:00
ucef 4687bc8d2b fix(ci): preserve SSH key linebreaks with printf and add custom port support
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m45s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m8s
2026-09-03 10:04:34 +02:00
ucef 0d3270e852 fix(ci): check all SSH key secret variants and force rsync deployment to DB server
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m0s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m18s
2026-09-03 08:03:03 +02:00
ucef 3e9daef770 feat(ci): add step to deploy backup script and env to DB server (10.8.0.3) via rsync
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m55s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 2m10s
2026-09-03 07:54:18 +02:00
ucef 86ddad513d feat(backup): add automated DB backup script, rsync support and Gitea CI secret integration
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m55s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m14s
2026-09-03 07:46:56 +02:00
ucef 8fa4437864 chore: bump version to 1.9-SNAPSHOT 2026-08-27 23:23:39 +02:00
ucef eeb1794754 feat(db): add V48 migration to copy sizes for new equipment IDs 36 and 37
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m8s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m45s
2026-08-27 22:26:08 +02:00
ucef 9fc4312d1c db: migration V47 pour reattribuer l'equipement ID 20 vers ID 4 et nettoyer l'ID 20
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m58s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m29s
2026-08-27 14:00:40 +02:00
ucef 658c811634 feat: ajout du filtre et de la fonction de relance des adherents avec tailles manquantes
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m33s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 8m33s
2026-08-27 10:40:33 +02:00
ucef 504b2df791 fix: exclusion des equipements sans taille et tailles non renseignees de l'export commande equipementier 2026-08-27 10:40:00 +02:00
ucef 2bc702d9bc feat: ajout du systeme d'historique et de persistance des exports CSV 2026-08-27 10:37:54 +02:00
ucef 851fb36c2a fix: passer le temps d'expiration du token de pre-inscription a 30 minutes
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 4m59s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m25s
2026-08-10 23:06:14 +02:00
ucef 2b0b0a9d6a chore: bump version to 1.8-SNAPSHOT
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m43s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m55s
2026-08-09 01:05:57 +02:00
ucef 48de522a26 fix: ajouter migration Flyway V45 pour mettre a jour la base existante avec les nouvelles colonnes de flocage
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m3s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m38s
2026-08-09 00:55:25 +02:00
ucef 03869841d5 refactor: separer les champs d export flocage en DB entre initiales et prenom/numero 2026-08-09 00:51:09 +02:00
ucef 6539e33f08 feat: ajouter les exports CSV individuels des equipements commandes pour le flocage (initiales et prenom/numero) 2026-08-09 00:44:51 +02:00
ucef cb281aa3e0 feat: ajouter l'envoi par e-mail du planning hebdomadaire global aux éducateurs
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m3s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 7m7s
2026-08-09 00:28:16 +02:00
ucef 1e2bc23603 feat(paiement): plafonner la saisie des paiements en incluant les paiements non remis
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m31s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m18s
2026-08-08 00:23:27 +02:00
ucef be1ec1c96a fix(paiement): envoi de l'email de confirmation uniquement si le paiement est remis 2026-08-08 00:17:59 +02:00
ucef 2f68af6fb5 feat(paiement): gestion specifique du mode Cheque Sport mairie (masquage num cheque, option remis oui/non, calcul reste a payer) 2026-08-08 00:08:50 +02:00
ucef 76e54de182 sec(licence): restriction de l'option et de la visibilité réduction éducateur aux seuls administrateurs 2026-08-07 23:56:03 +02:00
ucef b0fe8002c5 feat(equipe): possibilité de modifier le nom d'une équipe directement depuis la liste 2026-08-07 23:55:55 +02:00
ucef 1e85655540 feat(equipement): ajout d'un indicateur visuel pour les équipements sans référence 2026-08-07 23:55:46 +02:00
ucef dae86c70dd fix(public): réinitialisation dynamique et nettoyage serveur des champs du formulaire selon le type de demande 2026-08-07 23:30:29 +02:00
ucef 1bd6407c39 feat(mail): ajout du service de relances par e-mail et intégration HTMX dans l'admin 2026-08-07 23:30:18 +02:00
ucef 5f372254f0 ui(adherents): afficher le detail des equipements dans un popover au clic sur le badge
AS Talange CI/CD Pipeline / Build & Run Unit Tests (push) Successful in 5m1s
AS Talange CI/CD Pipeline / Deploy to Test Environment (push) Successful in 6m20s
2026-08-07 16:12:29 +02:00
52 changed files with 3174 additions and 172 deletions
+15
View File
@@ -17,6 +17,21 @@ SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE=true
# Expéditeur E-mail (doit être un expéditeur validé dans Brevo)
APP_MAIL_FROM=astalange1933@gmail.com
# Configuration Sauvegarde Automatique & API Brevo (v3)
BREVO_API_KEY=xkeysib-votre_cle_api_brevo
NOTIFICATION_EMAIL=astalange1933@gmail.com
BACKUP_DIR=/var/backups/as-talange
RETENTION_DAYS=7
# Optionnel: Transfert automatique de la sauvegarde de la BDD vers le VPS via SCP/SSH
ENABLE_REMOTE_COPY=false
REMOTE_HOST=votre-vps-ip-ou-domaine
REMOTE_USER=root
REMOTE_PORT=22
REMOTE_BACKUP_DIR=/var/backups/as-talange
SSH_KEY_PATH=/home/user/.ssh/id_rsa
# Configuration Captcha (si applicable)
CAPTCHA_SITEKEY=
CAPTCHA_SECRET=
+103
View File
@@ -49,14 +49,26 @@ jobs:
env:
PROD_DB_USER: ${{ secrets.PROD_DB_USER }}
PROD_DB_PASSWORD: ${{ secrets.PROD_DB_PASSWORD }}
PROD_DB_NAME: ${{ secrets.PROD_DB_NAME }}
CAPTCHA_SECRET: ${{ secrets.CAPTCHA_SECRET }}
CAPTCHA_SITEKEY: ${{ secrets.CAPTCHA_SITEKEY }}
MAIL_USERNAME: ${{ secrets.MAIL_USERNAME }}
MAIL_PASSWORD: ${{ secrets.MAIL_PASSWORD }}
MAIL_FROM: ${{ secrets.MAIL_FROM }}
BREVO_API_KEY: ${{ secrets.BREVO_API_KEY }}
NOTIFICATION_EMAIL: ${{ secrets.NOTIFICATION_EMAIL }}
BACKUP_DIR: ${{ secrets.BACKUP_DIR }}
RETENTION_DAYS: ${{ secrets.RETENTION_DAYS }}
ENABLE_REMOTE_COPY: ${{ secrets.ENABLE_REMOTE_COPY }}
REMOTE_HOST: ${{ secrets.REMOTE_HOST }}
REMOTE_USER: ${{ secrets.REMOTE_USER }}
REMOTE_PORT: ${{ secrets.REMOTE_PORT }}
REMOTE_BACKUP_DIR: ${{ secrets.REMOTE_BACKUP_DIR }}
SSH_KEY_PATH: ${{ secrets.SSH_KEY_PATH }}
run: |
echo "POSTGRES_USER=${PROD_DB_USER:-myuser}" > .env
echo "POSTGRES_PASSWORD=${PROD_DB_PASSWORD:-mypassword}" >> .env
[ -n "${PROD_DB_NAME}" ] && echo "POSTGRES_DB=${PROD_DB_NAME}" >> .env
echo "CAPTCHA_SECRET=${CAPTCHA_SECRET:-1x0000000000000000000000000000000AA}" >> .env
echo "CAPTCHA_SITEKEY=${CAPTCHA_SITEKEY:-1x00000000000000000000AA}" >> .env
if [ -n "${MAIL_USERNAME}" ]; then
@@ -70,6 +82,19 @@ jobs:
echo "APP_MAIL_FROM=${MAIL_FROM}" >> .env
fi
fi
# Configuration des sauvegardes de BDD
[ -n "${BREVO_API_KEY}" ] && echo "BREVO_API_KEY=${BREVO_API_KEY}" >> .env
[ -n "${NOTIFICATION_EMAIL}" ] && echo "NOTIFICATION_EMAIL=${NOTIFICATION_EMAIL}" >> .env
[ -n "${BACKUP_DIR}" ] && echo "BACKUP_DIR=${BACKUP_DIR}" >> .env
[ -n "${RETENTION_DAYS}" ] && echo "RETENTION_DAYS=${RETENTION_DAYS}" >> .env
if [ "${ENABLE_REMOTE_COPY}" = "true" ]; then
echo "ENABLE_REMOTE_COPY=true" >> .env
[ -n "${REMOTE_HOST}" ] && echo "REMOTE_HOST=${REMOTE_HOST}" >> .env
[ -n "${REMOTE_USER}" ] && echo "REMOTE_USER=${REMOTE_USER}" >> .env
[ -n "${REMOTE_PORT}" ] && echo "REMOTE_PORT=${REMOTE_PORT}" >> .env
[ -n "${REMOTE_BACKUP_DIR}" ] && echo "REMOTE_BACKUP_DIR=${REMOTE_BACKUP_DIR}" >> .env
[ -n "${SSH_KEY_PATH}" ] && echo "SSH_KEY_PATH=${SSH_KEY_PATH}" >> .env
fi
docker compose down app || true
docker compose up -d --build app
@@ -89,3 +114,81 @@ jobs:
echo "Application failed to start or login page is not accessible."
docker logs astalange_app
exit 1
- name: Deploy Backup Script & Config to DB Server (10.8.0.3)
env:
DB_SERVER_HOST: ${{ secrets.PROD_DB_HOST }}
DB_SERVER_USER: ${{ secrets.PROD_DB_SSH_USER }}
REMOTE_PORT: ${{ secrets.REMOTE_PORT }}
PROD_DB_SSH_KEY: ${{ secrets.PROD_DB_SSH_KEY }}
SSH_KEY_PATH_SECRET: ${{ secrets.SSH_KEY_PATH }}
SSH_KEY_SECRET: ${{ secrets.SSH_KEY }}
run: |
TARGET_HOST="${DB_SERVER_HOST:-10.8.0.3}"
TARGET_USER="${DB_SERVER_USER:-root}"
PORT="${REMOTE_PORT:-22}"
DEST_DIR="/opt/as-talange"
RAW_KEY="${PROD_DB_SSH_KEY:-${SSH_KEY_PATH_SECRET:-${SSH_KEY_SECRET}}}"
if [ -n "${RAW_KEY}" ] && [ -f "${RAW_KEY}" ]; then
RAW_KEY=$(cat "${RAW_KEY}")
fi
if [ -z "${RAW_KEY}" ]; then
if [ -f /root/.ssh/gitea_ci_key ]; then
RAW_KEY=$(cat /root/.ssh/gitea_ci_key)
elif [ -f /home/ucef/.ssh/gitea_ci_key ]; then
RAW_KEY=$(cat /home/ucef/.ssh/gitea_ci_key)
fi
fi
if [ -z "${RAW_KEY}" ]; then
echo "========================================================================="
echo "ERREUR : Le secret PROD_DB_SSH_KEY est totalement vide dans Gitea !"
echo "========================================================================="
exit 1
fi
KEY_B64=$(printf "%s" "${RAW_KEY}" | tr -d '\r' | base64 | tr -d '\r\n')
SCRIPT_B64=$(base64 scripts/backup_db.sh | tr -d '\r\n')
[ -f .env ] && ENV_B64=$(base64 .env | tr -d '\r\n') || ENV_B64=""
docker run --rm --net=host \
-e TARGET_HOST="${TARGET_HOST}" \
-e TARGET_USER="${TARGET_USER}" \
-e PORT="${PORT}" \
-e DEST_DIR="${DEST_DIR}" \
-e KEY_B64="${KEY_B64}" \
-e SCRIPT_B64="${SCRIPT_B64}" \
-e ENV_B64="${ENV_B64}" \
alpine:latest sh -c '
apk add --no-cache openssh-client rsync coreutils && \
(echo "$KEY_B64" | base64 -d 2>/dev/null || echo "$KEY_B64" | base64 --decode) > /tmp/raw_key && \
HEADER=$(grep "BEGIN" /tmp/raw_key) && \
FOOTER=$(grep "END" /tmp/raw_key) && \
BODY=$(grep -v "BEGIN" /tmp/raw_key | grep -v "END" | tr -d " \r\n") && \
printf "%s\n" "$HEADER" > /tmp/working_key && \
printf "%s\n" "$BODY" | fold -w 64 >> /tmp/working_key && \
printf "%s\n" "$FOOTER" >> /tmp/working_key && \
echo "" >> /tmp/working_key && \
chmod 600 /tmp/working_key && \
(echo "$SCRIPT_B64" | base64 -d 2>/dev/null || echo "$SCRIPT_B64" | base64 --decode) > /tmp/backup_db.sh && \
if [ -n "$ENV_B64" ]; then \
(echo "$ENV_B64" | base64 -d 2>/dev/null || echo "$ENV_B64" | base64 --decode) > /tmp/.env ; \
else \
touch /tmp/.env ; \
fi && \
echo "=== 🔍 DIAGNOSTIC DETAILS ===" && \
echo "Target Host: ${TARGET_USER}@${TARGET_HOST} (Port: ${PORT})" && \
echo "Destination Directory: ${DEST_DIR}" && \
echo "=== 🔑 KEY FINGERPRINT ===" && \
ssh-keygen -l -f /tmp/working_key && \
SSH_CMD="ssh -p ${PORT} -i /tmp/working_key -o IdentitiesOnly=yes -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=15" && \
echo "=== 🚀 EXECUTING REMOTE COMMAND ===" && \
$SSH_CMD "${TARGET_USER}@${TARGET_HOST}" "mkdir -p ${DEST_DIR}/scripts" && \
echo "=== 📦 RSYNC TRANSFER SCRIPT & ENV ===" && \
rsync -avz -e "$SSH_CMD" /tmp/backup_db.sh "${TARGET_USER}@${TARGET_HOST}:${DEST_DIR}/scripts/backup_db.sh" && \
rsync -avz -e "$SSH_CMD" /tmp/.env "${TARGET_USER}@${TARGET_HOST}:${DEST_DIR}/.env" && \
$SSH_CMD "${TARGET_USER}@${TARGET_HOST}" "chmod +x ${DEST_DIR}/scripts/backup_db.sh" && \
echo "SUCCESS: Backup script and .env deployed successfully to ${DEST_DIR} on DB Server!"
'
+5
View File
@@ -33,3 +33,8 @@ Thumbs.db
.env
.env.local
.env.*.local
# Database / Local Scripts
anonymize_db.sql
refresh_test_db.sh
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>as-talange-parent</artifactId>
<groupId>com.astalange</groupId>
<version>1.7-SNAPSHOT</version>
<version>1.9-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>as-talange-parent</artifactId>
<groupId>com.astalange</groupId>
<version>1.7-SNAPSHOT</version>
<version>1.9-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -42,6 +42,18 @@ public class Dotation {
@Column(name = "date_commande")
private java.time.LocalDateTime dateCommande;
@Column(name = "flocage_initiales_exporte", nullable = false)
private Boolean flocageInitialesExporte = false;
@Column(name = "date_flocage_initiales")
private java.time.LocalDateTime dateFlocageInitiales;
@Column(name = "flocage_prenom_numero_exporte", nullable = false)
private Boolean flocagePrenomNumeroExporte = false;
@Column(name = "date_flocage_prenom_numero")
private java.time.LocalDateTime dateFlocagePrenomNumero;
// Getters and Setters
public Long getId() { return id; }
@@ -77,6 +89,20 @@ public class Dotation {
public java.time.LocalDateTime getDateCommande() { return dateCommande; }
public void setDateCommande(java.time.LocalDateTime dateCommande) { this.dateCommande = dateCommande; }
public Boolean getFlocageInitialesExporte() { return flocageInitialesExporte; }
public void setFlocageInitialesExporte(Boolean flocageInitialesExporte) { this.flocageInitialesExporte = flocageInitialesExporte; }
public java.time.LocalDateTime getDateFlocageInitiales() { return dateFlocageInitiales; }
public void setDateFlocageInitiales(java.time.LocalDateTime dateFlocageInitiales) { this.dateFlocageInitiales = dateFlocageInitiales; }
public Boolean getFlocagePrenomNumeroExporte() { return flocagePrenomNumeroExporte; }
public void setFlocagePrenomNumeroExporte(Boolean flocagePrenomNumeroExporte) { this.flocagePrenomNumeroExporte = flocagePrenomNumeroExporte; }
public java.time.LocalDateTime getDateFlocagePrenomNumero() { return dateFlocagePrenomNumero; }
public void setDateFlocagePrenomNumero(java.time.LocalDateTime dateFlocagePrenomNumero) { this.dateFlocagePrenomNumero = dateFlocagePrenomNumero; }
public static boolean isSizeMatch(String option, String adherentSize) {
if (option == null || adherentSize == null) return false;
String opt = option.trim();
@@ -0,0 +1,115 @@
package com.astalange.core.entity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "export_history")
public class ExportHistory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "type_export", nullable = false, length = 50)
private TypeExport typeExport;
@Column(name = "nom_fichier", nullable = false)
private String nomFichier;
@Column(name = "date_export", nullable = false)
private LocalDateTime dateExport;
@Column(name = "nombre_elements")
private Integer nombreElements = 0;
@Lob
@Column(name = "contenu", nullable = false, columnDefinition = "TEXT")
private String contenu;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "saison_id")
private Saison saison;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "utilisateur_id")
private AppUser utilisateur;
public ExportHistory() {
}
public ExportHistory(TypeExport typeExport, String nomFichier, LocalDateTime dateExport, Integer nombreElements, String contenu, Saison saison, AppUser utilisateur) {
this.typeExport = typeExport;
this.nomFichier = nomFichier;
this.dateExport = dateExport;
this.nombreElements = nombreElements;
this.contenu = contenu;
this.saison = saison;
this.utilisateur = utilisateur;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TypeExport getTypeExport() {
return typeExport;
}
public void setTypeExport(TypeExport typeExport) {
this.typeExport = typeExport;
}
public String getNomFichier() {
return nomFichier;
}
public void setNomFichier(String nomFichier) {
this.nomFichier = nomFichier;
}
public LocalDateTime getDateExport() {
return dateExport;
}
public void setDateExport(LocalDateTime dateExport) {
this.dateExport = dateExport;
}
public Integer getNombreElements() {
return nombreElements;
}
public void setNombreElements(Integer nombreElements) {
this.nombreElements = nombreElements;
}
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
public Saison getSaison() {
return saison;
}
public void setSaison(Saison saison) {
this.saison = saison;
}
public AppUser getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(AppUser utilisateur) {
this.utilisateur = utilisateur;
}
}
@@ -141,6 +141,7 @@ public class Licence {
}
BigDecimal totalPaye = paiements.stream()
.filter(p -> p.getRemis() == null || Boolean.TRUE.equals(p.getRemis()))
.map(Paiement::getMontant)
.reduce(BigDecimal.ZERO, BigDecimal::add);
@@ -154,10 +155,27 @@ public class Licence {
return BigDecimal.ZERO;
}
return paiements.stream()
.filter(p -> p.getRemis() == null || Boolean.TRUE.equals(p.getRemis()))
.map(Paiement::getMontant)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
@Transient
public BigDecimal getSoldeRestantEngage() {
BigDecimal prixTotal = getPrixTotal();
if (paiements == null || paiements.isEmpty()) {
return prixTotal;
}
BigDecimal totalTousPaiements = paiements.stream()
.map(Paiement::getMontant)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal reste = prixTotal.subtract(totalTousPaiements);
return reste.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : reste;
}
// Getters and Setters
public Long getId() { return id; }
@@ -35,6 +35,9 @@ public class Paiement {
@Column(name = "commentaire", columnDefinition = "TEXT")
private String commentaire;
@Column(name = "remis", nullable = false)
private Boolean remis = true;
// Getters and Setters
public Long getId() { return id; }
@@ -60,4 +63,7 @@ public class Paiement {
public String getCommentaire() { return commentaire; }
public void setCommentaire(String commentaire) { this.commentaire = commentaire; }
public Boolean getRemis() { return remis != null ? remis : true; }
public void setRemis(Boolean remis) { this.remis = remis != null ? remis : true; }
}
@@ -0,0 +1,18 @@
package com.astalange.core.entity;
public enum TypeExport {
COMMANDE_EQUIPEMENT("Commande Équipementier (Regroupé)"),
FLOCAGE_INITIALES("Flocage Initiales"),
FLOCAGE_PRENOM_NUMERO("Flocage Prénom / N°"),
RECHERCHE_EQUIPEMENTS("Recherche Équipements");
private final String libelle;
TypeExport(String libelle) {
this.libelle = libelle;
}
public String getLibelle() {
return libelle;
}
}
@@ -12,4 +12,8 @@ import com.astalange.core.entity.Saison;
public interface DotationRepository extends JpaRepository<Dotation, Long>, JpaSpecificationExecutor<Dotation> {
List<Dotation> findByLicence_SaisonAndChoisiTrueAndFourniFalse(Saison saison);
List<Dotation> findByLicence_SaisonAndChoisiTrueAndCommandeeFalse(Saison saison);
List<Dotation> findByLicence_SaisonAndChoisiTrueAndCommandeeTrueAndFlocageInitialesExporteFalse(Saison saison);
List<Dotation> findByLicence_SaisonAndChoisiTrueAndCommandeeTrueAndFlocagePrenomNumeroExporteFalse(Saison saison);
}
@@ -0,0 +1,20 @@
package com.astalange.core.repository;
import com.astalange.core.entity.ExportHistory;
import com.astalange.core.entity.Saison;
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.util.List;
@Repository
public interface ExportHistoryRepository extends JpaRepository<ExportHistory, Long> {
@Query("SELECT e FROM ExportHistory e LEFT JOIN FETCH e.saison LEFT JOIN FETCH e.utilisateur ORDER BY e.dateExport DESC")
List<ExportHistory> findAllWithDetails();
@Query("SELECT e FROM ExportHistory e LEFT JOIN FETCH e.saison LEFT JOIN FETCH e.utilisateur WHERE e.saison = :saison ORDER BY e.dateExport DESC")
List<ExportHistory> findBySaisonWithDetails(@Param("saison") Saison saison);
}
@@ -34,9 +34,19 @@ public class DotationService {
Map<String, Integer> groupCountMap = new LinkedHashMap<>();
for (Dotation d : dotations) {
String equipement = d.getEquipement() != null ? d.getEquipement().getNom() : "Inconnu";
String reference = d.getEquipement() != null && d.getEquipement().getReference() != null ? d.getEquipement().getReference() : "";
String taille = d.getTaille() != null && !d.getTaille().trim().isEmpty() ? d.getTaille() : "Non renseignée";
// Exclure les équipements sans choix de tailles (ex: sacs à dos, ballons, etc.)
if (d.getEquipement() == null || d.getEquipement().getTaillesDisponibles() == null || d.getEquipement().getTaillesDisponibles().trim().isEmpty()) {
continue;
}
// Exclure les dotations pour lesquelles la taille n'est pas renseignée/choisie
if (d.getTaille() == null || d.getTaille().trim().isEmpty()) {
continue;
}
String equipement = d.getEquipement().getNom();
String reference = d.getEquipement().getReference() != null ? d.getEquipement().getReference() : "";
String taille = d.getTaille().trim();
String key = equipement + "|||" + reference + "|||" + taille;
groupCountMap.put(key, groupCountMap.getOrDefault(key, 0) + 1);
@@ -79,15 +89,17 @@ public class DotationService {
sb.append('\ufeff');
// Header
sb.append("Saison;Catégorie;Nom;Prénom;Poste;Sexe;Équipement;Référence;Taille;Flocage;Numéro;Fourni;Commandé;Date Commande\n");
sb.append("Saison;Catégorie;Nom;Prénom;Email;Téléphone;Poste;Sexe;Équipement;Référence;Taille;Flocage;Numéro;Fourni;Commandé;Date Commande\n");
for (Dotation d : dotations) {
String saison = d.getLicence().getSaison() != null ? d.getLicence().getSaison().getNom() : "";
String categorie = d.getLicence().getCategorie() != null ? d.getLicence().getCategorie().getNom() : "";
String nom = d.getLicence().getAdherent().getNom();
String prenom = d.getLicence().getAdherent().getPrenom();
String poste = d.getLicence().getAdherent().getTypeMaillot() != null ? d.getLicence().getAdherent().getTypeMaillot() : "";
String sexe = d.getLicence().getAdherent().getSexe() != null ? d.getLicence().getAdherent().getSexe() : "";
String nom = d.getLicence().getAdherent() != null ? d.getLicence().getAdherent().getNom() : "";
String prenom = d.getLicence().getAdherent() != null ? d.getLicence().getAdherent().getPrenom() : "";
String email = d.getLicence().getAdherent() != null && d.getLicence().getAdherent().getEmail() != null ? d.getLicence().getAdherent().getEmail() : "";
String telephone = d.getLicence().getAdherent() != null && d.getLicence().getAdherent().getTelephone() != null ? d.getLicence().getAdherent().getTelephone() : "";
String poste = d.getLicence().getAdherent() != null && d.getLicence().getAdherent().getTypeMaillot() != null ? d.getLicence().getAdherent().getTypeMaillot() : "";
String sexe = d.getLicence().getAdherent() != null && d.getLicence().getAdherent().getSexe() != null ? d.getLicence().getAdherent().getSexe() : "";
String equipement = d.getEquipement() != null ? d.getEquipement().getNom() : "";
String reference = d.getEquipement() != null && d.getEquipement().getReference() != null ? d.getEquipement().getReference() : "";
String taille = d.getTaille() != null ? d.getTaille() : "";
@@ -101,6 +113,8 @@ public class DotationService {
.append(escapeCsv(categorie)).append(";")
.append(escapeCsv(nom)).append(";")
.append(escapeCsv(prenom)).append(";")
.append(escapeCsv(email)).append(";")
.append(escapeCsv(telephone)).append(";")
.append(escapeCsv(poste)).append(";")
.append(escapeCsv(sexe)).append(";")
.append(escapeCsv(equipement)).append(";")
@@ -116,6 +130,107 @@ public class DotationService {
return sb.toString();
}
@Transactional
public String genererCsvFlocageInitiales(Saison saisonActive) {
List<Dotation> dotations = dotationRepository.findByLicence_SaisonAndChoisiTrueAndCommandeeTrueAndFlocageInitialesExporteFalse(saisonActive);
LocalDateTime now = LocalDateTime.now();
String dateExportFormatted = now.format(DATE_FORMATTER);
StringBuilder sb = new StringBuilder();
sb.append('\ufeff'); // BOM UTF-8 for Excel
sb.append("Saison;Catégorie;Nom;Prénom;Équipement;Référence;Taille;Initiales;Date Export Flocage\n");
for (Dotation d : dotations) {
if (d.getEquipement() == null || !d.getEquipement().isHasFlocageInitiales()) {
continue;
}
String initiales = d.getFlocage() != null ? d.getFlocage().trim() : "";
if (initiales.isEmpty()) {
continue;
}
String saison = d.getLicence().getSaison() != null ? d.getLicence().getSaison().getNom() : "";
String categorie = d.getLicence().getCategorie() != null ? d.getLicence().getCategorie().getNom() : "";
String nom = d.getLicence().getAdherent() != null ? d.getLicence().getAdherent().getNom() : "";
String prenom = d.getLicence().getAdherent() != null ? d.getLicence().getAdherent().getPrenom() : "";
String equipement = d.getEquipement().getNom();
String reference = d.getEquipement().getReference() != null ? d.getEquipement().getReference() : "";
String taille = d.getTaille() != null ? d.getTaille() : "";
sb.append(escapeCsv(saison)).append(";")
.append(escapeCsv(categorie)).append(";")
.append(escapeCsv(nom)).append(";")
.append(escapeCsv(prenom)).append(";")
.append(escapeCsv(equipement)).append(";")
.append(escapeCsv(reference)).append(";")
.append(escapeCsv(taille)).append(";")
.append(escapeCsv(initiales)).append(";")
.append(escapeCsv(dateExportFormatted)).append("\n");
d.setFlocageInitialesExporte(true);
d.setDateFlocageInitiales(now);
dotationRepository.save(d);
}
return sb.toString();
}
@Transactional
public String genererCsvFlocagePrenomNumero(Saison saisonActive) {
List<Dotation> dotations = dotationRepository.findByLicence_SaisonAndChoisiTrueAndCommandeeTrueAndFlocagePrenomNumeroExporteFalse(saisonActive);
LocalDateTime now = LocalDateTime.now();
String dateExportFormatted = now.format(DATE_FORMATTER);
StringBuilder sb = new StringBuilder();
sb.append('\ufeff'); // BOM UTF-8 for Excel
sb.append("Saison;Catégorie;Nom;Prénom;Équipement;Référence;Taille;Prénom Floqué;Numéro;Date Export Flocage\n");
for (Dotation d : dotations) {
if (d.getEquipement() == null) {
continue;
}
boolean handlesPrenom = d.getEquipement().isHasFlocagePrenom();
boolean handlesNumero = d.getEquipement().isHasFlocageNumero();
if (!handlesPrenom && !handlesNumero) {
continue;
}
String prenomFloque = d.getFlocage() != null ? d.getFlocage().trim() : "";
String numero = d.getNumero() != null ? d.getNumero().trim() : "";
if (prenomFloque.isEmpty() && numero.isEmpty()) {
continue;
}
String saison = d.getLicence().getSaison() != null ? d.getLicence().getSaison().getNom() : "";
String categorie = d.getLicence().getCategorie() != null ? d.getLicence().getCategorie().getNom() : "";
String nom = d.getLicence().getAdherent() != null ? d.getLicence().getAdherent().getNom() : "";
String prenom = d.getLicence().getAdherent() != null ? d.getLicence().getAdherent().getPrenom() : "";
String equipement = d.getEquipement().getNom();
String reference = d.getEquipement().getReference() != null ? d.getEquipement().getReference() : "";
String taille = d.getTaille() != null ? d.getTaille() : "";
sb.append(escapeCsv(saison)).append(";")
.append(escapeCsv(categorie)).append(";")
.append(escapeCsv(nom)).append(";")
.append(escapeCsv(prenom)).append(";")
.append(escapeCsv(equipement)).append(";")
.append(escapeCsv(reference)).append(";")
.append(escapeCsv(taille)).append(";")
.append(escapeCsv(prenomFloque)).append(";")
.append(escapeCsv(numero)).append(";")
.append(escapeCsv(dateExportFormatted)).append("\n");
d.setFlocagePrenomNumeroExporte(true);
d.setDateFlocagePrenomNumero(now);
dotationRepository.save(d);
}
return sb.toString();
}
private String escapeCsv(String value) {
if (value == null) {
return "";
@@ -130,3 +245,4 @@ public class DotationService {
return result;
}
}
@@ -0,0 +1,55 @@
package com.astalange.core.service;
import com.astalange.core.entity.AppUser;
import com.astalange.core.entity.ExportHistory;
import com.astalange.core.entity.Saison;
import com.astalange.core.entity.TypeExport;
import com.astalange.core.repository.ExportHistoryRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
@Service
public class ExportHistoryService {
private final ExportHistoryRepository exportHistoryRepository;
public ExportHistoryService(ExportHistoryRepository exportHistoryRepository) {
this.exportHistoryRepository = exportHistoryRepository;
}
@Transactional
public ExportHistory enregistrerExport(TypeExport typeExport, String nomFichier, String csvContent, Integer nombreElements, Saison saison, AppUser utilisateur) {
ExportHistory history = new ExportHistory(
typeExport,
nomFichier,
LocalDateTime.now(),
nombreElements,
csvContent,
saison,
utilisateur
);
return exportHistoryRepository.save(history);
}
@Transactional(readOnly = true)
public List<ExportHistory> obtenirToutLHistorique() {
return exportHistoryRepository.findAllWithDetails();
}
@Transactional(readOnly = true)
public List<ExportHistory> obtenirHistoriqueParSaison(Saison saison) {
if (saison == null) {
return obtenirToutLHistorique();
}
return exportHistoryRepository.findBySaisonWithDetails(saison);
}
@Transactional(readOnly = true)
public Optional<ExportHistory> trouverParId(Long id) {
return exportHistoryRepository.findById(id);
}
}
@@ -70,6 +70,11 @@ public class PaiementEmailService {
return false;
}
if (Boolean.FALSE.equals(paiement.getRemis())) {
log.info("Paiement non remis (remis=false) pour le paiement ID {}. L'e-mail de confirmation ne sera pas envoyé.", paiement.getId());
return false;
}
Licence licence = paiement.getLicence();
String recipientEmail = licence.getAdherent() != null ? licence.getAdherent().getEmail() : null;
log.info(">>> [PaiementEmailService] Adhérent: {} {}, Email: {}",
@@ -0,0 +1,245 @@
package com.astalange.core.service;
import com.astalange.core.entity.*;
import com.astalange.core.repository.CreneauEntrainementRepository;
import com.astalange.core.repository.EducateurRepository;
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 java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@Service
public class PlanningEmailService {
private static final Logger log = LoggerFactory.getLogger(PlanningEmailService.class);
private final JavaMailSender mailSender;
private final SaisonRepository saisonRepository;
private final CreneauEntrainementRepository creneauRepository;
private final EducateurRepository educateurRepository;
@Value("${app.mail.from:${spring.mail.username:astalange1933@gmail.com}}")
private String fromEmail = "astalange1933@gmail.com";
public PlanningEmailService(@Autowired(required = false) JavaMailSender mailSender,
SaisonRepository saisonRepository,
CreneauEntrainementRepository creneauRepository,
EducateurRepository educateurRepository) {
this.mailSender = mailSender;
this.saisonRepository = saisonRepository;
this.creneauRepository = creneauRepository;
this.educateurRepository = educateurRepository;
}
private String getEffectiveFromEmail() {
if (fromEmail != null && !fromEmail.trim().isEmpty() && fromEmail.contains("@")) {
return fromEmail.trim();
}
return "astalange1933@gmail.com";
}
/**
* Envoie le planning global hebdomadaire à tous les éducateurs enregistrés possédant un e-mail.
* @return Le nombre d'éducateurs à qui l'e-mail a été envoyé (ou planifié).
*/
public int sendPlanningGlobalToEducateurs() {
Saison saisonActive = saisonRepository.findByEstActiveTrue().orElse(null);
if (saisonActive == null) {
log.warn("Impossible d'envoyer le planning : aucune saison active.");
return 0;
}
List<Educateur> educateurs = educateurRepository.findAllWithCategorieAndEquipe();
List<Educateur> recipientEducateurs = educateurs.stream()
.filter(e -> e.getEmail() != null && !e.getEmail().trim().isEmpty())
.collect(Collectors.toList());
if (recipientEducateurs.isEmpty()) {
log.warn("Aucun éducateur avec adresse e-mail valide trouvé.");
return 0;
}
List<CreneauEntrainement> creneaux = creneauRepository.findBySaisonFetch(saisonActive);
// Map creneau -> list of matching educateurs names
Map<Long, String> creneauEducateursNames = new HashMap<>();
for (CreneauEntrainement c : creneaux) {
List<String> names = new ArrayList<>();
for (Educateur ed : educateurs) {
boolean match = false;
if (c.getEquipe() != null) {
if (ed.getEquipe() != null && ed.getEquipe().getId().equals(c.getEquipe().getId())) {
match = true;
}
} else if (c.getCategorie() != null) {
if (ed.getCategorie() != null && ed.getCategorie().getId().equals(c.getCategorie().getId())) {
match = true;
} else if (ed.getEquipe() != null && ed.getEquipe().getCategorie() != null
&& ed.getEquipe().getCategorie().getId().equals(c.getCategorie().getId())) {
match = true;
}
}
if (match) {
names.add(ed.getPrenom() + " " + ed.getNom());
}
}
creneauEducateursNames.put(c.getId(), names.isEmpty() ? "-" : String.join(", ", names));
}
// Group creneaux by JourSemaine
Map<JourSemaine, List<CreneauEntrainement>> creneauxParJour = new LinkedHashMap<>();
for (JourSemaine jour : JourSemaine.values()) {
List<CreneauEntrainement> listForJour = creneaux.stream()
.filter(c -> c.getJourSemaine() == jour)
.sorted(Comparator.comparing(CreneauEntrainement::getHeureDebut))
.collect(Collectors.toList());
creneauxParJour.put(jour, listForJour);
}
String subject = "AS Talange - Planning Hebdomadaire des Entraînements (" + saisonActive.getNom() + ")";
String htmlBody = buildPlanningGlobalHtml(saisonActive, creneauxParJour, creneauEducateursNames);
for (Educateur ed : recipientEducateurs) {
String recipientEmail = ed.getEmail().trim();
CompletableFuture.runAsync(() -> {
if (mailSender != null) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(getEffectiveFromEmail());
helper.setTo(recipientEmail);
helper.setSubject(subject);
helper.setText(htmlBody, true);
mailSender.send(message);
log.info("Planning global envoyé avec succès par e-mail à {} ({})", recipientEmail, ed.getPrenom() + " " + ed.getNom());
} catch (Exception e) {
log.warn("Erreur d'envoi du planning par e-mail à {}: {}. Simulation log.", recipientEmail, e.getMessage());
logDevEmail(recipientEmail, subject, htmlBody);
}
} else {
log.info("Mode DEV (MailSender non configuré) : simulation d'envoi du planning global à {}.", recipientEmail);
logDevEmail(recipientEmail, subject, htmlBody);
}
});
}
return recipientEducateurs.size();
}
private void logDevEmail(String recipient, String subject, String body) {
log.info("==================== [SIMULATION E-MAIL PLANNING GLOBAL] ====================");
log.info("Destinataire: {}", recipient);
log.info("Sujet: {}", subject);
log.info("Contenu:\n{}", body);
log.info("=============================================================================");
}
private String buildPlanningGlobalHtml(Saison saison, Map<JourSemaine, List<CreneauEntrainement>> creneauxParJour, Map<Long, String> creneauEducateursNames) {
StringBuilder contentBuilder = new StringBuilder();
for (Map.Entry<JourSemaine, List<CreneauEntrainement>> entry : creneauxParJour.entrySet()) {
JourSemaine jour = entry.getKey();
List<CreneauEntrainement> creneaux = entry.getValue();
contentBuilder.append("<div class=\"day-section\">");
contentBuilder.append("<h2 class=\"day-title\">").append(jour.getLibelle()).append("</h2>");
if (creneaux.isEmpty()) {
contentBuilder.append("<p class=\"no-training\">Aucun entraînement planifié ce jour.</p>");
} else {
contentBuilder.append("<table class=\"planning-table\">");
contentBuilder.append("<thead><tr>")
.append("<th>Horaires</th>")
.append("<th>Catégorie / Équipe</th>")
.append("<th>Terrain & Zone</th>")
.append("<th>Éducateurs référents</th>")
.append("</tr></thead><tbody>");
for (CreneauEntrainement c : creneaux) {
String horaire = (c.getHeureDebut() != null ? c.getHeureDebut().toString() : "") + " - " + (c.getHeureFin() != null ? c.getHeureFin().toString() : "");
String catStr = c.getCategorie() != null ? c.getCategorie().getNom() : "";
if (c.getEquipe() != null) {
catStr += " (" + c.getEquipe().getNom() + ")";
}
String terrainZone = (c.getTerrain() != null ? c.getTerrain().getNom() : "") + " - " + (c.getZone() != null ? c.getZone().getLibelle() : "");
String educateursStr = creneauEducateursNames.getOrDefault(c.getId(), "-");
contentBuilder.append("<tr>")
.append("<td class=\"time-cell\">").append(horaire).append("</td>")
.append("<td class=\"cat-cell\"><strong>").append(catStr).append("</strong></td>")
.append("<td class=\"terrain-cell\">").append(terrainZone).append("</td>")
.append("<td class=\"educ-cell\">").append(educateursStr).append("</td>")
.append("</tr>");
}
contentBuilder.append("</tbody></table>");
}
contentBuilder.append("</div>");
}
return """
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<style>
body { font-family: 'Segoe UI', Helvetica, Arial, sans-serif; background-color: #f4f6f8; margin: 0; padding: 20px; color: #1e293b; }
.container { max-width: 800px; margin: 0 auto; background: #ffffff; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
.header { background-color: #1e3a8a; color: #ffffff; padding: 28px 24px; text-align: center; }
.header h1 { margin: 0; font-size: 24px; font-weight: 700; letter-spacing: -0.5px; }
.header p { margin: 8px 0 0 0; font-size: 14px; opacity: 0.9; }
.content { padding: 24px; }
.day-section { margin-bottom: 24px; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden; }
.day-title { background: #f8fafc; border-bottom: 2px solid #1e3a8a; color: #1e3a8a; margin: 0; padding: 12px 18px; font-size: 16px; font-weight: 700; }
.no-training { padding: 14px 18px; margin: 0; font-size: 13px; color: #64748b; font-style: italic; }
.planning-table { width: 100%%; border-collapse: collapse; font-size: 13px; text-align: left; }
.planning-table th { background: #f1f5f9; color: #475569; font-weight: 600; padding: 10px 14px; border-bottom: 1px solid #e2e8f0; }
.planning-table td { padding: 10px 14px; border-bottom: 1px solid #f1f5f9; }
.planning-table tr:last-child td { border-bottom: none; }
.time-cell { font-weight: 600; color: #2563eb; white-space: nowrap; width: 120px; }
.cat-cell { color: #0f172a; }
.terrain-cell { color: #475569; }
.educ-cell { color: #059669; font-weight: 500; }
.footer { background: #f8fafc; border-top: 1px solid #e2e8f0; padding: 18px; text-align: center; font-size: 12px; color: #64748b; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>AS TALANGE - Planning Global des Entraînements</h1>
<p>Saison %s - Vue d'ensemble hebdomadaire pour le corps éducatif</p>
</div>
<div class="content">
<p style="font-size: 14px; line-height: 1.6; margin-bottom: 24px;">
Chers éducateurs,<br>
Voici le planning général d'occupation des terrains et des créneaux d'entraînement de l'<strong>AS Talange</strong> pour toute la semaine.
</p>
%s
<p style="margin-top: 24px; font-size: 13px; color: #475569;">
En cas de changement ou de modification sur les créneaux, merci d'en informer le responsable technique du club.<br><br>
Sportivement,<br>
<strong>Le Bureau & la Direction Technique - AS Talange</strong>
</p>
</div>
<div class="footer">
Cet e-mail automatique est destiné à l'ensemble du corps éducatif de l'AS Talange.
</div>
</div>
</body>
</html>
""".formatted(saison.getNom(), contentBuilder.toString());
}
}
@@ -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,4 @@
ALTER TABLE paiement ADD COLUMN IF NOT EXISTS remis BOOLEAN NOT NULL DEFAULT TRUE;
INSERT INTO mode_paiement (nom) VALUES ('Chèque Sport mairie')
ON CONFLICT (nom) DO NOTHING;
@@ -0,0 +1,2 @@
ALTER TABLE dotation ADD COLUMN flocage_exporte BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE dotation ADD COLUMN date_flocage TIMESTAMP NULL;
@@ -0,0 +1,7 @@
ALTER TABLE dotation DROP COLUMN IF EXISTS flocage_exporte;
ALTER TABLE dotation DROP COLUMN IF EXISTS date_flocage;
ALTER TABLE dotation ADD COLUMN IF NOT EXISTS flocage_initiales_exporte BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE dotation ADD COLUMN IF NOT EXISTS date_flocage_initiales TIMESTAMP NULL;
ALTER TABLE dotation ADD COLUMN IF NOT EXISTS flocage_prenom_numero_exporte BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE dotation ADD COLUMN IF NOT EXISTS date_flocage_prenom_numero TIMESTAMP NULL;
@@ -0,0 +1,12 @@
CREATE TABLE export_history (
id BIGSERIAL PRIMARY KEY,
type_export VARCHAR(50) NOT NULL,
nom_fichier VARCHAR(255) NOT NULL,
date_export TIMESTAMP NOT NULL,
nombre_elements INT DEFAULT 0,
contenu TEXT NOT NULL,
saison_id BIGINT,
utilisateur_id BIGINT,
CONSTRAINT fk_export_history_saison FOREIGN KEY (saison_id) REFERENCES saison(id) ON DELETE SET NULL,
CONSTRAINT fk_export_history_user FOREIGN KEY (utilisateur_id) REFERENCES app_user(id) ON DELETE SET NULL
);
@@ -0,0 +1,24 @@
-- Migration V47: Remplacement de l'équipement ID 20 (Survêtement de sortie Puma Féminin Junior) par l'équipement ID 4 (Survêtement de sortie Puma Junior)
-- 1. Associer l'équipement ID 4 aux catégories qui possédaient l'équipement ID 20
INSERT INTO categorie_equipement (categorie_id, equipement_id, obligatoire, prix)
SELECT DISTINCT ce.categorie_id, 4, ce.obligatoire, ce.prix
FROM categorie_equipement ce
WHERE ce.equipement_id = 20
AND NOT EXISTS (
SELECT 1 FROM categorie_equipement ce_exists
WHERE ce_exists.categorie_id = ce.categorie_id AND ce_exists.equipement_id = 4
);
-- 2. Migrer les dotations des adhérents de l'équipement ID 20 vers l'équipement ID 4 (conserve tailles, flocages, etc.)
UPDATE dotation
SET equipement_id = 4
WHERE equipement_id = 20;
-- 3. Supprimer les associations de l'équipement ID 20 dans la table de liaison categorie_equipement
DELETE FROM categorie_equipement
WHERE equipement_id = 20;
-- 4. Supprimer l'équipement ID 20
DELETE FROM equipement
WHERE id = 20;
@@ -0,0 +1,45 @@
-- Migration V48: Copier la taille des équipements d'origine vers les nouveaux équipements ajoutés (36 depuis 4, et 37 depuis 10)
-- 1. Attribution de la même taille que l'équipement ID 4 aux dotations de l'équipement ID 36 (lorsqu'elle est non renseignée)
UPDATE dotation d36
SET taille = (
SELECT d4.taille
FROM dotation d4
WHERE d4.licence_id = d36.licence_id
AND d4.equipement_id = 4
AND d4.taille IS NOT NULL
AND TRIM(d4.taille) <> ''
LIMIT 1
)
WHERE d36.equipement_id = 36
AND (d36.taille IS NULL OR TRIM(d36.taille) = '')
AND EXISTS (
SELECT 1
FROM dotation d4
WHERE d4.licence_id = d36.licence_id
AND d4.equipement_id = 4
AND d4.taille IS NOT NULL
AND TRIM(d4.taille) <> ''
);
-- 2. Attribution de la même taille que l'équipement ID 10 aux dotations de l'équipement ID 37 (lorsqu'elle est non renseignée)
UPDATE dotation d37
SET taille = (
SELECT d10.taille
FROM dotation d10
WHERE d10.licence_id = d37.licence_id
AND d10.equipement_id = 10
AND d10.taille IS NOT NULL
AND TRIM(d10.taille) <> ''
LIMIT 1
)
WHERE d37.equipement_id = 37
AND (d37.taille IS NULL OR TRIM(d37.taille) = '')
AND EXISTS (
SELECT 1
FROM dotation d10
WHERE d10.licence_id = d37.licence_id
AND d10.equipement_id = 10
AND d10.taille IS NOT NULL
AND TRIM(d10.taille) <> ''
);
@@ -95,4 +95,37 @@ class LicenceReductionTest {
assertEquals(new BigDecimal("40.00"), licence.getMontantReduction());
assertEquals(new BigDecimal("160.00"), licence.getResteAPayer());
}
@Test
@DisplayName("Devrait inclure le paiement dans le total payé uniquement s'il est remis")
void testPaiementRemisVsNonRemis() {
Categorie cat = new Categorie();
cat.setTarifBase(new BigDecimal("100.00"));
Adherent adh = new Adherent();
adh.setResidentTalange(true);
Licence licence = new Licence();
licence.setCategorie(cat);
licence.setAdherent(adh);
com.astalange.core.entity.Paiement p1 = new com.astalange.core.entity.Paiement();
p1.setMontant(new BigDecimal("40.00"));
p1.setRemis(false); // Non remis (ex: Chèque Sport mairie en attente)
licence.addPaiement(p1);
// La somme de ce chèque non remis n'est PAS déduite du financier => reste à payer = 100.00 €
assertEquals(0, BigDecimal.ZERO.compareTo(licence.getSommePayee()));
assertEquals(0, new BigDecimal("100.00").compareTo(licence.getResteAPayer()));
// En revanche, le solde disponible engagé prend en compte TOUS les paiements => reste engagé = 60.00 €
assertEquals(0, new BigDecimal("60.00").compareTo(licence.getSoldeRestantEngage()));
// Passage à remis = true (remis/encaissé)
p1.setRemis(true);
// La somme est déduite du financier => reste à payer = 60.00 €
assertEquals(0, new BigDecimal("40.00").compareTo(licence.getSommePayee()));
assertEquals(0, new BigDecimal("60.00").compareTo(licence.getResteAPayer()));
assertEquals(0, new BigDecimal("60.00").compareTo(licence.getSoldeRestantEngage()));
}
}
@@ -0,0 +1,176 @@
package com.astalange.core.service;
import com.astalange.core.entity.*;
import com.astalange.core.repository.DotationRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class DotationServiceTest {
@Mock
private DotationRepository dotationRepository;
@InjectMocks
private DotationService dotationService;
private Saison saison;
private Categorie categorie;
private Adherent adherent;
private Licence licence;
@BeforeEach
public void setUp() {
saison = new Saison();
saison.setId(1L);
saison.setNom("2026-2027");
categorie = new Categorie();
categorie.setId(10L);
categorie.setNom("U15");
adherent = new Adherent();
adherent.setId(100L);
adherent.setNom("Dupont");
adherent.setPrenom("Jean");
licence = new Licence();
licence.setId(500L);
licence.setSaison(saison);
licence.setCategorie(categorie);
licence.setAdherent(adherent);
}
@Test
@DisplayName("Générer CSV Flocage Initiales - Uniquement équipements avec initiales et commandés")
public void testGenererCsvFlocageInitiales() {
Equipement eqVeste = new Equipement();
eqVeste.setId(1L);
eqVeste.setNom("Veste de sortie");
eqVeste.setReference("REF-VESTE");
eqVeste.setHasFlocageInitiales(true);
Dotation d1 = new Dotation();
d1.setId(1L);
d1.setLicence(licence);
d1.setEquipement(eqVeste);
d1.setTaille("M");
d1.setFlocage("JD");
d1.setChoisi(true);
d1.setCommandee(true);
d1.setFlocageInitialesExporte(false);
when(dotationRepository.findByLicence_SaisonAndChoisiTrueAndCommandeeTrueAndFlocageInitialesExporteFalse(saison))
.thenReturn(List.of(d1));
String csv = dotationService.genererCsvFlocageInitiales(saison);
assertNotNull(csv);
assertTrue(csv.contains("JD"));
assertTrue(csv.contains("Veste de sortie"));
assertTrue(csv.contains("Dupont"));
assertTrue(d1.getFlocageInitialesExporte());
assertNotNull(d1.getDateFlocageInitiales());
verify(dotationRepository, times(1)).save(d1);
}
@Test
@DisplayName("Générer CSV Flocage Prénom / Numéro - Uniquement équipements commandés avec prénom ou numéro")
public void testGenererCsvFlocagePrenomNumero() {
Equipement eqMaillot = new Equipement();
eqMaillot.setId(2L);
eqMaillot.setNom("Maillot de match");
eqMaillot.setReference("REF-MAILLOT");
eqMaillot.setHasFlocagePrenom(true);
eqMaillot.setHasFlocageNumero(true);
Dotation d2 = new Dotation();
d2.setId(2L);
d2.setLicence(licence);
d2.setEquipement(eqMaillot);
d2.setTaille("L");
d2.setFlocage("JEAN");
d2.setNumero("10");
d2.setChoisi(true);
d2.setCommandee(true);
d2.setFlocagePrenomNumeroExporte(false);
when(dotationRepository.findByLicence_SaisonAndChoisiTrueAndCommandeeTrueAndFlocagePrenomNumeroExporteFalse(saison))
.thenReturn(List.of(d2));
String csv = dotationService.genererCsvFlocagePrenomNumero(saison);
assertNotNull(csv);
assertTrue(csv.contains("JEAN"));
assertTrue(csv.contains("10"));
assertTrue(csv.contains("Maillot de match"));
assertTrue(d2.getFlocagePrenomNumeroExporte());
assertNotNull(d2.getDateFlocagePrenomNumero());
verify(dotationRepository, times(1)).save(d2);
}
@Test
@DisplayName("Générer CSV Commande - Équipement regroupé par taille (Exclut les articles sans grille de tailles)")
public void testGenererCsvCommandeEquipement_ExclutSansTaille() {
Equipement eqMaillot = new Equipement();
eqMaillot.setId(1L);
eqMaillot.setNom("Maillot de match");
eqMaillot.setReference("REF-MAILLOT");
eqMaillot.setTaillesDisponibles("S,M,L,XL");
Equipement eqSac = new Equipement();
eqSac.setId(2L);
eqSac.setNom("Sac à dos");
eqSac.setReference("REF-SAC");
eqSac.setTaillesDisponibles(null); // No size options!
Dotation dMaillot = new Dotation();
dMaillot.setId(1L);
dMaillot.setLicence(licence);
dMaillot.setEquipement(eqMaillot);
dMaillot.setTaille("M");
dMaillot.setChoisi(true);
dMaillot.setCommandee(false);
Dotation dSac = new Dotation();
dSac.setId(2L);
dSac.setLicence(licence);
dSac.setEquipement(eqSac);
dSac.setChoisi(true);
dSac.setCommandee(false);
Dotation dMaillotSansTaille = new Dotation();
dMaillotSansTaille.setId(3L);
dMaillotSansTaille.setLicence(licence);
dMaillotSansTaille.setEquipement(eqMaillot);
dMaillotSansTaille.setTaille(null); // Taille non choisie par l'adhérent
dMaillotSansTaille.setChoisi(true);
dMaillotSansTaille.setCommandee(false);
when(dotationRepository.findByLicence_SaisonAndChoisiTrueAndCommandeeFalse(saison))
.thenReturn(List.of(dMaillot, dSac, dMaillotSansTaille));
String csv = dotationService.genererCsvCommandeEquipement(saison);
assertNotNull(csv);
assertTrue(csv.contains("Maillot de match"));
assertTrue(csv.contains("M"));
assertFalse(csv.contains("Sac à dos"), "Le sac à dos sans grille de tailles doit être exclu de l'export fournisseur par taille");
assertTrue(dMaillot.getCommandee());
assertFalse(dSac.getCommandee());
assertFalse(dMaillotSansTaille.getCommandee(), "Le maillot dont la taille n'est pas choisie doit rester non commandé");
}
}
@@ -0,0 +1,91 @@
package com.astalange.core.service;
import com.astalange.core.entity.AppUser;
import com.astalange.core.entity.ExportHistory;
import com.astalange.core.entity.Saison;
import com.astalange.core.entity.TypeExport;
import com.astalange.core.repository.ExportHistoryRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class ExportHistoryServiceTest {
@Mock
private ExportHistoryRepository exportHistoryRepository;
@InjectMocks
private ExportHistoryService exportHistoryService;
private Saison saison;
private AppUser user;
@BeforeEach
public void setUp() {
saison = new Saison();
saison.setId(1L);
saison.setNom("2026-2027");
user = new AppUser();
user.setId(10L);
user.setUsername("admin");
}
@Test
@DisplayName("Enregistrer un export - doit sauvegarder les métadonnées et le contenu CSV")
public void testEnregistrerExport() {
String csv = "Header1;Header2\nValue1;Value2";
when(exportHistoryRepository.save(any(ExportHistory.class))).thenAnswer(invocation -> {
ExportHistory arg = invocation.getArgument(0);
arg.setId(100L);
return arg;
});
ExportHistory result = exportHistoryService.enregistrerExport(
TypeExport.COMMANDE_EQUIPEMENT,
"commande.csv",
csv,
1,
saison,
user
);
assertNotNull(result);
assertEquals(100L, result.getId());
assertEquals(TypeExport.COMMANDE_EQUIPEMENT, result.getTypeExport());
assertEquals("commande.csv", result.getNomFichier());
assertEquals(csv, result.getContenu());
assertEquals(1, result.getNombreElements());
assertEquals(saison, result.getSaison());
assertEquals(user, result.getUtilisateur());
verify(exportHistoryRepository, times(1)).save(any(ExportHistory.class));
}
@Test
@DisplayName("Obtenir l'historique par saison")
public void testObtenirHistoriqueParSaison() {
ExportHistory h = new ExportHistory();
h.setId(1L);
h.setTypeExport(TypeExport.FLOCAGE_INITIALES);
when(exportHistoryRepository.findBySaisonWithDetails(saison)).thenReturn(List.of(h));
List<ExportHistory> result = exportHistoryService.obtenirHistoriqueParSaison(saison);
assertEquals(1, result.size());
assertEquals(TypeExport.FLOCAGE_INITIALES, result.get(0).getTypeExport());
verify(exportHistoryRepository, times(1)).findBySaisonWithDetails(saison);
}
}
@@ -170,4 +170,23 @@ class PaiementEmailServiceTest {
assertTrue(result);
verify(mailSenderMock, timeout(2000).times(1)).send(any(MimeMessage.class));
}
@Test
void testSendPaiementConfirmation_NonRemis() {
Adherent adherent = new Adherent();
adherent.setNom("DUPONT");
adherent.setPrenom("Jean");
adherent.setEmail("jean.dupont@example.com");
Licence licence = new Licence();
licence.setAdherent(adherent);
Paiement paiement = new Paiement();
paiement.setLicence(licence);
paiement.setMontant(new BigDecimal("50.00"));
paiement.setRemis(false);
boolean result = paiementEmailService.sendPaiementConfirmation(paiement);
assertFalse(result, "Devrait retourner false et ne pas envoyer d'email si remis = false");
}
}
@@ -0,0 +1,125 @@
package com.astalange.core.service;
import com.astalange.core.entity.*;
import com.astalange.core.repository.CreneauEntrainementRepository;
import com.astalange.core.repository.EducateurRepository;
import com.astalange.core.repository.SaisonRepository;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mail.javamail.JavaMailSender;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class PlanningEmailServiceTest {
private PlanningEmailService planningEmailService;
private JavaMailSender mailSenderMock;
private SaisonRepository saisonRepositoryMock;
private CreneauEntrainementRepository creneauRepositoryMock;
private EducateurRepository educateurRepositoryMock;
@BeforeEach
void setUp() {
mailSenderMock = mock(JavaMailSender.class);
MimeMessage mimeMessage = new MimeMessage((jakarta.mail.Session) null);
when(mailSenderMock.createMimeMessage()).thenReturn(mimeMessage);
saisonRepositoryMock = mock(SaisonRepository.class);
creneauRepositoryMock = mock(CreneauEntrainementRepository.class);
educateurRepositoryMock = mock(EducateurRepository.class);
planningEmailService = new PlanningEmailService(
mailSenderMock,
saisonRepositoryMock,
creneauRepositoryMock,
educateurRepositoryMock
);
}
@Test
void testSendPlanningGlobalToEducateurs_SansSaisonActive() {
when(saisonRepositoryMock.findByEstActiveTrue()).thenReturn(Optional.empty());
int count = planningEmailService.sendPlanningGlobalToEducateurs();
assertEquals(0, count);
verify(mailSenderMock, never()).send(any(MimeMessage.class));
}
@Test
void testSendPlanningGlobalToEducateurs_SansEducateursAvecEmail() {
Saison saison = new Saison();
saison.setNom("2026/2027");
when(saisonRepositoryMock.findByEstActiveTrue()).thenReturn(Optional.of(saison));
Educateur ed1 = new Educateur();
ed1.setNom("DUPONT");
ed1.setPrenom("Jean");
ed1.setEmail(null);
Educateur ed2 = new Educateur();
ed2.setNom("MARTIN");
ed2.setPrenom("Paul");
ed2.setEmail("");
when(educateurRepositoryMock.findAllWithCategorieAndEquipe()).thenReturn(List.of(ed1, ed2));
int count = planningEmailService.sendPlanningGlobalToEducateurs();
assertEquals(0, count);
verify(mailSenderMock, never()).send(any(MimeMessage.class));
}
@Test
void testSendPlanningGlobalToEducateurs_Succes() {
Saison saison = new Saison();
saison.setNom("2026/2027");
when(saisonRepositoryMock.findByEstActiveTrue()).thenReturn(Optional.of(saison));
Educateur ed1 = new Educateur();
ed1.setId(1L);
ed1.setNom("DUPONT");
ed1.setPrenom("Jean");
ed1.setEmail("jean.dupont@example.com");
Educateur ed2 = new Educateur();
ed2.setId(2L);
ed2.setNom("BERNARD");
ed2.setPrenom("Luc");
ed2.setEmail("luc.bernard@example.com");
when(educateurRepositoryMock.findAllWithCategorieAndEquipe()).thenReturn(List.of(ed1, ed2));
Categorie cat = new Categorie();
cat.setId(10L);
cat.setNom("U13");
Terrain terrain = new Terrain();
terrain.setId(100L);
terrain.setNom("Terrain Synthétique");
CreneauEntrainement creneau = new CreneauEntrainement();
creneau.setId(50L);
creneau.setSaison(saison);
creneau.setCategorie(cat);
creneau.setTerrain(terrain);
creneau.setZone(ZoneTerrain.DEMI_A);
creneau.setJourSemaine(JourSemaine.MERCREDI);
creneau.setHeureDebut(LocalTime.of(14, 0));
creneau.setHeureFin(LocalTime.of(16, 0));
when(creneauRepositoryMock.findBySaisonFetch(saison)).thenReturn(List.of(creneau));
int count = planningEmailService.sendPlanningGlobalToEducateurs();
assertEquals(2, count);
verify(mailSenderMock, timeout(2000).times(2)).send(any(MimeMessage.class));
}
}
@@ -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));
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>as-talange-parent</artifactId>
<groupId>com.astalange</groupId>
<version>1.7-SNAPSHOT</version>
<version>1.9-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -25,8 +25,9 @@ public class AdherentController {
private final SaisonRepository saisonRepository;
private final com.astalange.core.service.CategorieService categorieService;
private final com.astalange.core.service.SportEasyEmailService sportEasyEmailService;
private final com.astalange.core.service.RelanceEmailService relanceEmailService;
public AdherentController(AdherentRepository adherentRepository, CategorieRepository categorieRepository, com.astalange.core.repository.LicenceRepository licenceRepository, com.astalange.core.repository.ModePaiementRepository modePaiementRepository, SaisonRepository saisonRepository, com.astalange.core.service.CategorieService categorieService, com.astalange.core.service.SportEasyEmailService sportEasyEmailService) {
public AdherentController(AdherentRepository adherentRepository, CategorieRepository categorieRepository, com.astalange.core.repository.LicenceRepository licenceRepository, com.astalange.core.repository.ModePaiementRepository modePaiementRepository, SaisonRepository saisonRepository, com.astalange.core.service.CategorieService categorieService, com.astalange.core.service.SportEasyEmailService sportEasyEmailService, com.astalange.core.service.RelanceEmailService relanceEmailService) {
this.adherentRepository = adherentRepository;
this.categorieRepository = categorieRepository;
this.licenceRepository = licenceRepository;
@@ -34,6 +35,7 @@ public class AdherentController {
this.saisonRepository = saisonRepository;
this.categorieService = categorieService;
this.sportEasyEmailService = sportEasyEmailService;
this.relanceEmailService = relanceEmailService;
}
@org.springframework.web.bind.annotation.ModelAttribute("equipes")
@@ -382,4 +384,54 @@ public class AdherentController {
return "redirect:/adherents";
}
@org.springframework.web.bind.annotation.PostMapping("/{id}/relancer-paiement")
public String relancerPaiement(
@org.springframework.web.bind.annotation.PathVariable Long id,
org.springframework.web.servlet.mvc.support.RedirectAttributes redirectAttributes) {
Adherent adherent = adherentRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Adhérent invalide : " + id));
Licence licence = adherent.getLicenceActuelle();
if (licence == null) {
redirectAttributes.addFlashAttribute("errorMessage", "Cet adhérent n'a pas de licence enregistrée.");
return "redirect:/adherents";
}
if (licence.getResteAPayer().compareTo(java.math.BigDecimal.ZERO) <= 0) {
redirectAttributes.addFlashAttribute("infoMessage", "Cet adhérent est déjà à jour de sa cotisation.");
return "redirect:/adherents";
}
boolean sent = relanceEmailService.sendRelancePaiementCotisation(licence);
if (sent) {
redirectAttributes.addFlashAttribute("successMessage", "L'e-mail de relance de paiement pour " + adherent.getPrenom() + " " + adherent.getNom() + " a été envoyé avec succès.");
} else {
redirectAttributes.addFlashAttribute("errorMessage", "Impossible d'envoyer l'e-mail de relance (adresse e-mail manquante).");
}
return "redirect:/adherents";
}
@org.springframework.web.bind.annotation.PostMapping("/{id}/relancer-paiement-htmx")
@org.springframework.web.bind.annotation.ResponseBody
public String relancerPaiementHtmx(@org.springframework.web.bind.annotation.PathVariable Long id) {
Adherent adherent = adherentRepository.findById(id).orElse(null);
if (adherent == null || adherent.getLicenceActuelle() == null) {
return "<span class=\"text-xs text-red-600 font-medium bg-red-50 px-2.5 py-1 rounded-full border border-red-200\">Introuvable</span>";
}
Licence licence = adherent.getLicenceActuelle();
if (licence.getResteAPayer().compareTo(java.math.BigDecimal.ZERO) <= 0) {
return "<span class=\"text-xs text-green-700 font-medium bg-green-50 px-2.5 py-1 rounded-full border border-green-200\">Déjà réglé</span>";
}
boolean sent = relanceEmailService.sendRelancePaiementCotisation(licence);
if (sent) {
return "<span class=\"text-xs text-amber-700 font-medium bg-amber-50 px-2 py-0.5 rounded-full border border-amber-200 inline-flex items-center gap-1\"><svg class=\"w-3 h-3\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 002-2H5a2 2 0 00-2 2v10a2 2 0 002 2z\"/></svg> Relance envoyée</span>";
} else {
return "<span class=\"text-xs text-red-600 font-medium bg-red-50 px-2 py-0.5 rounded-full border border-red-200\">Email manquant</span>";
}
}
}
@@ -8,17 +8,23 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.astalange.core.entity.PreInscription;
import com.astalange.core.service.RelanceEmailService;
@Controller
@RequestMapping("/admin/pre-inscriptions")
public class AdminPreInscriptionController {
private final PreInscriptionRepository preInscriptionRepository;
private final PreInscriptionService preInscriptionService;
private final RelanceEmailService relanceEmailService;
public AdminPreInscriptionController(PreInscriptionRepository preInscriptionRepository,
PreInscriptionService preInscriptionService) {
PreInscriptionService preInscriptionService,
RelanceEmailService relanceEmailService) {
this.preInscriptionRepository = preInscriptionRepository;
this.preInscriptionService = preInscriptionService;
this.relanceEmailService = relanceEmailService;
}
@GetMapping
@@ -46,6 +52,20 @@ public class AdminPreInscriptionController {
return ""; // HTMX target la ligne avec outerHTML -> supprime la ligne
}
@PostMapping("/{id}/relancer")
@ResponseBody
public String relancer(@PathVariable Long id) {
PreInscription pre = preInscriptionRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Pré-inscription introuvable : " + id));
boolean sent = relanceEmailService.sendRelancePreInscription(pre);
if (sent) {
return "<span class=\"text-xs text-amber-700 font-medium bg-amber-50 px-2.5 py-1 rounded-full border border-amber-200 inline-flex items-center gap-1\"><svg class=\"w-3.5 h-3.5\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\"><path stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"2\" d=\"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 002-2H5a2 2 0 00-2 2v10a2 2 0 002 2z\"/></svg> Relance envoyée</span>";
} else {
return "<span class=\"text-xs text-red-600 font-medium bg-red-50 px-2.5 py-1 rounded-full border border-red-200\">Erreur (sans email)</span>";
}
}
@GetMapping("/count")
@ResponseBody
public String countBadge() {
@@ -1,32 +1,34 @@
package com.astalange.web.controller;
import com.astalange.core.entity.AppUser;
import com.astalange.core.entity.Dotation;
import com.astalange.core.entity.ExportHistory;
import com.astalange.core.entity.Saison;
import com.astalange.core.entity.TypeExport;
import com.astalange.core.repository.AppUserRepository;
import com.astalange.core.repository.CategorieRepository;
import com.astalange.core.repository.DotationRepository;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import com.astalange.core.repository.EquipementRepository;
import com.astalange.core.repository.SaisonRepository;
import com.astalange.core.security.CustomUserDetails;
import com.astalange.core.service.DotationService;
import com.astalange.core.service.ExportHistoryService;
import jakarta.persistence.criteria.Predicate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.http.ResponseEntity;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.time.LocalDate;
import com.astalange.core.service.DotationService;
import com.astalange.core.repository.SaisonRepository;
import com.astalange.core.entity.Saison;
import com.astalange.core.repository.EquipementRepository;
import com.astalange.core.repository.CategorieRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.data.jpa.domain.Specification;
import jakarta.persistence.criteria.Predicate;
import java.util.ArrayList;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Controller
public class DotationController {
@@ -36,16 +38,44 @@ public class DotationController {
private final SaisonRepository saisonRepository;
private final EquipementRepository equipementRepository;
private final CategorieRepository categorieRepository;
private final ExportHistoryService exportHistoryService;
private final AppUserRepository appUserRepository;
public DotationController(DotationRepository dotationRepository, DotationService dotationService, SaisonRepository saisonRepository, EquipementRepository equipementRepository, CategorieRepository categorieRepository) {
public DotationController(DotationRepository dotationRepository,
DotationService dotationService,
SaisonRepository saisonRepository,
EquipementRepository equipementRepository,
CategorieRepository categorieRepository,
ExportHistoryService exportHistoryService,
AppUserRepository appUserRepository) {
this.dotationRepository = dotationRepository;
this.dotationService = dotationService;
this.saisonRepository = saisonRepository;
this.equipementRepository = equipementRepository;
this.categorieRepository = categorieRepository;
this.exportHistoryService = exportHistoryService;
this.appUserRepository = appUserRepository;
}
private Specification<Dotation> buildSpecification(Long equipementId, Long categorieId, Boolean fourni, Boolean commandee, Saison saisonActive) {
private AppUser getCurrentUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getPrincipal() instanceof CustomUserDetails userDetails) {
return appUserRepository.findById(userDetails.getId()).orElse(null);
}
return null;
}
private int compterElementsCsv(String csvContent) {
if (csvContent == null || csvContent.trim().isEmpty()) {
return 0;
}
int lines = (int) Arrays.stream(csvContent.split("\n"))
.filter(l -> !l.trim().isEmpty())
.count();
return Math.max(0, lines - 1);
}
private Specification<Dotation> buildSpecification(Long equipementId, Long categorieId, Boolean fourni, Boolean commandee, Boolean tailleRenseignee, Saison saisonActive) {
return (root, query, cb) -> {
if (Long.class != query.getResultType() && long.class != query.getResultType()) {
root.fetch("equipement", jakarta.persistence.criteria.JoinType.LEFT);
@@ -70,6 +100,24 @@ public class DotationController {
if (commandee != null) {
predicates.add(cb.equal(root.get("commandee"), commandee));
}
if (tailleRenseignee != null) {
if (tailleRenseignee) {
predicates.add(cb.and(
cb.isNotNull(root.get("taille")),
cb.notEqual(cb.trim(root.get("taille")), "")
));
} else {
// Uniquement les équipements proposant une grille de tailles mais dont la taille n'est pas encore saisie
predicates.add(cb.and(
cb.isNotNull(root.get("equipement").get("taillesDisponibles")),
cb.notEqual(cb.trim(root.get("equipement").get("taillesDisponibles")), ""),
cb.or(
cb.isNull(root.get("taille")),
cb.equal(cb.trim(root.get("taille")), "")
)
));
}
}
return cb.and(predicates.toArray(new Predicate[0]));
};
}
@@ -80,12 +128,13 @@ public class DotationController {
@RequestParam(required = false) Long categorieId,
@RequestParam(required = false) Boolean fourni,
@RequestParam(required = false) Boolean commandee,
@RequestParam(required = false) Boolean tailleRenseignee,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
Model model) {
Saison saisonActive = saisonRepository.findByEstActiveTrue().orElse(null);
Specification<Dotation> spec = buildSpecification(equipementId, categorieId, fourni, commandee, saisonActive);
Specification<Dotation> spec = buildSpecification(equipementId, categorieId, fourni, commandee, tailleRenseignee, saisonActive);
List<Dotation> allDotations = dotationRepository.findAll(spec);
int totalElements = allDotations.size();
@@ -104,6 +153,7 @@ public class DotationController {
model.addAttribute("categorieId", categorieId);
model.addAttribute("fourni", fourni);
model.addAttribute("commandee", commandee);
model.addAttribute("tailleRenseignee", tailleRenseignee);
model.addAttribute("currentPage", page);
model.addAttribute("totalPages", totalPages);
@@ -118,17 +168,21 @@ public class DotationController {
@RequestParam(required = false) Long equipementId,
@RequestParam(required = false) Long categorieId,
@RequestParam(required = false) Boolean fourni,
@RequestParam(required = false) Boolean commandee) {
@RequestParam(required = false) Boolean commandee,
@RequestParam(required = false) Boolean tailleRenseignee) {
Saison saisonActive = saisonRepository.findByEstActiveTrue().orElse(null);
Specification<Dotation> spec = buildSpecification(equipementId, categorieId, fourni, commandee, saisonActive);
Specification<Dotation> spec = buildSpecification(equipementId, categorieId, fourni, commandee, tailleRenseignee, saisonActive);
List<Dotation> dotations = dotationRepository.findAll(spec);
String csvContent = dotationService.genererCsvSearchEquipement(dotations);
String filename = Boolean.FALSE.equals(tailleRenseignee) ? "relance_tailles_manquantes_" + LocalDate.now() + ".csv" : "recherche_equipements_" + LocalDate.now() + ".csv";
exportHistoryService.enregistrerExport(TypeExport.RECHERCHE_EQUIPEMENTS, filename, csvContent, compterElementsCsv(csvContent), saisonActive, getCurrentUser());
byte[] csvBytes = csvContent.getBytes(java.nio.charset.StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", "recherche_equipements_" + LocalDate.now() + ".csv");
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
return new ResponseEntity<>(csvBytes, headers, org.springframework.http.HttpStatus.OK);
@@ -140,15 +194,119 @@ public class DotationController {
.orElseThrow(() -> new IllegalStateException("Aucune saison active"));
String csvContent = dotationService.genererCsvCommandeEquipement(saisonActive);
String filename = "commande_equipements_regroupee_" + LocalDate.now() + ".csv";
exportHistoryService.enregistrerExport(TypeExport.COMMANDE_EQUIPEMENT, filename, csvContent, compterElementsCsv(csvContent), saisonActive, getCurrentUser());
byte[] csvBytes = csvContent.getBytes(java.nio.charset.StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", "commande_equipements_regroupee_" + LocalDate.now() + ".csv");
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
return new ResponseEntity<>(csvBytes, headers, org.springframework.http.HttpStatus.OK);
}
@GetMapping("/admin/equipements/export-flocage-initiales")
public ResponseEntity<byte[]> exportFlocageInitiales() {
Saison saisonActive = saisonRepository.findByEstActiveTrue()
.orElseThrow(() -> new IllegalStateException("Aucune saison active"));
String csvContent = dotationService.genererCsvFlocageInitiales(saisonActive);
String filename = "flocage_initiales_" + LocalDate.now() + ".csv";
exportHistoryService.enregistrerExport(TypeExport.FLOCAGE_INITIALES, filename, csvContent, compterElementsCsv(csvContent), saisonActive, getCurrentUser());
byte[] csvBytes = csvContent.getBytes(java.nio.charset.StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
return new ResponseEntity<>(csvBytes, headers, org.springframework.http.HttpStatus.OK);
}
@GetMapping("/admin/equipements/export-flocage-prenom-numero")
public ResponseEntity<byte[]> exportFlocagePrenomNumero() {
Saison saisonActive = saisonRepository.findByEstActiveTrue()
.orElseThrow(() -> new IllegalStateException("Aucune saison active"));
String csvContent = dotationService.genererCsvFlocagePrenomNumero(saisonActive);
String filename = "flocage_prenom_numero_" + LocalDate.now() + ".csv";
exportHistoryService.enregistrerExport(TypeExport.FLOCAGE_PRENOM_NUMERO, filename, csvContent, compterElementsCsv(csvContent), saisonActive, getCurrentUser());
byte[] csvBytes = csvContent.getBytes(java.nio.charset.StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
return new ResponseEntity<>(csvBytes, headers, org.springframework.http.HttpStatus.OK);
}
@GetMapping("/admin/exports/historique")
public String historiqueExports(@RequestParam(required = false) Long saisonId, Model model) {
List<Saison> saisons = saisonRepository.findAll();
Saison saisonFiltre = null;
if (saisonId != null) {
saisonFiltre = saisonRepository.findById(saisonId).orElse(null);
}
List<ExportHistory> historique = exportHistoryService.obtenirHistoriqueParSaison(saisonFiltre);
model.addAttribute("historique", historique);
model.addAttribute("saisons", saisons);
model.addAttribute("saisonId", saisonId);
return "parametrage/export_history";
}
@GetMapping("/admin/exports/{id}/download")
public ResponseEntity<byte[]> downloadExport(@PathVariable Long id) {
ExportHistory history = exportHistoryService.trouverParId(id)
.orElseThrow(() -> new IllegalArgumentException("Export introuvable ID: " + id));
byte[] csvBytes = history.getContenu().getBytes(java.nio.charset.StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", history.getNomFichier());
headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
return new ResponseEntity<>(csvBytes, headers, org.springframework.http.HttpStatus.OK);
}
@GetMapping("/admin/exports/{id}/apercu")
@ResponseBody
public ResponseEntity<Map<String, Object>> apercuExport(@PathVariable Long id) {
ExportHistory history = exportHistoryService.trouverParId(id)
.orElseThrow(() -> new IllegalArgumentException("Export introuvable ID: " + id));
String content = history.getContenu();
if (content.startsWith("\ufeff")) {
content = content.substring(1);
}
String[] lines = content.split("\n");
List<String> headers = new ArrayList<>();
List<List<String>> rows = new ArrayList<>();
if (lines.length > 0) {
headers = Arrays.asList(lines[0].split(";"));
for (int i = 1; i < lines.length; i++) {
if (!lines[i].trim().isEmpty()) {
rows.add(Arrays.asList(lines[i].split(";", -1)));
}
}
}
Map<String, Object> response = new HashMap<>();
response.put("id", history.getId());
response.put("typeExport", history.getTypeExport().getLibelle());
response.put("nomFichier", history.getNomFichier());
response.put("dateExport", history.getDateExport().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")));
response.put("headers", headers);
response.put("rows", rows);
return ResponseEntity.ok(response);
}
@PostMapping("/dotations/{id}")
public String updateDotation(
@PathVariable Long id,
@@ -63,6 +63,17 @@ public class EquipeController {
return "redirect:/equipes";
}
@PostMapping("/equipes/{id}/update")
public String updateEquipe(@PathVariable Long id, @RequestParam String nom) {
Equipe equipe = equipeRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Équipe invalide : " + id));
if (nom != null && !nom.trim().isEmpty()) {
equipe.setNom(nom.trim());
equipeRepository.save(equipe);
}
return "redirect:/equipes";
}
@PostMapping("/equipes/{id}/delete")
public String deleteEquipe(@PathVariable Long id) {
Equipe equipe = equipeRepository.findById(id)
@@ -77,8 +77,13 @@ public class LicenceController {
licence.setTypeDemande(typeDemande);
licence.setTypeLicence(typeLicence);
licence.setCommentaire(commentaire);
licence.setReductionEducateur(Boolean.TRUE.equals(reductionEducateur));
licence.setPourcentageReductionEducateur(pourcentageReductionEducateur != null ? pourcentageReductionEducateur : 100);
if (isUserAdmin()) {
licence.setReductionEducateur(Boolean.TRUE.equals(reductionEducateur));
licence.setPourcentageReductionEducateur(pourcentageReductionEducateur != null ? pourcentageReductionEducateur : 100);
} else {
licence.setReductionEducateur(false);
licence.setPourcentageReductionEducateur(100);
}
if (equipeId != null) {
Equipe equipe = equipeRepository.findById(equipeId)
@@ -120,8 +125,10 @@ public class LicenceController {
licence.setTypeDemande(typeDemande);
licence.setTypeLicence(typeLicence);
licence.setCommentaire(commentaire);
licence.setReductionEducateur(Boolean.TRUE.equals(reductionEducateur));
licence.setPourcentageReductionEducateur(pourcentageReductionEducateur != null ? pourcentageReductionEducateur : 100);
if (isUserAdmin()) {
licence.setReductionEducateur(Boolean.TRUE.equals(reductionEducateur));
licence.setPourcentageReductionEducateur(pourcentageReductionEducateur != null ? pourcentageReductionEducateur : 100);
}
if (equipeId != null) {
Equipe equipe = equipeRepository.findById(equipeId)
@@ -270,4 +277,10 @@ public class LicenceController {
return cb.and(predicates.toArray(new jakarta.persistence.criteria.Predicate[0]));
};
}
private boolean isUserAdmin() {
org.springframework.security.core.Authentication auth = org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
return auth != null && auth.getAuthorities().stream()
.anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN") || a.getAuthority().equals("ADMIN"));
}
}
@@ -52,6 +52,7 @@ public class PaiementController {
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate datePaiement,
@RequestParam Long modePaiementId,
@RequestParam(required = false) String numeroCheque,
@RequestParam(required = false, defaultValue = "true") Boolean remis,
@RequestParam(required = false) String commentaire,
Principal principal) {
@@ -60,11 +61,12 @@ public class PaiementController {
ModePaiement mode = modePaiementRepository.findById(modePaiementId)
.orElseThrow(() -> new IllegalArgumentException("Invalid ModePaiement ID"));
log.info(">>> [PaiementController] Demande de création de paiement reçue pour Licence ID: {}, Adhérent ID: {}, Montant: {} €", id, adherentId, montant);
log.info(">>> [PaiementController] Demande de création de paiement reçue pour Licence ID: {}, Adhérent ID: {}, Montant: {} €, Remis: {}", id, adherentId, montant, remis);
// Validation basique pour ne pas payer plus que le reste à payer
if (montant.compareTo(licence.getResteAPayer()) > 0) {
montant = licence.getResteAPayer();
// Validation pour ne pas dépasser le tarif global (tous paiements remis ou non inclus)
BigDecimal maxAutorise = licence.getSoldeRestantEngage();
if (montant.compareTo(maxAutorise) > 0) {
montant = maxAutorise;
}
if (montant.compareTo(BigDecimal.ZERO) > 0) {
@@ -75,6 +77,7 @@ public class PaiementController {
paiement.setDatePaiement(datePaiement);
paiement.setNumeroCheque(numeroCheque);
paiement.setCommentaire(commentaire);
paiement.setRemis(Boolean.TRUE.equals(remis));
if (principal != null) {
paiement.setGestionnaire(principal.getName());
}
@@ -88,7 +91,7 @@ public class PaiementController {
auditLog.setPaiementId(paiement.getId());
auditLog.setMontant(montant);
auditLog.setAdherentNomComplet(licence.getAdherent().getNom() + " " + licence.getAdherent().getPrenom());
auditLog.setDetails("Création d'un paiement de " + montant + "€ via " + mode.getNom() + " pour la licence " + (licence.getNumeroLicence() != null ? licence.getNumeroLicence() : "sans numéro"));
auditLog.setDetails("Création d'un paiement de " + montant + "€ via " + mode.getNom() + " (Remis: " + (Boolean.TRUE.equals(remis) ? "Oui" : "Non") + ") pour la licence " + (licence.getNumeroLicence() != null ? licence.getNumeroLicence() : "sans numéro"));
auditLogPaiementRepository.save(auditLog);
try {
@@ -109,6 +112,7 @@ public class PaiementController {
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate datePaiement,
@RequestParam Long modePaiementId,
@RequestParam(required = false) String numeroCheque,
@RequestParam(required = false, defaultValue = "true") Boolean remis,
@RequestParam(required = false) String commentaire,
@RequestParam(required = false) String redirect,
Principal principal) {
@@ -121,11 +125,12 @@ public class PaiementController {
BigDecimal ancienMontant = paiement.getMontant();
String ancienMode = paiement.getModePaiement().getNom();
Boolean ancienRemis = paiement.getRemis();
Licence licence = paiement.getLicence();
// Validation basique pour ne pas dépasser le montant total de la licence
BigDecimal maxAmount = licence.getResteAPayer().add(paiement.getMontant());
// Validation pour ne pas dépasser le tarif global (tous paiements remis ou non inclus)
BigDecimal maxAmount = licence.getSoldeRestantEngage().add(paiement.getMontant());
if (montant.compareTo(maxAmount) > 0) {
montant = maxAmount;
}
@@ -136,6 +141,7 @@ public class PaiementController {
paiement.setDatePaiement(datePaiement);
paiement.setNumeroCheque(numeroCheque);
paiement.setCommentaire(commentaire);
paiement.setRemis(Boolean.TRUE.equals(remis));
if (principal != null) {
paiement.setGestionnaire(principal.getName());
}
@@ -147,8 +153,18 @@ public class PaiementController {
auditLog.setPaiementId(paiement.getId());
auditLog.setMontant(montant);
auditLog.setAdherentNomComplet(licence.getAdherent().getNom() + " " + licence.getAdherent().getPrenom());
auditLog.setDetails("Modification du paiement: montant " + ancienMontant + "€ -> " + montant + "€, mode " + ancienMode + " -> " + mode.getNom());
auditLog.setDetails("Modification du paiement: montant " + ancienMontant + "€ -> " + montant + "€, mode " + ancienMode + " -> " + mode.getNom() + ", remis -> " + (Boolean.TRUE.equals(remis) ? "Oui" : "Non"));
auditLogPaiementRepository.save(auditLog);
// Si le paiement passe de non remis (ex: Chèque Sport mairie) à remis (Oui), envoyer l'email de confirmation
if (Boolean.FALSE.equals(ancienRemis) && Boolean.TRUE.equals(remis)) {
try {
log.info("Appel de sendPaiementConfirmation depuis updatePaiement (passage de remis=false à remis=true) pour le paiement ID: {}", paiement.getId());
paiementEmailService.sendPaiementConfirmation(paiement);
} catch (Exception e) {
log.error("Erreur lors de l'envoi de l'e-mail de confirmation après la remise du paiement ID {}: ", id, e);
}
}
}
if (redirect != null && !redirect.isEmpty()) {
@@ -7,6 +7,7 @@ import com.astalange.core.repository.EducateurRepository;
import com.astalange.core.repository.EquipeRepository;
import com.astalange.core.repository.SaisonRepository;
import com.astalange.core.repository.TerrainRepository;
import com.astalange.core.service.PlanningEmailService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
@@ -25,19 +26,22 @@ public class PlanningController {
private final SaisonRepository saisonRepository;
private final EquipeRepository equipeRepository;
private final EducateurRepository educateurRepository;
private final PlanningEmailService planningEmailService;
public PlanningController(CreneauEntrainementRepository creneauRepository,
TerrainRepository terrainRepository,
CategorieRepository categorieRepository,
SaisonRepository saisonRepository,
EquipeRepository equipeRepository,
EducateurRepository educateurRepository) {
EducateurRepository educateurRepository,
PlanningEmailService planningEmailService) {
this.creneauRepository = creneauRepository;
this.terrainRepository = terrainRepository;
this.categorieRepository = categorieRepository;
this.saisonRepository = saisonRepository;
this.equipeRepository = equipeRepository;
this.educateurRepository = educateurRepository;
this.planningEmailService = planningEmailService;
}
@GetMapping
@@ -202,4 +206,16 @@ public class PlanningController {
redirectAttributes.addFlashAttribute("success", "Créneau d'entraînement supprimé avec succès.");
return "redirect:/planning?jour=" + jour.name();
}
@PostMapping("/envoyer-educateurs")
public String envoyerPlanningEducateurs(@RequestParam(required = false) JourSemaine jour, RedirectAttributes redirectAttributes) {
int count = planningEmailService.sendPlanningGlobalToEducateurs();
if (count > 0) {
redirectAttributes.addFlashAttribute("success", "Le planning global de la semaine a été envoyé par e-mail à " + count + " éducateur(s).");
} else {
redirectAttributes.addFlashAttribute("error", "Aucun e-mail n'a pu être envoyé. Vérifiez qu'une saison est active et que des éducateurs possèdent un e-mail valide.");
}
String returnJour = (jour != null) ? jour.name() : "LUNDI";
return "redirect:/planning?jour=" + returnJour;
}
}
@@ -81,7 +81,7 @@ public class PublicInscriptionController {
TokenPreInscription token = new TokenPreInscription();
token.setValeurUuid(UUID.randomUUID().toString());
token.setDateExpiration(LocalDateTime.now().plusMinutes(15));
token.setDateExpiration(LocalDateTime.now().plusMinutes(30));
tokenRepository.save(token);
return "redirect:/inscription-public/formulaire?token=" + token.getValeurUuid();
@@ -135,6 +135,20 @@ public class PublicInscriptionController {
return "redirect:/inscription-public/demarrer";
}
// Nettoyage défensif des champs non applicables
if ("RENOUVELLEMENT".equals(preInscription.getTypeDemande())) {
preInscription.setAncienClub(null);
preInscription.setRaisonChangementClub(null);
preInscription.setAncienneCategorie(null);
preInscription.setCommentConnuClub(null);
}
if (preInscription.getDateNaissance() != null) {
int age = java.time.Period.between(preInscription.getDateNaissance(), java.time.LocalDate.now()).getYears();
if (age >= 18) {
preInscription.setRepresentantLegal(null);
}
}
// Sauvegarde de la pré-inscription
preInscription.setSaison(activeSaison);
preInscription.setStatutTraite(false);
@@ -10,6 +10,8 @@
body { font-family: 'Inter', sans-serif; }
.hidden-block { display: none; }
</style>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
</head>
<body class="bg-gray-50 text-gray-900 flex h-screen overflow-hidden">
@@ -271,15 +273,20 @@
th:text="${lic.etat}">Brouillon</span>
</td>
<td class="py-4 px-4 font-medium cell-tarif-global">
<div th:if="${lic.reductionEducateur}" class="flex flex-col">
<span class="text-[10px] font-bold text-amber-700 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-full inline-block w-max mb-0.5"
th:text="'Éducateur (-' + ${lic.pourcentageReductionEducateur != null ? lic.pourcentageReductionEducateur : 100} + '%)'">Éducateur (-100%)</span>
<div class="flex items-center space-x-1 text-xs">
<span th:if="${lic.getPrixBrut().compareTo(lic.getPrixTotal()) != 0}" class="line-through text-gray-400" th:text="${lic.getPrixBrut() + ' €'}">150.00 €</span>
<span class="text-gray-900 font-bold" th:text="${lic.getPrixTotal() + ' €'}">0.00 €</span>
<div sec:authorize="hasRole('ROLE_ADMIN')">
<div th:if="${lic.reductionEducateur}" class="flex flex-col">
<span class="text-[10px] font-bold text-amber-700 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-full inline-block w-max mb-0.5"
th:text="'Éducateur (-' + ${lic.pourcentageReductionEducateur != null ? lic.pourcentageReductionEducateur : 100} + '%)'">Éducateur (-100%)</span>
<div class="flex items-center space-x-1 text-xs">
<span th:if="${lic.getPrixBrut().compareTo(lic.getPrixTotal()) != 0}" class="line-through text-gray-400" th:text="${lic.getPrixBrut() + ' €'}">150.00 €</span>
<span class="text-gray-900 font-bold" th:text="${lic.getPrixTotal() + ' €'}">0.00 €</span>
</div>
</div>
<div th:if="${!lic.reductionEducateur}">
<span class="text-gray-900" th:text="${lic.getPrixTotal() + ' €'}">130.00 €</span>
</div>
</div>
<div th:if="${!lic.reductionEducateur}">
<div sec:authorize="!hasRole('ROLE_ADMIN')">
<span class="text-gray-900" th:text="${lic.getPrixTotal() + ' €'}">130.00 €</span>
</div>
</td>
@@ -300,12 +307,21 @@
th:data-pourcentage-reduction="${lic.pourcentageReductionEducateur != null ? lic.pourcentageReductionEducateur : 100}"
onclick="openLicenceModal(this.getAttribute('data-licence-id'), this.getAttribute('data-categorie-id'), this.getAttribute('data-numero-licence'), this.getAttribute('data-etat'), this.getAttribute('data-type-demande'), this.getAttribute('data-type-licence'), this.getAttribute('data-equipe-id'), this.getAttribute('data-commentaire'), this.getAttribute('data-reduction-educateur'), this.getAttribute('data-pourcentage-reduction'))"
class="text-blue-600 hover:text-blue-800 font-medium bg-blue-50 px-3 py-1 rounded-lg">Modifier</button>
<button th:if="${lic.getResteAPayer().compareTo(T(java.math.BigDecimal).ZERO) > 0}"
<button th:if="${lic.getSoldeRestantEngage().compareTo(T(java.math.BigDecimal).ZERO) > 0}"
type="button"
th:data-licence-id="${lic.id}"
th:data-reste-a-payer="${lic.getResteAPayer()}"
onclick="openPaiementModal(this.getAttribute('data-licence-id'), this.getAttribute('data-reste-a-payer'))"
th:data-solde-restant="${lic.getSoldeRestantEngage()}"
onclick="openPaiementModal(this.getAttribute('data-licence-id'), this.getAttribute('data-solde-restant'))"
class="text-green-600 hover:text-green-800 font-medium bg-green-50 px-3 py-1 rounded-lg btn-payer">Payer</button>
<span th:if="${lic.getResteAPayer().compareTo(T(java.math.BigDecimal).ZERO) > 0}" th:id="'relance-licence-container-' + ${lic.id}">
<button type="button"
th:attr="hx-post=@{/adherents/{id}/relancer-paiement-htmx(id=${adherent.id})}, hx-target=|#relance-licence-container-${lic.id}|"
hx-swap="innerHTML"
class="text-amber-700 hover:text-amber-900 font-medium bg-amber-50 hover:bg-amber-100 border border-amber-200 px-3 py-1 rounded-lg inline-flex items-center gap-1.5 transition-colors cursor-pointer" title="Envoyer un e-mail de relance pour la cotisation impayée">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 002-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
Relancer
</button>
</span>
</td>
</tr>
<tr th:if="${!#lists.isEmpty(lic.paiements)}" class="bg-gray-50/50">
@@ -328,6 +344,7 @@
<td class="py-2 px-3 text-gray-600 font-medium" th:text="${#temporals.format(paiement.datePaiement, 'dd/MM/yyyy')}">01/01/2026</td>
<td class="py-2 px-3 text-gray-600">
<span class="px-2 py-0.5 rounded bg-gray-100 text-gray-700 font-mono text-[10px]" th:text="${paiement.modePaiement.nom}">Chèque</span>
<span th:if="${paiement.remis == false}" class="px-1.5 py-0.5 rounded bg-amber-100 text-amber-800 text-[10px] font-semibold ml-1" title="Montant non encore déduit du solde">Non remis</span>
</td>
<td class="py-2 px-3 text-gray-500 text-xs">
<div th:if="${paiement.numeroCheque != null and !paiement.numeroCheque.isEmpty()}" class="text-[10px]">
@@ -355,10 +372,11 @@
th:data-date="${paiement.datePaiement}"
th:data-mode-id="${paiement.modePaiement.id}"
th:data-licence-id="${lic.id}"
th:data-max-amount="${lic.getResteAPayer().add(paiement.montant)}"
th:data-max-amount="${lic.getSoldeRestantEngage().add(paiement.montant)}"
th:data-cheque="${paiement.numeroCheque}"
th:data-commentaire="${paiement.commentaire}"
onclick="openEditPaiementModal(this.getAttribute('data-paiement-id'), this.getAttribute('data-montant'), this.getAttribute('data-date'), this.getAttribute('data-mode-id'), this.getAttribute('data-licence-id'), this.getAttribute('data-max-amount'), this.getAttribute('data-cheque'), this.getAttribute('data-commentaire'))"
th:data-remis="${paiement.remis}"
onclick="openEditPaiementModal(this.getAttribute('data-paiement-id'), this.getAttribute('data-montant'), this.getAttribute('data-date'), this.getAttribute('data-mode-id'), this.getAttribute('data-licence-id'), this.getAttribute('data-max-amount'), this.getAttribute('data-cheque'), this.getAttribute('data-commentaire'), this.getAttribute('data-remis'))"
class="text-blue-600 hover:text-blue-900 bg-blue-50 hover:bg-blue-100 p-1.5 rounded transition-colors inline-flex items-center"
title="Modifier">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -568,7 +586,7 @@
<label class="block text-sm font-medium text-gray-700 mb-1">Commentaire</label>
<textarea id="licenceCommentaireInput" name="commentaire" rows="3" class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" placeholder="Commentaire optionnel..."></textarea>
</div>
<div class="bg-amber-50 p-3 rounded-lg border border-amber-200">
<div sec:authorize="hasRole('ROLE_ADMIN')" class="bg-amber-50 p-3 rounded-lg border border-amber-200">
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input type="checkbox" id="reductionEducateurInput" name="reductionEducateur" value="true" onchange="toggleReductionPourcentageVisibility()" class="w-4 h-4 text-amber-600 border-gray-300 rounded focus:ring-amber-500">
<span class="text-sm font-semibold text-amber-900">Enfant d'éducateur / Réduction</span>
@@ -608,7 +626,7 @@
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Mode de paiement</label>
<select id="addPaiementMode" name="modePaiementId" required class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" onchange="toggleChequeVisibility(this, 'addChequeBlock', 'addNumeroCheque')">
<select id="addPaiementMode" name="modePaiementId" required class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" onchange="toggleChequeVisibility(this, 'addChequeBlock', 'addNumeroCheque', 'addRemisBlock', 'addRemisOui', 'addRemisNon')">
<option value="">Sélectionnez un mode...</option>
<option th:each="mode : ${modesPaiement}" th:value="${mode.id}" th:data-nom="${#strings.toLowerCase(mode.nom)}" th:text="${mode.nom}"></option>
</select>
@@ -617,6 +635,20 @@
<label class="block text-sm font-medium text-gray-700 mb-1">Numéro du chèque <span class="text-red-500">*</span></label>
<input type="text" id="addNumeroCheque" name="numeroCheque" class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<div id="addRemisBlock" class="hidden bg-amber-50 p-3 rounded-lg border border-amber-200">
<label class="block text-xs font-semibold text-amber-900 mb-1.5">Remis / Encaissé ?</label>
<div class="flex items-center space-x-6">
<label class="flex items-center space-x-1.5 cursor-pointer text-sm text-gray-700">
<input type="radio" id="addRemisOui" name="remis" value="true" class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500">
<span>Oui</span>
</label>
<label class="flex items-center space-x-1.5 cursor-pointer text-sm text-gray-700">
<input type="radio" id="addRemisNon" name="remis" value="false" checked class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500">
<span>Non</span>
</label>
</div>
<p class="text-[11px] text-amber-700 mt-1">Si "Non", cette somme reste à payer.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Commentaire (facultatif)</label>
<textarea id="addCommentaire" name="commentaire" rows="2" class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none"></textarea>
@@ -648,7 +680,7 @@
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Mode de paiement</label>
<select id="editPaiementMode" name="modePaiementId" required class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" onchange="toggleChequeVisibility(this, 'editChequeBlock', 'editNumeroCheque')">
<select id="editPaiementMode" name="modePaiementId" required class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" onchange="toggleChequeVisibility(this, 'editChequeBlock', 'editNumeroCheque', 'editRemisBlock', 'editRemisOui', 'editRemisNon', true)">
<option value="">Sélectionnez un mode...</option>
<option th:each="mode : ${modesPaiement}" th:value="${mode.id}" th:data-nom="${#strings.toLowerCase(mode.nom)}" th:text="${mode.nom}"></option>
</select>
@@ -657,6 +689,20 @@
<label class="block text-sm font-medium text-gray-700 mb-1">Numéro du chèque <span class="text-red-500">*</span></label>
<input type="text" id="editNumeroCheque" name="numeroCheque" class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<div id="editRemisBlock" class="hidden bg-amber-50 p-3 rounded-lg border border-amber-200">
<label class="block text-xs font-semibold text-amber-900 mb-1.5">Remis / Encaissé ?</label>
<div class="flex items-center space-x-6">
<label class="flex items-center space-x-1.5 cursor-pointer text-sm text-gray-700">
<input type="radio" id="editRemisOui" name="remis" value="true" class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500">
<span>Oui</span>
</label>
<label class="flex items-center space-x-1.5 cursor-pointer text-sm text-gray-700">
<input type="radio" id="editRemisNon" name="remis" value="false" class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500">
<span>Non</span>
</label>
</div>
<p class="text-[11px] text-amber-700 mt-1">Si "Non", cette somme reste à payer.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Commentaire (facultatif)</label>
<textarea id="editCommentaire" name="commentaire" rows="2" class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none"></textarea>
@@ -800,12 +846,15 @@
document.getElementById('paiementMontant').value = maxAmount;
document.getElementById('paiementMontant').max = maxAmount;
document.getElementById('paiementDate').valueAsDate = new Date();
document.getElementById('addPaiementMode').value = '';
document.getElementById('addRemisNon').checked = true;
toggleChequeVisibility(document.getElementById('addPaiementMode'), 'addChequeBlock', 'addNumeroCheque', 'addRemisBlock', 'addRemisOui', 'addRemisNon');
}
function closePaiementModal() {
document.getElementById('paiementModal').classList.add('hidden');
}
function openEditPaiementModal(paiementId, montant, date, modePaiementId, licenceId, maxAmount, numeroCheque, commentaire) {
function openEditPaiementModal(paiementId, montant, date, modePaiementId, licenceId, maxAmount, numeroCheque, commentaire, remis) {
document.getElementById('editPaiementModal').classList.remove('hidden');
document.getElementById('editPaiementForm').action = '/paiements/' + paiementId + '/update';
document.getElementById('editPaiementMontant').value = montant;
@@ -814,18 +863,34 @@
document.getElementById('editPaiementMode').value = modePaiementId;
document.getElementById('editNumeroCheque').value = numeroCheque || '';
document.getElementById('editCommentaire').value = commentaire || '';
toggleChequeVisibility(document.getElementById('editPaiementMode'), 'editChequeBlock', 'editNumeroCheque');
const isRemis = (remis === true || remis === 'true' || remis === null || remis === '');
if (isRemis) {
document.getElementById('editRemisOui').checked = true;
} else {
document.getElementById('editRemisNon').checked = true;
}
toggleChequeVisibility(document.getElementById('editPaiementMode'), 'editChequeBlock', 'editNumeroCheque', 'editRemisBlock', 'editRemisOui', 'editRemisNon', true);
}
function closeEditPaiementModal() {
document.getElementById('editPaiementModal').classList.add('hidden');
}
function toggleChequeVisibility(selectElement, blockId, inputId) {
function toggleChequeVisibility(selectElement, blockId, inputId, remisBlockId, remisOuiId, remisNonId, isEdit = false) {
const block = document.getElementById(blockId);
const input = document.getElementById(inputId);
const remisBlock = remisBlockId ? document.getElementById(remisBlockId) : null;
const remisOui = remisOuiId ? document.getElementById(remisOuiId) : null;
const remisNon = remisNonId ? document.getElementById(remisNonId) : null;
const selectedOption = selectElement.options[selectElement.selectedIndex];
if (selectedOption && selectedOption.getAttribute('data-nom') && selectedOption.getAttribute('data-nom').includes('chèque')) {
const dataNom = selectedOption ? (selectedOption.getAttribute('data-nom') || selectedOption.textContent || '').toLowerCase().trim() : '';
const isChequeSportMairie = dataNom.includes('mairie') || dataNom.includes('chèque sport') || dataNom.includes('cheque sport');
const isStandardCheque = dataNom.includes('chèque') && !isChequeSportMairie;
if (isStandardCheque) {
block.classList.remove('hidden');
input.required = true;
} else {
@@ -833,6 +898,14 @@
input.required = false;
input.value = '';
}
if (isChequeSportMairie) {
if (remisBlock) remisBlock.classList.remove('hidden');
if (!isEdit && remisNon) remisNon.checked = true;
} else {
if (remisBlock) remisBlock.classList.add('hidden');
if (remisOui) remisOui.checked = true;
}
}
document.addEventListener("DOMContentLoaded", function() {
const dateInput = document.getElementById('dateNaissance');
@@ -1081,6 +1154,14 @@
if (typeMaillotSelect) {
typeMaillotSelect.addEventListener('change', updateEquipmentStyleLabels);
}
document.body.addEventListener('htmx:configRequest', function(evt) {
var csrfHeader = document.querySelector('meta[name="_csrf_header"]');
var csrfToken = document.querySelector('meta[name="_csrf"]');
if (csrfHeader && csrfToken) {
evt.detail.headers[csrfHeader.content] = csrfToken.content;
}
});
});
</script>
</body>
@@ -9,6 +9,8 @@
<style>
body { font-family: 'Inter', sans-serif; }
</style>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
</head>
<body class="bg-gray-50 text-gray-900 flex h-screen overflow-hidden">
@@ -200,23 +202,47 @@
<!-- Équipements Column -->
<td class="py-3 px-4 text-center">
<div th:with="choisis=${adherent.getLicenceActuelle() != null ? adherent.getLicenceActuelle().dotations.?[choisi == true] : null}">
<div th:if="${choisis != null and !#lists.isEmpty(choisis)}" class="flex flex-col items-center space-y-1">
<span class="px-2 py-0.5 text-[9px] font-bold rounded-full border uppercase tracking-wider"
th:with="total=${#lists.size(choisis)},
fournis=${#lists.size(choisis.?[fourni == true])}"
th:classappend="${fournis == total ? 'bg-emerald-100 text-emerald-800 border-emerald-200' : (fournis > 0 ? 'bg-amber-100 text-amber-800 border-amber-200' : 'bg-rose-100 text-rose-800 border-rose-200')}"
th:text="${fournis == total ? '🟢 Complet (' + fournis + '/' + total + ')' : (fournis > 0 ? '🟠 Partiel (' + fournis + '/' + total + ')' : '🔴 Non fourni (0/' + total + ')')}"
>
Complet (3/3)
</span>
<div class="flex flex-wrap justify-center gap-1 max-w-[190px]">
<span th:each="dot : ${choisis}"
class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium border"
th:classappend="${dot.fourni ? 'bg-green-50 text-green-700 border-green-200' : 'bg-gray-50 text-gray-500 border-gray-200'}"
th:title="${(dot.equipement != null ? dot.equipement.nom : '') + (dot.taille != null and !dot.taille.isEmpty() ? ' (' + dot.taille + ')' : '') + ' : ' + (dot.fourni ? 'Fourni' : 'Non fourni')}">
<span class="mr-0.5" th:text="${dot.fourni ? '✓' : '✗'}"></span>
<span th:text="${dot.equipement != null ? dot.equipement.nom : 'Équipement'}">Maillot</span>
<div th:if="${choisis != null and !#lists.isEmpty(choisis)}" class="relative inline-block text-left">
<button type="button"
class="px-2.5 py-1 text-[9px] font-bold rounded-full border uppercase tracking-wider cursor-pointer hover:ring-2 hover:ring-offset-1 hover:ring-indigo-300 transition-all flex items-center space-x-1 mx-auto"
th:with="total=${#lists.size(choisis)},
fournis=${#lists.size(choisis.?[fourni == true])}"
th:classappend="${fournis == total ? 'bg-emerald-100 text-emerald-800 border-emerald-200' : (fournis > 0 ? 'bg-amber-100 text-amber-800 border-amber-200' : 'bg-rose-100 text-rose-800 border-rose-200')}"
onclick="toggleEquipementsPopover(this, event)">
<span th:text="${fournis == total ? '🟢 Complet (' + fournis + '/' + total + ')' : (fournis > 0 ? '🟠 Partiel (' + fournis + '/' + total + ')' : '🔴 Non fourni (0/' + total + ')')}"
th:data-total="${total}" th:data-fournis="${fournis}">
Complet (3/3)
</span>
<svg class="w-3 h-3 text-current opacity-70" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
</button>
<!-- Popover dropdown -->
<div class="hidden absolute left-1/2 -translate-x-1/2 mt-2 w-64 bg-white rounded-xl shadow-xl border border-gray-200 p-3 z-50 text-left transition-all equipement-popover">
<div class="flex items-center justify-between pb-2 mb-2 border-b border-gray-100">
<span class="text-xs font-semibold text-gray-800 flex items-center space-x-1">
<span>Détail Équipements</span>
<span class="text-[10px] font-bold text-gray-500 bg-gray-100 px-1.5 py-0.5 rounded-full" th:text="${#lists.size(choisis.?[fourni == true]) + '/' + #lists.size(choisis)}">3/3</span>
</span>
<button type="button" class="text-gray-400 hover:text-gray-600 text-xs font-bold px-1" onclick="closeAllEquipementPopovers()">&times;</button>
</div>
<div class="space-y-1.5 max-h-48 overflow-y-auto pr-0.5">
<div th:each="dot : ${choisis}"
class="flex items-center justify-between p-2 rounded-lg text-xs border"
th:classappend="${dot.fourni ? 'bg-emerald-50/60 border-emerald-100 text-emerald-900' : 'bg-gray-50 border-gray-200 text-gray-700'}">
<div class="flex flex-col">
<span class="font-medium text-gray-900 leading-tight" th:text="${dot.equipement != null ? dot.equipement.nom : 'Équipement'}">Maillot</span>
<div class="text-[10px] text-gray-500 flex flex-wrap items-center gap-1 mt-0.5" th:if="${(dot.taille != null and !dot.taille.isEmpty()) or (dot.flocage != null and !dot.flocage.isEmpty()) or (dot.numero != null and !dot.numero.isEmpty())}">
<span th:if="${dot.taille != null and !dot.taille.isEmpty()}" class="font-mono bg-white/80 px-1 py-0.2 rounded border border-gray-200" th:text="'Taille: ' + ${dot.taille}">Taille: M</span>
<span th:if="${dot.flocage != null and !dot.flocage.isEmpty()}" class="italic" th:text="${dot.flocage}">Flocage</span>
<span th:if="${dot.numero != null and !dot.numero.isEmpty()}" class="font-mono font-bold" th:text="'#' + ${dot.numero}">#10</span>
</div>
</div>
<span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-bold flex-shrink-0"
th:classappend="${dot.fourni ? 'bg-emerald-100 text-emerald-800' : 'bg-gray-200 text-gray-600'}">
<span th:text="${dot.fourni ? '✓ Fourni' : '✗ Non fourni'}">✓ Fourni</span>
</span>
</div>
</div>
</div>
</div>
<div th:if="${choisis == null or #lists.isEmpty(choisis)}" class="text-xs text-gray-400 italic">
@@ -255,6 +281,16 @@
<span class="font-bold" th:classappend="${adherent.getLicenceActuelle().getResteAPayer().compareTo(T(java.math.BigDecimal).ZERO) == 0 ? 'text-gray-800' : 'text-red-600'}" th:text="|${adherent.getLicenceActuelle().getResteAPayer()} €|">50 €</span>
</div>
</div>
<!-- Bouton Relancer Solde -->
<div th:if="${adherent.getLicenceActuelle().getResteAPayer().compareTo(T(java.math.BigDecimal).ZERO) > 0}" class="mt-1 text-center" th:id="'relance-paiement-container-' + ${adherent.id}">
<button type="button"
th:attr="hx-post=@{/adherents/{id}/relancer-paiement-htmx(id=${adherent.id})}, hx-target=|#relance-paiement-container-${adherent.id}|"
hx-swap="innerHTML"
class="text-[10px] text-amber-700 hover:text-amber-900 bg-amber-50 hover:bg-amber-100 border border-amber-200 px-2 py-0.5 rounded transition-colors inline-flex items-center gap-1 font-medium">
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 002-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
Relancer
</button>
</div>
</div>
</td>
<!-- SportEasy Status Column -->
@@ -371,6 +407,34 @@
}
sf.dispatchEvent(new Event('change', { bubbles: true }));
}
function toggleEquipementsPopover(btn, event) {
if (event) event.stopPropagation();
const popover = btn.nextElementSibling;
const isVisible = popover && !popover.classList.contains('hidden');
closeAllEquipementPopovers();
if (popover && !isVisible) {
popover.classList.remove('hidden');
}
}
function closeAllEquipementPopovers() {
document.querySelectorAll('.equipement-popover').forEach(p => p.classList.add('hidden'));
}
document.addEventListener('click', function(event) {
if (!event.target.closest('.equipement-popover')) {
closeAllEquipementPopovers();
}
});
document.body.addEventListener('htmx:configRequest', function(evt) {
var csrfHeader = document.querySelector('meta[name="_csrf_header"]');
var csrfToken = document.querySelector('meta[name="_csrf"]');
if (csrfHeader && csrfToken) {
evt.detail.headers[csrfHeader.content] = csrfToken.content;
}
});
</script>
</body>
</html>
@@ -30,6 +30,7 @@
<div class="pt-4 pb-2 px-3 text-xs font-semibold text-gray-400 uppercase tracking-wider">Recherches & Exports</div>
<a href="/admin/licences/recherche" th:classappend="${requestURI != null and requestURI.startsWith('/admin/licences/recherche') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}" class="block px-3 py-2 rounded-lg transition-colors">Recherche Licences</a>
<a href="/admin/equipements/recherche" th:classappend="${requestURI != null and requestURI.startsWith('/admin/equipements/recherche') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}" class="block px-3 py-2 rounded-lg transition-colors">Recherche Équipements</a>
<a href="/admin/exports/historique" th:classappend="${requestURI != null and requestURI.startsWith('/admin/exports/historique') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}" class="block px-3 py-2 rounded-lg transition-colors">Historique des Exports</a>
<!-- Paramétrage -->
<div class="pt-4 pb-2 px-3 text-xs font-semibold text-gray-400 uppercase tracking-wider">Paramétrage</div>
@@ -89,6 +89,7 @@
<td class="py-4 px-6 text-gray-600">
<span class="px-2 py-0.5 rounded border border-gray-200 bg-gray-50 text-gray-700 text-xs"
th:text="${p.modePaiement.nom}">Chèque</span>
<span th:if="${p.remis == false}" class="px-1.5 py-0.5 rounded bg-amber-100 text-amber-800 text-xs font-semibold ml-1">Non remis</span>
</td>
<td class="py-4 px-6 text-right font-semibold text-green-600" th:text="${p.montant + ' €'}">50.00 €</td>
<td class="py-4 px-6 text-right pr-6">
@@ -108,8 +109,10 @@
th:data-date="${p.datePaiement}"
th:data-mode-id="${p.modePaiement.id}"
th:data-licence-id="${p.licence.id}"
th:data-max-amount="${p.licence.getResteAPayer().add(p.montant)}"
onclick="openEditPaiementModal(this.getAttribute('data-paiement-id'), this.getAttribute('data-montant'), this.getAttribute('data-date'), this.getAttribute('data-mode-id'), this.getAttribute('data-licence-id'), this.getAttribute('data-max-amount'))"
th:data-max-amount="${p.licence.getSoldeRestantEngage().add(p.montant)}"
th:data-cheque="${p.numeroCheque}"
th:data-remis="${p.remis}"
onclick="openEditPaiementModal(this.getAttribute('data-paiement-id'), this.getAttribute('data-montant'), this.getAttribute('data-date'), this.getAttribute('data-mode-id'), this.getAttribute('data-licence-id'), this.getAttribute('data-max-amount'), this.getAttribute('data-cheque'), this.getAttribute('data-remis'))"
class="text-blue-600 hover:text-blue-900 bg-blue-50 hover:bg-blue-100 p-1.5 rounded transition-colors inline-flex items-center"
title="Modifier">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -212,11 +215,29 @@
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Mode de paiement</label>
<select id="editPaiementMode" name="modePaiementId" required class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
<select id="editPaiementMode" name="modePaiementId" required class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" onchange="toggleChequeVisibility(this, 'editChequeBlock', 'editNumeroCheque', 'editRemisBlock', 'editRemisOui', 'editRemisNon', true)">
<option value="">Sélectionnez un mode...</option>
<option th:each="mode : ${modesPaiement}" th:value="${mode.id}" th:text="${mode.nom}"></option>
<option th:each="mode : ${modesPaiement}" th:value="${mode.id}" th:data-nom="${#strings.toLowerCase(mode.nom)}" th:text="${mode.nom}"></option>
</select>
</div>
<div id="editChequeBlock" class="hidden">
<label class="block text-sm font-medium text-gray-700 mb-1">Numéro du chèque <span class="text-red-500">*</span></label>
<input type="text" id="editNumeroCheque" name="numeroCheque" class="w-full border border-gray-300 rounded-lg px-4 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
</div>
<div id="editRemisBlock" class="hidden bg-amber-50 p-3 rounded-lg border border-amber-200">
<label class="block text-xs font-semibold text-amber-900 mb-1.5">Remis / Encaissé ?</label>
<div class="flex items-center space-x-6">
<label class="flex items-center space-x-1.5 cursor-pointer text-sm text-gray-700">
<input type="radio" id="editRemisOui" name="remis" value="true" class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500">
<span>Oui</span>
</label>
<label class="flex items-center space-x-1.5 cursor-pointer text-sm text-gray-700">
<input type="radio" id="editRemisNon" name="remis" value="false" class="w-4 h-4 text-blue-600 border-gray-300 focus:ring-blue-500">
<span>Non</span>
</label>
</div>
<p class="text-[11px] text-amber-700 mt-1">Si "Non", cette somme reste à payer.</p>
</div>
<div class="items-center px-4 py-3 flex justify-end space-x-2">
<button type="button" onclick="closeEditPaiementModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">Annuler</button>
<button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700">Enregistrer</button>
@@ -227,17 +248,58 @@
</div>
<script>
function openEditPaiementModal(paiementId, montant, date, modePaiementId, licenceId, maxAmount) {
function openEditPaiementModal(paiementId, montant, date, modePaiementId, licenceId, maxAmount, numeroCheque, remis) {
document.getElementById('editPaiementModal').classList.remove('hidden');
document.getElementById('editPaiementForm').action = '/paiements/' + paiementId + '/update';
document.getElementById('editPaiementMontant').value = montant;
document.getElementById('editPaiementMontant').max = maxAmount;
document.getElementById('editPaiementDate').value = date;
document.getElementById('editPaiementMode').value = modePaiementId;
document.getElementById('editNumeroCheque').value = numeroCheque || '';
const isRemis = (remis === true || remis === 'true' || remis === null || remis === '');
if (isRemis) {
document.getElementById('editRemisOui').checked = true;
} else {
document.getElementById('editRemisNon').checked = true;
}
toggleChequeVisibility(document.getElementById('editPaiementMode'), 'editChequeBlock', 'editNumeroCheque', 'editRemisBlock', 'editRemisOui', 'editRemisNon', true);
}
function closeEditPaiementModal() {
document.getElementById('editPaiementModal').classList.add('hidden');
}
function toggleChequeVisibility(selectElement, blockId, inputId, remisBlockId, remisOuiId, remisNonId, isEdit = false) {
const block = document.getElementById(blockId);
const input = document.getElementById(inputId);
const remisBlock = remisBlockId ? document.getElementById(remisBlockId) : null;
const remisOui = remisOuiId ? document.getElementById(remisOuiId) : null;
const remisNon = remisNonId ? document.getElementById(remisNonId) : null;
const selectedOption = selectElement.options[selectElement.selectedIndex];
const dataNom = selectedOption ? (selectedOption.getAttribute('data-nom') || selectedOption.textContent || '').toLowerCase().trim() : '';
const isChequeSportMairie = dataNom.includes('mairie') || dataNom.includes('chèque sport') || dataNom.includes('cheque sport');
const isStandardCheque = dataNom.includes('chèque') && !isChequeSportMairie;
if (isStandardCheque) {
block.classList.remove('hidden');
input.required = true;
} else {
block.classList.add('hidden');
input.required = false;
input.value = '';
}
if (isChequeSportMairie) {
if (remisBlock) remisBlock.classList.remove('hidden');
if (!isEdit && remisNon) remisNon.checked = true;
} else {
if (remisBlock) remisBlock.classList.add('hidden');
if (remisOui) remisOui.checked = true;
}
}
</script>
</body>
</html>
@@ -31,16 +31,27 @@
<thead>
<tr class="bg-gray-50 text-gray-500 text-sm uppercase tracking-wider border-b border-gray-200">
<th class="py-3 px-6 font-medium text-left">Nom de l'équipement</th>
<th class="py-3 px-6 font-medium text-left">Référence</th>
<th class="py-3 px-6 font-medium text-left">Description</th>
<th class="py-3 px-6 font-medium text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200 text-sm">
<tr th:if="${#lists.isEmpty(equipements)}">
<td colspan="3" class="py-8 text-center text-gray-500">Aucun équipement n'est paramétré.</td>
<td colspan="4" class="py-8 text-center text-gray-500">Aucun équipement n'est paramétré.</td>
</tr>
<tr th:each="equip : ${equipements}" class="hover:bg-gray-50 transition-colors">
<td class="py-4 px-6 font-medium text-gray-900" th:text="${equip.nom}">Maillot</td>
<td class="py-4 px-6">
<span th:if="${equip.reference != null and !equip.reference.trim().isEmpty()}"
class="font-mono text-xs text-gray-700 bg-gray-100 border border-gray-200 px-2.5 py-1 rounded-md font-semibold"
th:text="${equip.reference}">REF-001</span>
<span th:if="${equip.reference == null or equip.reference.trim().isEmpty()}"
class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold bg-amber-50 text-amber-700 border border-amber-200" title="Référence non renseignée - Cliquez sur Modifier pour l'ajouter">
<svg class="w-3.5 h-3.5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
Non renseignée
</span>
</td>
<td class="py-4 px-6 text-gray-600" th:text="${equip.description != null ? equip.description : '-'}">Maillot de match officiel</td>
<td class="py-4 px-6 text-right flex justify-end space-x-3 items-center">
<a th:href="@{/equipements/{id}/edit(id=${equip.id})}" class="text-indigo-600 hover:text-indigo-900 font-medium bg-indigo-50 px-3 py-1 rounded-lg">Modifier</a>
@@ -21,7 +21,7 @@
<div class="bg-white p-6 rounded-lg border border-gray-200 shadow-sm mb-6">
<form th:action="@{/admin/equipements/recherche}" method="get" class="space-y-4">
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div class="grid grid-cols-1 md:grid-cols-5 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Équipement</label>
<select name="equipementId" class="w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm px-3 py-2 border">
@@ -36,6 +36,14 @@
<option th:each="cat : ${categories}" th:value="${cat.id}" th:text="${cat.nom}" th:selected="${cat.id == categorieId}"></option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Taille renseignée</label>
<select name="tailleRenseignee" class="w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm px-3 py-2 border">
<option value="">Toutes</option>
<option value="true" th:selected="${tailleRenseignee != null && tailleRenseignee}">Oui (Renseignée)</option>
<option value="false" th:selected="${tailleRenseignee != null && !tailleRenseignee}">Non (Manquante)</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Fourni</label>
<select name="fourni" class="w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm px-3 py-2 border">
@@ -53,20 +61,57 @@
</select>
</div>
</div>
<div class="flex justify-between items-center pt-2">
<a th:href="@{/admin/equipements/export-commande}"
onclick="return confirm('Exporter les équipements non encore commandés et les marquer comme commandés ?');"
class="bg-indigo-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-indigo-700 flex items-center space-x-1 shadow-sm">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
Exporter Commande Équipementier (Regroupé)
</a>
<div class="flex flex-wrap items-center justify-between gap-3 pt-2">
<div class="flex flex-wrap items-center gap-2">
<a th:href="@{/admin/equipements/export-commande}"
onclick="return confirm('Exporter les équipements non encore commandés et les marquer comme commandés ?');"
class="bg-indigo-600 text-white px-3.5 py-2 rounded-lg text-sm font-medium hover:bg-indigo-700 flex items-center space-x-1 shadow-sm transition-colors">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
Exporter Commande Équipementier (Regroupé)
</a>
<a th:href="@{/admin/equipements/export-flocage-initiales}"
onclick="return confirm('Exporter la liste des équipements commandés pour le flocage des initiales et les marquer comme exportés ?');"
class="bg-purple-600 text-white px-3.5 py-2 rounded-lg text-sm font-medium hover:bg-purple-700 flex items-center space-x-1 shadow-sm transition-colors"
title="Exporter les articles commandés nécessitant le flocage des initiales">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h10M7 12h10M7 17h10"/>
</svg>
Exporter Flocage Initiales
</a>
<a th:href="@{/admin/equipements/export-flocage-prenom-numero}"
onclick="return confirm('Exporter la liste des équipements commandés pour le flocage du prénom/numéro et les marquer comme exportés ?');"
class="bg-teal-600 text-white px-3.5 py-2 rounded-lg text-sm font-medium hover:bg-teal-700 flex items-center space-x-1 shadow-sm transition-colors"
title="Exporter les articles commandés nécessitant le flocage prénom et/ou numéro">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
</svg>
Exporter Flocage Prénom / N°
</a>
<a th:href="@{/admin/equipements/recherche(commandee=false,tailleRenseignee=false)}"
class="bg-amber-600 text-white px-3.5 py-2 rounded-lg text-sm font-medium hover:bg-amber-700 flex items-center space-x-1 shadow-sm transition-colors"
title="Filtrer immédiatement les équipements non commandés dont la taille est manquante pour relancer les adhérents">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
</svg>
Relance Tailles Manquantes
</a>
<a th:href="@{/admin/exports/historique}"
class="bg-gray-700 text-white px-3.5 py-2 rounded-lg text-sm font-medium hover:bg-gray-800 flex items-center space-x-1 shadow-sm transition-colors"
title="Consulter et re-télécharger les anciens exports">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
Historique des Exports
</a>
</div>
<div class="flex space-x-3">
<button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-700">Rechercher</button>
<a th:href="@{/admin/equipements/recherche/export(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee})}" class="bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-green-700">Exporter Recherche</a>
<a th:href="@{/admin/equipements/recherche/export(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee},tailleRenseignee=${tailleRenseignee})}" class="bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-green-700">Exporter Recherche</a>
</div>
</div>
</form>
</div>
@@ -90,7 +135,16 @@
</tr>
<tr th:each="dotation : ${dotations}" class="hover:bg-gray-50">
<td class="py-3 px-4 font-medium text-gray-900">
<span th:text="${dotation.licence.adherent.nom + ' ' + dotation.licence.adherent.prenom}">Nom Prénom</span>
<div class="font-semibold text-gray-900" th:text="${dotation.licence.adherent.nom + ' ' + dotation.licence.adherent.prenom}">Nom Prénom</div>
<div class="text-xs text-gray-500 font-normal mt-0.5 flex flex-wrap items-center gap-1.5">
<a th:if="${dotation.licence.adherent.email != null && !dotation.licence.adherent.email.isEmpty()}"
th:href="'mailto:' + ${dotation.licence.adherent.email}"
class="hover:underline text-blue-600 flex items-center"
th:text="${dotation.licence.adherent.email}">email</a>
<span th:if="${dotation.licence.adherent.telephone != null && !dotation.licence.adherent.telephone.isEmpty()}"
class="text-gray-500 font-medium"
th:text="'📞 ' + ${dotation.licence.adherent.telephone}">tél</span>
</div>
</td>
<td class="py-3 px-4 text-gray-600 text-xs">
<div th:text="${dotation.licence.adherent.typeMaillot}">Joueur</div>
@@ -98,11 +152,29 @@
</td>
<td class="py-3 px-4 text-gray-600" th:text="${dotation.licence.categorie != null ? dotation.licence.categorie.nom : '-'}">Catégorie</td>
<td class="py-3 px-4 text-gray-900 font-medium" th:text="${dotation.equipement != null ? dotation.equipement.nom : '-'}">Maillot</td>
<td class="py-3 px-4 text-gray-600 font-mono text-xs" th:text="${dotation.equipement != null && dotation.equipement.reference != null ? dotation.equipement.reference : '-'}">REF-01</td>
<td class="py-3 px-4">
<span th:if="${dotation.equipement != null && dotation.equipement.reference != null && !dotation.equipement.reference.trim().isEmpty()}"
class="font-mono text-xs text-gray-700 bg-gray-100 border border-gray-200 px-2 py-0.5 rounded font-semibold"
th:text="${dotation.equipement.reference}">REF-01</span>
<span th:unless="${dotation.equipement != null && dotation.equipement.reference != null && !dotation.equipement.reference.trim().isEmpty()}"
class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold bg-amber-50 text-amber-700 border border-amber-200" title="Référence non renseignée sur cet équipement">
⚠️ Non renseignée
</span>
</td>
<td class="py-3 px-4 text-gray-600">
<div th:text="'T: ' + (${dotation.taille != null && !dotation.taille.isEmpty() ? dotation.taille : '-'})">Taille</div>
<div th:if="${dotation.flocage != null && !dotation.flocage.isEmpty()}" th:text="'F: ' + ${dotation.flocage}">Flocage</div>
<div th:if="${dotation.numero != null && !dotation.numero.isEmpty()}" th:text="'N: ' + ${dotation.numero}"></div>
<div th:if="${dotation.taille != null && !dotation.taille.trim().isEmpty()}" th:text="'T: ' + ${dotation.taille}">Taille</div>
<div th:unless="${dotation.taille != null && !dotation.taille.trim().isEmpty()}">
<span th:if="${dotation.equipement != null && dotation.equipement.taillesDisponibles != null && !dotation.equipement.taillesDisponibles.trim().isEmpty()}"
class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-red-100 text-red-700 border border-red-200">
⚠️ Taille manquante
</span>
<span th:unless="${dotation.equipement != null && dotation.equipement.taillesDisponibles != null && !dotation.equipement.taillesDisponibles.trim().isEmpty()}"
class="text-gray-400 text-xs italic">
Sans taille
</span>
</div>
<div th:if="${dotation.flocage != null && !dotation.flocage.isEmpty()}" th:text="'F: ' + ${dotation.flocage}" class="text-xs">Flocage</div>
<div th:if="${dotation.numero != null && !dotation.numero.isEmpty()}" th:text="'N: ' + ${dotation.numero}" class="text-xs"></div>
</td>
<td class="py-3 px-4 text-center">
<span th:if="${dotation.commandee}" class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800" th:title="${dotation.dateCommande != null ? #temporals.format(dotation.dateCommande, 'dd/MM/yyyy HH:mm') : ''}">
@@ -131,12 +203,12 @@
<div class="flex items-center space-x-2" th:if="${totalPages > 1}">
<!-- Page Précédente -->
<a th:if="${currentPage > 0}"
th:href="@{/admin/equipements/recherche(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee},page=${currentPage - 1})}"
th:href="@{/admin/equipements/recherche(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee},tailleRenseignee=${tailleRenseignee},page=${currentPage - 1})}"
hx-get="/admin/equipements/recherche"
hx-target="#equipements-table-container"
hx-select="#equipements-table-container"
hx-push-url="true"
th:attr="hx-vals=|{&quot;equipementId&quot;: &quot;${equipementId != null ? equipementId : ''}&quot;, &quot;categorieId&quot;: &quot;${categorieId != null ? categorieId : ''}&quot;, &quot;fourni&quot;: &quot;${fourni != null ? fourni : ''}&quot;, &quot;commandee&quot;: &quot;${commandee != null ? commandee : ''}&quot;, &quot;page&quot;: ${currentPage - 1}}|"
th:attr="hx-vals=|{&quot;equipementId&quot;: &quot;${equipementId != null ? equipementId : ''}&quot;, &quot;categorieId&quot;: &quot;${categorieId != null ? categorieId : ''}&quot;, &quot;fourni&quot;: &quot;${fourni != null ? fourni : ''}&quot;, &quot;commandee&quot;: &quot;${commandee != null ? commandee : ''}&quot;, &quot;tailleRenseignee&quot;: &quot;${tailleRenseignee != null ? tailleRenseignee : ''}&quot;, &quot;page&quot;: ${currentPage - 1}}|"
class="px-3 py-1 border border-gray-300 rounded hover:bg-gray-100 transition-colors">
Précédent
</a>
@@ -146,12 +218,12 @@
<!-- Numéros de pages -->
<th:block th:each="pageNum : ${#numbers.sequence(0, totalPages - 1)}" th:if="${totalPages > 0}">
<a th:href="@{/admin/equipements/recherche(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee},page=${pageNum})}"
<a th:href="@{/admin/equipements/recherche(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee},tailleRenseignee=${tailleRenseignee},page=${pageNum})}"
hx-get="/admin/equipements/recherche"
hx-target="#equipements-table-container"
hx-select="#equipements-table-container"
hx-push-url="true"
th:attr="hx-vals=|{&quot;equipementId&quot;: &quot;${equipementId != null ? equipementId : ''}&quot;, &quot;categorieId&quot;: &quot;${categorieId != null ? categorieId : ''}&quot;, &quot;fourni&quot;: &quot;${fourni != null ? fourni : ''}&quot;, &quot;commandee&quot;: &quot;${commandee != null ? commandee : ''}&quot;, &quot;page&quot;: ${pageNum}}|"
th:attr="hx-vals=|{&quot;equipementId&quot;: &quot;${equipementId != null ? equipementId : ''}&quot;, &quot;categorieId&quot;: &quot;${categorieId != null ? categorieId : ''}&quot;, &quot;fourni&quot;: &quot;${fourni != null ? fourni : ''}&quot;, &quot;commandee&quot;: &quot;${commandee != null ? commandee : ''}&quot;, &quot;tailleRenseignee&quot;: &quot;${tailleRenseignee != null ? tailleRenseignee : ''}&quot;, &quot;page&quot;: ${pageNum}}|"
th:text="${pageNum + 1}"
class="px-3 py-1 rounded transition-colors"
th:classappend="${currentPage == pageNum ? 'bg-blue-600 text-white' : 'border border-gray-300 hover:bg-gray-100'}">
@@ -161,12 +233,12 @@
<!-- Page Suivante -->
<a th:if="${currentPage < totalPages - 1}"
th:href="@{/admin/equipements/recherche(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee},page=${currentPage + 1})}"
th:href="@{/admin/equipements/recherche(equipementId=${equipementId},categorieId=${categorieId},fourni=${fourni},commandee=${commandee},tailleRenseignee=${tailleRenseignee},page=${currentPage + 1})}"
hx-get="/admin/equipements/recherche"
hx-target="#equipements-table-container"
hx-select="#equipements-table-container"
hx-push-url="true"
th:attr="hx-vals=|{&quot;equipementId&quot;: &quot;${equipementId != null ? equipementId : ''}&quot;, &quot;categorieId&quot;: &quot;${categorieId != null ? categorieId : ''}&quot;, &quot;fourni&quot;: &quot;${fourni != null ? fourni : ''}&quot;, &quot;commandee&quot;: &quot;${commandee != null ? commandee : ''}&quot;, &quot;page&quot;: ${currentPage + 1}}|"
th:attr="hx-vals=|{&quot;equipementId&quot;: &quot;${equipementId != null ? equipementId : ''}&quot;, &quot;categorieId&quot;: &quot;${categorieId != null ? categorieId : ''}&quot;, &quot;fourni&quot;: &quot;${fourni != null ? fourni : ''}&quot;, &quot;commandee&quot;: &quot;${commandee != null ? commandee : ''}&quot;, &quot;tailleRenseignee&quot;: &quot;${tailleRenseignee != null ? tailleRenseignee : ''}&quot;, &quot;page&quot;: ${currentPage + 1}}|"
class="px-3 py-1 border border-gray-300 rounded hover:bg-gray-100 transition-colors">
Suivant
</a>
@@ -67,13 +67,53 @@
<tr th:if="${#lists.isEmpty(equipes)}">
<td colspan="4" class="py-8 text-center text-gray-500">Aucune équipe configurée pour le moment. Usez du formulaire à gauche pour en créer une.</td>
</tr>
<tr th:each="team : ${equipes}" class="hover:bg-gray-50 transition-colors">
<td class="py-4 px-6 font-medium text-gray-900" th:text="${team.nom}">Équipe 1</td>
<tr th:each="team : ${equipes}" class="hover:bg-gray-50 transition-colors" th:id="'team-row-' + ${team.id}">
<td class="py-4 px-6 font-medium text-gray-900">
<!-- Affichage Normal -->
<div th:id="'team-name-display-' + ${team.id}" class="flex items-center gap-2">
<span th:text="${team.nom}" class="font-semibold text-gray-900">Équipe 1</span>
<button type="button"
th:onclick="|enableEditTeam('${team.id}')|"
class="text-gray-400 hover:text-indigo-600 p-1 rounded transition-colors"
title="Modifier le nom">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
</button>
</div>
<!-- Formulaire d'édition Inline (Masqué par défaut) -->
<form th:id="'team-name-form-' + ${team.id}"
th:action="@{/equipes/{id}/update(id=${team.id})}"
method="post"
class="hidden flex items-center gap-2 m-0">
<input type="text"
name="nom"
th:value="${team.nom}"
required
class="border border-indigo-300 rounded-lg px-3 py-1 text-sm font-medium focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none w-48 shadow-sm">
<button type="submit"
class="bg-indigo-600 hover:bg-indigo-700 text-white p-1.5 rounded-lg text-xs font-semibold transition-colors shadow-sm"
title="Enregistrer">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
</button>
<button type="button"
th:onclick="|cancelEditTeam('${team.id}')|"
class="bg-gray-100 hover:bg-gray-200 text-gray-600 p-1.5 rounded-lg text-xs font-semibold transition-colors"
title="Annuler">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</form>
</td>
<td class="py-4 px-6 text-gray-600">
<span class="bg-blue-50 text-blue-700 px-2.5 py-1 rounded-full text-xs font-medium" th:text="${team.categorie.nom}">U15</span>
</td>
<td class="py-4 px-6 text-gray-500" th:text="${team.saison.nom}">2024-2025</td>
<td class="py-4 px-6 text-right flex justify-end items-center">
<td class="py-4 px-6 text-right flex justify-end items-center space-x-2">
<button type="button"
th:onclick="|enableEditTeam('${team.id}')|"
class="text-indigo-600 hover:text-indigo-800 font-medium text-xs bg-indigo-50 hover:bg-indigo-100 px-2.5 py-1.5 rounded-lg transition-colors inline-flex items-center gap-1">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
Modifier
</button>
<form th:action="@{/equipes/{id}/delete(id=${team.id})}" method="post" onsubmit="return confirm('Supprimer cette équipe ? Elle sera dissociée de toutes ses licences.');">
<button type="submit" class="text-red-500 hover:text-red-700 font-medium text-xs bg-red-50 hover:bg-red-100 px-2.5 py-1.5 rounded-lg transition-colors">
Supprimer
@@ -89,5 +129,23 @@
</div>
</div>
</main>
<script>
function enableEditTeam(teamId) {
document.getElementById('team-name-display-' + teamId).classList.add('hidden');
const form = document.getElementById('team-name-form-' + teamId);
form.classList.remove('hidden');
const input = form.querySelector('input[name="nom"]');
if (input) {
input.focus();
input.select();
}
}
function cancelEditTeam(teamId) {
document.getElementById('team-name-display-' + teamId).classList.remove('hidden');
document.getElementById('team-name-form-' + teamId).classList.add('hidden');
}
</script>
</body>
</html>
@@ -0,0 +1,191 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<script src="https://unpkg.com/htmx.org@1.9.11"></script>
<meta charset="UTF-8">
<title>Historique des Exports</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style> body { font-family: 'Inter', sans-serif; } </style>
</head>
<body class="bg-gray-50 text-gray-900 flex h-screen overflow-hidden">
<!-- Sidebar -->
<div th:replace="~{fragments/sidebar :: sidebar}"></div>
<main class="flex-1 flex flex-col h-screen overflow-hidden">
<header class="h-16 bg-white border-b border-gray-200 flex items-center px-6 justify-between">
<h2 class="text-lg font-semibold text-gray-800">Historique des Exports</h2>
<a th:href="@{/admin/equipements/recherche}" class="text-sm text-blue-600 hover:text-blue-800 font-medium flex items-center gap-1">
← Retour à la recherche équipements
</a>
</header>
<div class="flex-1 overflow-auto p-6">
<!-- Filtre par saison -->
<div class="bg-white p-4 rounded-lg border border-gray-200 shadow-sm mb-6 flex items-center justify-between">
<form th:action="@{/admin/exports/historique}" method="get" class="flex items-center space-x-4">
<label class="text-sm font-medium text-gray-700">Filtrer par Saison :</label>
<select name="saisonId" onchange="this.form.submit()" class="border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm px-3 py-1.5 border">
<option value="">Toutes les saisons</option>
<option th:each="s : ${saisons}" th:value="${s.id}" th:text="${s.nom}" th:selected="${s.id == saisonId}"></option>
</select>
</form>
<div class="text-xs text-gray-500">
Tous les fichiers exportés sont conservés et téléchargeables à tout moment.
</div>
</div>
<!-- Tableau de l'historique -->
<div class="bg-white rounded-lg border border-gray-200 overflow-hidden shadow-sm">
<table class="w-full text-left border-collapse">
<thead>
<tr class="bg-gray-50 text-gray-500 text-xs uppercase tracking-wider border-b border-gray-200">
<th class="py-3 px-4 font-medium text-left">Date & Heure</th>
<th class="py-3 px-4 font-medium text-left">Type d'Export</th>
<th class="py-3 px-4 font-medium text-left">Nom du Fichier</th>
<th class="py-3 px-4 font-medium text-center">Saison</th>
<th class="py-3 px-4 font-medium text-center">Éléments</th>
<th class="py-3 px-4 font-medium text-left">Généré par</th>
<th class="py-3 px-4 font-medium text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200 text-sm">
<tr th:if="${#lists.isEmpty(historique)}">
<td colspan="7" class="py-8 text-center text-gray-500">Aucun export enregistré pour le moment.</td>
</tr>
<tr th:each="export : ${historique}" class="hover:bg-gray-50">
<td class="py-3 px-4 text-gray-900 font-medium whitespace-nowrap" th:text="${#temporals.format(export.dateExport, 'dd/MM/yyyy HH:mm')}">
27/08/2026 10:30
</td>
<td class="py-3 px-4 whitespace-nowrap">
<span th:if="${export.typeExport.name() == 'COMMANDE_EQUIPEMENT'}" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold bg-indigo-100 text-indigo-800">
Commande Équipementier
</span>
<span th:if="${export.typeExport.name() == 'FLOCAGE_INITIALES'}" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold bg-purple-100 text-purple-800">
Flocage Initiales
</span>
<span th:if="${export.typeExport.name() == 'FLOCAGE_PRENOM_NUMERO'}" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold bg-teal-100 text-teal-800">
Flocage Prénom / N°
</span>
<span th:if="${export.typeExport.name() == 'RECHERCHE_EQUIPEMENTS'}" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-semibold bg-blue-100 text-blue-800">
Recherche Équipements
</span>
</td>
<td class="py-3 px-4 font-mono text-xs text-gray-700 font-medium" th:text="${export.nomFichier}">
commande_equipements.csv
</td>
<td class="py-3 px-4 text-center text-gray-600 text-xs font-medium" th:text="${export.saison != null ? export.saison.nom : '-'}">
2026/2027
</td>
<td class="py-3 px-4 text-center">
<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-gray-100 text-gray-800" th:text="${export.nombreElements}">
42
</span>
</td>
<td class="py-3 px-4 text-gray-600 text-xs" th:text="${export.utilisateur != null ? export.utilisateur.username : 'Système'}">
Admin User
</td>
<td class="py-3 px-4 text-right space-x-2 whitespace-nowrap">
<button type="button"
th:onclick="'ouvrirApercu(' + ${export.id} + ')'"
class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 transition-colors">
<svg class="w-3.5 h-3.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
Aperçu
</button>
<a th:href="@{/admin/exports/{id}/download(id=${export.id})}"
class="inline-flex items-center px-2.5 py-1 text-xs font-medium rounded text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-sm">
<svg class="w-3.5 h-3.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
Télécharger
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</main>
<!-- Modal d'aperçu CSV -->
<div id="modalApercu" class="fixed inset-0 z-50 hidden bg-black bg-opacity-50 flex items-center justify-center p-4">
<div class="bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] flex flex-col overflow-hidden">
<div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between bg-gray-50">
<div>
<h3 id="modalTitre" class="text-base font-semibold text-gray-900">Aperçu de l'export</h3>
<p id="modalSousTitre" class="text-xs text-gray-500 mt-0.5"></p>
</div>
<button onclick="fermerApercu()" class="text-gray-400 hover:text-gray-600 text-xl font-bold p-1">&times;</button>
</div>
<div class="p-6 overflow-auto flex-1">
<div id="apercuLoader" class="text-center py-8 text-gray-500 font-medium">Chargement des données...</div>
<div id="apercuContent" class="hidden border border-gray-200 rounded-lg overflow-hidden">
<table class="w-full text-left border-collapse text-xs">
<thead id="apercuThead" class="bg-gray-100 text-gray-700 border-b border-gray-200"></thead>
<tbody id="apercuTbody" class="divide-y divide-gray-200 bg-white"></tbody>
</table>
</div>
</div>
<div class="px-6 py-3 border-t border-gray-200 bg-gray-50 flex justify-end">
<button onclick="fermerApercu()" class="px-4 py-2 bg-gray-200 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-300">Fermer</button>
</div>
</div>
</div>
<script>
function ouvrirApercu(exportId) {
const modal = document.getElementById('modalApercu');
const loader = document.getElementById('apercuLoader');
const content = document.getElementById('apercuContent');
const thead = document.getElementById('apercuThead');
const tbody = document.getElementById('apercuTbody');
const titre = document.getElementById('modalTitre');
const sousTitre = document.getElementById('modalSousTitre');
modal.classList.remove('hidden');
loader.classList.remove('hidden');
content.classList.add('hidden');
thead.innerHTML = '';
tbody.innerHTML = '';
fetch('/admin/exports/' + exportId + '/apercu')
.then(res => res.json())
.then(data => {
loader.classList.add('hidden');
content.classList.remove('hidden');
titre.innerText = data.typeExport + " - " + data.nomFichier;
sousTitre.innerText = "Généré le " + data.dateExport + " (" + data.rows.length + " ligne(s))";
// Headers
let headerTr = document.createElement('tr');
data.headers.forEach(h => {
let th = document.createElement('th');
th.className = "py-2 px-3 font-semibold uppercase tracking-wider text-gray-600 border-r border-gray-200 last:border-r-0";
th.innerText = h.trim();
headerTr.appendChild(th);
});
thead.appendChild(headerTr);
// Rows
data.rows.forEach(r => {
let tr = document.createElement('tr');
tr.className = "hover:bg-gray-50";
r.forEach(val => {
let td = document.createElement('td');
td.className = "py-2 px-3 border-r border-gray-200 last:border-r-0 text-gray-800 whitespace-nowrap";
td.innerText = val.trim();
tr.appendChild(td);
});
tbody.appendChild(tr);
});
})
.catch(err => {
loader.innerText = "Erreur lors du chargement de l'aperçu.";
});
}
function fermerApercu() {
document.getElementById('modalApercu').classList.add('hidden');
}
</script>
</body>
</html>
@@ -88,7 +88,7 @@
<td class="py-3 px-4 text-gray-600 font-mono" th:text="${licence.numeroLicence != null ? licence.numeroLicence : '-'}"></td>
<td class="py-3 px-4 text-gray-600">
<div th:text="${licence.typeDemande != null ? licence.typeDemande : '-'}">Type</div>
<span th:if="${licence.reductionEducateur}" class="text-[10px] font-bold text-amber-700 bg-amber-50 border border-amber-200 px-1.5 py-0.5 rounded-full inline-block mt-0.5" th:text="'Éducateur (-' + ${licence.pourcentageReductionEducateur} + '%)'">Éducateur (-100%)</span>
<span sec:authorize="hasRole('ROLE_ADMIN')" th:if="${licence.reductionEducateur}" class="text-[10px] font-bold text-amber-700 bg-amber-50 border border-amber-200 px-1.5 py-0.5 rounded-full inline-block mt-0.5" th:text="'Éducateur (-' + ${licence.pourcentageReductionEducateur} + '%)'">Éducateur (-100%)</span>
</td>
<td class="py-3 px-4 text-gray-600" th:text="${licence.adherent.email != null ? licence.adherent.email : '-'}">Email</td>
<td class="py-3 px-4 text-gray-600" th:text="${licence.etat != null ? licence.etat : '-'}">Etat</td>
@@ -48,13 +48,26 @@
<div th:if="${success}" class="bg-green-50 border-l-4 border-green-500 p-4 mb-6 rounded-lg">
<p class="text-sm text-green-700 font-medium" th:text="${success}"></p>
</div>
<div th:if="${error}" class="bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded-lg">
<p class="text-sm text-red-700 font-medium" th:text="${error}"></p>
</div>
<!-- Page actions -->
<div class="flex justify-between items-center mb-6" th:if="${saisonActive != null}">
<h3 class="text-xl font-bold text-gray-900">Planning Hebdomadaire</h3>
<a th:href="@{/planning/new}" class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-700 shadow transition-colors">
+ Ajouter un Créneau
</a>
<div class="flex items-center space-x-3">
<form th:action="@{/planning/envoyer-educateurs(jour=${selectedDay != null ? selectedDay.name() : 'LUNDI'})}" method="post" onsubmit="return confirm('Êtes-vous sûr de vouloir envoyer le planning global de la semaine par e-mail à tous les éducateurs ?');">
<button type="submit" class="bg-emerald-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-emerald-700 shadow transition-colors flex items-center space-x-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
</svg>
<span>Envoyer le planning aux éducateurs</span>
</button>
</form>
<a th:href="@{/planning/new}" class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-700 shadow transition-colors">
+ Ajouter un Créneau
</a>
</div>
</div>
<!-- Tabs: Days of the week -->
@@ -45,15 +45,25 @@
<td class="py-4 px-6">
<div class="text-xs text-gray-500" th:text="${pre.email}"></div>
</td>
<td class="py-4 px-6 text-right space-x-2">
<td class="py-4 px-6 text-right flex items-center justify-end space-x-2">
<span th:id="'relance-container-' + ${pre.id}">
<button th:attr="hx-post=@{/admin/pre-inscriptions/{id}/relancer(id=${pre.id})}, hx-target=|#relance-container-${pre.id}|"
hx-swap="innerHTML"
class="bg-amber-50 text-amber-700 border border-amber-200 px-3 py-1.5 rounded hover:bg-amber-100 transition-colors inline-flex items-center gap-1.5 font-medium">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 002-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
</svg>
Relancer
</button>
</span>
<button th:attr="hx-post=@{/admin/pre-inscriptions/{id}/valider(id=${pre.id})}"
class="bg-blue-600 text-white px-3 py-1.5 rounded hover:bg-blue-700 transition-colors">
class="bg-blue-600 text-white px-3 py-1.5 rounded hover:bg-blue-700 transition-colors font-medium">
Créer la fiche
</button>
<button th:attr="hx-post=@{/admin/pre-inscriptions/{id}/rejeter(id=${pre.id})}, hx-target=|#pre-${pre.id}|"
hx-swap="outerHTML"
hx-confirm="Confirmer le rejet du dossier ?"
class="bg-red-50 text-red-600 border border-red-200 px-3 py-1.5 rounded hover:bg-red-100 transition-colors">
class="bg-red-50 text-red-600 border border-red-200 px-3 py-1.5 rounded hover:bg-red-100 transition-colors font-medium">
Rejeter
</button>
</td>
@@ -206,6 +206,7 @@
<script>
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault();
@@ -230,32 +231,71 @@
const typeDemandeRadios = document.querySelectorAll('input[name="typeDemande"]');
const nouvelleLicenceBlock = document.getElementById('nouvelleLicenceBlock');
typeDemandeRadios.forEach(radio => {
radio.addEventListener('change', function() {
if (this.value === 'NOUVELLE') {
nouvelleLicenceBlock.classList.remove('hidden');
} else {
nouvelleLicenceBlock.classList.add('hidden');
}
});
});
// Trigger on load if already checked (e.g. going back or validation error)
const checkedRadio = document.querySelector('input[name="typeDemande"]:checked');
if (checkedRadio && checkedRadio.value === 'NOUVELLE') {
nouvelleLicenceBlock.classList.remove('hidden');
}
const ancienClubInput = document.getElementById('ancienClub');
const ancienneCategorieBlock = document.getElementById('ancienneCategorieBlock');
const ancienneCategorieSelect = document.getElementById('ancienneCategorie');
const raisonChangementClubBlock = document.getElementById('raisonChangementClubBlock');
const raisonChangementClubInput = document.getElementById('raisonChangementClub');
const commentConnuInput = document.querySelector('input[name="commentConnuClub"]');
function updateTypeDemandeState(typeValue) {
if (typeValue === 'NOUVELLE') {
nouvelleLicenceBlock.classList.remove('hidden');
// Synchroniser l'état de l'ancien club s'il contient du texte
if (ancienClubInput && ancienClubInput.value.trim().length > 0) {
ancienneCategorieBlock.classList.remove('hidden');
ancienneCategorieSelect.required = true;
raisonChangementClubBlock.classList.remove('hidden');
raisonChangementClubInput.required = true;
} else {
ancienneCategorieBlock.classList.add('hidden');
ancienneCategorieSelect.required = false;
raisonChangementClubBlock.classList.add('hidden');
raisonChangementClubInput.required = false;
}
} else {
// RENOUVELLEMENT
nouvelleLicenceBlock.classList.add('hidden');
// Réinitialisation complète des champs spécifiques aux nouvelles demandes
if (ancienClubInput) ancienClubInput.value = '';
if (raisonChangementClubInput) {
raisonChangementClubInput.value = '';
raisonChangementClubInput.required = false;
}
if (ancienneCategorieSelect) {
ancienneCategorieSelect.value = 'NA';
ancienneCategorieSelect.required = false;
}
if (commentConnuInput) commentConnuInput.value = '';
if (ancienneCategorieBlock) ancienneCategorieBlock.classList.add('hidden');
if (raisonChangementClubBlock) raisonChangementClubBlock.classList.add('hidden');
}
// Si le formulaire redevient valide, masquer le message d'erreur
const errorMsg = document.getElementById('form-error-msg');
if (errorMsg && form.checkValidity()) {
errorMsg.remove();
}
}
typeDemandeRadios.forEach(radio => {
radio.addEventListener('change', function() {
updateTypeDemandeState(this.value);
});
});
// Exécution initiale au chargement si un type est déjà coché
const checkedRadio = document.querySelector('input[name="typeDemande"]:checked');
if (checkedRadio) {
updateTypeDemandeState(checkedRadio.value);
}
if (ancienClubInput) {
ancienClubInput.addEventListener('input', function() {
if (this.value.trim().length > 0) {
const isNouvelle = document.querySelector('input[name="typeDemande"]:checked')?.value === 'NOUVELLE';
if (isNouvelle && this.value.trim().length > 0) {
ancienneCategorieBlock.classList.remove('hidden');
ancienneCategorieSelect.required = true;
raisonChangementClubBlock.classList.remove('hidden');
@@ -267,35 +307,36 @@
raisonChangementClubInput.required = false;
}
});
// Initial check
if (ancienClubInput.value.trim().length > 0) {
ancienneCategorieBlock.classList.remove('hidden');
ancienneCategorieSelect.required = true;
raisonChangementClubBlock.classList.remove('hidden');
raisonChangementClubInput.required = true;
}
}
document.getElementById('dateNaissance').addEventListener('change', function() {
const dateInput = this.value;
const repBlock = document.getElementById('representantBlock');
const repInput = document.getElementById('representantLegal');
if (dateInput) {
const dob = new Date(dateInput);
const ageDifMs = Date.now() - dob.getTime();
const ageDate = new Date(ageDifMs);
const age = Math.abs(ageDate.getUTCFullYear() - 1970);
const dateNaissanceInput = document.getElementById('dateNaissance');
if (dateNaissanceInput) {
dateNaissanceInput.addEventListener('change', function() {
const dateInput = this.value;
const repBlock = document.getElementById('representantBlock');
const repInput = document.getElementById('representantLegal');
if (age < 18) {
repBlock.classList.remove('hidden');
repInput.required = true;
} else {
repBlock.classList.add('hidden');
repInput.required = false;
if (dateInput) {
const dob = new Date(dateInput);
const ageDifMs = Date.now() - dob.getTime();
const ageDate = new Date(ageDifMs);
const age = Math.abs(ageDate.getUTCFullYear() - 1970);
if (age < 18) {
repBlock.classList.remove('hidden');
repInput.required = true;
} else {
repBlock.classList.add('hidden');
repInput.required = false;
repInput.value = '';
}
}
});
// Vérification initiale si la date est pré-remplie
if (dateNaissanceInput.value) {
dateNaissanceInput.dispatchEvent(new Event('change'));
}
});
}
</script>
</body>
</html>
+1 -1
View File
@@ -13,7 +13,7 @@
<groupId>com.astalange</groupId>
<artifactId>as-talange-parent</artifactId>
<version>1.7-SNAPSHOT</version>
<version>1.9-SNAPSHOT</version>
<packaging>pom</packaging>
<name>as-talange-parent</name>
+349
View File
@@ -0,0 +1,349 @@
#!/usr/bin/env bash
# ==============================================================================
# Script de sauvegarde automatisée de la base de données PostgreSQL AS Talange
# Exécution : Sur le serveur distant / interne hébergeant la base de données
# Rétention : 7 jours glissants (en local et sur le serveur de stockage VPS)
# Transfert : Copie sécurisée via SCP/SSH vers le serveur VPS (optionnel)
# Notification : Email de bilan (Succès/Échec + Logs) via l'API Brevo
# ==============================================================================
set -u
# Localisation du répertoire du script et du projet
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
# Chargement du fichier .env si présent dans le projet
if [ -f "${PROJECT_DIR}/.env" ]; then
set -a
source "${PROJECT_DIR}/.env"
set +a
fi
# Variables de configuration (avec valeurs par défaut)
BACKUP_DIR="${BACKUP_DIR:-${PROJECT_DIR}/backups}"
RETENTION_DAYS="${RETENTION_DAYS:-7}"
DB_NAME="${POSTGRES_DB:-astalange}"
DB_USER="${POSTGRES_USER:-myuser}"
DB_PASSWORD="${POSTGRES_PASSWORD:-mypassword}"
DB_HOST="${POSTGRES_HOST:-localhost}"
DB_PORT="${POSTGRES_PORT:-5432}"
CONTAINER_NAME="${DOCKER_CONTAINER_NAME:-astalange_db}"
# Variables UAT
ENABLE_UAT_RESTORE="${ENABLE_UAT_RESTORE:-true}"
UAT_DB_HOST="${UAT_DB_HOST:-10.8.0.2}"
UAT_DB_PORT="${UAT_DB_PORT:-5433}"
UAT_DB_NAME="${UAT_DB_NAME:-astalange}"
UAT_DB_USER="${UAT_DB_USER:-myuser}"
UAT_DB_PASSWORD="${UAT_DB_PASSWORD:-mypassword}"
# Configuration du transfert distant vers le VPS (optionnel)
ENABLE_REMOTE_COPY="${ENABLE_REMOTE_COPY:-false}"
REMOTE_HOST="${REMOTE_HOST:-}"
REMOTE_USER="${REMOTE_USER:-root}"
REMOTE_PORT="${REMOTE_PORT:-22}"
REMOTE_BACKUP_DIR="${REMOTE_BACKUP_DIR:-/var/backups/as-talange}"
SSH_KEY_PATH="${SSH_KEY_PATH:-${HOME}/.ssh/id_rsa}"
# Configuration Brevo
BREVO_API_KEY="${BREVO_API_KEY:-}"
BREVO_SENDER_EMAIL="${APP_MAIL_FROM:-astalange1933@gmail.com}"
BREVO_SENDER_NAME="${BREVO_SENDER_NAME:-AS Talange Backup}"
RECIPIENT_EMAIL="${NOTIFICATION_EMAIL:-astalange1933@gmail.com}"
# Fichier journal temporaire pour cette exécution
TIMESTAMP=$(date +"%Y-%m-%d_%H%M%S")
DATE_HUMAN=$(date +"%d/%m/%Y à %H:%M:%S")
LOG_FILE=$(mktemp /tmp/astalange_backup_${TIMESTAMP}_XXXXXX.log)
DUMP_FILENAME="astalange_db_backup_${TIMESTAMP}.sql.gz"
DUMP_PATH="${BACKUP_DIR}/${DUMP_FILENAME}"
STATUS="SUCCESS"
DUMP_SIZE="0 KB"
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
log "======================================================================"
log " Démarrage du script de sauvegarde AS Talange (Serveur BDD)"
log "======================================================================"
log "Date d'exécution : ${DATE_HUMAN}"
log "Dossier local de sauvegarde : ${BACKUP_DIR}"
log "Fichier cible : ${DUMP_FILENAME}"
log "Rétention : ${RETENTION_DAYS} jours"
# 1. Création du répertoire de sauvegarde local si nécessaire
if ! mkdir -p "$BACKUP_DIR" >> "$LOG_FILE" 2>&1; then
log "ERREUR: Impossible de créer le dossier de sauvegarde local ${BACKUP_DIR}"
STATUS="FAILURE"
fi
# 2. Déroulement du Dump PostgreSQL
if [ "$STATUS" = "SUCCESS" ]; then
log "Démarrage de l'extraction (dump) de la base de données..."
# Vérification si le conteneur Docker est actif
if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
log "Mode détection: Conteneur Docker '${CONTAINER_NAME}' trouvé. Utilisation de pg_dump via docker exec."
docker exec -e PGPASSWORD="${DB_PASSWORD}" "${CONTAINER_NAME}" pg_dump --no-owner --no-privileges -U "${DB_USER}" -d "${DB_NAME}" | gzip > "$DUMP_PATH" 2>> "$LOG_FILE"
DUMP_EXIT_CODE=${PIPESTATUS[0]}
else
log "Mode détection: Exécution directe de pg_dump (hôte local)."
PGPASSWORD="${DB_PASSWORD}" pg_dump --no-owner --no-privileges -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" | gzip > "$DUMP_PATH" 2>> "$LOG_FILE"
DUMP_EXIT_CODE=${PIPESTATUS[0]}
fi
if [ ${DUMP_EXIT_CODE} -eq 0 ] || [ ${DUMP_EXIT_CODE} -eq 141 ]; then
if [ -s "$DUMP_PATH" ]; then
DUMP_SIZE=$(du -h "$DUMP_PATH" | cut -f1)
log "✅ Dump généré avec succès ! Taille du fichier : ${DUMP_SIZE}"
DUMP_EXIT_CODE=0
fi
fi
if [ ${DUMP_EXIT_CODE} -ne 0 ]; then
log "❌ ERREUR lors de l'extraction de la base de données (code de sortie: ${DUMP_EXIT_CODE})."
STATUS="FAILURE"
rm -f "$DUMP_PATH"
fi
fi
# 2b. Restauration et Anonymisation vers la BDD UAT (10.8.0.2)
if [ "$STATUS" = "SUCCESS" ] && [ "$ENABLE_UAT_RESTORE" = "true" ]; then
log "Démarrage de la restauration et l'anonymisation sur UAT (${UAT_DB_USER}@${UAT_DB_HOST}:${UAT_DB_PORT}/${UAT_DB_NAME})..."
CLEAN_SCHEMA_SQL="
DO \$\$ DECLARE r RECORD; BEGIN FOR r IN (SELECT oid FROM pg_largeobject_metadata) LOOP PERFORM lo_unlink(r.oid); END LOOP; EXCEPTION WHEN OTHERS THEN NULL; END \$\$;
DROP SCHEMA IF EXISTS public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO ${UAT_DB_USER};
GRANT ALL ON SCHEMA public TO public;
"
ANONYMIZE_SQL="
UPDATE adherent SET
nom = 'Nom_Adherent_' || id,
prenom = 'Prenom_Adherent_' || id,
email = 'adherent' || id || '@test.local',
telephone = '06' || LPAD((id)::text, 8, '0'),
lieu_naissance_ville = 'Ville_' || id,
representant_legal = CASE
WHEN representant_legal IS NOT NULL AND TRIM(representant_legal) <> ''
THEN 'Representant_' || id
ELSE representant_legal
END;
UPDATE pre_inscription SET
nom = 'Nom_PreInscr_' || id,
prenom = 'Prenom_PreInscr_' || id,
email = 'preinscr' || id || '@test.local',
telephone = '06' || LPAD((id)::text, 8, '0'),
lieu_naissance_ville = 'Ville_' || id,
representant_legal = CASE
WHEN representant_legal IS NOT NULL AND TRIM(representant_legal) <> ''
THEN 'Representant_PreInscr_' || id
ELSE representant_legal
END;
UPDATE educateur SET
nom = 'Nom_Educ_' || id,
prenom = 'Prenom_Educ_' || id,
email = 'educ' || id || '@test.local',
telephone = '06' || LPAD((id)::text, 8, '0');
"
RESTORE_SUCCESS=false
if command -v psql >/dev/null 2>&1; then
log "Réinitialisation du schéma public sur UAT..."
PGPASSWORD="${UAT_DB_PASSWORD}" psql -h "${UAT_DB_HOST}" -p "${UAT_DB_PORT}" -U "${UAT_DB_USER}" -d "${UAT_DB_NAME}" -c "$CLEAN_SCHEMA_SQL" >> "$LOG_FILE" 2>&1
log "Restauration du dump Prod vers UAT..."
if gunzip -c "$DUMP_PATH" | PGPASSWORD="${UAT_DB_PASSWORD}" psql -h "${UAT_DB_HOST}" -p "${UAT_DB_PORT}" -U "${UAT_DB_USER}" -d "${UAT_DB_NAME}" >> "$LOG_FILE" 2>&1; then
log "Exécution des requêtes d'anonymisation sur UAT..."
if PGPASSWORD="${UAT_DB_PASSWORD}" psql -h "${UAT_DB_HOST}" -p "${UAT_DB_PORT}" -U "${UAT_DB_USER}" -d "${UAT_DB_NAME}" -c "$ANONYMIZE_SQL" >> "$LOG_FILE" 2>&1; then
RESTORE_SUCCESS=true
fi
fi
elif command -v docker >/dev/null 2>&1; then
log "Réinitialisation du schéma public sur UAT via Docker..."
docker run --rm --net=host -e PGPASSWORD="${UAT_DB_PASSWORD}" postgres:15-alpine psql -h "${UAT_DB_HOST}" -p "${UAT_DB_PORT}" -U "${UAT_DB_USER}" -d "${UAT_DB_NAME}" -c "$CLEAN_SCHEMA_SQL" >> "$LOG_FILE" 2>&1
log "Restauration du dump Prod vers UAT via Docker..."
if gunzip -c "$DUMP_PATH" | docker run --rm -i --net=host -e PGPASSWORD="${UAT_DB_PASSWORD}" postgres:15-alpine psql -h "${UAT_DB_HOST}" -p "${UAT_DB_PORT}" -U "${UAT_DB_USER}" -d "${UAT_DB_NAME}" >> "$LOG_FILE" 2>&1; then
log "Exécution des requêtes d'anonymisation sur UAT via Docker..."
if docker run --rm --net=host -e PGPASSWORD="${UAT_DB_PASSWORD}" postgres:15-alpine psql -h "${UAT_DB_HOST}" -p "${UAT_DB_PORT}" -U "${UAT_DB_USER}" -d "${UAT_DB_NAME}" -c "$ANONYMIZE_SQL" >> "$LOG_FILE" 2>&1; then
RESTORE_SUCCESS=true
fi
fi
fi
if [ "$RESTORE_SUCCESS" = "true" ]; then
log "✅ Restauration et anonymisation UAT réussies avec succès !"
else
log "⚠️ AVERTISSEMENT: Impossible d'effectuer la restauration/anonymisation UAT."
fi
fi
# 3. Transfert sécurisé RSYNC / SCP vers le serveur VPS (Optionnel)
if [ "$STATUS" = "SUCCESS" ] && [ "$ENABLE_REMOTE_COPY" = "true" ] && [ -n "$REMOTE_HOST" ]; then
log "Transfert du dump vers le serveur VPS distant (${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_BACKUP_DIR})..."
SSH_CMD="ssh -i ${SSH_KEY_PATH} -p ${REMOTE_PORT} -o StrictHostKeyChecking=no -o ConnectTimeout=10"
# Création du dossier distant si nécessaire
$SSH_CMD "${REMOTE_USER}@${REMOTE_HOST}" "mkdir -p ${REMOTE_BACKUP_DIR}" >> "$LOG_FILE" 2>&1
TRANSFER_SUCCESS=false
# Privilégier rsync si disponible
if command -v rsync >/dev/null 2>&1; then
log "Utilisation de RSYNC pour le transfert..."
RSYNC_CMD="rsync -avz -e \"ssh -i ${SSH_KEY_PATH} -p ${REMOTE_PORT} -o StrictHostKeyChecking=no -o ConnectTimeout=10\""
if eval $RSYNC_CMD "$DUMP_PATH" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_BACKUP_DIR}/${DUMP_FILENAME}" >> "$LOG_FILE" 2>&1; then
TRANSFER_SUCCESS=true
fi
fi
# Fallback vers SCP si rsync échoue ou n'est pas installé
if [ "$TRANSFER_SUCCESS" = "false" ]; then
log "Utilisation de SCP pour le transfert..."
SCP_CMD="scp -i ${SSH_KEY_PATH} -P ${REMOTE_PORT} -o StrictHostKeyChecking=no -o ConnectTimeout=10"
if $SCP_CMD "$DUMP_PATH" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_BACKUP_DIR}/${DUMP_FILENAME}" >> "$LOG_FILE" 2>&1; then
TRANSFER_SUCCESS=true
fi
fi
if [ "$TRANSFER_SUCCESS" = "true" ]; then
log "✅ Copie distante vers le VPS réussie !"
# Nettoyage des sauvegardes distantes sur le VPS (> 7 jours)
log "Nettoyage des sauvegardes distantes de plus de ${RETENTION_DAYS} jours sur le VPS..."
$SSH_CMD "${REMOTE_USER}@${REMOTE_HOST}" "find ${REMOTE_BACKUP_DIR} -type f -name 'astalange_db_backup_*.sql.gz' -mtime +${RETENTION_DAYS} -delete" >> "$LOG_FILE" 2>&1
else
log "❌ ERREUR lors du transfert (rsync/scp) vers le serveur VPS."
STATUS="FAILURE"
fi
fi
# 4. Nettoyage des anciennes sauvegardes locales (> 7 jours)
if [ "$STATUS" = "SUCCESS" ]; then
log "Nettoyage des sauvegardes locales de plus de ${RETENTION_DAYS} jours..."
DELETED_FILES=$(find "$BACKUP_DIR" -type f -name "astalange_db_backup_*.sql.gz" -mtime +${RETENTION_DAYS} -print)
if [ -n "$DELETED_FILES" ]; then
log "Fichiers locaux supprimés (obsolètes) :"
echo "$DELETED_FILES" | tee -a "$LOG_FILE"
find "$BACKUP_DIR" -type f -name "astalange_db_backup_*.sql.gz" -mtime +${RETENTION_DAYS} -delete >> "$LOG_FILE" 2>&1
else
log "Aucune sauvegarde locale obsolète à supprimer."
fi
fi
log "======================================================================"
log " Fin du traitement de sauvegarde. Statut global : ${STATUS}"
log "======================================================================"
# 5. Envoi de l'email de rapport via Brevo API
send_email_notification() {
if [ -z "${BREVO_API_KEY}" ]; then
log "ATTENTION: BREVO_API_KEY n'est pas définie. Envoi d'email ignoré."
return 0
fi
log "Envoi du rapport par email via l'API Brevo à ${RECIPIENT_EMAIL}..."
if [ "$STATUS" = "SUCCESS" ]; then
SUBJECT="[AS Talange] ✅ Backup Base de Données Réussi - $(date +'%d/%m/%Y')"
HEADER_BG="#28a745"
STATUS_LABEL="SUCCÈS"
else
SUBJECT="[AS Talange] ❌ ECHEC du Backup Base de Données - $(date +'%d/%m/%Y')"
HEADER_BG="#dc3545"
STATUS_LABEL="ÉCHEC"
fi
LOG_CONTENT=$(cat "$LOG_FILE")
PYTHON_JSON_GEN=$(python3 -c '
import json, sys
status_label = sys.argv[1]
header_bg = sys.argv[2]
timestamp = sys.argv[3]
dump_name = sys.argv[4]
dump_size = sys.argv[5]
log_content = sys.argv[6]
sender_name = sys.argv[7]
sender_email = sys.argv[8]
recipient_email = sys.argv[9]
subject = sys.argv[10]
html = f"""
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="font-family: Arial, sans-serif; background-color: #f4f6f9; padding: 20px; color: #333;">
<div style="max-width: 650px; margin: 0 auto; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<div style="background-color: {header_bg}; color: white; padding: 15px 20px; text-align: center;">
<h2 style="margin:0;">Sauvegarde Base de Données AS Talange</h2>
<p style="margin: 5px 0 0 0; font-weight: bold;">Statut : {status_label}</p>
</div>
<div style="padding: 20px;">
<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
<tr><td style="padding: 8px; font-weight: bold; width: 35%;">Date :</td><td style="padding: 8px;">{timestamp}</td></tr>
<tr><td style="padding: 8px; font-weight: bold;">Fichier Dump :</td><td style="padding: 8px;"><code>{dump_name}</code></td></tr>
<tr><td style="padding: 8px; font-weight: bold;">Taille :</td><td style="padding: 8px;">{dump_size}</td></tr>
</table>
<h3 style="border-bottom: 2px solid #eee; padding-bottom: 8px; color: #555;">Logs d&apos;exécution :</h3>
<pre style="background: #272822; color: #f8f8f2; padding: 15px; border-radius: 5px; font-size: 12px; overflow-x: auto; white-space: pre-wrap;">{log_content}</pre>
</div>
<div style="background: #e9ecef; padding: 10px 20px; font-size: 12px; text-align: center; color: #6c757d;">
Script automatique de sauvegarde AS Talange - Rétention 7 jours
</div>
</div>
</body>
</html>
"""
payload = {
"sender": {"name": sender_name, "email": sender_email},
"to": [{"email": recipient_email}],
"subject": subject,
"htmlContent": html
}
print(json.dumps(payload))
' "$STATUS_LABEL" "$HEADER_BG" "$DATE_HUMAN" "$DUMP_FILENAME" "${DUMP_SIZE:-N/A}" "$LOG_CONTENT" "$BREVO_SENDER_NAME" "$BREVO_SENDER_EMAIL" "$RECIPIENT_EMAIL" "$SUBJECT" 2>/dev/null)
if [ -n "$PYTHON_JSON_GEN" ]; then
RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" -X POST "https://api.brevo.com/v3/smtp/email" \
-H "accept: application/json" \
-H "api-key: ${BREVO_API_KEY}" \
-H "content-type: application/json" \
-d "$PYTHON_JSON_GEN")
HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2)
if [ "$HTTP_CODE" = "201" ] || [ "$HTTP_CODE" = "200" ]; then
log "✅ Email envoyé avec succès via l'API Brevo !"
else
log "❌ ERREUR lors de l'envoi de l'email via Brevo (Code HTTP: ${HTTP_CODE}). Réponse: ${RESPONSE}"
fi
else
log "❌ ERREUR: Échec de la génération du payload JSON pour l'email."
fi
}
send_email_notification
# Nettoyage du fichier log temporaire
rm -f "$LOG_FILE"
if [ "$STATUS" = "FAILURE" ]; then
exit 1
fi
exit 0