ajout envoi smtp (paramètres, test envois, envoi à 1 participant). protège vue mot de passe

- ajout filtre page statistiques
This commit is contained in:
Yannick Le Duc
2025-08-25 18:28:14 +02:00
parent caed358661
commit b0a945f07b
21 changed files with 3523 additions and 30 deletions

View File

@@ -8,6 +8,7 @@ import AddParticipantModal from '@/components/AddParticipantModal';
import EditParticipantModal from '@/components/EditParticipantModal';
import DeleteParticipantModal from '@/components/DeleteParticipantModal';
import ImportCSVModal from '@/components/ImportCSVModal';
import SendParticipantEmailModal from '@/components/SendParticipantEmailModal';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -29,6 +30,7 @@ function CampaignParticipantsPageContent() {
const [showEditModal, setShowEditModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showImportModal, setShowImportModal] = useState(false);
const [showSendEmailModal, setShowSendEmailModal] = useState(false);
const [selectedParticipant, setSelectedParticipant] = useState<Participant | null>(null);
const [copiedParticipantId, setCopiedParticipantId] = useState<string | null>(null);
@@ -357,6 +359,18 @@ function CampaignParticipantsPageContent() {
</>
)}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => {
setSelectedParticipant(participant);
setShowSendEmailModal(true);
}}
className="text-xs"
>
<Mail className="w-3 h-3 mr-1" />
Envoyer un mail
</Button>
</div>
</div>
</div>
@@ -402,6 +416,15 @@ function CampaignParticipantsPageContent() {
type="participants"
campaignTitle={campaign?.title}
/>
{selectedParticipant && campaign && (
<SendParticipantEmailModal
isOpen={showSendEmailModal}
onClose={() => setShowSendEmailModal(false)}
participant={selectedParticipant}
campaign={campaign}
/>
)}
</div>
</div>
);

View File

