feat: ajout du systeme d'historique et de persistance des exports CSV

This commit is contained in:
2026-08-27 10:37:54 +02:00
parent 851fb36c2a
commit 2bc702d9bc
8 changed files with 503 additions and 0 deletions
@@ -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);
}
@@ -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,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);
}
}
@@ -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> <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/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/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 --> <!-- Paramétrage -->
<div class="pt-4 pb-2 px-3 text-xs font-semibold text-gray-400 uppercase tracking-wider">Paramétrage</div> <div class="pt-4 pb-2 px-3 text-xs font-semibold text-gray-400 uppercase tracking-wider">Paramétrage</div>
@@ -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>