fix: Improve active elections endpoint with timezone buffer and debug endpoint

This commit is contained in:
Alexis Bruneteau 2025-11-07 02:55:39 +01:00
parent b8fa1a4b95
commit becdf3bdee
2 changed files with 69 additions and 29 deletions

View File

@ -11,18 +11,51 @@ from ..models import Voter
router = APIRouter(prefix="/api/elections", tags=["elections"]) router = APIRouter(prefix="/api/elections", tags=["elections"])
@router.get("/active", response_model=list[schemas.ElectionResponse]) @router.get("/debug/all")
def get_active_elections(db: Session = Depends(get_db)): def debug_all_elections(db: Session = Depends(get_db)):
"""Récupérer toutes les élections actives en cours (limité aux vraies élections actives)""" """DEBUG: Return all elections with dates for troubleshooting"""
from datetime import datetime from datetime import datetime
from .. import models from .. import models
now = datetime.utcnow() now = datetime.utcnow()
all_elections = db.query(models.Election).all()
return {
"current_time": now.isoformat(),
"elections": [
{
"id": e.id,
"name": e.name,
"is_active": e.is_active,
"start_date": e.start_date.isoformat() if e.start_date else None,
"end_date": e.end_date.isoformat() if e.end_date else None,
"should_be_active": (
e.start_date <= now <= e.end_date and e.is_active
if e.start_date and e.end_date
else False
),
}
for e in all_elections
],
}
@router.get("/active", response_model=list[schemas.ElectionResponse])
def get_active_elections(db: Session = Depends(get_db)):
"""Récupérer toutes les élections actives en cours"""
from datetime import datetime, timedelta
from .. import models
now = datetime.utcnow()
# Allow 1 hour buffer for timezone issues
start_buffer = now - timedelta(hours=1)
end_buffer = now + timedelta(hours=1)
active = db.query(models.Election).filter( active = db.query(models.Election).filter(
(models.Election.start_date <= now) & (models.Election.start_date <= end_buffer) &
(models.Election.end_date >= now) & (models.Election.end_date >= start_buffer) &
(models.Election.is_active == True) # Vérifier que is_active=1 (models.Election.is_active == True)
).order_by(models.Election.id.asc()).limit(10).all() # Limiter à 10 max ).order_by(models.Election.id.asc()).all()
return active return active

View File

@ -1,32 +1,39 @@
-- ================================================================ -- ================================================================
-- Create ONE active election for demo (current date/time) -- Ensure at least ONE active election exists for demo
-- ================================================================ -- ================================================================
-- Insert active election (now + 24 hours) -- Check if election 1 exists and update it to be active (from init.sql)
INSERT INTO elections (name, description, start_date, end_date, elgamal_p, elgamal_g, is_active, results_published) UPDATE elections
VALUES ( SET
'Election Présidentielle 2025 - Demo', is_active = TRUE,
'Démonstration du système de vote en ligne avec blockchain', start_date = DATE_SUB(NOW(), INTERVAL 1 HOUR),
NOW(), end_date = DATE_ADD(NOW(), INTERVAL 7 DAY)
DATE_ADD(NOW(), INTERVAL 24 HOUR), WHERE id = 1;
-- If no active elections exist, create one
INSERT IGNORE INTO elections (id, name, description, start_date, end_date, elgamal_p, elgamal_g, is_active, results_published)
SELECT
1,
'Election Présidentielle 2025',
'Vote pour la présidence',
DATE_SUB(NOW(), INTERVAL 1 HOUR),
DATE_ADD(NOW(), INTERVAL 7 DAY),
23, 23,
5, 5,
TRUE, TRUE,
FALSE FALSE
); WHERE NOT EXISTS (SELECT 1 FROM elections WHERE id = 1);
-- Get the election ID (should be 11 if 10 past elections exist) -- Ensure election 1 has candidates (from init.sql)
SET @election_id = LAST_INSERT_ID(); INSERT IGNORE INTO candidates (id, election_id, name, description, `order`)
-- Insert 3 candidates for the demo election
INSERT INTO candidates (election_id, name, description, `order`)
VALUES VALUES
(@election_id, 'Alice Dupont', 'Candidate A - Progressive', 1), (1, 1, 'Alice Dupont', 'Candidate pour le changement', 1),
(@election_id, 'Bob Martin', 'Candidate B - Centrist', 2), (2, 1, 'Bob Martin', 'Candidate pour la stabilité', 2),
(@election_id, 'Claire Laurent', 'Candidate C - Conservative', 3); (3, 1, 'Charlie Leclerc', 'Candidate pour l''innovation', 3),
(4, 1, 'Diana Fontaine', 'Candidate pour l''environnement', 4);
-- Confirmation -- Confirmation
SELECT CONCAT('Active election created: ID=', @election_id) as status; SELECT 'Active elections configured' as status;
SELECT COUNT(*) as total_elections FROM elections; SELECT COUNT(*) as total_elections FROM elections;
SELECT * FROM elections WHERE id = @election_id; SELECT COUNT(*) as active_elections FROM elections WHERE is_active = TRUE;
SELECT * FROM candidates WHERE election_id = @election_id; SELECT id, name, is_active, start_date, end_date FROM elections LIMIT 5;