- améliore l'export/import (format de fichiers en paramètres, amélioration de la robustesse, )

- ajout bouton tout effacer des propositions et participants
This commit is contained in:
Yannick Le Duc
2025-09-16 15:45:28 +02:00
parent 6aead108d7
commit 2a2738f5c0
16 changed files with 1455 additions and 81 deletions

View File

@@ -1,5 +1,21 @@
import * as XLSX from 'xlsx';
import { Proposition, Participant, Vote } from '@/types';
import { settingsService } from './services';
export type ExportFileFormat = 'ods' | 'csv' | 'xls';
/**
* Obtient le format de fichier d'export configuré dans les paramètres
*/
export async function getExportFileFormat(): Promise<ExportFileFormat> {
try {
const format = await settingsService.getStringValue('export_file_format', 'ods');
return format as ExportFileFormat;
} catch (error) {
console.error('Erreur lors de la récupération du format d\'export:', error);
return 'ods'; // Format par défaut
}
}
export interface ExportData {
campaignTitle: string;
@@ -25,6 +41,73 @@ export interface PropositionStats {
consensusScore: number;
}
export async function generateVoteExport(data: ExportData): Promise<{ data: Uint8Array | string; format: ExportFileFormat }> {
const format = await getExportFileFormat();
// Créer la matrice de données
const matrix: (string | number)[][] = [];
// Pour les formats Excel/ODS, ajouter un titre
if (format !== 'csv') {
matrix.push([`Statistiques de vote - ${data.campaignTitle}`]);
matrix.push([]); // Ligne vide
}
// En-têtes des colonnes : propositions + total
const headers = ['Participant', ...data.propositions.map(p => p.title), 'Total voté', 'Budget restant'];
matrix.push(headers);
// Données des participants
data.participants.forEach(participant => {
const row: (string | number)[] = [];
// Nom du participant (avec anonymisation)
const participantName = anonymizeParticipantName(participant, data.anonymizationLevel || 'full');
row.push(participantName);
// Votes pour chaque proposition
let totalVoted = 0;
data.propositions.forEach(proposition => {
const vote = data.votes.find(v =>
v.participant_id === participant.id &&
v.proposition_id === proposition.id
);
const amount = vote ? vote.amount : 0;
row.push(amount);
totalVoted += amount;
});
// Total voté par le participant
row.push(totalVoted);
// Budget restant
const budgetRemaining = data.budgetPerUser - totalVoted;
row.push(budgetRemaining);
matrix.push(row);
});
// Ligne des totaux
const totalRow: (string | number)[] = ['TOTAL'];
let grandTotal = 0;
data.propositions.forEach(proposition => {
const propositionTotal = data.votes
.filter(v => v.proposition_id === proposition.id)
.reduce((sum, vote) => sum + vote.amount, 0);
totalRow.push(propositionTotal);
grandTotal += propositionTotal;
});
totalRow.push(grandTotal);
totalRow.push(data.participants.length * data.budgetPerUser - grandTotal);
matrix.push(totalRow);
const exportData = generateExportFile(matrix, format);
return { data: exportData, format };
}
// Fonction de compatibilité (à supprimer plus tard)
export function generateVoteExportODS(data: ExportData): Uint8Array {
const { campaignTitle, propositions, participants, votes, budgetPerUser, propositionStats, anonymizationLevel = 'full' } = data;
@@ -248,6 +331,66 @@ export function generateVoteExportODS(data: ExportData): Uint8Array {
return new Uint8Array(odsBuffer);
}
/**
* Génère un fichier d'export dans le format spécifié
*/
export function generateExportFile(matrix: (string | number)[][], format: ExportFileFormat): Uint8Array | string {
if (format === 'csv') {
// Générer du CSV
return matrix.map(row =>
row.map(cell => {
const cellStr = String(cell || '');
// Échapper les guillemets et entourer de guillemets si nécessaire
if (cellStr.includes(',') || cellStr.includes('"') || cellStr.includes('\n')) {
return `"${cellStr.replace(/"/g, '""')}"`;
}
return cellStr;
}).join(',')
).join('\n');
} else {
// Générer un fichier Excel/ODS
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.aoa_to_sheet(matrix);
XLSX.utils.book_append_sheet(workbook, worksheet, 'Données');
const buffer = XLSX.write(workbook, {
bookType: format,
type: 'array'
});
return new Uint8Array(buffer);
}
}
/**
* Télécharge un fichier d'export
*/
export function downloadExportFile(data: Uint8Array | string, filename: string, format: ExportFileFormat): void {
let blob: Blob;
let mimeType: string;
if (format === 'csv') {
mimeType = 'text/csv;charset=utf-8';
blob = new Blob([data as string], { type: mimeType });
} else {
mimeType = format === 'ods'
? 'application/vnd.oasis.opendocument.spreadsheet'
: 'application/vnd.ms-excel';
blob = new Blob([data as Uint8Array], { type: mimeType });
}
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
export function downloadODS(data: Uint8Array, filename: string): void {
const blob = new Blob([data], {
type: 'application/vnd.oasis.opendocument.spreadsheet'
@@ -280,7 +423,145 @@ export function anonymizeParticipantName(participant: Participant, level: Anonym
}
}
export function formatFilename(campaignTitle: string): string {
/**
* Anonymise le nom d'un auteur de proposition
*/
export function anonymizeAuthorName(name: string, level: AnonymizationLevel): string {
switch (level) {
case 'full':
return 'XXXX';
case 'initials':
return name.charAt(0).toUpperCase() + '.';
case 'none':
return name;
default:
return 'XXXX';
}
}
/**
* Anonymise l'email d'un auteur de proposition
*/
export function anonymizeAuthorEmail(email: string, level: AnonymizationLevel): string {
switch (level) {
case 'full':
return 'xxxx@xxxx.xxx';
case 'initials':
// Garder le domaine mais anonymiser la partie locale
const [localPart, domain] = email.split('@');
if (domain) {
return `${localPart.charAt(0)}***@${domain}`;
}
return 'x***@xxxx.xxx';
case 'none':
return email;
default:
return 'xxxx@xxxx.xxx';
}
}
export async function generatePropositionsExport(propositions: Proposition[], campaignTitle: string): Promise<{ data: Uint8Array | string; format: ExportFileFormat }> {
const format = await getExportFileFormat();
const anonymizationLevel = await settingsService.getStringValue('export_anonymization', 'full') as AnonymizationLevel;
// Créer la matrice de données
const matrix: (string | number)[][] = [];
// Pour les formats Excel/ODS, ajouter un titre
if (format !== 'csv') {
matrix.push([`Liste des propositions - ${campaignTitle}`]);
matrix.push([]); // Ligne vide
}
// En-têtes des colonnes (en français)
const headers = ['Titre', 'Description', 'Prénom', 'Nom', 'Email'];
matrix.push(headers);
// Données des propositions avec anonymisation
propositions.forEach(proposition => {
const row: (string | number)[] = [
proposition.title,
proposition.description,
anonymizeAuthorName(proposition.author_first_name, anonymizationLevel),
anonymizeAuthorName(proposition.author_last_name, anonymizationLevel),
anonymizeAuthorEmail(proposition.author_email, anonymizationLevel)
];
matrix.push(row);
});
const data = generateExportFile(matrix, format);
return { data, format };
}
// Fonction de compatibilité (à supprimer plus tard)
export function generatePropositionsExportODS(propositions: Proposition[], campaignTitle: string): Uint8Array {
// Créer la matrice de données
const matrix: (string | number)[][] = [];
// En-têtes : Titre de la campagne
matrix.push([`Liste des propositions - ${campaignTitle}`]);
matrix.push([]); // Ligne vide
// En-têtes des colonnes (en français)
const headers = ['Titre', 'Description', 'Prénom', 'Nom', 'Email'];
matrix.push(headers);
// Données des propositions (sans anonymisation pour la compatibilité - utiliser la nouvelle fonction)
propositions.forEach(proposition => {
const row: (string | number)[] = [
proposition.title,
proposition.description,
proposition.author_first_name,
proposition.author_last_name,
proposition.author_email
];
matrix.push(row);
});
// Créer le workbook et worksheet
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.aoa_to_sheet(matrix);
// Ajouter des styles pour les colonnes
worksheet['!cols'] = [
{ width: 30 }, // Titre
{ width: 50 }, // Description
{ width: 15 }, // Prénom
{ width: 15 }, // Nom
{ width: 25 }, // Email
{ width: 15 } // Date de création
];
// Style pour les en-têtes (texte en gras)
for (let col = 0; col < headers.length; col++) {
const cellRef = XLSX.utils.encode_cell({ r: 2, c: col }); // Ligne 3 (index 2) pour les en-têtes
if (!worksheet[cellRef]) {
worksheet[cellRef] = { v: matrix[2][col] };
}
worksheet[cellRef].s = {
font: { bold: true },
border: {
top: { style: 'thick' },
bottom: { style: 'thick' },
left: { style: 'thin' },
right: { style: 'thin' }
}
};
}
// Ajouter le worksheet au workbook
XLSX.utils.book_append_sheet(workbook, worksheet, 'Propositions');
// Générer le fichier ODS
const odsBuffer = XLSX.write(workbook, {
bookType: 'ods',
type: 'array'
});
return new Uint8Array(odsBuffer);
}
export function formatFilename(campaignTitle: string, format: ExportFileFormat = 'ods'): string {
const sanitizedTitle = campaignTitle
.replace(/[^a-zA-Z0-9\s]/g, '')
.replace(/\s+/g, '_')
@@ -290,7 +571,23 @@ export function formatFilename(campaignTitle: string): string {
const date = new Date().toISOString().split('T')[0];
const prefix = sanitizedTitle ? `statistiques_vote_${sanitizedTitle}_` : 'statistiques_vote_';
const filename = `${prefix}${date}.ods`;
const filename = `${prefix}${date}.${format}`;
// Nettoyer les underscores multiples à la fin
return filename.replace(/_+/g, '_');
}
export function formatPropositionsFilename(campaignTitle: string, format: ExportFileFormat = 'ods'): string {
const sanitizedTitle = campaignTitle
.replace(/[^a-zA-Z0-9\s]/g, '')
.replace(/\s+/g, '_')
.replace(/_+/g, '_') // Remplacer les underscores multiples par un seul
.toLowerCase()
.trim();
const date = new Date().toISOString().split('T')[0];
const prefix = sanitizedTitle ? `propositions_${sanitizedTitle}_` : 'propositions_';
const filename = `${prefix}${date}.${format}`;
// Nettoyer les underscores multiples à la fin
return filename.replace(/_+/g, '_');

View File

@@ -23,15 +23,34 @@ export function parseCSV(file: File): Promise<ParsedFileData> {
return;
}
const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''));
const data = lines.slice(1).map(line => {
const values = line.split(',').map(v => v.trim().replace(/"/g, ''));
const row: any = {};
headers.forEach((header, index) => {
row[header] = values[index] || '';
// Trouver la ligne d'en-têtes (ignorer les lignes de titre et vides)
let headerLineIndex = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Si la ligne contient des virgules et ressemble à des en-têtes
if (line.includes(',') && !line.toLowerCase().includes('modèle') && !line.toLowerCase().includes('liste')) {
headerLineIndex = i;
break;
}
}
const headers = lines[headerLineIndex].split(',').map(h => h.trim().replace(/"/g, ''));
const dataLines = lines.slice(headerLineIndex + 1);
const data = dataLines
.filter(line => line.trim()) // Ignorer les lignes vides
.map(line => {
const values = line.split(',').map(v => v.trim().replace(/"/g, ''));
const row: any = {};
headers.forEach((header, index) => {
row[header] = values[index] || '';
});
return row;
})
.filter(row => {
// Ignorer les lignes où tous les champs sont vides
return Object.values(row).some(value => value && value.toString().trim());
});
return row;
});
resolve({ data, headers });
} catch (error) {
@@ -62,16 +81,39 @@ export function parseExcel(file: File): Promise<ParsedFileData> {
return;
}
const headers = jsonData[0] as string[];
const rows = jsonData.slice(1) as any[][];
// Trouver la ligne d'en-têtes (ignorer les lignes de titre et vides)
let headerLineIndex = 0;
for (let i = 0; i < jsonData.length; i++) {
const row = jsonData[i] as any[];
if (row && row.length > 0) {
const firstCell = row[0];
// Si la première cellule ressemble à un en-tête et pas à un titre
if (firstCell && typeof firstCell === 'string' &&
!firstCell.toLowerCase().includes('modèle') &&
!firstCell.toLowerCase().includes('liste') &&
!firstCell.toLowerCase().includes('propositions')) {
headerLineIndex = i;
break;
}
}
}
const headers = (jsonData[headerLineIndex] as string[]).filter(h => h && h.toString().trim());
const rows = jsonData.slice(headerLineIndex + 1) as any[][];
const parsedData = rows.map(row => {
const rowData: any = {};
headers.forEach((header, index) => {
rowData[header] = row[index] || '';
const parsedData = rows
.filter(row => row && row.length > 0) // Ignorer les lignes vides
.map(row => {
const rowData: any = {};
headers.forEach((header, index) => {
rowData[header] = row[index] || '';
});
return rowData;
})
.filter(rowData => {
// Ignorer les lignes où tous les champs sont vides
return Object.values(rowData).some(value => value && value.toString().trim());
});
return rowData;
});
resolve({ data: parsedData, headers });
} catch (error) {
@@ -84,22 +126,47 @@ export function parseExcel(file: File): Promise<ParsedFileData> {
export function getExpectedColumns(type: 'propositions' | 'participants'): string[] {
if (type === 'propositions') {
return ['title', 'description', 'author_first_name', 'author_last_name', 'author_email'];
return ['Titre', 'Description', 'Prénom', 'Nom', 'Email'];
} else {
return ['first_name', 'last_name', 'email'];
return ['Prénom', 'Nom', 'Email'];
}
}
export function downloadTemplate(type: 'propositions' | 'participants'): void {
export async function downloadTemplate(type: 'propositions' | 'participants'): Promise<void> {
const columns = getExpectedColumns(type);
const csvContent = columns.join(',') + '\n';
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `template_${type}.csv`;
a.click();
window.URL.revokeObjectURL(url);
// Importer dynamiquement la fonction pour éviter les dépendances circulaires
const { getExportFileFormat, generateExportFile, downloadExportFile } = await import('./export-utils');
const format = await getExportFileFormat();
// Créer la matrice de données avec les en-têtes
const matrix: string[][] = [];
// Pour les formats Excel/ODS, ajouter un titre
if (format !== 'csv') {
matrix.push([`Modèle d'import - ${type === 'propositions' ? 'Propositions' : 'Participants'}`]);
matrix.push([]); // Ligne vide
}
matrix.push(columns); // En-têtes des colonnes
// Ajouter quelques lignes d'exemple
if (type === 'propositions') {
matrix.push(['Exemple de proposition', 'Description de la proposition', 'Jean', 'Dupont', 'jean.dupont@example.com']);
matrix.push(['Autre proposition', 'Autre description', 'Marie', 'Martin', 'marie.martin@example.com']);
} else {
matrix.push(['Jean', 'Dupont', 'jean.dupont@example.com']);
matrix.push(['Marie', 'Martin', 'marie.martin@example.com']);
}
// Générer le fichier dans le format configuré
const data = generateExportFile(matrix, format);
// Créer le nom de fichier avec l'extension appropriée
const filename = `template_${type}.${format}`;
// Télécharger le fichier
downloadExportFile(data, filename, format);
}
export function validateFileType(file: File): { isValid: boolean; error?: string } {

View File

@@ -276,6 +276,15 @@ export const propositionService = {
.delete()
.eq('id', id);
if (error) throw error;
},
async deleteAllByCampaign(campaignId: string): Promise<void> {
const { error } = await supabase
.from('propositions')
.delete()
.eq('campaign_id', campaignId);
if (error) throw error;
}
};
@@ -363,6 +372,15 @@ export const participantService = {
if (error) throw error;
},
async deleteAllByCampaign(campaignId: string): Promise<void> {
const { error } = await supabase
.from('participants')
.delete()
.eq('campaign_id', campaignId);
if (error) throw error;
},
// Nouvelle méthode pour récupérer un participant par short_id
async getByShortId(shortId: string): Promise<Participant | null> {
const { data, error } = await supabase