Compare commits

..

7 Commits

Author SHA1 Message Date
Yannick Le Duc
bfc87ae0a9 enlève allowedDevOrigins 2025-08-27 09:06:58 +02:00
Yannick Le Duc
29f5f37194 migration de base avant liens courts 2025-08-27 09:04:31 +02:00
Yannick Le Duc
8cfa14a693 fix problème possible de "logique delete + create pouvait créer des conditions de concurrence" 2025-08-27 00:25:32 +02:00
Yannick Le Duc
ba3a7c3ea1 améliore la création de campagnes (proposition de paliers harmonieux automatiques) 2025-08-26 23:58:00 +02:00
Yannick Le Duc
4ce52f300f redesign de la page /admin 2025-08-26 23:39:58 +02:00
Yannick Le Duc
caf0478e02 - 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
2025-08-26 22:28:11 +02:00
Yannick Le Duc
bd4f63b99c fine tux à max la page de vote (better ux) 2025-08-26 21:49:45 +02:00
27 changed files with 2334 additions and 599 deletions

View File

@@ -17,6 +17,7 @@ CREATE TABLE campaigns (
status TEXT NOT NULL CHECK (status IN ('deposit', 'voting', 'closed')) DEFAULT 'deposit', status TEXT NOT NULL CHECK (status IN ('deposit', 'voting', 'closed')) DEFAULT 'deposit',
budget_per_user INTEGER NOT NULL CHECK (budget_per_user > 0), budget_per_user INTEGER NOT NULL CHECK (budget_per_user > 0),
spending_tiers TEXT NOT NULL, -- Montants séparés par des virgules (ex: "10,25,50,100") spending_tiers TEXT NOT NULL, -- Montants séparés par des virgules (ex: "10,25,50,100")
slug TEXT UNIQUE, -- Slug unique pour les liens courts
created_by UUID REFERENCES admin_users(id), created_by UUID REFERENCES admin_users(id),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
@@ -41,6 +42,7 @@ CREATE TABLE participants (
first_name TEXT NOT NULL, first_name TEXT NOT NULL,
last_name TEXT NOT NULL, last_name TEXT NOT NULL,
email TEXT NOT NULL, email TEXT NOT NULL,
short_id TEXT UNIQUE, -- Identifiant court unique pour les liens de vote
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
); );
@@ -72,6 +74,8 @@ CREATE INDEX idx_propositions_campaign_id ON propositions(campaign_id);
CREATE INDEX idx_participants_campaign_id ON participants(campaign_id); CREATE INDEX idx_participants_campaign_id ON participants(campaign_id);
CREATE INDEX idx_campaigns_status ON campaigns(status); CREATE INDEX idx_campaigns_status ON campaigns(status);
CREATE INDEX idx_campaigns_created_at ON campaigns(created_at DESC); CREATE INDEX idx_campaigns_created_at ON campaigns(created_at DESC);
CREATE INDEX idx_campaigns_slug ON campaigns(slug);
CREATE INDEX idx_participants_short_id ON participants(short_id);
CREATE INDEX idx_votes_campaign_participant ON votes(campaign_id, participant_id); CREATE INDEX idx_votes_campaign_participant ON votes(campaign_id, participant_id);
CREATE INDEX idx_votes_proposition ON votes(proposition_id); CREATE INDEX idx_votes_proposition ON votes(proposition_id);
CREATE INDEX idx_admin_users_email ON admin_users(email); CREATE INDEX idx_admin_users_email ON admin_users(email);
@@ -99,6 +103,69 @@ CREATE TRIGGER update_settings_updated_at BEFORE UPDATE ON settings
CREATE TRIGGER update_admin_users_updated_at BEFORE UPDATE ON admin_users CREATE TRIGGER update_admin_users_updated_at BEFORE UPDATE ON admin_users
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-- Fonction pour générer un slug à partir d'un titre
CREATE OR REPLACE FUNCTION generate_slug(title TEXT)
RETURNS TEXT AS $$
DECLARE
slug TEXT;
counter INTEGER := 0;
base_slug TEXT;
BEGIN
-- Convertir en minuscules et remplacer les caractères spéciaux
base_slug := lower(regexp_replace(title, '[^a-zA-Z0-9\s]', '', 'g'));
base_slug := regexp_replace(base_slug, '\s+', '-', 'g');
base_slug := trim(both '-' from base_slug);
-- Si le slug est vide, utiliser 'campagne'
IF base_slug = '' THEN
base_slug := 'campagne';
END IF;
slug := base_slug;
-- Vérifier si le slug existe déjà et ajouter un numéro si nécessaire
WHILE EXISTS (SELECT 1 FROM campaigns WHERE campaigns.slug = slug) LOOP
counter := counter + 1;
slug := base_slug || '-' || counter;
END LOOP;
RETURN slug;
END;
$$ LANGUAGE plpgsql;
-- Fonction pour générer un short_id unique
CREATE OR REPLACE FUNCTION generate_short_id()
RETURNS TEXT AS $$
DECLARE
chars TEXT := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
result TEXT := '';
i INTEGER;
short_id TEXT;
counter INTEGER := 0;
BEGIN
LOOP
-- Générer un identifiant de 6 caractères
result := '';
FOR i IN 1..6 LOOP
result := result || substr(chars, floor(random() * length(chars))::integer + 1, 1);
END LOOP;
short_id := result;
-- Vérifier si le short_id existe déjà
IF NOT EXISTS (SELECT 1 FROM participants WHERE participants.short_id = short_id) THEN
RETURN short_id;
END IF;
-- Éviter les boucles infinies
counter := counter + 1;
IF counter > 100 THEN
RAISE EXCEPTION 'Impossible de générer un short_id unique après 100 tentatives';
END IF;
END LOOP;
END;
$$ LANGUAGE plpgsql;
-- Activer RLS sur toutes les tables -- Activer RLS sur toutes les tables
ALTER TABLE admin_users ENABLE ROW LEVEL SECURITY; ALTER TABLE admin_users ENABLE ROW LEVEL SECURITY;
ALTER TABLE campaigns ENABLE ROW LEVEL SECURITY; ALTER TABLE campaigns ENABLE ROW LEVEL SECURITY;
@@ -245,3 +312,42 @@ BEGIN
(SELECT COALESCE(SUM(amount), 0) FROM votes WHERE campaign_id = campaign_uuid) as total_budget_voted; (SELECT COALESCE(SUM(amount), 0) FROM votes WHERE campaign_id = campaign_uuid) as total_budget_voted;
END; END;
$$ LANGUAGE plpgsql SECURITY DEFINER; $$ LANGUAGE plpgsql SECURITY DEFINER;
-- Fonction pour remplacer tous les votes d'un participant de manière atomique
CREATE OR REPLACE FUNCTION replace_participant_votes(
p_campaign_id UUID,
p_participant_id UUID,
p_votes JSONB
)
RETURNS VOID AS $$
DECLARE
vote_record RECORD;
BEGIN
-- Commencer une transaction
BEGIN
-- Supprimer tous les votes existants pour ce participant dans cette campagne
DELETE FROM votes
WHERE campaign_id = p_campaign_id
AND participant_id = p_participant_id;
-- Insérer les nouveaux votes
FOR vote_record IN
SELECT * FROM jsonb_array_elements(p_votes)
LOOP
INSERT INTO votes (campaign_id, participant_id, proposition_id, amount)
VALUES (
p_campaign_id,
p_participant_id,
(vote_record.value->>'proposition_id')::UUID,
(vote_record.value->>'amount')::INTEGER
);
END LOOP;
-- La transaction sera automatiquement commitée si tout va bien
EXCEPTION
WHEN OTHERS THEN
-- En cas d'erreur, la transaction sera automatiquement rollbackée
RAISE EXCEPTION 'Erreur lors du remplacement des votes: %', SQLERRM;
END;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

View File

