- Add slug/short_id fields to database with auto-generation
- Create migration script for existing data - Update admin interface to show only short URLs - Implement redirect system to avoid code duplication - Maintain backward compatibility with old URLs
This commit is contained in:
@@ -14,6 +14,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import Navigation from '@/components/Navigation';
|
||||
import AuthGuard from '@/components/AuthGuard';
|
||||
import { Users, User, Calendar, Mail, Vote, Copy, Check, Upload } from 'lucide-react';
|
||||
@@ -95,8 +96,11 @@ function CampaignParticipantsPageContent() {
|
||||
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
|
||||
};
|
||||
|
||||
const copyVoteLink = (participantId: string) => {
|
||||
const voteUrl = `${window.location.origin}/campaigns/${campaignId}/vote/${participantId}`;
|
||||
const copyVoteLink = (participantId: string, shortId?: string) => {
|
||||
// Utiliser le lien court si disponible, sinon le lien long
|
||||
const voteUrl = shortId
|
||||
? `${window.location.origin}/v/${shortId}`
|
||||
: `${window.location.origin}/campaigns/${campaignId}/vote/${participantId}`;
|
||||
navigator.clipboard.writeText(voteUrl);
|
||||
setCopiedParticipantId(participantId);
|
||||
setTimeout(() => setCopiedParticipantId(null), 2000);
|
||||
@@ -338,14 +342,18 @@ function CampaignParticipantsPageContent() {
|
||||
<Input
|
||||
type="text"
|
||||
readOnly
|
||||
value={`${window.location.origin}/campaigns/${campaignId}/vote/${participant.id}`}
|
||||
value={participant.short_id
|
||||
? `${window.location.origin}/v/${participant.short_id}`
|
||||
: 'Génération en cours...'
|
||||
}
|
||||
className="flex-1 text-xs bg-white dark:bg-slate-800 border-blue-300 dark:border-blue-600 text-blue-700 dark:text-blue-300 font-mono"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => copyVoteLink(participant.id)}
|
||||
onClick={() => copyVoteLink(participant.id, participant.short_id)}
|
||||
className="text-xs"
|
||||
disabled={!participant.short_id}
|
||||
>
|
||||
{copiedParticipantId === participant.id ? (
|
||||
<>
|
||||
@@ -359,24 +367,26 @@ 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>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Email 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>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import Navigation from '@/components/Navigation';
|
||||
import AuthGuard from '@/components/AuthGuard';
|
||||
@@ -324,14 +325,14 @@ function AdminPageContent() {
|
||||
<Input
|
||||
type="text"
|
||||
readOnly
|
||||
value={`${window.location.origin}/campaigns/${campaign.id}/propose`}
|
||||
value={`${window.location.origin}/p/${campaign.slug || 'campagne'}`}
|
||||
className="flex-1 text-sm bg-white dark:bg-slate-800 border-blue-300 dark:border-blue-600 text-blue-700 dark:text-blue-300 font-mono"
|
||||
/>
|
||||
<Button
|
||||
variant={copiedCampaignId === campaign.id ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
copyToClipboard(`${window.location.origin}/campaigns/${campaign.id}/propose`, campaign.id);
|
||||
copyToClipboard(`${window.location.origin}/p/${campaign.slug || 'campagne'}`, campaign.id);
|
||||
}}
|
||||
className="text-xs"
|
||||
>
|
||||
|
||||
285
src/app/p/[slug]/page.tsx
Normal file
285
src/app/p/[slug]/page.tsx
Normal file
@@ -0,0 +1,285 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { Campaign } from '@/types';
|
||||
import { campaignService } from '@/lib/services';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2, CheckCircle, AlertCircle } from 'lucide-react';
|
||||
|
||||
// Force dynamic rendering to avoid SSR issues with Supabase
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function ShortProposePage() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const slug = params.slug as string;
|
||||
|
||||
const [campaign, setCampaign] = useState<Campaign | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
description: '',
|
||||
author_first_name: '',
|
||||
author_last_name: '',
|
||||
author_email: ''
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (slug) {
|
||||
loadCampaign();
|
||||
}
|
||||
}, [slug]);
|
||||
|
||||
const loadCampaign = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const campaignData = await campaignService.getBySlug(slug);
|
||||
|
||||
if (!campaignData) {
|
||||
setError('Campagne non trouvée');
|
||||
return;
|
||||
}
|
||||
|
||||
if (campaignData.status !== 'deposit') {
|
||||
setError('Cette campagne n\'accepte plus de propositions');
|
||||
return;
|
||||
}
|
||||
|
||||
setCampaign(campaignData);
|
||||
} catch (error) {
|
||||
console.error('Erreur lors du chargement de la campagne:', error);
|
||||
setError('Erreur lors du chargement de la campagne');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!campaign) return;
|
||||
|
||||
// Validation basique
|
||||
if (!formData.title.trim() || !formData.description.trim() ||
|
||||
!formData.author_first_name.trim() || !formData.author_last_name.trim() ||
|
||||
!formData.author_email.trim()) {
|
||||
setError('Veuillez remplir tous les champs obligatoires');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation email basique
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(formData.author_email)) {
|
||||
setError('Veuillez saisir une adresse email valide');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
|
||||
const { propositionService } = await import('@/lib/services');
|
||||
|
||||
await propositionService.create({
|
||||
campaign_id: campaign.id,
|
||||
title: formData.title.trim(),
|
||||
description: formData.description.trim(),
|
||||
author_first_name: formData.author_first_name.trim(),
|
||||
author_last_name: formData.author_last_name.trim(),
|
||||
author_email: formData.author_email.trim()
|
||||
});
|
||||
|
||||
setSuccess(true);
|
||||
setFormData({
|
||||
title: '',
|
||||
description: '',
|
||||
author_first_name: '',
|
||||
author_last_name: '',
|
||||
author_email: ''
|
||||
});
|
||||
|
||||
// Rediriger vers la page de succès après 3 secondes
|
||||
setTimeout(() => {
|
||||
router.push(`/p/${slug}/success`);
|
||||
}, 3000);
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Erreur lors de la soumission:', error);
|
||||
setError(error.message || 'Erreur lors de la soumission de la proposition');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (field: string, value: string) => {
|
||||
setFormData(prev => ({ ...prev, [field]: value }));
|
||||
if (error) setError(''); // Effacer l'erreur quand l'utilisateur commence à taper
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-slate-900 dark:to-slate-800 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-blue-600 dark:text-blue-400" />
|
||||
<p className="text-gray-600 dark:text-gray-400">Chargement de la campagne...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error && !campaign) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-slate-900 dark:to-slate-800 flex items-center justify-center">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="p-6">
|
||||
<div className="text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2">
|
||||
Erreur
|
||||
</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400">{error}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-slate-900 dark:to-slate-800 flex items-center justify-center">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="p-6">
|
||||
<div className="text-center">
|
||||
<CheckCircle className="w-12 h-12 text-green-500 mx-auto mb-4" />
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2">
|
||||
Proposition soumise avec succès !
|
||||
</h2>
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
Votre proposition a été enregistrée. Vous allez être redirigé...
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-slate-900 dark:to-slate-800 py-8 px-4">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<Card className="shadow-lg">
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="text-2xl font-bold text-gray-900 dark:text-gray-100">
|
||||
Dépôt de proposition
|
||||
</CardTitle>
|
||||
<CardDescription className="text-lg">
|
||||
{campaign?.title}
|
||||
</CardDescription>
|
||||
{campaign?.description && (
|
||||
<p className="text-gray-600 dark:text-gray-400 mt-2">
|
||||
{campaign.description}
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="p-6">
|
||||
{error && (
|
||||
<Alert className="mb-6 border-red-200 bg-red-50 dark:bg-red-900/20 dark:border-red-800">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="text-red-700 dark:text-red-300">
|
||||
{error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="author_first_name">Prénom *</Label>
|
||||
<Input
|
||||
id="author_first_name"
|
||||
value={formData.author_first_name}
|
||||
onChange={(e) => handleInputChange('author_first_name', e.target.value)}
|
||||
placeholder="Votre prénom"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="author_last_name">Nom *</Label>
|
||||
<Input
|
||||
id="author_last_name"
|
||||
value={formData.author_last_name}
|
||||
onChange={(e) => handleInputChange('author_last_name', e.target.value)}
|
||||
placeholder="Votre nom"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="author_email">Email *</Label>
|
||||
<Input
|
||||
id="author_email"
|
||||
type="email"
|
||||
value={formData.author_email}
|
||||
onChange={(e) => handleInputChange('author_email', e.target.value)}
|
||||
placeholder="votre.email@exemple.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="title">Titre de la proposition *</Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={formData.title}
|
||||
onChange={(e) => handleInputChange('title', e.target.value)}
|
||||
placeholder="Titre de votre proposition"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="description">Description *</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
value={formData.description}
|
||||
onChange={(e) => handleInputChange('description', e.target.value)}
|
||||
placeholder="Décrivez votre proposition en détail..."
|
||||
rows={6}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={submitting}
|
||||
>
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Envoi en cours...
|
||||
</>
|
||||
) : (
|
||||
'Soumettre ma proposition'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
46
src/app/p/[slug]/success/page.tsx
Normal file
46
src/app/p/[slug]/success/page.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
'use client';
|
||||
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { CheckCircle, ArrowLeft } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useParams } from 'next/navigation';
|
||||
|
||||
export default function ProposeSuccessPage() {
|
||||
const params = useParams();
|
||||
const slug = params.slug as string;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-slate-900 dark:to-slate-800 flex items-center justify-center py-8 px-4">
|
||||
<Card className="w-full max-w-md shadow-lg">
|
||||
<CardContent className="p-8 text-center">
|
||||
<CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-6" />
|
||||
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-4">
|
||||
Proposition soumise avec succès !
|
||||
</h1>
|
||||
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-6">
|
||||
Votre proposition a été enregistrée et sera examinée par l'équipe organisatrice.
|
||||
Vous recevrez une confirmation par email.
|
||||
</p>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button asChild className="w-full">
|
||||
<Link href={`/p/${slug}`}>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Déposer une autre proposition
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" asChild className="w-full">
|
||||
<Link href="/">
|
||||
Retour à l'accueil
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
83
src/app/v/[shortId]/page.tsx
Normal file
83
src/app/v/[shortId]/page.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { participantService } from '@/lib/services';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
// Force dynamic rendering to avoid SSR issues with Supabase
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function ShortVoteRedirect() {
|
||||
const params = useParams();
|
||||
const router = useRouter();
|
||||
const shortId = params.shortId as string;
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (shortId) {
|
||||
redirectToVotePage();
|
||||
}
|
||||
}, [shortId]);
|
||||
|
||||
const redirectToVotePage = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Récupérer le participant par short_id
|
||||
const participant = await participantService.getByShortId(shortId);
|
||||
|
||||
if (!participant) {
|
||||
setError('Lien de vote invalide ou expiré');
|
||||
return;
|
||||
}
|
||||
|
||||
// Rediriger vers l'ancienne route avec les IDs complets
|
||||
const voteUrl = `/campaigns/${participant.campaign_id}/vote/${participant.id}`;
|
||||
router.replace(voteUrl);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la redirection:', error);
|
||||
setError('Erreur lors du chargement du lien de vote');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin mx-auto mb-4 text-indigo-600" />
|
||||
<p className="text-gray-600">Redirection vers la page de vote...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="bg-white rounded-lg shadow-lg p-8 max-w-md mx-auto">
|
||||
<svg className="mx-auto h-12 w-12 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
|
||||
</svg>
|
||||
<h2 className="mt-4 text-lg font-medium text-gray-900">Erreur</h2>
|
||||
<p className="mt-2 text-sm text-gray-600">{error}</p>
|
||||
<button
|
||||
onClick={() => router.push('/')}
|
||||
className="mt-4 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700"
|
||||
>
|
||||
Retour à l'accueil
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -152,22 +152,35 @@ export default function AuthGuard({ children, requireSuperAdmin = false }: AuthG
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Mot de passe</Label>
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute left-3 top-3 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
// Si l'utilisateur appuie sur Tab depuis le champ mot de passe,
|
||||
// déplacer le focus vers le bouton œil
|
||||
if (e.key === 'Tab' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
const eyeButton = document.getElementById('password-toggle');
|
||||
if (eyeButton) {
|
||||
eyeButton.focus();
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="pl-10"
|
||||
required
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
id="password-toggle"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute left-3 top-3 text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 rounded"
|
||||
tabIndex={0}
|
||||
>
|
||||
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -29,8 +29,10 @@ export default function SendParticipantEmailModal({
|
||||
const [sending, setSending] = useState(false);
|
||||
const [result, setResult] = useState<{ success: boolean; message: string } | null>(null);
|
||||
|
||||
// Générer le lien de vote
|
||||
const voteUrl = `${typeof window !== 'undefined' ? window.location.origin : ''}/campaigns/${campaign.id}/vote/${participant.id}`;
|
||||
// Générer le lien de vote (utiliser uniquement le lien court)
|
||||
const voteUrl = participant.short_id
|
||||
? `${typeof window !== 'undefined' ? window.location.origin : ''}/v/${participant.short_id}`
|
||||
: `${typeof window !== 'undefined' ? window.location.origin : ''}/v/EN_ATTENTE`;
|
||||
|
||||
// Initialiser le message par défaut quand le modal s'ouvre
|
||||
useEffect(() => {
|
||||
|
||||
@@ -3,6 +3,39 @@ import { Campaign, Proposition, Participant, Vote, ParticipantWithVoteStatus, Se
|
||||
import { encryptionService } from './encryption';
|
||||
import { emailService } from './email';
|
||||
|
||||
// Fonction utilitaire pour générer un slug côté client
|
||||
function generateSlugClient(title: string): string {
|
||||
// Convertir en minuscules et remplacer les caractères spéciaux
|
||||
let slug = title.toLowerCase()
|
||||
.replace(/[^a-z0-9\s]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.trim();
|
||||
|
||||
// Si le slug est vide, utiliser 'campagne'
|
||||
if (!slug) {
|
||||
slug = 'campagne';
|
||||
}
|
||||
|
||||
// Ajouter un timestamp pour éviter les conflits
|
||||
const timestamp = Date.now().toString().slice(-6);
|
||||
return `${slug}-${timestamp}`;
|
||||
}
|
||||
|
||||
// Fonction utilitaire pour générer un short_id côté client
|
||||
function generateShortIdClient(): string {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
let result = '';
|
||||
|
||||
// Générer un identifiant de 6 caractères
|
||||
for (let i = 0; i < 6; i++) {
|
||||
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
|
||||
// Ajouter un timestamp pour éviter les conflits
|
||||
const timestamp = Date.now().toString().slice(-3);
|
||||
return `${result}${timestamp}`;
|
||||
}
|
||||
|
||||
// Services pour les campagnes
|
||||
export const campaignService = {
|
||||
async getAll(): Promise<Campaign[]> {
|
||||
@@ -17,6 +50,27 @@ export const campaignService = {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async create(campaign: any): Promise<Campaign> {
|
||||
// Générer automatiquement le slug si non fourni
|
||||
if (!campaign.slug) {
|
||||
try {
|
||||
// Essayer d'utiliser la fonction PostgreSQL
|
||||
const { data: slugData, error: slugError } = await supabase
|
||||
.rpc('generate_slug', { title: campaign.title });
|
||||
|
||||
if (slugError) {
|
||||
// Si la fonction n'existe pas, générer le slug côté client
|
||||
console.warn('Fonction generate_slug non disponible, génération côté client:', slugError);
|
||||
campaign.slug = generateSlugClient(campaign.title);
|
||||
} else {
|
||||
campaign.slug = slugData;
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback vers la génération côté client
|
||||
console.warn('Erreur avec generate_slug, génération côté client:', error);
|
||||
campaign.slug = generateSlugClient(campaign.title);
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('campaigns')
|
||||
.insert(campaign)
|
||||
@@ -29,6 +83,27 @@ export const campaignService = {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async update(id: string, updates: any): Promise<Campaign> {
|
||||
// Générer automatiquement le slug si le titre a changé et qu'aucun slug n'est fourni
|
||||
if (updates.title && !updates.slug) {
|
||||
try {
|
||||
// Essayer d'utiliser la fonction PostgreSQL
|
||||
const { data: slugData, error: slugError } = await supabase
|
||||
.rpc('generate_slug', { title: updates.title });
|
||||
|
||||
if (slugError) {
|
||||
// Si la fonction n'existe pas, générer le slug côté client
|
||||
console.warn('Fonction generate_slug non disponible, génération côté client:', slugError);
|
||||
updates.slug = generateSlugClient(updates.title);
|
||||
} else {
|
||||
updates.slug = slugData;
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback vers la génération côté client
|
||||
console.warn('Erreur avec generate_slug, génération côté client:', error);
|
||||
updates.slug = generateSlugClient(updates.title);
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('campaigns')
|
||||
.update(updates)
|
||||
@@ -77,6 +152,23 @@ export const campaignService = {
|
||||
propositions: propositionsResult.count || 0,
|
||||
participants: participantsResult.count || 0
|
||||
};
|
||||
},
|
||||
|
||||
// Nouvelle méthode pour récupérer une campagne par slug
|
||||
async getBySlug(slug: string): Promise<Campaign | null> {
|
||||
const { data, error } = await supabase
|
||||
.from('campaigns')
|
||||
.select('*')
|
||||
.eq('slug', slug)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') {
|
||||
return null; // Aucune campagne trouvée
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -160,6 +252,27 @@ export const participantService = {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async create(participant: any): Promise<Participant> {
|
||||
// Générer automatiquement le short_id si non fourni
|
||||
if (!participant.short_id) {
|
||||
try {
|
||||
// Essayer d'utiliser la fonction PostgreSQL
|
||||
const { data: shortIdData, error: shortIdError } = await supabase
|
||||
.rpc('generate_short_id');
|
||||
|
||||
if (shortIdError) {
|
||||
// Si la fonction n'existe pas, générer le short_id côté client
|
||||
console.warn('Fonction generate_short_id non disponible, génération côté client:', shortIdError);
|
||||
participant.short_id = generateShortIdClient();
|
||||
} else {
|
||||
participant.short_id = shortIdData;
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback vers la génération côté client
|
||||
console.warn('Erreur avec generate_short_id, génération côté client:', error);
|
||||
participant.short_id = generateShortIdClient();
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('participants')
|
||||
.insert(participant)
|
||||
@@ -207,6 +320,23 @@ export const participantService = {
|
||||
.eq('id', id);
|
||||
|
||||
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
|
||||
.from('participants')
|
||||
.select('*')
|
||||
.eq('short_id', shortId)
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') {
|
||||
return null; // Aucun participant trouvé
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface Campaign {
|
||||
status: CampaignStatus;
|
||||
budget_per_user: number;
|
||||
spending_tiers: string; // Montants séparés par des virgules
|
||||
slug?: string; // Slug unique pour les liens courts
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
@@ -35,6 +36,7 @@ export interface Participant {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
short_id?: string; // Identifiant court unique pour les liens de vote
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user