@@ -9,6 +9,7 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import Navigation from '@/components/Navigation';
import AuthGuard from '@/components/AuthGuard';
import {
@@ -20,7 +21,12 @@ import {
Award,
FileText,
Calendar,
ArrowLeft
ArrowLeft,
SortAsc,
TrendingDown,
Users2,
Target as TargetIcon,
Hash
} from 'lucide-react';
export const dynamic = 'force-dynamic';
@@ -31,8 +37,29 @@ interface PropositionStats {
averageAmount: number;
minAmount: number;
maxAmount: number;
totalAmount: number;
participationRate: number;
voteDistribution: number;
consensusScore: number;
}
type SortOption =
| 'popularity'
| 'total_impact'
| 'consensus'
| 'engagement'
| 'distribution'
| 'alphabetical';
const sortOptions = [
{ value: 'popularity', label: 'Popularité', icon: TrendingUp, description: 'Moyenne décroissante puis nombre de votants' },
{ value: 'total_impact', label: 'Impact total', icon: Target, description: 'Somme totale investie décroissante' },
{ value: 'consensus', label: 'Consensus', icon: Users2, description: 'Plus petit écart-type = plus de consensus' },
{ value: 'engagement', label: 'Engagement', icon: Users, description: 'Taux de participation décroissant' },
{ value: 'distribution', label: 'Répartition', icon: BarChart3, description: 'Nombre de votes différents' },
{ value: 'alphabetical', label: 'Alphabétique', icon: Hash, description: 'Ordre alphabétique par titre' }
];
function CampaignStatsPageContent() {
const params = useParams();
const campaignId = params.id as string;
@@ -43,6 +70,7 @@ function CampaignStatsPageContent() {
const [votes, setVotes] = useState<Vote[]>([]);
const [loading, setLoading] = useState(true);
const [propositionStats, setPropositionStats] = useState<PropositionStats[]>([]);
const [sortBy, setSortBy] = useState<SortOption>('popularity');
useEffect(() => {
if (campaignId) {
@@ -74,13 +102,33 @@ function CampaignStatsPageContent() {
const stats = propositionsData.map(proposition => {
const propositionVotes = votesData.filter(vote => vote.proposition_id === proposition.id && vote.amount > 0);
const amounts = propositionVotes.map(vote => vote.amount);
const totalAmount = amounts.reduce((sum, amount) => sum + amount, 0);
// Calculer l'écart-type pour le consensus
const mean = amounts.length > 0 ? totalAmount / amounts.length : 0;
const variance = amounts.length > 0
? amounts.reduce((sum, amount) => sum + Math.pow(amount - mean, 2), 0) / amounts.length
: 0;
const consensusScore = Math.sqrt(variance);
// Calculer le taux de participation pour cette proposition
const participationRate = participantsData.length > 0
? (propositionVotes.length / participantsData.length) * 100
: 0;
// Calculer la répartition des votes (nombre de montants différents)
const uniqueAmounts = new Set(amounts).size;
return {
proposition,
voteCount: propositionVotes.length,
averageAmount: amounts.length > 0 ? Math.round(amounts.reduce((sum, amount) => sum + amount, 0) / amounts.length) : 0,
averageAmount: amounts.length > 0 ? Math.round(totalAmount / amounts.length) : 0,
minAmount: amounts.length > 0 ? Math.min(...amounts) : 0,
maxAmount: amounts.length > 0 ? Math.max(...amounts) : 0
maxAmount: amounts.length > 0 ? Math.max(...amounts) : 0,
totalAmount,
participationRate: Math.round(participationRate * 100) / 100,
voteDistribution: uniqueAmounts,
consensusScore: Math.round(consensusScore * 100) / 100
};
});
@@ -92,6 +140,38 @@ function CampaignStatsPageContent() {
}
};
const getSortedStats = () => {
const sorted = [...propositionStats];
switch (sortBy) {
case 'popularity':
return sorted.sort((a, b) => {
if (b.averageAmount !== a.averageAmount) {
return b.averageAmount - a.averageAmount;
}
return b.voteCount - a.voteCount;
});
case 'total_impact':
return sorted.sort((a, b) => b.totalAmount - a.totalAmount);
case 'consensus':
return sorted.sort((a, b) => a.consensusScore - b.consensusScore);
case 'engagement':
return sorted.sort((a, b) => b.participationRate - a.participationRate);
case 'distribution':
return sorted.sort((a, b) => b.voteDistribution - a.voteDistribution);
case 'alphabetical':
return sorted.sort((a, b) => a.proposition.title.localeCompare(b.proposition.title));
default:
return sorted;
}
};
const getParticipationRate = () => {
if (participants.length === 0) return 0;
const votedParticipants = participants.filter(p => {
@@ -101,8 +181,6 @@ function CampaignStatsPageContent() {
return Math.round((votedParticipants.length / participants.length) * 100);
};
const getAverageVotesPerProposition = () => {
if (propositions.length === 0) return 0;
const totalVotes = votes.filter(v => v.amount > 0).length;
@@ -230,13 +308,42 @@ function CampaignStatsPageContent() {
{/* Propositions Stats */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<VoteIcon className="w-5 h-5" />
Préférences par proposition
</CardTitle>
<CardDescription>
Statistiques des montants exprimés par les participants pour chaque proposition
</CardDescription>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<CardTitle className="flex items-center gap-2">
<VoteIcon className="w-5 h-5" />
Préférences par proposition
</CardTitle>
<CardDescription>
Statistiques des montants exprimés par les participants pour chaque proposition
</CardDescription>
</div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-slate-600 dark:text-slate-300">Trier par :</span>
<Select value={sortBy} onValueChange={(value: SortOption) => setSortBy(value)}>
<SelectTrigger className="w-48">
<SelectValue />
</SelectTrigger>
<SelectContent>
{sortOptions.map((option) => {
const IconComponent = option.icon;
return (
<SelectItem key={option.value} value={option.value}>
<div className="flex items-center gap-2">
<IconComponent className="w-4 h-4" />
<div>
<div className="font-medium">{option.label}</div>
<div className="text-xs text-slate-500">{option.description}</div>
</div>
</div>
</SelectItem>
);
})}
</SelectContent>
</Select>
</div>
</div>
</CardHeader>
<CardContent>
{propositionStats.length === 0 ? (
@@ -251,9 +358,7 @@ function CampaignStatsPageContent() {
</div>
) : (
<div className="space-y-6">
{propositionStats
.sort((a, b) => b.averageAmount - a.averageAmount) // Trier par moyenne décroissante
.map((stat, index) => (
{getSortedStats().map((stat, index) => (
<div key={stat.proposition.id} className="border rounded-lg p-6 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
@@ -269,15 +374,19 @@ function CampaignStatsPageContent() {
{stat.proposition.description}
</p>
</div>
{index === 0 && stat.averageAmount > 0 && (
<Badge className="bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200">
<Award className="w-3 h-3 mr-1" />
Préférée
</Badge>
)}
{index === 0 && stat.averageAmount > 0 && (
<Badge className="bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200">
<Award className="w-3 h-3 mr-1" />
{sortBy === 'popularity' ? 'Préférée' :
sortBy === 'total_impact' ? 'Plus d\'impact' :
sortBy === 'consensus' ? 'Plus de consensus' :
sortBy === 'engagement' ? 'Plus d\'engagement' :
sortBy === 'distribution' ? 'Plus de répartition' : 'Première'}
</Badge>
)}
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
<div className="text-center">
<p className="text-2xl font-bold text-blue-600 dark:text-blue-400">
{stat.voteCount}
@@ -292,6 +401,12 @@ function CampaignStatsPageContent() {
</p>
<p className="text-xs text-slate-500 dark:text-slate-400">Moyenne</p>
</div>
<div className="text-center">
<p className="text-2xl font-bold text-purple-600 dark:text-purple-400">
{stat.totalAmount}
</p>
<p className="text-xs text-slate-500 dark:text-slate-400">Total</p>
</div>
<div className="text-center">
<p className="text-2xl font-bold text-orange-600 dark:text-orange-400">
{stat.minAmount}
@@ -304,6 +419,34 @@ function CampaignStatsPageContent() {
</p>
<p className="text-xs text-slate-500 dark:text-slate-400">Maximum</p>
</div>
<div className="text-center">
<p className="text-2xl font-bold text-indigo-600 dark:text-indigo-400">
{stat.participationRate}%
</p>
<p className="text-xs text-slate-500 dark:text-slate-400">Participation</p>
</div>
</div>
{/* Métriques avancées */}
<div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
<div className="flex items-center gap-2">
<Users2 className="w-4 h-4 text-slate-500" />
<span className="text-sm text-slate-600 dark:text-slate-300">Consensus</span>
</div>
<Badge variant="outline" className="text-xs">
Écart-type: {stat.consensusScore}
</Badge>
</div>
<div className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
<div className="flex items-center gap-2">
<BarChart3 className="w-4 h-4 text-slate-500" />
<span className="text-sm text-slate-600 dark:text-slate-300">Répartition</span>
</div>
<Badge variant="outline" className="text-xs">
{stat.voteDistribution} montants différents
</Badge>
</div>
</div>
{stat.voteCount > 0 && (

View File

@@ -13,7 +13,7 @@ import { Input } from '@/components/ui/input';
import { Progress } from '@/components/ui/progress';
import Navigation from '@/components/Navigation';
import AuthGuard from '@/components/AuthGuard';
import { FolderOpen, Users, FileText, CheckCircle, Clock, Plus, BarChart3 } from 'lucide-react';
import { FolderOpen, Users, FileText, CheckCircle, Clock, Plus, BarChart3, Settings } from 'lucide-react';
export const dynamic = 'force-dynamic';
@@ -123,10 +123,18 @@ function AdminPageContent() {
<h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100">Administration</h1>
<p className="text-slate-600 dark:text-slate-300 mt-2">Gérez vos campagnes de budget participatif</p>
</div>
<Button onClick={() => setShowCreateModal(true)} size="lg">
<Plus className="w-4 h-4 mr-2" />
Nouvelle campagne
</Button>
<div className="flex gap-2">
<Button asChild variant="outline" size="lg">
<Link href="/admin/settings">
<Settings className="w-4 h-4 mr-2" />
Paramètres
</Link>
</Button>
<Button onClick={() => setShowCreateModal(true)} size="lg">
<Plus className="w-4 h-4 mr-2" />
Nouvelle campagne
</Button>
</div>
</div>
</div>

View File

@@ -0,0 +1,181 @@
'use client';
import { useState, useEffect } from 'react';
import { Setting } from '@/types';
import { settingsService } from '@/lib/services';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import Navigation from '@/components/Navigation';
import AuthGuard from '@/components/AuthGuard';
import SmtpSettingsForm from '@/components/SmtpSettingsForm';
import { Settings, Monitor, Save, CheckCircle, Mail } from 'lucide-react';
export const dynamic = 'force-dynamic';
function SettingsPageContent() {
const [settings, setSettings] = useState<Setting[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [randomizePropositions, setRandomizePropositions] = useState(false);
useEffect(() => {
loadSettings();
}, []);
const loadSettings = async () => {
try {
setLoading(true);
const settingsData = await settingsService.getAll();
setSettings(settingsData);
// Charger la valeur du paramètre d'ordre aléatoire
const randomizeValue = await settingsService.getBooleanValue('randomize_propositions', false);
setRandomizePropositions(randomizeValue);
} catch (error) {
console.error('Erreur lors du chargement des paramètres:', error);
} finally {
setLoading(false);
}
};
const handleRandomizeChange = async (checked: boolean) => {
setRandomizePropositions(checked);
};
const handleSave = async () => {
try {
setSaving(true);
await settingsService.setBooleanValue('randomize_propositions', randomizePropositions);
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} catch (error) {
console.error('Erreur lors de la sauvegarde des paramètres:', error);
} finally {
setSaving(false);
}
};
if (loading) {
return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-900">
<div className="container mx-auto px-4 py-8">
<Navigation />
<div className="flex items-center justify-center h-64">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-slate-900 dark:border-slate-100 mx-auto mb-4"></div>
<p className="text-slate-600 dark:text-slate-300">Chargement des paramètres...</p>
</div>
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-900">
<div className="container mx-auto px-4 py-8">
<Navigation />
{/* Header */}
<div className="mb-8">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100">Paramètres</h1>
<p className="text-slate-600 dark:text-slate-300 mt-2">Configurez les paramètres de l'application</p>
</div>
<Button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-2"
>
{saving ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Sauvegarde...
</>
) : saved ? (
<>
<CheckCircle className="w-4 h-4" />
Sauvegardé
</>
) : (
<>
<Save className="w-4 h-4" />
Sauvegarder
</>
)}
</Button>
</div>
</div>
{/* Settings Categories */}
<div className="space-y-8">
{/* Affichage Category */}
<Card>
<CardHeader>
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
<Monitor className="w-5 h-5 text-blue-600 dark:text-blue-300" />
</div>
<div>
<CardTitle className="text-xl">Affichage</CardTitle>
<CardDescription>
Paramètres d'affichage de l'interface utilisateur
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="space-y-6">
{/* Randomize Propositions Setting */}
<div className="flex items-center justify-between p-4 bg-slate-50 dark:bg-slate-800 rounded-lg">
<div className="flex-1">
<Label htmlFor="randomize-propositions" className="text-base font-medium">
Afficher les propositions dans un ordre aléatoire lors du vote
</Label>
<p className="text-sm text-slate-600 dark:text-slate-300 mt-1">
Lorsque activé, les propositions seront affichées dans un ordre aléatoire pour chaque participant lors du vote.
</p>
</div>
<Switch
id="randomize-propositions"
checked={randomizePropositions}
onCheckedChange={handleRandomizeChange}
className="ml-4"
/>
</div>
</CardContent>
</Card>
{/* Email Category */}
<SmtpSettingsForm onSave={() => {
setSaved(true);
setTimeout(() => setSaved(false), 2000);
}} />
{/* Future Categories Placeholder */}
<Card className="border-dashed">
<CardContent className="p-8 text-center">
<Settings className="w-12 h-12 text-slate-400 mx-auto mb-4" />
<h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2">
Plus de catégories à venir
</h3>
<p className="text-slate-600 dark:text-slate-300">
D'autres catégories de paramètres seront ajoutées prochainement.
</p>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
export default function SettingsPage() {
return (
<AuthGuard>
<SettingsPageContent />
</AuthGuard>
);
}

View File

@@ -0,0 +1,151 @@
import { NextRequest, NextResponse } from 'next/server';
import * as nodemailer from 'nodemailer';
import { SmtpSettings } from '@/types';
export async function POST(request: NextRequest) {
try {
const {
smtpSettings,
toEmail,
toName,
subject,
message,
campaignTitle,
voteUrl
} = await request.json();
// Validation des paramètres
if (!smtpSettings || !toEmail || !toName || !subject || !message) {
return NextResponse.json(
{ success: false, error: 'Paramètres manquants' },
{ status: 400 }
);
}
// Validation de l'email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(toEmail)) {
return NextResponse.json(
{ success: false, error: 'Adresse email de destination invalide' },
{ status: 400 }
);
}
// Validation des paramètres SMTP
if (!smtpSettings.host || !smtpSettings.port || !smtpSettings.username || !smtpSettings.password) {
return NextResponse.json(
{ success: false, error: 'Paramètres SMTP incomplets' },
{ status: 400 }
);
}
// Créer le transporteur SMTP
const transporter = nodemailer.createTransport({
host: smtpSettings.host,
port: smtpSettings.port,
secure: smtpSettings.secure,
auth: {
user: smtpSettings.username,
pass: smtpSettings.password,
},
tls: {
rejectUnauthorized: false,
},
connectionTimeout: 10000,
greetingTimeout: 10000,
socketTimeout: 10000,
});
// Vérifier la connexion
await transporter.verify();
// Créer le contenu HTML de l'email
const htmlContent = `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; line-height: 1.6;">
<div style="background-color: #2563eb; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0;">
<h1 style="margin: 0; font-size: 24px;">Mes Budgets Participatifs</h1>
</div>
<div style="background-color: #ffffff; padding: 30px; border: 1px solid #e5e7eb; border-top: none;">
<h2 style="color: #1f2937; margin-top: 0;">Bonjour ${toName},</h2>
<div style="background-color: #f3f4f6; padding: 20px; border-radius: 8px; margin: 20px 0;">
<h3 style="margin-top: 0; color: #374151;">Campagne : ${campaignTitle}</h3>
<p style="margin-bottom: 0; color: #6b7280;">${message.replace(/\n/g, '<br>')}</p>
</div>
<div style="text-align: center; margin: 30px 0;">
<a href="${voteUrl}"
style="background-color: #2563eb; color: white; padding: 15px 30px; text-decoration: none; border-radius: 6px; font-weight: bold; display: inline-block;">
🗳️ Voter maintenant
</a>
</div>
<div style="background-color: #fef3c7; padding: 15px; border-radius: 6px; margin: 20px 0;">
<p style="margin: 0; color: #92400e; font-size: 14px;">
<strong>💡 Conseil :</strong> Ce lien est personnel et unique. Ne le partagez pas avec d'autres personnes.
</p>
</div>
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 30px 0;">
<p style="color: #6b7280; font-size: 14px; margin-bottom: 10px;">
Si le bouton ne fonctionne pas, vous pouvez copier et coller ce lien dans votre navigateur :
</p>
<p style="background-color: #f3f4f6; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; word-break: break-all; color: #374151;">
${voteUrl}
</p>
</div>
<div style="background-color: #f9fafb; padding: 20px; text-align: center; border-radius: 0 0 8px 8px; border: 1px solid #e5e7eb; border-top: none;">
<p style="color: #6b7280; font-size: 12px; margin: 0;">
Cet email a été envoyé automatiquement par Mes Budgets Participatifs.<br>
Si vous avez des questions, contactez l'administrateur de la campagne.
</p>
</div>
</div>
`;
// Envoyer l'email
const info = await transporter.sendMail({
from: `"${smtpSettings.from_name}" <${smtpSettings.from_email}>`,
to: `"${toName}" <${toEmail}>`,
subject: subject,
text: message,
html: htmlContent,
});
return NextResponse.json({
success: true,
messageId: info.messageId,
message: 'Email envoyé avec succès'
});
} catch (error) {
console.error('Erreur lors de l\'envoi de l\'email au participant:', error);
let errorMessage = 'Erreur lors de l\'envoi de l\'email';
if (error instanceof Error) {
if (error.message.includes('EBADNAME')) {
errorMessage = 'Impossible de résoudre le nom d\'hôte SMTP. Vérifiez que le serveur SMTP est correct.';
} else if (error.message.includes('ECONNREFUSED')) {
errorMessage = 'Connexion refusée. Vérifiez le serveur et le port SMTP.';
} else if (error.message.includes('ETIMEDOUT')) {
errorMessage = 'Délai d\'attente dépassé. Vérifiez votre connexion internet et les paramètres SMTP.';
} else if (error.message.includes('EAUTH')) {
errorMessage = 'Authentification échouée. Vérifiez le nom d\'utilisateur et le mot de passe SMTP.';
} else {
errorMessage = error.message;
}
}
return NextResponse.json(
{
success: false,
error: errorMessage
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,134 @@
import { NextRequest, NextResponse } from 'next/server';
import * as nodemailer from 'nodemailer';
import { SmtpSettings } from '@/types';
export async function POST(request: NextRequest) {
try {
const { smtpSettings, toEmail } = await request.json();
// Validation des paramètres
if (!smtpSettings || !toEmail) {
return NextResponse.json(
{ success: false, error: 'Paramètres manquants' },
{ status: 400 }
);
}
// Validation de l'email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(toEmail)) {
return NextResponse.json(
{ success: false, error: 'Adresse email de destination invalide' },
{ status: 400 }
);
}
// Validation des paramètres SMTP
if (!smtpSettings.host || !smtpSettings.port || !smtpSettings.username || !smtpSettings.password) {
return NextResponse.json(
{ success: false, error: 'Paramètres SMTP incomplets' },
{ status: 400 }
);
}
// Créer le transporteur SMTP avec options de résolution DNS
const transporter = nodemailer.createTransport({
host: smtpSettings.host,
port: smtpSettings.port,
secure: smtpSettings.secure, // true pour 465, false pour les autres ports
auth: {
user: smtpSettings.username,
pass: smtpSettings.password,
},
// Options pour résoudre les problèmes DNS
tls: {
rejectUnauthorized: false, // Accepte les certificats auto-signés
},
// Timeout pour éviter les blocages
connectionTimeout: 10000, // 10 secondes
greetingTimeout: 10000,
socketTimeout: 10000,
});
// Vérifier la connexion
await transporter.verify();
// Envoyer l'email de test
const info = await transporter.sendMail({
from: `"${smtpSettings.from_name}" <${smtpSettings.from_email}>`,
to: toEmail,
subject: 'Test de configuration SMTP - Mes Budgets Participatifs',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #2563eb;">✅ Test de configuration SMTP réussi !</h2>
<p>Bonjour,</p>
<p>Cet email confirme que votre configuration SMTP fonctionne correctement.</p>
<div style="background-color: #f3f4f6; padding: 15px; border-radius: 8px; margin: 20px 0;">
<h3 style="margin-top: 0;">Configuration utilisée :</h3>
<ul style="margin: 0; padding-left: 20px;">
<li><strong>Serveur :</strong> ${smtpSettings.host}:${smtpSettings.port}</li>
<li><strong>Sécurisé :</strong> ${smtpSettings.secure ? 'Oui (SSL/TLS)' : 'Non'}</li>
<li><strong>Utilisateur :</strong> ${smtpSettings.username}</li>
<li><strong>Expéditeur :</strong> ${smtpSettings.from_name} &lt;${smtpSettings.from_email}&gt;</li>
</ul>
</div>
<p>Vous pouvez maintenant utiliser cette configuration pour envoyer des emails automatiques depuis votre application.</p>
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 20px 0;">
<p style="color: #6b7280; font-size: 12px;">
Cet email a été envoyé automatiquement par Mes Budgets Participatifs pour tester la configuration SMTP.
</p>
</div>
`,
text: `
Test de configuration SMTP réussi !
Bonjour,
Cet email confirme que votre configuration SMTP fonctionne correctement.
Configuration utilisée :
- Serveur : ${smtpSettings.host}:${smtpSettings.port}
- Sécurisé : ${smtpSettings.secure ? 'Oui (SSL/TLS)' : 'Non'}
- Utilisateur : ${smtpSettings.username}
- Expéditeur : ${smtpSettings.from_name} <${smtpSettings.from_email}>
Vous pouvez maintenant utiliser cette configuration pour envoyer des emails automatiques depuis votre application.
---
Cet email a été envoyé automatiquement par Mes Budgets Participatifs pour tester la configuration SMTP.
`
});
return NextResponse.json({
success: true,
messageId: info.messageId
});
} catch (error) {
console.error('Erreur lors de l\'envoi de l\'email de test:', error);
let errorMessage = 'Erreur lors de l\'envoi de l\'email';
if (error instanceof Error) {
if (error.message.includes('EBADNAME')) {
errorMessage = 'Impossible de résoudre le nom d\'hôte SMTP. Vérifiez que le serveur SMTP est correct.';
} else if (error.message.includes('ECONNREFUSED')) {
errorMessage = 'Connexion refusée. Vérifiez le serveur et le port SMTP.';
} else if (error.message.includes('ETIMEDOUT')) {
errorMessage = 'Délai d\'attente dépassé. Vérifiez votre connexion internet et les paramètres SMTP.';
} else if (error.message.includes('EAUTH')) {
errorMessage = 'Authentification échouée. Vérifiez le nom d\'utilisateur et le mot de passe.';
} else {
errorMessage = error.message;
}
}
return NextResponse.json(
{
success: false,
error: errorMessage
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,95 @@
import { NextRequest, NextResponse } from 'next/server';
import * as nodemailer from 'nodemailer';
import { SmtpSettings } from '@/types';
export async function POST(request: NextRequest) {
try {
const { smtpSettings } = await request.json();
// Validation des paramètres
if (!smtpSettings) {
return NextResponse.json(
{ success: false, error: 'Paramètres SMTP manquants' },
{ status: 400 }
);
}
// Validation des paramètres SMTP
if (!smtpSettings.host || !smtpSettings.port || !smtpSettings.username || !smtpSettings.password) {
return NextResponse.json(
{ success: false, error: 'Paramètres SMTP incomplets' },
{ status: 400 }
);
}
// Validation du port
if (smtpSettings.port < 1 || smtpSettings.port > 65535) {
return NextResponse.json(
{ success: false, error: 'Port SMTP invalide' },
{ status: 400 }
);
}
// Validation de l'email d'expédition
if (!smtpSettings.from_email.includes('@')) {
return NextResponse.json(
{ success: false, error: 'Adresse email d\'expédition invalide' },
{ status: 400 }
);
}
// Créer le transporteur SMTP avec options de résolution DNS
const transporter = nodemailer.createTransport({
host: smtpSettings.host,
port: smtpSettings.port,
secure: smtpSettings.secure, // true pour 465, false pour les autres ports
auth: {
user: smtpSettings.username,
pass: smtpSettings.password,
},
// Options pour résoudre les problèmes DNS
tls: {
rejectUnauthorized: false, // Accepte les certificats auto-signés
},
// Timeout pour éviter les blocages
connectionTimeout: 10000, // 10 secondes
greetingTimeout: 10000,
socketTimeout: 10000,
});
// Vérifier la connexion
await transporter.verify();
return NextResponse.json({
success: true,
message: 'Connexion SMTP réussie'
});
} catch (error) {
console.error('Erreur lors du test de connexion SMTP:', error);
let errorMessage = 'Erreur de connexion SMTP';
if (error instanceof Error) {
if (error.message.includes('EBADNAME')) {
errorMessage = 'Impossible de résoudre le nom d\'hôte SMTP. Vérifiez que le serveur SMTP est correct.';
} else if (error.message.includes('ECONNREFUSED')) {
errorMessage = 'Connexion refusée. Vérifiez le serveur et le port SMTP.';
} else if (error.message.includes('ETIMEDOUT')) {
errorMessage = 'Délai d\'attente dépassé. Vérifiez votre connexion internet et les paramètres SMTP.';
} else if (error.message.includes('EAUTH')) {
errorMessage = 'Authentification échouée. Vérifiez le nom d\'utilisateur et le mot de passe.';
} else {
errorMessage = error.message;
}
}
return NextResponse.json(
{
success: false,
error: errorMessage
},
{ status: 500 }
);
}
}

View File

@@ -4,7 +4,7 @@ import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { Campaign, Proposition, Participant, Vote, PropositionWithVote } from '@/types';
import { campaignService, participantService, propositionService, voteService } from '@/lib/services';
import { campaignService, participantService, propositionService, voteService, settingsService } from '@/lib/services';
// Force dynamic rendering to avoid SSR issues with Supabase
export const dynamic = 'force-dynamic';
@@ -26,6 +26,7 @@ export default function PublicVotePage() {
// Votes temporaires stockés localement
const [localVotes, setLocalVotes] = useState<Record<string, number>>({});
const [totalVoted, setTotalVoted] = useState(0);
const [isRandomOrder, setIsRandomOrder] = useState(false);
useEffect(() => {
if (campaignId && participantId) {
@@ -73,11 +74,20 @@ export default function PublicVotePage() {
const votes = await voteService.getByParticipant(campaignId, participantId);
// Combiner les propositions avec leurs votes
const propositionsWithVotes = propositionsData.map(proposition => ({
let propositionsWithVotes = propositionsData.map(proposition => ({
...proposition,
vote: votes.find(vote => vote.proposition_id === proposition.id)
}));
// Vérifier si l'ordre aléatoire est activé
const randomizePropositions = await settingsService.getBooleanValue('randomize_propositions', false);
if (randomizePropositions) {
// Mélanger les propositions de manière aléatoire
propositionsWithVotes = propositionsWithVotes.sort(() => Math.random() - 0.5);
setIsRandomOrder(true);
}
setPropositions(propositionsWithVotes);
// Initialiser les votes locaux avec les votes existants
@@ -278,6 +288,14 @@ export default function PublicVotePage() {
<div>
<h3 className="text-sm font-medium text-gray-500">Description</h3>
<p className="mt-1 text-sm text-gray-900">{campaign?.description}</p>
{isRandomOrder && (
<div className="mt-3 p-2 bg-blue-50 border border-blue-200 rounded-md">
<p className="text-xs text-blue-700 flex items-center gap-1">
<span className="text-blue-500"></span>
Les propositions sont affichées dans un ordre aléatoire pour éviter les biais liés à l'ordre de présentation.
</p>
</div>
)}
</div>
</div>
</div>