@@ -1,106 +1,201 @@
# 📁 Structure du Projet - Mes Budgets Participatifs # Structure du Projet
## 🗂️ **Organisation des dossiers** ## 📁 Organisation des fichiers
``` ```
mes-budgets-participatifs/ mes-budgets-participatifs/
├── 📚 docs/ # Documentation complète ├── src/
│ ├── README.md # Index de la documentation │ ├── app/ # Pages Next.js (App Router)
│ ├── SETUP.md # Guide de configuration │ ├── page.tsx # Page d'accueil
│ ├── MIGRATION-GUIDE.md # Migration vers la sécurité │ ├── admin/ # Pages d'administration (protégées)
├── SECURITY-SUMMARY.md # Résumé de la sécurisation │ │ ├── page.tsx # Dashboard principal
└── SETTINGS.md # Configuration avancée │ │ ├── settings/ # Paramètres SMTP
│ │ └── campaigns/[id]/ # Pages de gestion par campagne
├── 🗄️ database/ # Scripts de base de données │ │ ├── api/ # API Routes
└── supabase-schema.sql # Schéma complet avec sécurité │ │ ├── send-participant-email/
│ │ ├── test-email/
├── 🛠️ scripts/ # Outils et scripts └── test-smtp/
└── test-security.js # Tests de sécurité │ ├── campaigns/[id]/ # Pages publiques (anciennes routes)
│ │ ├── propose/ # Dépôt de propositions
├── 📱 src/ # Code source de l'application └── vote/[participantId] # Vote public
│ ├── app/ # Pages Next.js (App Router) │ ├── p/[slug]/ # Pages publiques (nouvelles routes courtes)
├── components/ # Composants React │ │ ├── page.tsx # Dépôt de propositions par slug
├── lib/ # Services et utilitaires └── success/ # Page de succès pour dépôt
└── types/ # Types TypeScript └── page.tsx
│ └── v/[shortId]/ # Pages de vote (nouvelles routes courtes)
├── 🎨 public/ # Assets statiques │ │ ├── page.tsx # Vote par short_id
├── 📦 node_modules/ # Dépendances (généré) │ │ └── success/ # Page de succès pour vote
├── ⚙️ Configuration files # Fichiers de configuration │ │ └── page.tsx
└── 📖 README.md # Documentation principale │ ├── components/ # Composants React
│ │ ├── ui/ # Composants Shadcn/ui
│ │ ├── AuthGuard.tsx # Protection des routes
│ │ ├── Navigation.tsx # Navigation principale
│ │ ├── SmtpSettingsForm.tsx # Configuration SMTP
│ │ └── [Modals] # Modales de gestion
│ ├── lib/ # Services et configuration
│ │ ├── supabase.ts # Configuration Supabase
│ │ ├── services.ts # Services de données
│ │ ├── email.ts # Service d'envoi d'emails
│ │ ├── encryption.ts # Chiffrement des données sensibles
│ │ └── utils.ts # Utilitaires
│ └── types/ # Types TypeScript
├── database/
│ └── supabase-schema.sql # Schéma de base de données
├── scripts/
│ ├── test-security.js # Tests de sécurité
│ └── migrate-short-links.js # Migration des liens courts
└── docs/ # Documentation
``` ```
## 📋 **Fichiers principaux** ## 🔗 Routes de l'application
### **Configuration** ### Routes publiques
- `package.json` - Dépendances et scripts
- `tsconfig.json` - Configuration TypeScript
- `next.config.ts` - Configuration Next.js
- `env.example` - Exemple de variables d'environnement
### **Documentation** #### Nouvelles routes courtes (recommandées)
- `README.md` - Documentation principale - **`/p/[slug]`** - Dépôt de propositions
- `docs/README.md` - Index de la documentation - Exemple : `/p/budget-2024`
- `PROJECT-STRUCTURE.md` - Ce fichier - Utilise le slug de la campagne pour un lien court et lisible
### **Base de données** - **`/v/[shortId]`** - Vote public
- `database/supabase-schema.sql` - Schéma complet avec sécurité - Exemple : `/v/ABC123`
- Utilise un identifiant court unique pour chaque participant
### **Outils** #### Anciennes routes (compatibilité)
- `scripts/test-security.js` - Tests de sécurité - **`/campaigns/[id]/propose`** - Dépôt de propositions
- Exemple : `/campaigns/123e4567-e89b-12d3-a456-426614174000/propose`
## 🔧 **Scripts disponibles** - **`/campaigns/[id]/vote/[participantId]`** - Vote public
- Exemple : `/campaigns/123e4567-e89b-12d3-a456-426614174000/vote/987fcdeb-51a2-43d1-b789-123456789abc`
### Routes d'administration
- **`/admin`** - Dashboard principal
- **`/admin/settings`** - Paramètres SMTP
- **`/admin/campaigns/[id]/propositions`** - Gestion des propositions
- **`/admin/campaigns/[id]/participants`** - Gestion des participants
- **`/admin/campaigns/[id]/stats`** - Statistiques de la campagne
## 🗄️ Structure de la base de données
### Tables principales
#### `campaigns`
- `id` (UUID) - Identifiant unique
- `title` (TEXT) - Titre de la campagne
- `description` (TEXT) - Description
- `status` (TEXT) - Statut : 'deposit', 'voting', 'closed'
- `budget_per_user` (INTEGER) - Budget par utilisateur
- `spending_tiers` (TEXT) - Montants disponibles (ex: "10,25,50,100")
- **`slug` (TEXT, UNIQUE)** - Slug pour les liens courts
- `created_at`, `updated_at` (TIMESTAMP)
#### `participants`
- `id` (UUID) - Identifiant unique
- `campaign_id` (UUID) - Référence vers la campagne
- `first_name`, `last_name` (TEXT) - Nom et prénom
- `email` (TEXT) - Adresse email
- **`short_id` (TEXT, UNIQUE)** - Identifiant court pour les liens de vote
- `created_at` (TIMESTAMP)
#### `propositions`
- `id` (UUID) - Identifiant unique
- `campaign_id` (UUID) - Référence vers la campagne
- `title`, `description` (TEXT) - Titre et description
- `author_first_name`, `author_last_name`, `author_email` (TEXT) - Informations de l'auteur
- `created_at` (TIMESTAMP)
#### `votes`
- `id` (UUID) - Identifiant unique
- `campaign_id` (UUID) - Référence vers la campagne
- `participant_id` (UUID) - Référence vers le participant
- `proposition_id` (UUID) - Référence vers la proposition
- `amount` (INTEGER) - Montant voté
- `created_at`, `updated_at` (TIMESTAMP)
### Fonctions PostgreSQL
#### `generate_slug(title TEXT)`
Génère automatiquement un slug unique à partir du titre d'une campagne.
#### `generate_short_id()`
Génère automatiquement un identifiant court unique pour les participants.
## 🔧 Services et utilitaires
### Services principaux (`src/lib/services.ts`)
#### `campaignService`
- `getAll()` - Récupère toutes les campagnes
- `create(campaign)` - Crée une nouvelle campagne (génère automatiquement le slug)
- `update(id, updates)` - Met à jour une campagne
- `delete(id)` - Supprime une campagne
- `getBySlug(slug)` - Récupère une campagne par son slug
- `getStats(campaignId)` - Récupère les statistiques d'une campagne
#### `participantService`
- `getByCampaign(campaignId)` - Récupère les participants d'une campagne
- `create(participant)` - Crée un nouveau participant (génère automatiquement le short_id)
- `update(id, updates)` - Met à jour un participant
- `delete(id)` - Supprime un participant
- `getByShortId(shortId)` - Récupère un participant par son short_id
#### `propositionService`
- `getByCampaign(campaignId)` - Récupère les propositions d'une campagne
- `create(proposition)` - Crée une nouvelle proposition
- `update(id, updates)` - Met à jour une proposition
- `delete(id)` - Supprime une proposition
#### `voteService`
- `getByParticipant(campaignId, participantId)` - Récupère les votes d'un participant
- `create(vote)` - Crée un nouveau vote
- `deleteByParticipant(campaignId, participantId)` - Supprime tous les votes d'un participant
## 🚀 Scripts de migration
### `scripts/migrate-short-links.js`
Script pour migrer les données existantes et générer les slugs et short_ids manquants.
**Usage :**
```bash ```bash
# Développement node scripts/migrate-short-links.js
npm run dev
# Build de production
npm run build
# Tests de sécurité
npm run test:security
# Linting
npm run lint
npm run lint:fix
``` ```
## 📚 **Documentation par type** **Fonctionnalités :**
- Génère automatiquement les slugs pour les campagnes existantes
- Génère automatiquement les short_ids pour les participants existants
- Gère les conflits et génère des identifiants uniques
- Affiche un rapport détaillé de la migration
### **🚀 Démarrage rapide** ## 🔒 Sécurité
- `docs/SETUP.md` - Installation et configuration
### **🔒 Sécurité** ### Authentification
- `docs/SECURITY-SUMMARY.md` - Vue d'ensemble de la sécurité - Utilisation de Supabase Auth pour l'authentification des administrateurs
- `docs/SETTINGS.md` - Configuration SMTP et paramètres - Protection des routes d'administration avec `AuthGuard`
### **🗄️ Base de données** ### Autorisation
- `database/supabase-schema.sql` - Schéma complet avec RLS - Row Level Security (RLS) activé sur toutes les tables
- Contrôle d'accès basé sur les rôles utilisateur
## 🎯 **Points d'entrée** ### Validation des données
- Validation côté client et serveur
- Sanitisation des entrées utilisateur
- Protection contre les injections SQL
### **Pour les développeurs :** ## 📱 Interface utilisateur
1. `README.md` - Vue d'ensemble
2. `docs/SETUP.md` - Configuration
3. `src/` - Code source
### **Pour les administrateurs :** ### Composants UI
1. `docs/SECURITY-SUMMARY.md` - Sécurité - Utilisation de Shadcn/ui pour une interface cohérente
2. `docs/SETTINGS.md` - Configuration - Design responsive et accessible
- Support du mode sombre
- Composants réutilisables
### **Pour les déploiements :** ### Pages publiques
1. `database/supabase-schema.sql` - Base de données - Interface épurée et intuitive
2. `scripts/test-security.js` - Vérification - Formulaires de dépôt et de vote optimisés
3. `env.example` - Variables d'environnement - Feedback visuel en temps réel
- Gestion des erreurs et des états de chargement
## 🔄 **Workflow de développement** ### Interface d'administration
- Dashboard avec statistiques en temps réel
1. **Configuration**`docs/SETUP.md` - Gestion complète des campagnes, propositions et participants
2. **Développement**`src/` - Import/export de données
3. **Tests**`scripts/test-security.js` - Envoi d'emails personnalisés
4. **Documentation**`docs/`
5. **Déploiement**`database/` + configuration
---
**Dernière mise à jour :** Réorganisation complète de la structure ✅

12
public/favicon.svg Normal file
View File

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none">
<!-- Fond de l'urne -->
<rect x="2" y="4" width="12" height="10" rx="1" fill="#3B82F6"/>
<!-- Fente pour voter -->
<rect x="4" y="2" width="8" height="2" rx="1" fill="#3B82F6"/>
<!-- Bulletin de vote -->
<rect x="3" y="6" width="10" height="1" rx="0.5" fill="white" opacity="0.9"/>
<rect x="3" y="8" width="8" height="1" rx="0.5" fill="white" opacity="0.7"/>
<rect x="3" y="10" width="6" height="1" rx="0.5" fill="white" opacity="0.5"/>
<!-- Coche de validation -->
<path d="M5 12l2 2 4-4" stroke="#10B981" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 675 B

12
public/vote-icon.svg Normal file
View File

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#3B82F6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<!-- Urne de vote -->
<rect x="4" y="6" width="16" height="14" rx="2" ry="2" fill="#EFF6FF" stroke="#3B82F6"/>
<!-- Fente pour voter -->
<rect x="8" y="4" width="8" height="2" rx="1" ry="1" fill="#3B82F6"/>
<!-- Bulletin de vote -->
<rect x="7" y="8" width="10" height="2" rx="1" ry="1" fill="#3B82F6" opacity="0.8"/>
<rect x="7" y="11" width="8" height="2" rx="1" ry="1" fill="#3B82F6" opacity="0.6"/>
<rect x="7" y="14" width="6" height="2" rx="1" ry="1" fill="#3B82F6" opacity="0.4"/>
<!-- Coche de validation -->
<path d="M9 16l2 2 4-4" stroke="#10B981" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 805 B

View File

@@ -0,0 +1,41 @@
-- Script pour appliquer la fonction replace_participant_votes
-- À exécuter dans votre base de données Supabase
-- Fonction pour remplacer tous les votes d'un participant de manière atomique
CREATE OR REPLACE FUNCTION replace_participant_votes(
p_campaign_id UUID,
p_participant_id UUID,
p_votes JSONB
)
RETURNS VOID AS $$
DECLARE
vote_record RECORD;
BEGIN
-- Commencer une transaction
BEGIN
-- Supprimer tous les votes existants pour ce participant dans cette campagne
DELETE FROM votes
WHERE campaign_id = p_campaign_id
AND participant_id = p_participant_id;
-- Insérer les nouveaux votes
FOR vote_record IN
SELECT * FROM jsonb_array_elements(p_votes)
LOOP
INSERT INTO votes (campaign_id, participant_id, proposition_id, amount)
VALUES (
p_campaign_id,
p_participant_id,
(vote_record.value->>'proposition_id')::UUID,
(vote_record.value->>'amount')::INTEGER
);
END LOOP;
-- La transaction sera automatiquement commitée si tout va bien
EXCEPTION
WHEN OTHERS THEN
-- En cas d'erreur, la transaction sera automatiquement rollbackée
RAISE EXCEPTION 'Erreur lors du remplacement des votes: %', SQLERRM;
END;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

View File

