39 Commits
Author SHA1 Message Date
ucef b1d897a3c8 fix(backup): handle SIGPIPE exit code 141 in pg_dump pipeline
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m2s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 1m20s
2026-09-04 09:19:13 +02:00
ucef f6c853068f fix(backup): purge pg_largeobject metadata prior to UAT schema reset
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m15s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 1m29s
2026-09-04 09:07:31 +02:00
ucef 19e969eb09 fix(backup): clean UAT schema before restore and add --no-owner --no-privileges to pg_dump
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m1s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 1m25s
2026-09-04 08:54:48 +02:00
ucef e933218443 feat(backup): update DB UAT port
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m7s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 1m23s
2026-09-04 08:43:24 +02:00
ucef c994cbe155 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 c778dea9a0 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 - Production / Build & Run Unit Tests (push) Successful in 1m59s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 1m19s
2026-09-04 08:10:08 +02:00
ucef 2720a2193d fix(ci): execute deployment directly in runner step environment without nested container
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 1m59s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m27s
2026-09-04 08:03:23 +02:00
ucef e1d797eb01 fix(ci): use GITHUB_WORKSPACE for repository volume mount and absolute path /workspace/ for rsync
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m1s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m16s
2026-09-04 07:26:53 +02:00
ucef c06abb1d17 fix(ci): re-wrap PEM payload to 64 chars with explicit trailing newline
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 1m56s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m18s
2026-09-04 07:18:12 +02:00
ucef 0a56944daa fix(ci): validate SSH key header format and provide explicit guidance for Gitea secret value
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m3s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m13s
2026-09-04 07:04:21 +02:00
ucef 292c2bb8ec fix(ci): handle file paths in RAW_KEY and add key line count diagnostic logs
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m9s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m14s
2026-09-03 15:55:13 +02:00
ucef a991fd9f35 fix(ci): pass SSH key as base64 environment variable to completely eliminate volume mount issues
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m9s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m14s
2026-09-03 15:47:40 +02:00
ucef 5fb6356f8a fix(ci): strict regular file check and explicit error message when PROD_DB_SSH_KEY is missing
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m7s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m14s
2026-09-03 15:39:35 +02:00
ucef 9990bba799 fix(ci): write secret key to runner file before docker run to preserve multi-line format
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m4s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m14s
2026-09-03 15:26:22 +02:00
ucef 494fcfbf8a fix(ci): use PROD_DB_SSH_KEY Gitea secret for reliable cross-runner authentication
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m1s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m13s
2026-09-03 15:19:28 +02:00
ucef 5e7e5c461c security: replace key header log with safe public ssh-keygen fingerprint display
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m13s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m20s
2026-09-03 15:11:16 +02:00
ucef 63bc5da40c ci: add comprehensive diagnostic logs and ssh -vv trace to step 2026-09-03 15:09:07 +02:00
ucef a4c852d254 fix(ci): mount /home/ucef/.ssh and prioritize gitea_ci_key over generic host keys
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m5s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m22s
2026-09-03 15:02:09 +02:00
ucef 815eb72834 fix(ci): copy key to /tmp/id_rsa instead of ~/.ssh/id_rsa to avoid read-only mount error
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m6s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m23s
2026-09-03 14:56:31 +02:00
ucef 881a81f53b fix(ci): robust SSH key resolution supporting both file paths and Gitea secrets
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m6s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m15s
2026-09-03 14:49:33 +02:00
ucef 747cf1a0fa refactor(ci): simplify SSH step to directly copy and use /root/.ssh/gitea_ci_key with 600 permissions
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m8s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m14s
2026-09-03 14:40:45 +02:00
ucef 2472407cca fix(ci): prioritize /root/.ssh/gitea_ci_key mount
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m15s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m27s
2026-09-03 14:29:20 +02:00
ucef 02f9674b7a fix(ci): mount /home/ubuntu/.ssh and auto-detect gitea_ci_key location 2026-09-03 14:26:53 +02:00
ucef 0963e25cfb fix(ci): add UserKnownHostsFile=/dev/null and target gitea_ci_key to fix read-only ssh error
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m10s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m22s
2026-09-03 14:05:44 +02:00
ucef 8c8df282a4 refactor(ci): mount host .ssh directory directly in docker step container
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m15s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m26s
2026-09-03 13:16:03 +02:00
ucef 41f8b67602 fix(ci): strip carriage returns from SSH key and force IdentitiesOnly=yes to fix libcrypto unsupported error
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m14s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m23s
2026-09-03 12:59:24 +02:00
ucef 47b27d3cfd fix(ci): run rsync DB script deployment with host network (--net=host) to fix VPN timeout
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m33s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m31s
2026-09-03 12:51:10 +02:00
ucef 272a4ad8e2 fix(ci): preserve SSH key linebreaks with printf and add custom port support
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m2s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 1m23s
2026-09-03 10:04:34 +02:00
ucef deba5fafea fix(ci): check all SSH key secret variants and force rsync deployment to DB server
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m34s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Failing after 3m32s
2026-09-03 08:03:03 +02:00
ucef 0a56d83e2e feat(ci): add step to deploy backup script and env to DB server (10.8.0.3) via rsync
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m10s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 1m12s
2026-09-03 07:54:18 +02:00
ucef eaa54b767b feat(backup): add automated DB backup script, rsync support and Gitea CI secret integration
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m8s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 1m12s
2026-09-03 07:47:01 +02:00
ucef 21aabb778a chore: prepare release 1.8
AS Talange CI/CD Pipeline - Production / Build & Run Unit Tests (push) Successful in 2m12s
AS Talange CI/CD Pipeline - Production / Deploy to Prod Environment (push) Successful in 3m7s
2026-08-27 23:07:55 +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
23 changed files with 1332 additions and 56 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!"
'
+2 -1
View File
@@ -1,3 +1,4 @@
{
"java.compile.nullAnalysis.mode": "automatic"
"java.compile.nullAnalysis.mode": "automatic",
"java.configuration.updateBuildConfiguration": "interactive"
}
+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.8</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.8</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -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;
}
}
@@ -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;
}
}
@@ -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(";")
@@ -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);
}
}
@@ -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) <> ''
);
@@ -121,4 +121,56 @@ public class DotationServiceTest {
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);
}
}
+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.8</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -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,10 +194,13 @@ 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);
@@ -155,10 +212,13 @@ public class DotationController {
.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", "flocage_initiales_" + 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);
@@ -170,15 +230,82 @@ public class DotationController {
.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", "flocage_prenom_numero_" + 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/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(
@@ -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();
@@ -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>
@@ -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">
@@ -81,10 +89,26 @@
</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>
@@ -111,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>
@@ -129,9 +162,19 @@
</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') : ''}">
@@ -160,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>
@@ -175,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'}">
@@ -190,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>
@@ -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>
+1 -1
View File
@@ -13,7 +13,7 @@
<groupId>com.astalange</groupId>
<artifactId>as-talange-parent</artifactId>
<version>1.7-SNAPSHOT</version>
<version>1.8</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