@@ -0,0 +1,329 @@
-- Script de vérification de l'état de la base de données
-- À exécuter AVANT la migration pour diagnostiquer l'état actuel
-- ========================================
-- VÉRIFICATION DES COLONNES
-- ========================================
-- Vérifier si les colonnes de liens courts existent
SELECT
'campaigns.slug' as column_name,
CASE
WHEN EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'campaigns' AND column_name = 'slug'
) THEN '✅ Existe'
ELSE '❌ Manquante'
END as status
UNION ALL
SELECT
'participants.short_id' as column_name,
CASE
WHEN EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'participants' AND column_name = 'short_id'
) THEN '✅ Existe'
ELSE '❌ Manquante'
END as status;
-- ========================================
-- VÉRIFICATION DES FONCTIONS
-- ========================================
-- Vérifier si les fonctions utilitaires existent
SELECT
'generate_slug' as function_name,
CASE
WHEN EXISTS (
SELECT 1 FROM pg_proc p
JOIN pg_namespace n ON p.pronamespace = n.oid
WHERE p.proname = 'generate_slug' AND n.nspname = 'public'
) THEN '✅ Existe'
ELSE '❌ Manquante'
END as status
UNION ALL
SELECT
'generate_short_id' as function_name,
CASE
WHEN EXISTS (
SELECT 1 FROM pg_proc p
JOIN pg_namespace n ON p.pronamespace = n.oid
WHERE p.proname = 'generate_short_id' AND n.nspname = 'public'
) THEN '✅ Existe'
ELSE '❌ Manquante'
END as status
UNION ALL
SELECT
'replace_participant_votes' as function_name,
CASE
WHEN EXISTS (
SELECT 1 FROM pg_proc p
JOIN pg_namespace n ON p.pronamespace = n.oid
WHERE p.proname = 'replace_participant_votes' AND n.nspname = 'public'
) THEN '✅ Existe'
ELSE '❌ Manquante'
END as status;
-- ========================================
-- VÉRIFICATION DES INDEX
-- ========================================
-- Vérifier si les index de performance existent
SELECT
'idx_campaigns_slug' as index_name,
CASE
WHEN EXISTS (
SELECT 1 FROM pg_indexes
WHERE indexname = 'idx_campaigns_slug'
) THEN '✅ Existe'
ELSE '❌ Manquant'
END as status
UNION ALL
SELECT
'idx_participants_short_id' as index_name,
CASE
WHEN EXISTS (
SELECT 1 FROM pg_indexes
WHERE indexname = 'idx_participants_short_id'
) THEN '✅ Existe'
ELSE '❌ Manquant'
END as status;
-- ========================================
-- ANALYSE DES DONNÉES EXISTANTES
-- ========================================
-- Compter les campagnes et leur état (version sécurisée)
DO $$
DECLARE
campaigns_total INTEGER;
campaigns_with_slug INTEGER := 0;
participants_total INTEGER;
participants_with_short_id INTEGER := 0;
slug_exists BOOLEAN;
short_id_exists BOOLEAN;
BEGIN
-- Vérifier si les colonnes existent
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'campaigns' AND column_name = 'slug'
) INTO slug_exists;
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'participants' AND column_name = 'short_id'
) INTO short_id_exists;
-- Compter les campagnes
SELECT COUNT(*) INTO campaigns_total FROM campaigns;
-- Compter les participants
SELECT COUNT(*) INTO participants_total FROM participants;
-- Compter les campagnes avec slug si la colonne existe
IF slug_exists THEN
SELECT COUNT(*) INTO campaigns_with_slug FROM campaigns WHERE slug IS NOT NULL;
END IF;
-- Compter les participants avec short_id si la colonne existe
IF short_id_exists THEN
SELECT COUNT(*) INTO participants_with_short_id FROM participants WHERE short_id IS NOT NULL;
END IF;
-- Afficher les résultats
RAISE NOTICE '=== ANALYSE DES DONNÉES ===';
RAISE NOTICE 'Campagnes totales: %', campaigns_total;
IF slug_exists THEN
RAISE NOTICE 'Campagnes avec slug: %', campaigns_with_slug;
RAISE NOTICE 'Campagnes sans slug: %', campaigns_total - campaigns_with_slug;
ELSE
RAISE NOTICE 'Colonne slug: ❌ N''existe pas encore';
END IF;
RAISE NOTICE 'Participants totaux: %', participants_total;
IF short_id_exists THEN
RAISE NOTICE 'Participants avec short_id: %', participants_with_short_id;
RAISE NOTICE 'Participants sans short_id: %', participants_total - participants_with_short_id;
ELSE
RAISE NOTICE 'Colonne short_id: ❌ N''existe pas encore';
END IF;
END $$;
-- ========================================
-- EXEMPLES DE DONNÉES EXISTANTES
-- ========================================
-- Afficher quelques exemples de campagnes (version sécurisée)
DO $$
DECLARE
slug_exists BOOLEAN;
r RECORD;
BEGIN
-- Vérifier si la colonne slug existe
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'campaigns' AND column_name = 'slug'
) INTO slug_exists;
IF slug_exists THEN
RAISE NOTICE '=== EXEMPLES DE CAMPAGNES ===';
FOR r IN
SELECT
id,
title,
slug,
CASE
WHEN slug IS NULL THEN '❌ Besoin de migration'
ELSE '✅ OK'
END as status
FROM campaigns
ORDER BY created_at DESC
LIMIT 5
LOOP
RAISE NOTICE 'ID: %, Titre: %, Slug: %, Status: %', r.id, r.title, r.slug, r.status;
END LOOP;
ELSE
RAISE NOTICE '=== EXEMPLES DE CAMPAGNES ===';
FOR r IN
SELECT
id,
title
FROM campaigns
ORDER BY created_at DESC
LIMIT 5
LOOP
RAISE NOTICE 'ID: %, Titre: %, Slug: ❌ Colonne inexistante', r.id, r.title;
END LOOP;
END IF;
END $$;
-- Afficher quelques exemples de participants (version sécurisée)
DO $$
DECLARE
short_id_exists BOOLEAN;
r RECORD;
BEGIN
-- Vérifier si la colonne short_id existe
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'participants' AND column_name = 'short_id'
) INTO short_id_exists;
IF short_id_exists THEN
RAISE NOTICE '=== EXEMPLES DE PARTICIPANTS ===';
FOR r IN
SELECT
id,
first_name,
last_name,
short_id,
CASE
WHEN short_id IS NULL THEN '❌ Besoin de migration'
ELSE '✅ OK'
END as status
FROM participants
ORDER BY created_at DESC
LIMIT 5
LOOP
RAISE NOTICE 'ID: %, Nom: % %, Short ID: %, Status: %', r.id, r.first_name, r.last_name, r.short_id, r.status;
END LOOP;
ELSE
RAISE NOTICE '=== EXEMPLES DE PARTICIPANTS ===';
FOR r IN
SELECT
id,
first_name,
last_name
FROM participants
ORDER BY created_at DESC
LIMIT 5
LOOP
RAISE NOTICE 'ID: %, Nom: % %, Short ID: ❌ Colonne inexistante', r.id, r.first_name, r.last_name;
END LOOP;
END IF;
END $$;
-- ========================================
-- RECOMMANDATIONS
-- ========================================
DO $$
DECLARE
missing_slug_count INTEGER := 0;
missing_short_id_count INTEGER := 0;
missing_functions INTEGER;
missing_indexes INTEGER;
slug_exists BOOLEAN;
short_id_exists BOOLEAN;
BEGIN
-- Vérifier si les colonnes existent
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'campaigns' AND column_name = 'slug'
) INTO slug_exists;
SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'participants' AND column_name = 'short_id'
) INTO short_id_exists;
-- Compter les éléments manquants seulement si les colonnes existent
IF slug_exists THEN
SELECT COUNT(*) INTO missing_slug_count FROM campaigns WHERE slug IS NULL;
ELSE
SELECT COUNT(*) INTO missing_slug_count FROM campaigns;
END IF;
IF short_id_exists THEN
SELECT COUNT(*) INTO missing_short_id_count FROM participants WHERE short_id IS NULL;
ELSE
SELECT COUNT(*) INTO missing_short_id_count FROM participants;
END IF;
SELECT COUNT(*) INTO missing_functions
FROM (
SELECT 'generate_slug' as func UNION ALL SELECT 'generate_short_id' UNION ALL SELECT 'replace_participant_votes'
) f
WHERE NOT EXISTS (
SELECT 1 FROM pg_proc p
JOIN pg_namespace n ON p.pronamespace = n.oid
WHERE p.proname = f.func AND n.nspname = 'public'
);
SELECT COUNT(*) INTO missing_indexes
FROM (
SELECT 'idx_campaigns_slug' as idx UNION ALL SELECT 'idx_participants_short_id'
) i
WHERE NOT EXISTS (
SELECT 1 FROM pg_indexes WHERE indexname = i.idx
);
RAISE NOTICE '=== RECOMMANDATIONS ===';
IF missing_slug_count > 0 OR missing_short_id_count > 0 OR missing_functions > 0 OR missing_indexes > 0 THEN
RAISE NOTICE '🔄 Migration nécessaire !';
IF missing_slug_count > 0 THEN
IF slug_exists THEN
RAISE NOTICE ' - % campagnes ont besoin d''un slug', missing_slug_count;
ELSE
RAISE NOTICE ' - % campagnes ont besoin de la colonne slug + génération', missing_slug_count;
END IF;
END IF;
IF missing_short_id_count > 0 THEN
IF short_id_exists THEN
RAISE NOTICE ' - % participants ont besoin d''un short_id', missing_short_id_count;
ELSE
RAISE NOTICE ' - % participants ont besoin de la colonne short_id + génération', missing_short_id_count;
END IF;
END IF;
IF missing_functions > 0 THEN
RAISE NOTICE ' - % fonctions utilitaires manquantes', missing_functions;
END IF;
IF missing_indexes > 0 THEN
RAISE NOTICE ' - % index de performance manquants', missing_indexes;
END IF;
RAISE NOTICE ' → Exécutez le script migration-to-latest-schema.sql';
ELSE
RAISE NOTICE '✅ Base de données à jour ! Aucune migration nécessaire.';
END IF;
END $$;

View File

@@ -0,0 +1,196 @@
#!/usr/bin/env node
/**
* Script de migration pour générer les slugs et short_ids pour les données existantes
*
* Usage: node scripts/migrate-short-links.js
*/
const { createClient } = require('@supabase/supabase-js');
require('dotenv').config({ path: '.env.local' });
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !supabaseServiceKey) {
console.error('❌ Variables d\'environnement manquantes');
console.error('NEXT_PUBLIC_SUPABASE_URL et SUPABASE_SERVICE_ROLE_KEY sont requis');
process.exit(1);
}
const supabase = createClient(supabaseUrl, supabaseServiceKey);
async function generateSlug(title) {
// 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';
}
// Vérifier si le slug existe déjà et ajouter un numéro si nécessaire
let counter = 0;
let finalSlug = slug;
while (true) {
const { data, error } = await supabase
.from('campaigns')
.select('id')
.eq('slug', finalSlug)
.single();
if (error && error.code === 'PGRST116') {
// Aucune campagne trouvée avec ce slug, on peut l'utiliser
break;
}
if (error) {
throw error;
}
// Le slug existe déjà, ajouter un numéro
counter++;
finalSlug = `${slug}-${counter}`;
}
return finalSlug;
}
async function generateShortId() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let counter = 0;
while (counter < 100) {
// Générer un identifiant de 6 caractères
let result = '';
for (let i = 0; i < 6; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
// Vérifier si le short_id existe déjà
const { data, error } = await supabase
.from('participants')
.select('id')
.eq('short_id', result)
.single();
if (error && error.code === 'PGRST116') {
// Aucun participant trouvé avec ce short_id, on peut l'utiliser
return result;
}
if (error) {
throw error;
}
counter++;
}
throw new Error('Impossible de générer un short_id unique après 100 tentatives');
}
async function migrateCampaigns() {
console.log('🔄 Migration des campagnes...');
// Récupérer toutes les campagnes sans slug
const { data: campaigns, error } = await supabase
.from('campaigns')
.select('id, title')
.is('slug', null);
if (error) {
console.error('❌ Erreur lors de la récupération des campagnes:', error);
return;
}
console.log(`📋 ${campaigns.length} campagnes à migrer`);
for (const campaign of campaigns) {
try {
const slug = await generateSlug(campaign.title);
const { error: updateError } = await supabase
.from('campaigns')
.update({ slug })
.eq('id', campaign.id);
if (updateError) {
console.error(`❌ Erreur lors de la mise à jour de la campagne ${campaign.id}:`, updateError);
} else {
console.log(`✅ Campagne "${campaign.title}" -> slug: ${slug}`);
}
} catch (error) {
console.error(`❌ Erreur lors de la génération du slug pour "${campaign.title}":`, error);
}
}
console.log('✅ Migration des campagnes terminée');
}
async function migrateParticipants() {
console.log('🔄 Migration des participants...');
// Récupérer tous les participants sans short_id
const { data: participants, error } = await supabase
.from('participants')
.select('id, first_name, last_name')
.is('short_id', null);
if (error) {
console.error('❌ Erreur lors de la récupération des participants:', error);
return;
}
console.log(`📋 ${participants.length} participants à migrer`);
for (const participant of participants) {
try {
const shortId = await generateShortId();
const { error: updateError } = await supabase
.from('participants')
.update({ short_id: shortId })
.eq('id', participant.id);
if (updateError) {
console.error(`❌ Erreur lors de la mise à jour du participant ${participant.id}:`, updateError);
} else {
console.log(`✅ Participant "${participant.first_name} ${participant.last_name}" -> short_id: ${shortId}`);
}
} catch (error) {
console.error(`❌ Erreur lors de la génération du short_id pour "${participant.first_name} ${participant.last_name}":`, error);
}
}
console.log('✅ Migration des participants terminée');
}
async function main() {
console.log('🚀 Début de la migration des liens courts...\n');
try {
await migrateCampaigns();
console.log('');
await migrateParticipants();
console.log('\n🎉 Migration terminée avec succès !');
console.log('\n📝 Résumé des nouvelles routes :');
console.log('- Dépôt de propositions : /p/[slug]');
console.log('- Vote : /v/[shortId]');
console.log('- Les anciennes routes restent fonctionnelles pour la compatibilité');
} catch (error) {
console.error('❌ Erreur lors de la migration:', error);
process.exit(1);
}
}
if (require.main === module) {
main();
}
module.exports = { migrateCampaigns, migrateParticipants };

View File

@@ -0,0 +1,223 @@
-- Script de migration vers le schéma le plus récent avec liens courts
-- À exécuter dans votre base de données Supabase
-- ========================================
-- ÉTAPE 1: Ajout des colonnes manquantes
-- ========================================
-- Ajouter la colonne slug aux campagnes si elle n'existe pas
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'campaigns' AND column_name = 'slug'
) THEN
ALTER TABLE campaigns ADD COLUMN slug TEXT UNIQUE;
RAISE NOTICE 'Colonne slug ajoutée à la table campaigns';
ELSE
RAISE NOTICE 'Colonne slug existe déjà dans la table campaigns';
END IF;
END $$;
-- Ajouter la colonne short_id aux participants si elle n'existe pas
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'participants' AND column_name = 'short_id'
) THEN
ALTER TABLE participants ADD COLUMN short_id TEXT UNIQUE;
RAISE NOTICE 'Colonne short_id ajoutée à la table participants';
ELSE
RAISE NOTICE 'Colonne short_id existe déjà dans la table participants';
END IF;
END $$;
-- ========================================
-- ÉTAPE 2: Création des fonctions utilitaires
-- ========================================
-- Fonction pour générer un slug à partir d'un titre
CREATE OR REPLACE FUNCTION generate_slug(title TEXT)
RETURNS TEXT AS $$
DECLARE
generated_slug TEXT;
counter INTEGER := 0;
base_slug TEXT;
BEGIN
-- Convertir en minuscules et remplacer les caractères spéciaux
base_slug := lower(regexp_replace(title, '[^a-zA-Z0-9\s]', '', 'g'));
base_slug := regexp_replace(base_slug, '\s+', '-', 'g');
base_slug := trim(both '-' from base_slug);
-- Si le slug est vide, utiliser 'campagne'
IF base_slug = '' THEN
base_slug := 'campagne';
END IF;
generated_slug := base_slug;
-- Vérifier si le slug existe déjà et ajouter un numéro si nécessaire
WHILE EXISTS (SELECT 1 FROM campaigns WHERE campaigns.slug = generated_slug) LOOP
counter := counter + 1;
generated_slug := base_slug || '-' || counter;
END LOOP;
RETURN generated_slug;
END;
$$ LANGUAGE plpgsql;
-- Fonction pour générer un short_id unique
CREATE OR REPLACE FUNCTION generate_short_id()
RETURNS TEXT AS $$
DECLARE
chars TEXT := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
result TEXT := '';
i INTEGER;
generated_short_id TEXT;
counter INTEGER := 0;
BEGIN
LOOP
-- Générer un identifiant de 6 caractères
result := '';
FOR i IN 1..6 LOOP
result := result || substr(chars, floor(random() * length(chars))::integer + 1, 1);
END LOOP;
generated_short_id := result;
-- Vérifier si le short_id existe déjà
IF NOT EXISTS (SELECT 1 FROM participants WHERE participants.short_id = generated_short_id) THEN
RETURN generated_short_id;
END IF;
-- Éviter les boucles infinies
counter := counter + 1;
IF counter > 100 THEN
RAISE EXCEPTION 'Impossible de générer un short_id unique après 100 tentatives';
END IF;
END LOOP;
END;
$$ LANGUAGE plpgsql;
-- ========================================
-- ÉTAPE 3: Mise à jour des données existantes
-- ========================================
-- Générer des slugs pour les campagnes qui n'en ont pas
UPDATE campaigns
SET slug = generate_slug(title)
WHERE slug IS NULL;
-- Générer des short_ids pour les participants qui n'en ont pas
UPDATE participants
SET short_id = generate_short_id()
WHERE short_id IS NULL;
-- ========================================
-- ÉTAPE 4: Création des index manquants
-- ========================================
-- Index pour les slugs de campagnes
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_indexes
WHERE indexname = 'idx_campaigns_slug'
) THEN
CREATE INDEX idx_campaigns_slug ON campaigns(slug);
RAISE NOTICE 'Index idx_campaigns_slug créé';
ELSE
RAISE NOTICE 'Index idx_campaigns_slug existe déjà';
END IF;
END $$;
-- Index pour les short_ids de participants
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_indexes
WHERE indexname = 'idx_participants_short_id'
) THEN
CREATE INDEX idx_participants_short_id ON participants(short_id);
RAISE NOTICE 'Index idx_participants_short_id créé';
ELSE
RAISE NOTICE 'Index idx_participants_short_id existe déjà';
END IF;
END $$;
-- ========================================
-- ÉTAPE 5: Fonction pour remplacer les votes
-- ========================================
-- Fonction pour remplacer tous les votes d'un participant de manière atomique
CREATE OR REPLACE FUNCTION replace_participant_votes(
p_campaign_id UUID,
p_participant_id UUID,
p_votes JSONB
)
RETURNS VOID AS $$
DECLARE
vote_record RECORD;
BEGIN
-- Commencer une transaction
BEGIN
-- Supprimer tous les votes existants pour ce participant dans cette campagne
DELETE FROM votes
WHERE campaign_id = p_campaign_id
AND participant_id = p_participant_id;
-- Insérer les nouveaux votes
FOR vote_record IN
SELECT * FROM jsonb_array_elements(p_votes)
LOOP
INSERT INTO votes (campaign_id, participant_id, proposition_id, amount)
VALUES (
p_campaign_id,
p_participant_id,
(vote_record.value->>'proposition_id')::UUID,
(vote_record.value->>'amount')::INTEGER
);
END LOOP;
-- La transaction sera automatiquement commitée si tout va bien
EXCEPTION
WHEN OTHERS THEN
-- En cas d'erreur, la transaction sera automatiquement rollbackée
RAISE EXCEPTION 'Erreur lors du remplacement des votes: %', SQLERRM;
END;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
-- ========================================
-- ÉTAPE 6: Vérification et rapport
-- ========================================
-- Afficher un rapport de la migration
DO $$
DECLARE
campaign_count INTEGER;
participant_count INTEGER;
campaign_with_slug INTEGER;
participant_with_short_id INTEGER;
BEGIN
-- Compter les campagnes
SELECT COUNT(*) INTO campaign_count FROM campaigns;
SELECT COUNT(*) INTO campaign_with_slug FROM campaigns WHERE slug IS NOT NULL;
-- Compter les participants
SELECT COUNT(*) INTO participant_count FROM participants;
SELECT COUNT(*) INTO participant_with_short_id FROM participants WHERE short_id IS NOT NULL;
RAISE NOTICE '=== RAPPORT DE MIGRATION ===';
RAISE NOTICE 'Campagnes totales: %', campaign_count;
RAISE NOTICE 'Campagnes avec slug: %', campaign_with_slug;
RAISE NOTICE 'Participants totaux: %', participant_count;
RAISE NOTICE 'Participants avec short_id: %', participant_with_short_id;
IF campaign_count = campaign_with_slug AND participant_count = participant_with_short_id THEN
RAISE NOTICE '✅ Migration réussie ! Toutes les données ont été migrées.';
ELSE
RAISE NOTICE '⚠️ Attention: Certaines données n''ont pas été migrées.';
END IF;
END $$;

View File

@@ -10,13 +10,13 @@ import DeleteParticipantModal from '@/components/DeleteParticipantModal';
import ImportFileModal from '@/components/ImportFileModal'; import ImportFileModal from '@/components/ImportFileModal';
import SendParticipantEmailModal from '@/components/SendParticipantEmailModal'; import SendParticipantEmailModal from '@/components/SendParticipantEmailModal';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar'; import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import Navigation from '@/components/Navigation'; import Navigation from '@/components/Navigation';
import AuthGuard from '@/components/AuthGuard'; import AuthGuard from '@/components/AuthGuard';
import { Users, User, Calendar, Mail, Vote, Copy, Check, Upload } from 'lucide-react'; import { User, Calendar, Mail, Vote, Copy, Check, Upload } from 'lucide-react';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
@@ -95,8 +95,11 @@ function CampaignParticipantsPageContent() {
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase(); return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
}; };
const copyVoteLink = (participantId: string) => { const copyVoteLink = (participantId: string, shortId?: string) => {
const voteUrl = `${window.location.origin}/campaigns/${campaignId}/vote/${participantId}`; // 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); navigator.clipboard.writeText(voteUrl);
setCopiedParticipantId(participantId); setCopiedParticipantId(participantId);
setTimeout(() => setCopiedParticipantId(null), 2000); setTimeout(() => setCopiedParticipantId(null), 2000);
@@ -144,8 +147,7 @@ function CampaignParticipantsPageContent() {
); );
} }
const votedCount = participants.filter(p => p.has_voted).length;
const totalBudget = participants.reduce((sum, p) => sum + (p.total_voted_amount || 0), 0);
return ( return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-900"> <div className="min-h-screen bg-slate-50 dark:bg-slate-900">
@@ -175,73 +177,14 @@ function CampaignParticipantsPageContent() {
</div> </div>
</div> </div>
{/* Stats Overview */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Total Participants</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{participants.length}</p>
</div>
<div className="w-8 h-8 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
<Users className="w-4 h-4 text-blue-600 dark:text-blue-300" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Ont voté</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{votedCount}</p>
</div>
<div className="w-8 h-8 bg-green-100 dark:bg-green-900 rounded-lg flex items-center justify-center">
<Vote className="w-4 h-4 text-green-600 dark:text-green-300" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Taux de participation</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
{participants.length > 0 ? Math.round((votedCount / participants.length) * 100) : 0}%
</p>
</div>
<div className="w-8 h-8 bg-purple-100 dark:bg-purple-900 rounded-lg flex items-center justify-center">
<span className="text-purple-600 dark:text-purple-300">📊</span>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Budget total voté</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{totalBudget}</p>
</div>
<div className="w-8 h-8 bg-yellow-100 dark:bg-yellow-900 rounded-lg flex items-center justify-center">
<span className="text-yellow-600 dark:text-yellow-300">💰</span>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Participants List */} {/* Participants List */}
{participants.length === 0 ? ( {participants.length === 0 ? (
<Card className="border-dashed"> <Card className="border-dashed">
<CardContent className="p-12 text-center"> <CardContent className="p-12 text-center">
<div className="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mx-auto mb-4"> <div className="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mx-auto mb-4">
<Users className="w-8 h-8 text-slate-400" /> <User className="w-8 h-8 text-slate-400" />
</div> </div>
<h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2"> <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2">
Aucun participant Aucun participant
@@ -269,9 +212,6 @@ function CampaignParticipantsPageContent() {
{participant.has_voted ? 'A voté' : 'N\'a pas voté'} {participant.has_voted ? 'A voté' : 'N\'a pas voté'}
</Badge> </Badge>
</div> </div>
<CardDescription className="text-base">
{participant.email}
</CardDescription>
</div> </div>
<div className="flex flex-col sm:flex-row gap-2"> <div className="flex flex-col sm:flex-row gap-2">
<Button <Button
@@ -327,55 +267,55 @@ function CampaignParticipantsPageContent() {
{/* Vote Link for voting campaigns */} {/* Vote Link for voting campaigns */}
{campaign.status === 'voting' && ( {campaign.status === 'voting' && (
<Card className="bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800"> <div className="flex items-center space-x-2">
<CardContent className="p-4"> <div className="flex-1 min-w-0">
<div className="flex items-center justify-between"> <div className="text-xs text-blue-700 dark:text-blue-300 mb-1">
<div className="flex-1"> Lien de vote :
<h4 className="text-sm font-medium text-blue-900 dark:text-blue-100 mb-1">
Lien de vote personnel
</h4>
<div className="flex items-center space-x-2">
<Input
type="text"
readOnly
value={`${window.location.origin}/campaigns/${campaignId}/vote/${participant.id}`}
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)}
className="text-xs"
>
{copiedParticipantId === participant.id ? (
<>
<Check className="w-3 h-3 mr-1" />
Copié !
</>
) : (
<>
<Copy className="w-3 h-3 mr-1" />
Copier
</>
)}
</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> </div>
</CardContent> <div className="flex items-center space-x-2">
</Card> <Input
type="text"
readOnly
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, participant.short_id)}
className="text-xs"
disabled={!participant.short_id}
>
{copiedParticipantId === participant.id ? (
<>
<Check className="w-3 h-3 mr-1" />
Copié !
</>
) : (
<>
<Copy className="w-3 h-3 mr-1" />
Copier
</>
)}
</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> </CardContent>
</Card> </Card>

View File

@@ -10,11 +10,11 @@ import DeletePropositionModal from '@/components/DeletePropositionModal';
import ImportFileModal from '@/components/ImportFileModal'; import ImportFileModal from '@/components/ImportFileModal';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar'; import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import Navigation from '@/components/Navigation'; import Navigation from '@/components/Navigation';
import AuthGuard from '@/components/AuthGuard'; import AuthGuard from '@/components/AuthGuard';
import { FileText, User, Calendar, Mail, Upload } from 'lucide-react'; import { FileText, Calendar, Mail, Upload } from 'lucide-react';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
@@ -89,6 +89,8 @@ function CampaignPropositionsPageContent() {
} }
}; };
const getInitials = (firstName: string, lastName: string) => { const getInitials = (firstName: string, lastName: string) => {
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase(); return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
}; };
@@ -161,57 +163,11 @@ function CampaignPropositionsPageContent() {
</Button> </Button>
</div> </div>
</div> </div>
</div> </div>
{/* Stats Overview */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Total Propositions</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{propositions.length}</p>
</div>
<div className="w-8 h-8 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
<FileText className="w-4 h-4 text-blue-600 dark:text-blue-300" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Auteurs uniques</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
{new Set(propositions.map(p => p.author_email)).size}
</p>
</div>
<div className="w-8 h-8 bg-green-100 dark:bg-green-900 rounded-lg flex items-center justify-center">
<User className="w-4 h-4 text-green-600 dark:text-green-300" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Statut Campagne</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">
{campaign.status === 'deposit' ? 'Dépôt' :
campaign.status === 'voting' ? 'Vote' : 'Terminée'}
</p>
</div>
<div className="w-8 h-8 bg-purple-100 dark:bg-purple-900 rounded-lg flex items-center justify-center">
<span className="text-purple-600 dark:text-purple-300">📊</span>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Propositions List */} {/* Propositions List */}
{propositions.length === 0 ? ( {propositions.length === 0 ? (

View File

@@ -3,17 +3,18 @@ import { useState, useEffect } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { Campaign, CampaignWithStats } from '@/types'; import { Campaign, CampaignWithStats } from '@/types';
import { campaignService } from '@/lib/services'; import { campaignService } from '@/lib/services';
import { authService } from '@/lib/auth';
import CreateCampaignModal from '@/components/CreateCampaignModal'; import CreateCampaignModal from '@/components/CreateCampaignModal';
import EditCampaignModal from '@/components/EditCampaignModal'; import EditCampaignModal from '@/components/EditCampaignModal';
import DeleteCampaignModal from '@/components/DeleteCampaignModal'; import DeleteCampaignModal from '@/components/DeleteCampaignModal';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Progress } from '@/components/ui/progress';
import Navigation from '@/components/Navigation';
import AuthGuard from '@/components/AuthGuard'; import AuthGuard from '@/components/AuthGuard';
import { FolderOpen, Users, FileText, CheckCircle, Clock, Plus, BarChart3, Settings } from 'lucide-react'; import { FolderOpen, Users, FileText, Plus, BarChart3, Settings, Check, Copy } from 'lucide-react';
import StatusSwitch from '@/components/StatusSwitch';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
@@ -24,7 +25,7 @@ function AdminPageContent() {
const [showEditModal, setShowEditModal] = useState(false); const [showEditModal, setShowEditModal] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false); const [showDeleteModal, setShowDeleteModal] = useState(false);
const [selectedCampaign, setSelectedCampaign] = useState<Campaign | null>(null); const [selectedCampaign, setSelectedCampaign] = useState<Campaign | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [copiedCampaignId, setCopiedCampaignId] = useState<string | null>(null); const [copiedCampaignId, setCopiedCampaignId] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
@@ -67,6 +68,23 @@ function AdminPageContent() {
loadCampaigns(); loadCampaigns();
}; };
const handleStatusChange = async (campaignId: string, newStatus: 'deposit' | 'voting' | 'closed') => {
try {
await campaignService.update(campaignId, { status: newStatus });
// Mettre à jour l'état local sans recharger toute la page
setCampaigns(prevCampaigns =>
prevCampaigns.map(campaign =>
campaign.id === campaignId
? { ...campaign, status: newStatus }
: campaign
)
);
} catch (error) {
console.error('Erreur lors du changement de statut:', error);
throw error; // Propager l'erreur pour que le composant puisse la gérer
}
};
const getStatusBadge = (status: string) => { const getStatusBadge = (status: string) => {
switch (status) { switch (status) {
case 'deposit': case 'deposit':
@@ -80,9 +98,7 @@ function AdminPageContent() {
} }
}; };
const getSpendingTiersDisplay = (tiers: string) => {
return tiers.split(',').map(tier => `${tier.trim()}`).join(', ');
};
const copyToClipboard = async (text: string, campaignId: string) => { const copyToClipboard = async (text: string, campaignId: string) => {
try { try {
@@ -107,23 +123,14 @@ function AdminPageContent() {
} }
}; };
const filteredCampaigns = campaigns.filter(campaign =>
campaign.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
campaign.description.toLowerCase().includes(searchTerm.toLowerCase())
);
const stats = {
total: campaigns.length,
deposit: campaigns.filter(c => c.status === 'deposit').length,
voting: campaigns.filter(c => c.status === 'voting').length,
closed: campaigns.filter(c => c.status === 'closed').length,
};
if (loading) { if (loading) {
return ( return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-900"> <div className="min-h-screen bg-slate-50 dark:bg-slate-900">
<div className="container mx-auto px-4 py-8"> <div className="container mx-auto px-4 py-8">
<Navigation />
<div className="flex items-center justify-center h-64"> <div className="flex items-center justify-center h-64">
<div className="text-center"> <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> <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>
@@ -138,233 +145,284 @@ function AdminPageContent() {
return ( return (
<div className="min-h-screen bg-slate-50 dark:bg-slate-900"> <div className="min-h-screen bg-slate-50 dark:bg-slate-900">
<div className="container mx-auto px-4 py-8"> <div className="container mx-auto px-4 py-8">
<Navigation />
{/* Header */} {/* Header */}
<div className="mb-8"> <div className="mb-10">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4"> <div className="relative overflow-hidden rounded-2xl bg-gradient-to-br from-slate-50 via-white to-gray-50 dark:from-slate-800 dark:via-slate-900 dark:to-slate-800 border border-slate-200 dark:border-slate-700">
<div> <div className="absolute inset-0 bg-grid-slate-100 dark:bg-grid-slate-800 [mask-image:linear-gradient(0deg,white,rgba(255,255,255,0.6))] dark:[mask-image:linear-gradient(0deg,rgba(255,255,255,0.1),rgba(255,255,255,0.05))]" />
<h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100">Administration</h1> <div className="relative p-8">
<p className="text-slate-600 dark:text-slate-300 mt-2">Gérez vos campagnes de budget participatif</p> <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
</div> <div className="space-y-2">
<div className="flex gap-2"> <div className="flex items-center gap-3">
<Button asChild variant="outline" size="lg"> <div className="w-10 h-10 bg-slate-100 dark:bg-slate-800 rounded-xl flex items-center justify-center">
<Link href="/admin/settings"> <svg className="w-5 h-5 text-slate-600 dark:text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<Settings className="w-4 h-4 mr-2" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
Paramètres </svg>
</Link> </div>
</Button> <div>
<Button onClick={() => setShowCreateModal(true)} size="lg"> <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100">
<Plus className="w-4 h-4 mr-2" /> Mes Budgets Participatifs
Nouvelle campagne </h1>
</Button> <p className="text-slate-600 dark:text-slate-400 font-medium">Administration</p>
</div>
</div>
<p className="text-slate-600 dark:text-slate-400 max-w-2xl">
Gérez vos campagnes de budget participatif, suivez les votes et analysez les résultats
</p>
</div>
<div className="flex flex-col sm:flex-row gap-3">
<Button
onClick={() => setShowCreateModal(true)}
size="lg"
className="bg-slate-900 hover:bg-slate-800 text-white shadow-lg hover:shadow-xl transition-all duration-200"
>
<Plus className="w-4 h-4 mr-2" />
Nouvelle campagne
</Button>
<div className="flex gap-2">
<Button
asChild
variant="outline"
size="lg"
className="border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 transition-all duration-200"
>
<Link href="/admin/settings">
<Settings className="w-4 h-4 mr-2" />
Paramètres
</Link>
</Button>
<Button
variant="outline"
size="lg"
className="border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 transition-all duration-200"
onClick={async () => {
try {
await authService.signOut();
window.location.href = '/';
} catch (error) {
console.error('Erreur lors de la déconnexion:', error);
}
}}
>
Déconnexion
</Button>
</div>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>
{/* Stats Overview */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Total Campagnes</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{stats.total}</p>
</div>
<div className="w-8 h-8 bg-blue-100 dark:bg-blue-900 rounded-lg flex items-center justify-center">
<FolderOpen className="w-4 h-4 text-blue-600 dark:text-blue-300" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">En cours</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{stats.voting}</p>
</div>
<div className="w-8 h-8 bg-green-100 dark:bg-green-900 rounded-lg flex items-center justify-center">
<Clock className="w-4 h-4 text-green-600 dark:text-green-300" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Dépôt</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{stats.deposit}</p>
</div>
<div className="w-8 h-8 bg-yellow-100 dark:bg-yellow-900 rounded-lg flex items-center justify-center">
<FileText className="w-4 h-4 text-yellow-600 dark:text-yellow-300" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium text-slate-600 dark:text-slate-300">Terminées</p>
<p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{stats.closed}</p>
</div>
<div className="w-8 h-8 bg-purple-100 dark:bg-purple-900 rounded-lg flex items-center justify-center">
<CheckCircle className="w-4 h-4 text-purple-600 dark:text-purple-300" />
</div>
</div>
</CardContent>
</Card>
</div>
{/* Search */}
<div className="mb-6">
<Input
type="text"
placeholder="Rechercher une campagne..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="max-w-md"
/>
</div>
{/* Campaigns List */} {/* Campaigns List */}
{filteredCampaigns.length === 0 ? ( {campaigns.length === 0 ? (
<Card className="border-dashed"> <div className="text-center py-16">
<CardContent className="p-12 text-center"> <div className="w-20 h-20 bg-gradient-to-br from-slate-50 to-gray-100 dark:from-slate-800 dark:to-slate-700 rounded-2xl flex items-center justify-center mx-auto mb-6">
<div className="w-16 h-16 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mx-auto mb-4"> <FolderOpen className="w-10 h-10 text-slate-600 dark:text-slate-400" />
<FolderOpen className="w-8 h-8 text-slate-400" /> </div>
</div> <h3 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-3">
<h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-2"> Aucune campagne
{searchTerm ? 'Aucune campagne trouvée' : 'Aucune campagne'} </h3>
</h3> <p className="text-slate-600 dark:text-slate-400 mb-8 max-w-md mx-auto">
<p className="text-slate-600 dark:text-slate-300 mb-6"> Créez votre première campagne de budget participatif pour commencer à collecter les idées de votre communauté
{searchTerm </p>
? 'Aucune campagne ne correspond à votre recherche.' <Button
: 'Commencez par créer votre première campagne de budget participatif.' onClick={() => setShowCreateModal(true)}
} size="lg"
</p> className="bg-slate-900 hover:bg-slate-800 text-white shadow-lg hover:shadow-xl transition-all duration-200"
{!searchTerm && ( >
<Button onClick={() => setShowCreateModal(true)}> <Plus className="w-4 h-4 mr-2" />
<Plus className="w-4 h-4 mr-2" /> Créer une campagne
Créer une campagne </Button>
</Button> </div>
)}
</CardContent>
</Card>
) : ( ) : (
<div className="grid gap-6"> <div className="grid gap-6 group/campaigns">
{filteredCampaigns.map((campaign) => ( {campaigns.map((campaign) => (
<Card key={campaign.id} className="hover:shadow-lg transition-shadow duration-200"> <Card key={campaign.id} className="group hover:shadow-xl hover:shadow-slate-100 dark:hover:shadow-slate-900/20 transition-all duration-300 border-slate-200 dark:border-slate-700 overflow-hidden group-hover/campaigns:opacity-30 hover:!opacity-100">
<CardHeader> <div className="relative">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
<div className="flex-1"> <CardHeader className="pb-4">
<div className="flex items-center gap-3 mb-2"> <div className="flex items-start justify-between">
<CardTitle className="text-xl">{campaign.title}</CardTitle> <div className="flex-1 space-y-4">
{getStatusBadge(campaign.status)} <div className="flex items-start gap-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-2">
<CardTitle className="text-xl font-bold text-slate-900 dark:text-slate-100 group-hover:text-slate-600 dark:group-hover:text-slate-400 transition-colors duration-200">
{campaign.title}
</CardTitle>
</div>
<CardDescription className="text-slate-600 dark:text-slate-400 text-sm leading-relaxed mb-4">
{campaign.description}
</CardDescription>
{/* Status Switch */}
<div className="mb-4">
<StatusSwitch
currentStatus={campaign.status}
onStatusChange={(newStatus) => handleStatusChange(campaign.id, newStatus)}
/>
</div>
</div>
</div>
{/* Stats avec icônes modernes et boutons intégrés */}
<div className="mb-3">
<p className="text-xs text-slate-500 dark:text-slate-400 text-center">
Cliquez sur les éléments pour les gérer
</p>
</div>
<div className="grid grid-cols-3 gap-4 pt-2">
<Button
asChild
variant="ghost"
className="h-auto p-3 bg-slate-50 dark:bg-slate-800/50 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg border-0 group relative"
>
<Link href={`/admin/campaigns/${campaign.id}/propositions`}>
<div className="flex items-center gap-2 w-full">
<div className="w-8 h-8 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center justify-center">
<FileText className="w-4 h-4 text-slate-600 dark:text-slate-400" />
</div>
<div className="text-left">
<div className="text-lg font-bold text-slate-900 dark:text-slate-100">
{campaign.stats.propositions}
</div>
<div className="text-xs text-slate-500 dark:text-slate-400">Propositions</div>
</div>
<div className="ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
</div>
</Link>
</Button>
<Button
asChild
variant="ghost"
className="h-auto p-3 bg-slate-50 dark:bg-slate-800/50 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-lg border-0 group relative"
>
<Link href={`/admin/campaigns/${campaign.id}/participants`}>
<div className="flex items-center gap-2 w-full">
<div className="w-8 h-8 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center justify-center">
<Users className="w-4 h-4 text-slate-600 dark:text-slate-400" />
</div>
<div className="text-left">
<div className="text-lg font-bold text-slate-900 dark:text-slate-100">
{campaign.stats.participants}
</div>
<div className="text-xs text-slate-500 dark:text-slate-400">Participants</div>
</div>
<div className="ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<svg className="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
</div>
</Link>
</Button>
<div className="flex items-center gap-2 p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg">
<div className="w-8 h-8 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center justify-center">
<BarChart3 className="w-4 h-4 text-slate-600 dark:text-slate-400" />
</div>
<div>
<div className="text-lg font-bold text-slate-900 dark:text-slate-100">
{campaign.budget_per_user}
</div>
<div className="text-xs text-slate-500 dark:text-slate-400">Budget</div>
</div>
</div>
</div>
</div> </div>
<CardDescription className="text-base">{campaign.description}</CardDescription>
</div>
<div className="flex flex-col sm:flex-row gap-2">
<Button
variant="outline"
size="sm"
onClick={() => {
setSelectedCampaign(campaign);
setShowEditModal(true);
}}
>
Modifier
</Button>
<Button
variant="outline"
size="sm"
onClick={() => {
setSelectedCampaign(campaign);
setShowDeleteModal(true);
}}
>
🗑 Supprimer
</Button>
</div>
</div>
</CardHeader>
<CardContent> {/* Boutons discrets en haut à droite */}
{/* <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4"> <div className="flex gap-1 ml-4">
<div className="text-center p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
<p className="text-sm text-slate-600 dark:text-slate-300">Propositions</p>
<p className="text-lg font-semibold text-slate-900 dark:text-slate-100">{campaign.stats.propositions}</p>
</div>
<div className="text-center p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
<p className="text-sm text-slate-600 dark:text-slate-300">Participants</p>
<p className="text-lg font-semibold text-slate-900 dark:text-slate-100">{campaign.stats.participants}</p>
</div>
<div className="text-center p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
<p className="text-sm text-slate-600 dark:text-slate-300">Budget/participant</p>
<p className="text-lg font-semibold text-slate-900 dark:text-slate-100">{campaign.budget_per_user}€</p>
</div>
<div className="text-center p-3 bg-slate-50 dark:bg-slate-800 rounded-lg">
<p className="text-sm text-slate-600 dark:text-slate-300">Paliers</p>
<p className="text-sm font-semibold text-slate-900 dark:text-slate-100">{getSpendingTiersDisplay(campaign.spending_tiers)}</p>
</div>
</div> */}
{/* Public URL for deposit campaigns */}
{campaign.status === 'deposit' && (
<div className="mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<h4 className="text-sm font-medium text-blue-900 dark:text-blue-100 mb-2">
Lien public pour le dépôt de propositions :
</h4>
<div className="flex items-center space-x-2">
<Input
type="text"
readOnly
value={`${window.location.origin}/campaigns/${campaign.id}/propose`}
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 <Button
variant={copiedCampaignId === campaign.id ? "default" : "outline"} variant="ghost"
size="sm" size="sm"
className="h-8 w-8 p-0 text-slate-400 hover:text-slate-600 hover:bg-slate-100 dark:hover:bg-slate-800"
onClick={() => { onClick={() => {
copyToClipboard(`${window.location.origin}/campaigns/${campaign.id}/propose`, campaign.id); setSelectedCampaign(campaign);
setShowEditModal(true);
}} }}
className="text-xs"
> >
{copiedCampaignId === campaign.id ? '✓ Copié !' : 'Copier'} <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20"
onClick={() => {
setSelectedCampaign(campaign);
setShowDeleteModal(true);
}}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</Button> </Button>
</div> </div>
</div> </div>
)} </CardHeader>
{/* Action Buttons */} <CardContent className="pt-0">
<div className="flex flex-col sm:flex-row gap-2 mt-4"> {/* Section actions - même espace pour lien public et statistiques */}
<Button asChild variant="outline" className="flex-1"> <div className="space-y-4">
<Link href={`/admin/campaigns/${campaign.id}/propositions`}> {/* Lien public OU Bouton Statistiques */}
<FileText className="w-4 h-4 mr-2" /> {campaign.status === 'deposit' ? (
Propositions ({campaign.stats.propositions}) /* Lien public pour les campagnes en dépôt */
</Link> <div className="p-3 bg-slate-50 dark:bg-slate-800/30 border border-slate-200 dark:border-slate-700 rounded-lg">
</Button> <div className="flex items-center justify-between">
<Button asChild variant="outline" className="flex-1"> <div className="flex items-center gap-2">
<Link href={`/admin/campaigns/${campaign.id}/participants`}> <svg className="w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<Users className="w-4 h-4 mr-2" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
Votants ({campaign.stats.participants}) </svg>
</Link> <span className="text-sm text-slate-600 dark:text-slate-400">Lien public pour déposer une proposition</span>
</Button> </div>
{(campaign.status === 'voting' || campaign.status === 'closed') && ( <div className="flex items-center gap-2">
<Button asChild variant="default" className="flex-1"> <div className="text-xs text-slate-500 dark:text-slate-400 font-mono">
<Link href={`/admin/campaigns/${campaign.id}/stats`}> {`${window.location.origin}/p/${campaign.slug || 'campagne'}`}
<BarChart3 className="w-4 h-4 mr-2" /> </div>
Statistiques <Button
</Link> variant="ghost"
</Button> size="sm"
)} className="h-7 w-7 p-0 text-slate-400 hover:text-slate-600"
</div> onClick={() => {
</CardContent> copyToClipboard(`${window.location.origin}/p/${campaign.slug || 'campagne'}`, campaign.id);
}}
>
{copiedCampaignId === campaign.id ? (
<Check className="w-3 h-3" />
) : (
<Copy className="w-3 h-3" />
)}
</Button>
</div>
</div>
</div>
) : (campaign.status === 'voting' || campaign.status === 'closed') ? (
/* Bouton Statistiques pour les campagnes en vote/fermées */
<div className="flex justify-center">
<Button asChild variant="outline" className="border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-300">
<Link href={`/admin/campaigns/${campaign.id}/stats`}>
<BarChart3 className="w-4 h-4 mr-2" />
Voir les statistiques
</Link>
</Button>
</div>
) : (
/* Espace vide pour les autres statuts */
<div className="h-12"></div>
)}
</div>
</CardContent>
</div>
</Card> </Card>
))} ))}
</div> </div>

View File

@@ -192,7 +192,9 @@ export default function PublicProposePage() {
<div className="space-y-4"> <div className="space-y-4">
<div> <div>
<h3 className="text-sm font-medium text-slate-600 dark:text-slate-300 mb-2">Description</h3> <h3 className="text-sm font-medium text-slate-600 dark:text-slate-300 mb-2">Description</h3>
<p className="text-slate-900 dark:text-slate-100 whitespace-pre-wrap">{campaign?.description}</p> <div className="text-slate-900 dark:text-slate-100 whitespace-pre-wrap leading-relaxed">
{campaign?.description}
</div>
</div> </div>
</div> </div>
</CardContent> </CardContent>

View File

@@ -27,6 +27,9 @@ export default function PublicVotePage() {
const [localVotes, setLocalVotes] = useState<Record<string, number>>({}); const [localVotes, setLocalVotes] = useState<Record<string, number>>({});
const [totalVoted, setTotalVoted] = useState(0); const [totalVoted, setTotalVoted] = useState(0);
const [isRandomOrder, setIsRandomOrder] = useState(false); const [isRandomOrder, setIsRandomOrder] = useState(false);
const [isCompactView, setIsCompactView] = useState(false);
const [currentVisibleProposition, setCurrentVisibleProposition] = useState(1);
const [isOverBudget, setIsOverBudget] = useState(false);
useEffect(() => { useEffect(() => {
if (campaignId && participantId) { if (campaignId && participantId) {
@@ -34,15 +37,92 @@ export default function PublicVotePage() {
} }
}, [campaignId, participantId]); }, [campaignId, participantId]);
// Écouter les changements de connectivité réseau
useEffect(() => {
const handleOnline = () => {
console.log('Connexion réseau rétablie');
setError('');
};
const handleOffline = () => {
console.log('Connexion réseau perdue');
setError('Connexion réseau perdue. Veuillez vérifier votre connexion internet.');
};
if (typeof window !== 'undefined') {
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
}
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
}
};
}, []);
// Calculer le total voté à partir des votes locaux // Calculer le total voté à partir des votes locaux
useEffect(() => { useEffect(() => {
const total = Object.values(localVotes).reduce((sum, amount) => sum + amount, 0); const total = Object.values(localVotes).reduce((sum, amount) => sum + amount, 0);
setTotalVoted(total); setTotalVoted(total);
}, [localVotes]);
// Vérifier si on dépasse le budget
if (campaign && total > campaign.budget_per_user) {
setIsOverBudget(true);
// Arrêter la vibration après 1 seconde
setTimeout(() => setIsOverBudget(false), 1000);
} else {
setIsOverBudget(false);
}
}, [localVotes, campaign]);
// Observer les propositions visibles
useEffect(() => {
if (propositions.length === 0) return;
const observer = new IntersectionObserver(
(entries) => {
let highestVisibleIndex = 1;
entries.forEach((entry) => {
if (entry.isIntersecting) {
const propositionIndex = parseInt(entry.target.getAttribute('data-proposition-index') || '1');
if (propositionIndex > highestVisibleIndex) {
highestVisibleIndex = propositionIndex;
}
}
});
if (highestVisibleIndex > 1) {
setCurrentVisibleProposition(highestVisibleIndex);
}
},
{
threshold: 0.3, // La proposition doit être visible à 30% pour être considérée comme active
rootMargin: '-10% 0px -10% 0px' // Zone de détection réduite
}
);
// Attendre que le DOM soit mis à jour
setTimeout(() => {
const propositionElements = document.querySelectorAll('[data-proposition-index]');
propositionElements.forEach((element) => observer.observe(element));
}, 100);
return () => observer.disconnect();
}, [propositions, isCompactView]);
const loadData = async () => { const loadData = async () => {
try { try {
setLoading(true); setLoading(true);
setError('');
// Vérifier la connectivité réseau
if (typeof window !== 'undefined' && !navigator.onLine) {
throw new Error('Pas de connexion internet. Veuillez vérifier votre connexion réseau.');
}
const [campaigns, participants, propositionsData] = await Promise.all([ const [campaigns, participants, propositionsData] = await Promise.all([
campaignService.getAll(), campaignService.getAll(),
participantService.getByCampaign(campaignId), participantService.getByCampaign(campaignId),
@@ -99,7 +179,23 @@ export default function PublicVotePage() {
} catch (error) { } catch (error) {
console.error('Erreur lors du chargement des données:', error); console.error('Erreur lors du chargement des données:', error);
setError('Erreur lors du chargement des données'); let errorMessage = 'Erreur lors du chargement des données';
if (error instanceof Error) {
errorMessage = error.message;
} else if (typeof error === 'object' && error !== null) {
// Essayer d'extraire plus d'informations de l'erreur
const errorObj = error as any;
if (errorObj.message) {
errorMessage = errorObj.message;
} else if (errorObj.error) {
errorMessage = errorObj.error;
} else if (errorObj.details) {
errorMessage = errorObj.details;
}
}
setError(errorMessage);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -130,28 +226,39 @@ export default function PublicVotePage() {
setError(''); setError('');
try { try {
// Supprimer tous les votes existants pour ce participant // Préparer les votes à sauvegarder (seulement ceux avec amount > 0)
const existingVotes = await voteService.getByParticipant(campaignId, participantId); const votesToSave = Object.entries(localVotes)
for (const vote of existingVotes) { .filter(([_, amount]) => amount > 0)
await voteService.delete(vote.id); .map(([propositionId, amount]) => ({
} proposition_id: propositionId,
amount
}));
// Créer les nouveaux votes // Utiliser la méthode atomique pour remplacer tous les votes
for (const [propositionId, amount] of Object.entries(localVotes)) { await voteService.replaceVotes(campaignId, participantId, votesToSave);
if (amount > 0) {
await voteService.create({
campaign_id: campaignId,
participant_id: participantId,
proposition_id: propositionId,
amount
});
}
}
setSuccess(true); setSuccess(true);
} catch (error) { } catch (error) {
console.error('Erreur lors de la validation:', error); console.error('Erreur lors de la validation:', error);
setError('Erreur lors de la validation des votes');
// Améliorer l'affichage de l'erreur
let errorMessage = 'Erreur lors de la validation des votes';
if (error instanceof Error) {
errorMessage = error.message;
} else if (typeof error === 'object' && error !== null) {
// Essayer d'extraire plus d'informations de l'erreur
const errorObj = error as any;
if (errorObj.message) {
errorMessage = errorObj.message;
} else if (errorObj.error) {
errorMessage = errorObj.error;
} else if (errorObj.details) {
errorMessage = errorObj.details;
}
}
setError(errorMessage);
} finally { } finally {
setSaving(false); setSaving(false);
} }
@@ -253,10 +360,18 @@ export default function PublicVotePage() {
<div className="flex items-center space-x-4"> <div className="flex items-center space-x-4">
<div className="text-right"> <div className="text-right">
<div className="text-2xl font-bold text-gray-900"> <div className={`text-2xl font-bold transition-all duration-300 ${
isOverBudget
? 'text-red-600 animate-pulse'
: totalVoted === campaign?.budget_per_user
? 'text-green-600 scale-105'
: totalVoted > 0
? 'text-indigo-600'
: 'text-gray-900'
} ${isOverBudget ? 'animate-bounce' : ''}`}>
{totalVoted}€ / {campaign?.budget_per_user}€ {totalVoted}€ / {campaign?.budget_per_user}€
</div> </div>
<div className={`text-sm font-medium ${ <div className={`text-sm font-medium transition-colors duration-300 ${
voteStatus.status === 'success' ? 'text-green-600' : voteStatus.status === 'success' ? 'text-green-600' :
voteStatus.status === 'warning' ? 'text-yellow-600' : voteStatus.status === 'warning' ? 'text-yellow-600' :
'text-red-600' 'text-red-600'
@@ -281,18 +396,15 @@ export default function PublicVotePage() {
</div> </div>
</div> </div>
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8"> <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8 pb-20">
{/* Informations de la campagne */} {/* Informations de la campagne */}
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8"> <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-8">
<div className="grid grid-cols-1 md:grid-cols-1 gap-6"> <div className="grid grid-cols-1 md:grid-cols-1 gap-6">
<div> <div>
<p className="mt-1 text-sm text-gray-900 whitespace-pre-wrap">{campaign?.description}</p> <p className="mt-1 text-base font-medium text-gray-900 whitespace-pre-wrap leading-relaxed">{campaign?.description}</p>
{isRandomOrder && ( {isRandomOrder && (
<div className="mt-3 p-2 bg-blue-50 border border-blue-200 rounded-md"> <div className="mt-4 text-xs text-gray-500 italic">
<p className="text-xs text-blue-700 flex items-center gap-1"> Les propositions sont affichées dans un ordre aléatoire pour éviter les biais liés à l'ordre de présentation.
<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>
@@ -309,35 +421,42 @@ export default function PublicVotePage() {
<p className="mt-1 text-sm text-gray-500">Aucune proposition n'a été soumise pour cette campagne.</p> <p className="mt-1 text-sm text-gray-500">Aucune proposition n'a été soumise pour cette campagne.</p>
</div> </div>
) : ( ) : (
<div className="space-y-6"> <div className={`${isCompactView ? 'space-y-3' : 'space-y-6'}`}>
{propositions.map((proposition) => ( {propositions.map((proposition, index) => (
<div <div
key={proposition.id} key={proposition.id}
data-proposition-index={index + 1}
className={`rounded-lg shadow-sm border overflow-hidden transition-all duration-200 relative ${ className={`rounded-lg shadow-sm border overflow-hidden transition-all duration-200 relative ${
localVotes[proposition.id] && localVotes[proposition.id] > 0 localVotes[proposition.id] && localVotes[proposition.id] > 0
? 'border-indigo-400 shadow-lg bg-indigo-100' ? 'border-indigo-400 shadow-lg bg-indigo-100'
: 'bg-white border-gray-200' : 'bg-white border-gray-200'
}`} }`}
> >
<div className="absolute -top-1 left-4 bg-white px-2 text-xs text-gray-500 font-medium z-10 border border-gray-200 rounded-t"> {!isCompactView && (
Proposition <div className="absolute -top-1 left-4 bg-white px-2 text-xs text-gray-500 font-medium z-10 border border-gray-200 rounded-t">
</div> Proposition
<div className="p-6">
<div className="flex items-start justify-between">
<div className="flex-1">
<h3 className="text-lg font-medium text-gray-900 mb-2">
{proposition.title}
</h3>
<p className="text-sm text-gray-600 mb-4 whitespace-pre-wrap">
{proposition.description}
</p>
</div>
</div> </div>
)}
<div className={`${isCompactView ? 'p-4' : 'p-6'}`}>
<div className="flex items-start justify-between">
<div className="flex-1">
<h3 className={`font-medium text-gray-900 ${isCompactView ? 'text-base mb-1' : 'text-lg mb-2'}`}>
{proposition.title}
</h3>
{!isCompactView && (
<p className="text-sm text-gray-600 mb-4 whitespace-pre-wrap">
{proposition.description}
</p>
)}
</div>
</div>
<div className="mt-6"> <div className={isCompactView ? 'mt-3' : 'mt-6'}>
<label className="block text-sm font-medium text-gray-700 mb-3"> {!isCompactView && (
Pour cette proposition, vous investissez : <label className="block text-sm font-medium text-gray-700 mb-3">
</label> Pour cette proposition, vous investissez :
</label>
)}
<div className="space-y-4"> <div className="space-y-4">
{/* Slider */} {/* Slider */}
<div className="relative"> <div className="relative">
@@ -384,7 +503,7 @@ export default function PublicVotePage() {
</div> </div>
{/* Valeur sélectionnée */} {/* Valeur sélectionnée */}
{(localVotes[proposition.id] && localVotes[proposition.id] > 0) && ( {(localVotes[proposition.id] && localVotes[proposition.id] > 0) && !isCompactView && (
<div className="text-center mt-12"> <div className="text-center mt-12">
<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-indigo-100 text-indigo-800"> <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-indigo-100 text-indigo-800">
Vote sélectionné : {localVotes[proposition.id]}€ Vote sélectionné : {localVotes[proposition.id]}€
@@ -405,6 +524,34 @@ export default function PublicVotePage() {
</div> </div>
)} )}
</div> </div>
{/* Barre fixe en bas */}
<div className="fixed bottom-0 left-0 right-0 z-40 bg-white shadow-lg border-t border-gray-200">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-3">
<div className="flex items-center justify-between">
<div className="text-sm text-gray-600">
Proposition {currentVisibleProposition} / {propositions.length}
</div>
<div className="flex items-center space-x-2 text-xs text-gray-500">
<span>Juste les titres</span>
<button
onClick={() => setIsCompactView(!isCompactView)}
className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${
!isCompactView ? 'bg-indigo-600' : 'bg-gray-200'
}`}
>
<span
className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${
!isCompactView ? 'translate-x-5' : 'translate-x-1'
}`}
/>
</button>
<span>Avec descriptions</span>
</div>
</div>
</div>
</div>
</div> </div>
); );
} }

View File

@@ -187,3 +187,18 @@
@apply bg-background text-foreground; @apply bg-background text-foreground;
} }
} }
/* Motif de grille pour le header */
.bg-grid-slate-100 {
background-image:
linear-gradient(rgba(148, 163, 184, 0.1) 1px, transparent 1px),
linear-gradient(90deg, rgba(148, 163, 184, 0.1) 1px, transparent 1px);
background-size: 20px 20px;
}
.bg-grid-slate-800 {
background-image:
linear-gradient(rgba(148, 163, 184, 0.05) 1px, transparent 1px),
linear-gradient(90deg, rgba(148, 163, 184, 0.05) 1px, transparent 1px);
background-size: 20px 20px;
}

View File

@@ -15,6 +15,9 @@ const geistMono = Geist_Mono({
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Mes budgets participatifs", title: "Mes budgets participatifs",
description: "Votez pour les dépenses de votre collectif", description: "Votez pour les dépenses de votre collectif",
icons: {
icon: '/favicon.svg',
},
}; };
export default function RootLayout({ export default function RootLayout({

88
src/app/p/[slug]/page.tsx Normal file
View File

@@ -0,0 +1,88 @@
'use client';
import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { campaignService } 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 ShortProposeRedirect() {
const params = useParams();
const router = useRouter();
const slug = params.slug as string;
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
if (slug) {
redirectToProposePage();
}
}, [slug]);
const redirectToProposePage = async () => {
try {
setLoading(true);
// Récupérer la campagne par slug
const campaign = await campaignService.getBySlug(slug);
if (!campaign) {
setError('Campagne non trouvée');
return;
}
if (campaign.status !== 'deposit') {
setError('Cette campagne n\'accepte plus de propositions');
return;
}
// Rediriger vers la route avec l'ID complet
const proposeUrl = `/campaigns/${campaign.id}/propose`;
router.replace(proposeUrl);
} catch (error) {
console.error('Erreur lors de la redirection:', error);
setError('Erreur lors du chargement de la campagne');
} 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 dépôt de propositions...</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;
}

View 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 é 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>
);
}

View 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;
}

View File

@@ -96,6 +96,8 @@ export default function AuthGuard({ children, requireSuperAdmin = false }: AuthG
} }
}; };
if (isLoading) { if (isLoading) {
return ( return (
<div className="min-h-screen flex items-center justify-center"> <div className="min-h-screen flex items-center justify-center">
@@ -152,22 +154,35 @@ export default function AuthGuard({ children, requireSuperAdmin = false }: AuthG
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="password">Mot de passe</Label> <Label htmlFor="password">Mot de passe</Label>
<div className="relative"> <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 <Input
id="password" id="password"
type={showPassword ? 'text' : 'password'} type={showPassword ? 'text' : 'password'}
placeholder="••••••••" placeholder="••••••••"
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} 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" className="pl-10"
required 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>
</div> </div>
@@ -205,21 +220,6 @@ export default function AuthGuard({ children, requireSuperAdmin = false }: AuthG
return ( return (
<div> <div>
{/* Barre de navigation admin */}
<div className="bg-white border-b px-4 py-2 flex justify-between items-center">
<div className="flex items-center space-x-2">
<Lock className="h-4 w-4 text-blue-600" />
<span className="font-medium text-sm">Administration</span>
</div>
<Button
variant="outline"
size="sm"
onClick={handleLogout}
>
Déconnexion
</Button>
</div>
{children} {children}
</div> </div>
); );

View File

@@ -47,13 +47,79 @@ export default function CreateCampaignModal({ isOpen, onClose, onSuccess }: Crea
} }
}; };
const generateOptimalTiers = (budget: number): string => {
if (budget <= 0) return "0";
// Cas spéciaux pour des budgets courants
if (budget === 10000) {
return "0, 500, 1000, 2000, 3000, 5000, 7500, 10000";
}
if (budget === 8000) {
return "0, 500, 1000, 2000, 3000, 4000, 6000, 8000";
}
const tiers = [0];
// Déterminer les paliers "ronds" selon la taille du budget
let roundValues: number[] = [];
if (budget <= 100) {
// Petits budgets : multiples de 5, 10, 25
roundValues = [5, 10, 25, 50, 75, 100];
} else if (budget <= 500) {
// Budgets moyens : multiples de 25, 50, 100
roundValues = [25, 50, 75, 100, 150, 200, 250, 300, 400, 500];
} else if (budget <= 2000) {
// Budgets moyens-grands : multiples de 100, 250, 500
roundValues = [100, 250, 500, 750, 1000, 1250, 1500, 1750, 2000];
} else if (budget <= 10000) {
// Gros budgets : multiples de 500, 1000, 2000
roundValues = [500, 1000, 1500, 2000, 2500, 3000, 4000, 5000, 6000, 7500, 10000];
} else {
// Très gros budgets : multiples de 1000, 2000, 5000
roundValues = [1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 25000, 50000];
}
// Sélectionner les paliers qui sont inférieurs ou égaux au budget
const validTiers = roundValues.filter(tier => tier <= budget);
// Prendre 6-8 paliers intermédiaires + 0 et le budget final
const targetCount = Math.min(8, Math.max(6, validTiers.length));
const step = Math.max(1, Math.floor(validTiers.length / targetCount));
for (let i = 0; i < validTiers.length && tiers.length < targetCount + 1; i += step) {
if (!tiers.includes(validTiers[i])) {
tiers.push(validTiers[i]);
}
}
// Ajouter le budget final s'il n'est pas déjà présent
if (!tiers.includes(budget)) {
tiers.push(budget);
}
// Trier et retourner
return tiers.sort((a, b) => a - b).join(', ');
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setFormData(prev => ({ setFormData(prev => ({
...prev, ...prev,
[e.target.name]: e.target.value [name]: value
})); }));
}; };
const handleBudgetBlur = (e: React.FocusEvent<HTMLInputElement>) => {
const budget = parseInt(e.target.value);
if (!isNaN(budget) && budget > 0 && !formData.spending_tiers) {
setFormData(prev => ({
...prev,
spending_tiers: generateOptimalTiers(budget)
}));
}
};
const handleClose = () => { const handleClose = () => {
setFormData({ setFormData({
title: '', title: '',
@@ -108,13 +174,14 @@ export default function CreateCampaignModal({ isOpen, onClose, onSuccess }: Crea
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="budget_per_user">Budget par utilisateur () *</Label> <Label htmlFor="budget_per_user">Budget () *</Label>
<Input <Input
id="budget_per_user" id="budget_per_user"
name="budget_per_user" name="budget_per_user"
type="number" type="number"
value={formData.budget_per_user} value={formData.budget_per_user}
onChange={handleChange} onChange={handleChange}
onBlur={handleBudgetBlur}
placeholder="100" placeholder="100"
min="1" min="1"
required required
@@ -133,6 +200,11 @@ export default function CreateCampaignModal({ isOpen, onClose, onSuccess }: Crea
/> />
<p className="text-xs text-slate-500 dark:text-slate-400"> <p className="text-xs text-slate-500 dark:text-slate-400">
Séparez les montants par des virgules (ex: 0, 10, 25, 50, 100) Séparez les montants par des virgules (ex: 0, 10, 25, 50, 100)
{formData.budget_per_user && !formData.spending_tiers && (
<span className="block mt-1 text-blue-600 dark:text-blue-400">
💡 Les paliers seront générés automatiquement après avoir saisi le budget
</span>
)}
</p> </p>
</div> </div>

View File

@@ -137,7 +137,7 @@ export default function EditCampaignModal({ isOpen, onClose, onSuccess, campaign
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="budget_per_user">Budget par utilisateur () *</Label> <Label htmlFor="budget_per_user">Budget () *</Label>
<Input <Input
id="budget_per_user" id="budget_per_user"
name="budget_per_user" name="budget_per_user"

View File

@@ -1,9 +1,9 @@
'use client'; 'use client';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card'; import { Card } from '@/components/ui/card';
import { Home, Settings, Users, FileText, ArrowLeft } from 'lucide-react'; import { Settings, ArrowLeft } from 'lucide-react';
interface NavigationProps { interface NavigationProps {
showBackButton?: boolean; showBackButton?: boolean;
@@ -11,11 +11,6 @@ interface NavigationProps {
} }
export default function Navigation({ showBackButton = false, backUrl = '/' }: NavigationProps) { export default function Navigation({ showBackButton = false, backUrl = '/' }: NavigationProps) {
const pathname = usePathname();
const isActive = (path: string) => {
return pathname === path;
};
return ( return (
<Card className="mb-6 border-0 shadow-sm"> <Card className="mb-6 border-0 shadow-sm">
@@ -30,36 +25,23 @@ export default function Navigation({ showBackButton = false, backUrl = '/' }: Na
</Link> </Link>
</Button> </Button>
)} )}
<h1 className="text-xl font-semibold text-slate-900 dark:text-slate-100">
<div className="flex items-center space-x-1"> Mes Budgets Participatifs - Admin
<Button </h1>
asChild
variant={isActive('/') ? 'default' : 'ghost'}
size="sm"
>
<Link href="/">
<Home className="w-4 h-4 mr-2" />
Accueil
</Link>
</Button>
<Button
asChild
variant={isActive('/admin') ? 'default' : 'ghost'}
size="sm"
>
<Link href="/admin">
<Settings className="w-4 h-4 mr-2" />
Administration
</Link>
</Button>
</div>
</div> </div>
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<div className="text-sm text-slate-600 dark:text-slate-300"> <Button asChild variant="ghost" size="sm">
Mes Budgets Participatifs <Link href="/admin/settings">
</div> <Settings className="w-4 h-4 mr-2" />
Paramètres
</Link>
</Button>
<Button asChild variant="ghost" size="sm">
<Link href="/api/auth/signout">
Déconnexion
</Link>
</Button>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -29,8 +29,10 @@ export default function SendParticipantEmailModal({
const [sending, setSending] = useState(false); const [sending, setSending] = useState(false);
const [result, setResult] = useState<{ success: boolean; message: string } | null>(null); const [result, setResult] = useState<{ success: boolean; message: string } | null>(null);
// Générer le lien de vote // Générer le lien de vote (utiliser uniquement le lien court)
const voteUrl = `${typeof window !== 'undefined' ? window.location.origin : ''}/campaigns/${campaign.id}/vote/${participant.id}`; 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 // Initialiser le message par défaut quand le modal s'ouvre
useEffect(() => { useEffect(() => {

View File

@@ -0,0 +1,133 @@
'use client';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { FileText, Vote, CheckCircle, Check } from 'lucide-react';
interface StatusSwitchProps {
currentStatus: 'deposit' | 'voting' | 'closed';
onStatusChange: (newStatus: 'deposit' | 'voting' | 'closed') => Promise<void>;
disabled?: boolean;
}
const statusConfig = {
deposit: {
label: 'Dépôt',
icon: FileText,
color: 'bg-blue-500',
hoverColor: 'hover:bg-blue-600',
activeColor: 'bg-blue-600',
textColor: 'text-blue-600',
bgColor: 'bg-blue-50',
borderColor: 'border-blue-200'
},
voting: {
label: 'Vote',
icon: Vote,
color: 'bg-orange-500',
hoverColor: 'hover:bg-orange-600',
activeColor: 'bg-orange-600',
textColor: 'text-orange-600',
bgColor: 'bg-orange-50',
borderColor: 'border-orange-200'
},
closed: {
label: 'Terminée',
icon: CheckCircle,
color: 'bg-green-500',
hoverColor: 'hover:bg-green-600',
activeColor: 'bg-green-600',
textColor: 'text-green-600',
bgColor: 'bg-green-50',
borderColor: 'border-green-200'
}
};
export default function StatusSwitch({ currentStatus, onStatusChange, disabled = false }: StatusSwitchProps) {
const [localStatus, setLocalStatus] = useState(currentStatus);
const [isChanging, setIsChanging] = useState(false);
const [showSuccess, setShowSuccess] = useState(false);
// Synchroniser l'état local avec les props
useEffect(() => {
setLocalStatus(currentStatus);
}, [currentStatus]);
const handleStatusChange = async (newStatus: 'deposit' | 'voting' | 'closed') => {
if (disabled || isChanging || newStatus === localStatus) return;
setIsChanging(true);
try {
// Mettre à jour l'état local immédiatement pour un feedback visuel instantané
setLocalStatus(newStatus);
// Appeler la fonction de mise à jour
await onStatusChange(newStatus);
// Afficher la notification de succès
setShowSuccess(true);
setTimeout(() => setShowSuccess(false), 2000);
} catch (error) {
// En cas d'erreur, revenir à l'état précédent
setLocalStatus(currentStatus);
console.error('Erreur lors du changement de statut:', error);
} finally {
setIsChanging(false);
}
};
return (
<div className="relative">
{/* Notification de succès */}
{showSuccess && (
<div className="absolute -top-12 left-1/2 transform -translate-x-1/2 z-10">
<div className="bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 animate-in slide-in-from-top-2 duration-300">
<Check className="w-4 h-4" />
<span className="text-sm font-medium">Statut mis à jour !</span>
</div>
</div>
)}
<div className="flex items-center bg-slate-100 dark:bg-slate-800 rounded-xl p-1 shadow-inner">
{(['deposit', 'voting', 'closed'] as const).map((status, index) => {
const config = statusConfig[status];
const Icon = config.icon;
const isActive = localStatus === status;
return (
<Button
key={status}
variant="ghost"
size="sm"
disabled={disabled || isChanging}
onClick={() => handleStatusChange(status)}
className={`
relative flex-1 h-10 px-3 rounded-lg transition-all duration-300 ease-out
${isActive
? `${config.activeColor} text-white shadow-lg transform scale-105`
: `${config.hoverColor} ${config.textColor} hover:text-white`
}
${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
${isChanging ? 'animate-pulse' : ''}
`}
>
<div className="flex items-center gap-2">
<Icon className={`w-4 h-4 transition-transform duration-300 ${isActive ? 'scale-110' : ''}`} />
<span className="text-sm font-medium">{config.label}</span>
</div>
{/* Indicateur de progression */}
{isActive && (
<div className="absolute inset-0 rounded-lg bg-gradient-to-r from-transparent via-white/20 to-transparent animate-pulse" />
)}
</Button>
);
})}
</div>
{/* Effet de brillance au survol */}
<div className="absolute inset-0 rounded-xl bg-gradient-to-r from-transparent via-white/10 to-transparent opacity-0 hover:opacity-100 transition-opacity duration-300 pointer-events-none" />
</div>
);
}

View File

@@ -3,6 +3,69 @@ import { Campaign, Proposition, Participant, Vote, ParticipantWithVoteStatus, Se
import { encryptionService } from './encryption'; import { encryptionService } from './encryption';
import { emailService } from './email'; 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}`;
}
// Fonction utilitaire pour gérer les erreurs Supabase
function handleSupabaseError(error: any, operation: string): never {
console.error(`Erreur Supabase lors de ${operation}:`, error);
// Extraire les détails de l'erreur
let errorMessage = `Erreur lors de ${operation}`;
if (error?.message) {
errorMessage = error.message;
} else if (error?.error_description) {
errorMessage = error.error_description;
} else if (error?.details) {
errorMessage = error.details;
} else if (typeof error === 'string') {
errorMessage = error;
}
// Ajouter des informations de débogage
const debugInfo = {
operation,
error,
timestamp: new Date().toISOString(),
userAgent: typeof window !== 'undefined' ? window.navigator.userAgent : 'server'
};
console.error('Informations de débogage:', debugInfo);
throw new Error(errorMessage);
}
// Services pour les campagnes // Services pour les campagnes
export const campaignService = { export const campaignService = {
async getAll(): Promise<Campaign[]> { async getAll(): Promise<Campaign[]> {
@@ -17,6 +80,27 @@ export const campaignService = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
async create(campaign: any): Promise<Campaign> { 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 const { data, error } = await supabase
.from('campaigns') .from('campaigns')
.insert(campaign) .insert(campaign)
@@ -29,6 +113,27 @@ export const campaignService = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
async update(id: string, updates: any): Promise<Campaign> { 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 const { data, error } = await supabase
.from('campaigns') .from('campaigns')
.update(updates) .update(updates)
@@ -77,6 +182,23 @@ export const campaignService = {
propositions: propositionsResult.count || 0, propositions: propositionsResult.count || 0,
participants: participantsResult.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 +282,27 @@ export const participantService = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
async create(participant: any): Promise<Participant> { 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 const { data, error } = await supabase
.from('participants') .from('participants')
.insert(participant) .insert(participant)
@@ -207,6 +350,23 @@ export const participantService = {
.eq('id', id); .eq('id', id);
if (error) throw error; 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;
} }
}; };
@@ -219,7 +379,7 @@ export const voteService = {
.eq('campaign_id', campaignId) .eq('campaign_id', campaignId)
.eq('participant_id', participantId); .eq('participant_id', participantId);
if (error) throw error; if (error) handleSupabaseError(error, 'récupération des votes par participant');
return data || []; return data || [];
}, },
@@ -229,7 +389,7 @@ export const voteService = {
.select('*') .select('*')
.eq('proposition_id', propositionId); .eq('proposition_id', propositionId);
if (error) throw error; if (error) handleSupabaseError(error, 'récupération des votes par proposition');
return data || []; return data || [];
}, },
@@ -241,7 +401,7 @@ export const voteService = {
.select() .select()
.single(); .single();
if (error) throw error; if (error) handleSupabaseError(error, 'création de vote');
return data; return data;
}, },
@@ -254,7 +414,7 @@ export const voteService = {
.select() .select()
.single(); .single();
if (error) throw error; if (error) handleSupabaseError(error, 'mise à jour de vote');
return data; return data;
}, },
@@ -265,7 +425,7 @@ export const voteService = {
.select() .select()
.single(); .single();
if (error) throw error; if (error) handleSupabaseError(error, 'upsert de vote');
return data; return data;
}, },
@@ -275,7 +435,7 @@ export const voteService = {
.delete() .delete()
.eq('id', id); .eq('id', id);
if (error) throw error; if (error) handleSupabaseError(error, 'suppression de vote');
}, },
async getByCampaign(campaignId: string): Promise<Vote[]> { async getByCampaign(campaignId: string): Promise<Vote[]> {
@@ -284,7 +444,7 @@ export const voteService = {
.select('*') .select('*')
.eq('campaign_id', campaignId); .eq('campaign_id', campaignId);
if (error) throw error; if (error) handleSupabaseError(error, 'récupération des votes par campagne');
return data || []; return data || [];
}, },
@@ -313,6 +473,22 @@ export const voteService = {
total_voted_amount: totalVotedAmount total_voted_amount: totalVotedAmount
}; };
}); });
},
// Méthode pour remplacer tous les votes d'un participant de manière atomique
async replaceVotes(
campaignId: string,
participantId: string,
votes: Array<{ proposition_id: string; amount: number }>
): Promise<void> {
// Utiliser une transaction pour garantir l'atomicité
const { error } = await supabase.rpc('replace_participant_votes', {
p_campaign_id: campaignId,
p_participant_id: participantId,
p_votes: votes
});
if (error) handleSupabaseError(error, 'remplacement des votes du participant');
} }
}; };

View File

@@ -3,4 +3,20 @@ import { createClient } from '@supabase/supabase-js';
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://placeholder.supabase.co'; const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://placeholder.supabase.co';
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || 'placeholder-key'; const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || 'placeholder-key';
export const supabase = createClient(supabaseUrl, supabaseAnonKey); export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true
},
realtime: {
params: {
eventsPerSecond: 10
}
},
global: {
headers: {
'X-Client-Info': 'mes-budgets-participatifs'
}
}
});

View File

@@ -7,6 +7,7 @@ export interface Campaign {
status: CampaignStatus; status: CampaignStatus;
budget_per_user: number; budget_per_user: number;
spending_tiers: string; // Montants séparés par des virgules spending_tiers: string; // Montants séparés par des virgules
slug?: string; // Slug unique pour les liens courts
created_at: string; created_at: string;
updated_at: string; updated_at: string;
} }
@@ -35,6 +36,7 @@ export interface Participant {
first_name: string; first_name: string;
last_name: string; last_name: string;
email: string; email: string;
short_id?: string; // Identifiant court unique pour les liens de vote
created_at: string; created_at: string;
} }