2020-12-23 11:19:30 +01:00
|
|
|
import csv
|
|
|
|
import io
|
2021-08-20 00:45:33 +02:00
|
|
|
import smtplib
|
2020-12-23 11:19:30 +01:00
|
|
|
|
2021-04-04 23:38:21 +02:00
|
|
|
import networkx as nx
|
2021-03-29 18:04:54 +02:00
|
|
|
import numpy as np
|
2021-04-04 23:38:21 +02:00
|
|
|
from networkx.algorithms.dag import ancestors, descendants
|
2021-03-29 18:04:54 +02:00
|
|
|
|
2021-05-29 12:05:47 +02:00
|
|
|
from django.contrib.auth import get_user_model
|
2020-12-24 00:41:29 +01:00
|
|
|
from django.contrib.auth.hashers import make_password
|
2020-12-23 16:28:38 +01:00
|
|
|
from django.core.exceptions import ValidationError
|
2021-08-20 00:45:33 +02:00
|
|
|
from django.core.mail import EmailMessage
|
2020-12-23 16:28:38 +01:00
|
|
|
from django.core.validators import validate_email
|
2021-03-29 20:35:34 +02:00
|
|
|
from django.template.loader import render_to_string
|
2021-04-11 19:27:47 +02:00
|
|
|
from django.urls import reverse
|
2020-12-23 16:28:38 +01:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
|
2021-04-26 17:54:07 +02:00
|
|
|
from shared.auth.utils import generate_password
|
|
|
|
|
2021-03-19 16:10:25 +01:00
|
|
|
# #############################################################################
|
|
|
|
# Classes pour différencier les différents types de questions
|
|
|
|
# #############################################################################
|
|
|
|
|
|
|
|
|
2021-03-19 14:25:13 +01:00
|
|
|
class CastFunctions:
|
|
|
|
"""Classe pour enregistrer les votes"""
|
|
|
|
|
|
|
|
def cast_select(user, vote_form):
|
2021-03-19 16:08:02 +01:00
|
|
|
"""On enregistre un vote classique"""
|
2021-03-19 14:25:13 +01:00
|
|
|
selected, n_selected = [], []
|
|
|
|
for v in vote_form:
|
|
|
|
if v.cleaned_data["selected"]:
|
|
|
|
selected.append(v.instance)
|
|
|
|
else:
|
|
|
|
n_selected.append(v.instance)
|
|
|
|
|
|
|
|
user.votes.add(*selected)
|
|
|
|
user.votes.remove(*n_selected)
|
|
|
|
|
2021-03-29 12:42:34 +02:00
|
|
|
def cast_rank(user, vote_form):
|
|
|
|
"""On enregistre un vote par classement"""
|
|
|
|
from .models import Rank, Vote
|
|
|
|
|
|
|
|
# On enregistre les votes pour pouvoir créér les classements
|
|
|
|
options = [v.instance for v in vote_form]
|
|
|
|
user.votes.add(*options)
|
|
|
|
|
|
|
|
votes = {
|
|
|
|
v.option: v for v in Vote.objects.filter(user=user, option__in=options)
|
|
|
|
}
|
|
|
|
ranks_create = []
|
|
|
|
ranks_update = []
|
|
|
|
|
|
|
|
for v in vote_form:
|
|
|
|
vote = votes[v.instance]
|
|
|
|
if hasattr(vote, "rank"):
|
|
|
|
vote.rank.rank = v.cleaned_data["rank"]
|
|
|
|
ranks_update.append(vote.rank)
|
|
|
|
else:
|
|
|
|
ranks_create.append(Rank(vote=vote, rank=v.cleaned_data["rank"]))
|
|
|
|
|
|
|
|
Rank.objects.bulk_update(ranks_update, ["rank"])
|
|
|
|
Rank.objects.bulk_create(ranks_create)
|
|
|
|
|
2021-03-19 14:25:13 +01:00
|
|
|
|
2021-03-19 16:08:02 +01:00
|
|
|
class TallyFunctions:
|
|
|
|
"""Classe pour gérer les dépouillements"""
|
|
|
|
|
|
|
|
def tally_select(question):
|
|
|
|
"""On dépouille un vote classique"""
|
|
|
|
from .models import Option
|
|
|
|
|
|
|
|
max_votes = 0
|
|
|
|
options = []
|
|
|
|
|
|
|
|
for o in question.options.prefetch_related("voters").all():
|
|
|
|
o.nb_votes = o.voters.count()
|
|
|
|
max_votes = max(max_votes, o.nb_votes)
|
|
|
|
options.append(o)
|
|
|
|
|
2021-04-04 23:38:21 +02:00
|
|
|
for o in options:
|
|
|
|
o.winner = o.nb_votes == max_votes
|
|
|
|
|
2021-03-19 16:08:02 +01:00
|
|
|
question.max_votes = max_votes
|
|
|
|
question.save()
|
|
|
|
|
2021-04-04 23:38:21 +02:00
|
|
|
Option.objects.bulk_update(options, ["nb_votes", "winner"])
|
2021-03-19 16:08:02 +01:00
|
|
|
|
2021-04-04 23:54:48 +02:00
|
|
|
def tally_schultze(question):
|
2021-03-29 18:04:54 +02:00
|
|
|
"""On dépouille un vote par classement et on crée la matrice des duels"""
|
2021-04-04 23:38:21 +02:00
|
|
|
from .models import Duel, Option, Rank
|
2021-03-29 18:04:54 +02:00
|
|
|
|
|
|
|
options = list(question.options.all())
|
2021-04-07 23:56:39 +02:00
|
|
|
nb_options = len(options)
|
2021-03-29 18:04:54 +02:00
|
|
|
ranks = Rank.objects.select_related("vote").filter(vote__option__in=options)
|
|
|
|
ranks_by_user = {}
|
|
|
|
|
|
|
|
for r in ranks:
|
|
|
|
user = r.vote.user
|
|
|
|
if user in ranks_by_user:
|
|
|
|
ranks_by_user[user].append(r)
|
|
|
|
else:
|
|
|
|
ranks_by_user[user] = [r]
|
|
|
|
|
|
|
|
ballots = []
|
|
|
|
|
|
|
|
# Pour chaque votant·e, on regarde son classement
|
|
|
|
for user in ranks_by_user:
|
|
|
|
votes = ranks_by_user[user]
|
2021-04-07 23:56:39 +02:00
|
|
|
ballot = np.zeros((nb_options, nb_options))
|
|
|
|
|
|
|
|
for i in range(nb_options):
|
|
|
|
for j in range(i):
|
|
|
|
ballot[i, j] = int(votes[i].rank < votes[j].rank)
|
|
|
|
ballot[j, i] = int(votes[j].rank < votes[i].rank)
|
|
|
|
|
|
|
|
ballots.append(ballot)
|
2021-03-29 18:04:54 +02:00
|
|
|
|
2021-04-04 23:38:21 +02:00
|
|
|
if ballots != []:
|
|
|
|
# On additionne les classements de tout le monde pour avoir la matrice
|
|
|
|
# des duels
|
2021-04-07 23:56:39 +02:00
|
|
|
duels = sum(ballots)
|
2021-04-04 23:38:21 +02:00
|
|
|
|
|
|
|
# Configuration du graphe
|
|
|
|
graph = nx.DiGraph()
|
|
|
|
|
|
|
|
graph.add_nodes_from(options)
|
|
|
|
|
|
|
|
cells = []
|
|
|
|
|
|
|
|
# On enregistre la matrice
|
2021-04-07 23:56:39 +02:00
|
|
|
for i in range(nb_options):
|
|
|
|
for j in range(nb_options):
|
|
|
|
if duels[i, j] > duels[j, i]:
|
|
|
|
graph.add_edge(
|
|
|
|
options[i], options[j], weight=(duels[i, j] - duels[j, i])
|
|
|
|
)
|
|
|
|
|
|
|
|
if duels[i, j] > 0:
|
2021-04-04 23:38:21 +02:00
|
|
|
cells.append(
|
|
|
|
Duel(
|
|
|
|
question=question,
|
2021-04-07 23:56:39 +02:00
|
|
|
winner=options[i],
|
|
|
|
loser=options[j],
|
|
|
|
amount=duels[i, j],
|
2021-04-04 23:38:21 +02:00
|
|
|
)
|
2021-03-29 18:04:54 +02:00
|
|
|
)
|
2021-04-04 23:38:21 +02:00
|
|
|
Duel.objects.bulk_create(cells)
|
|
|
|
|
2021-04-07 23:56:39 +02:00
|
|
|
# On utilise la méthode de Schwartz pour trouver les options gagnantes
|
2021-04-04 23:38:21 +02:00
|
|
|
while graph.edges():
|
|
|
|
losers = set() # Les options qui se font battre strictement
|
|
|
|
for n in graph.nodes():
|
|
|
|
losers |= set(descendants(graph, n)) - set(ancestors(graph, n))
|
|
|
|
|
|
|
|
if losers:
|
|
|
|
# On supprime les options perdantes
|
|
|
|
for n in losers:
|
|
|
|
graph.remove_node(n)
|
|
|
|
|
|
|
|
else:
|
|
|
|
# On n'a pas d'options perdantes, on supprime les arêtes de poids
|
|
|
|
# le plus faible
|
|
|
|
min_weight = min(nx.get_edge_attributes(graph, "weight").values())
|
|
|
|
min_edges = []
|
|
|
|
for (u, v) in graph.edges():
|
|
|
|
if graph[u][v]["weight"] == min_weight:
|
|
|
|
min_edges.append((u, v))
|
|
|
|
|
|
|
|
for (u, v) in min_edges:
|
|
|
|
graph.remove_edge(u, v)
|
|
|
|
|
|
|
|
# Les options gagnantes sont celles encore présentes dans le graphe
|
|
|
|
winners = graph.nodes()
|
|
|
|
for o in options:
|
|
|
|
o.winner = o in winners
|
|
|
|
|
|
|
|
Option.objects.bulk_update(options, ["winner"])
|
2021-03-29 18:04:54 +02:00
|
|
|
|
2021-03-19 16:08:02 +01:00
|
|
|
|
2021-03-19 22:24:27 +01:00
|
|
|
class ValidateFunctions:
|
|
|
|
"""Classe pour valider les formsets selon le type de question"""
|
|
|
|
|
|
|
|
def always_true(vote_form):
|
|
|
|
"""Retourne True pour les votes sans validation particulière"""
|
|
|
|
return True
|
|
|
|
|
|
|
|
def unique_selected(vote_form):
|
|
|
|
"""Vérifie qu'une seule option est choisie"""
|
|
|
|
nb_selected = 0
|
|
|
|
for v in vote_form:
|
|
|
|
nb_selected += v.cleaned_data["selected"]
|
|
|
|
|
|
|
|
if nb_selected == 0:
|
|
|
|
vote_form._non_form_errors.append(
|
|
|
|
ValidationError(_("Vous devez sélectionnner une option."))
|
|
|
|
)
|
|
|
|
return False
|
|
|
|
elif nb_selected > 1:
|
|
|
|
vote_form._non_form_errors.append(
|
|
|
|
ValidationError(_("Vous ne pouvez pas sélectionner plus d'une option."))
|
|
|
|
)
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2021-03-29 12:42:34 +02:00
|
|
|
def limit_ranks(vote_form):
|
|
|
|
"""Limite le classement au nombre d'options"""
|
|
|
|
nb_options = len(vote_form)
|
|
|
|
valid = True
|
|
|
|
|
|
|
|
for v in vote_form:
|
|
|
|
rank = v.cleaned_data["rank"]
|
|
|
|
if rank is None:
|
|
|
|
rank = nb_options
|
|
|
|
|
|
|
|
if rank > nb_options:
|
|
|
|
v.add_error(
|
|
|
|
"rank", _("Le classement maximal est {}.").format(nb_options)
|
|
|
|
)
|
|
|
|
valid = False
|
|
|
|
elif rank < 1:
|
|
|
|
v.add_error("rank", _("Le classement minimal est 1."))
|
|
|
|
valid = False
|
|
|
|
v.cleaned_data["rank"] = rank # On ajoute le défaut
|
|
|
|
|
|
|
|
return valid
|
|
|
|
|
2021-03-19 22:24:27 +01:00
|
|
|
|
2021-03-29 20:35:34 +02:00
|
|
|
class ResultsData:
|
|
|
|
"""Classe pour afficher des informations supplémentaires après la fin d'une élection"""
|
|
|
|
|
|
|
|
def select(question):
|
|
|
|
"""On renvoie l'explication des couleurs"""
|
|
|
|
return render_to_string("elections/results/select.html")
|
|
|
|
|
|
|
|
def rank(question):
|
2021-05-24 16:31:00 +02:00
|
|
|
"""On récupère la matrice des résultats et on l'affiche"""
|
|
|
|
duels = question.duels.all()
|
2021-03-29 20:35:34 +02:00
|
|
|
options = list(question.options.all())
|
|
|
|
n = len(options)
|
|
|
|
|
2021-06-28 21:33:07 +02:00
|
|
|
_matrix = np.full((n, n), {"value": 0}, dtype=dict)
|
|
|
|
matrix = np.empty((n, n), dtype=tuple)
|
2021-03-29 20:35:34 +02:00
|
|
|
|
|
|
|
for d in duels:
|
2021-04-07 14:47:36 +02:00
|
|
|
i, j = options.index(d.loser), options.index(d.winner)
|
2021-06-28 21:33:07 +02:00
|
|
|
_matrix[i, j] = {
|
|
|
|
"value": d.amount,
|
|
|
|
"winner": d.winner.get_abbr(j + 1),
|
|
|
|
"loser": d.loser.get_abbr(i + 1),
|
|
|
|
}
|
2021-04-16 17:27:42 +02:00
|
|
|
|
|
|
|
for i in range(n):
|
|
|
|
for j in range(n):
|
2021-06-28 21:33:07 +02:00
|
|
|
if _matrix[i, j]["value"] > _matrix[j, i]["value"]:
|
2021-04-16 17:27:42 +02:00
|
|
|
matrix[i, j] = (_matrix[i, j], "is-success")
|
2021-06-28 21:33:07 +02:00
|
|
|
elif _matrix[i, j]["value"] < _matrix[j, i]["value"]:
|
2021-04-16 17:27:42 +02:00
|
|
|
matrix[i, j] = (_matrix[i, j], "is-danger")
|
|
|
|
else:
|
|
|
|
matrix[i, j] = (_matrix[i, j], "")
|
2021-04-05 00:18:40 +02:00
|
|
|
|
2021-04-17 08:37:23 +02:00
|
|
|
matrix = zip(matrix.tolist(), options)
|
|
|
|
|
2021-03-29 20:35:34 +02:00
|
|
|
return render_to_string(
|
|
|
|
"elections/results/rank.html",
|
2021-05-24 16:31:00 +02:00
|
|
|
{"q": question, "matrix": matrix, "options": options},
|
2021-03-29 20:35:34 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-04-17 00:23:33 +02:00
|
|
|
class BallotsData:
|
|
|
|
"""Classe pour afficher les bulletins d'une question"""
|
|
|
|
|
|
|
|
def select(question):
|
2021-04-17 00:43:30 +02:00
|
|
|
"""Renvoie un tableau affichant les options sélectionnées pour chaque bulletin"""
|
2021-04-17 00:23:33 +02:00
|
|
|
from .models import Vote
|
|
|
|
|
2021-04-17 01:25:29 +02:00
|
|
|
votes = Vote.objects.filter(option__question=question).select_related("user")
|
2021-04-17 00:23:33 +02:00
|
|
|
|
|
|
|
options = list(question.options.all())
|
|
|
|
|
|
|
|
ballots = {}
|
|
|
|
for v in votes:
|
|
|
|
ballot = ballots.get(v.user, [False] * len(options))
|
|
|
|
ballot[options.index(v.option)] = True
|
|
|
|
|
|
|
|
ballots[v.user] = ballot
|
|
|
|
|
|
|
|
return render_to_string(
|
2021-07-10 19:56:45 +02:00
|
|
|
"elections/ballots/select.html",
|
|
|
|
{"options": options, "ballots": sorted(ballots.values(), reverse=True)},
|
2021-04-17 00:23:33 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
def rank(question):
|
2021-04-17 00:43:30 +02:00
|
|
|
"""Renvoie un tableau contenant les classements des options par bulletin"""
|
|
|
|
from .models import Rank
|
|
|
|
|
|
|
|
options = list(question.options.all())
|
2021-04-17 01:25:29 +02:00
|
|
|
ranks = Rank.objects.select_related("vote__user").filter(
|
|
|
|
vote__option__in=options
|
|
|
|
)
|
2021-04-17 00:43:30 +02:00
|
|
|
ranks_by_user = {}
|
|
|
|
|
|
|
|
for r in ranks:
|
|
|
|
user = r.vote.user
|
|
|
|
if user in ranks_by_user:
|
|
|
|
ranks_by_user[user].append(r.rank)
|
|
|
|
else:
|
|
|
|
ranks_by_user[user] = [r.rank]
|
|
|
|
|
|
|
|
return render_to_string(
|
|
|
|
"elections/ballots/rank.html",
|
2021-07-10 19:56:45 +02:00
|
|
|
{"options": options, "ballots": sorted(ranks_by_user.values())},
|
2021-04-17 00:43:30 +02:00
|
|
|
)
|
2021-04-17 00:23:33 +02:00
|
|
|
|
|
|
|
|
2021-03-19 16:10:25 +01:00
|
|
|
# #############################################################################
|
|
|
|
# Fonctions pour importer une liste de votant·e·s
|
|
|
|
# #############################################################################
|
|
|
|
|
|
|
|
|
2020-12-23 11:19:30 +01:00
|
|
|
def create_users(election, csv_file):
|
|
|
|
"""Crée les votant·e·s pour l'élection donnée, en remplissant les champs
|
|
|
|
`username`, `election` et `full_name`.
|
|
|
|
"""
|
2021-08-20 15:07:36 +02:00
|
|
|
User = get_user_model()
|
|
|
|
|
2020-12-23 17:08:43 +01:00
|
|
|
dialect = csv.Sniffer().sniff(csv_file.readline().decode("utf-8"))
|
2020-12-23 11:19:30 +01:00
|
|
|
csv_file.seek(0)
|
|
|
|
reader = csv.reader(io.StringIO(csv_file.read().decode("utf-8")), dialect)
|
2021-08-20 15:07:36 +02:00
|
|
|
|
|
|
|
users = [
|
|
|
|
User(
|
|
|
|
election=election,
|
|
|
|
username=f"{election.id}__{username}",
|
|
|
|
email=email,
|
|
|
|
full_name=full_name,
|
2021-10-04 10:02:16 +02:00
|
|
|
is_active=False,
|
2020-12-23 11:19:30 +01:00
|
|
|
)
|
2021-08-20 15:07:36 +02:00
|
|
|
for (username, full_name, email) in reader
|
|
|
|
]
|
|
|
|
|
|
|
|
User.objects.bulk_create(users)
|
2020-12-23 16:28:38 +01:00
|
|
|
|
|
|
|
|
|
|
|
def check_csv(csv_file):
|
|
|
|
"""Vérifie que le fichier donnant la liste de votant·e·s est bien formé"""
|
|
|
|
try:
|
2020-12-23 17:08:43 +01:00
|
|
|
dialect = csv.Sniffer().sniff(csv_file.readline().decode("utf-8"))
|
2020-12-23 16:28:38 +01:00
|
|
|
except csv.Error:
|
|
|
|
return [
|
|
|
|
_(
|
|
|
|
"Format invalide. Vérifiez que le fichier est bien formé (i.e. "
|
|
|
|
"chaque ligne de la forme 'login,nom,email')."
|
|
|
|
)
|
|
|
|
]
|
|
|
|
csv_file.seek(0)
|
|
|
|
reader = csv.reader(io.StringIO(csv_file.read().decode("utf-8")), dialect)
|
|
|
|
|
|
|
|
errors = []
|
2020-12-23 17:08:43 +01:00
|
|
|
users = {}
|
2020-12-23 16:28:38 +01:00
|
|
|
line_nb = 0
|
|
|
|
for line in reader:
|
|
|
|
line_nb += 1
|
|
|
|
if len(line) != 3:
|
|
|
|
errors.append(
|
|
|
|
_("La ligne {} n'a pas le bon nombre d'éléments.").format(line_nb)
|
|
|
|
)
|
|
|
|
else:
|
2020-12-23 17:08:43 +01:00
|
|
|
if line[0] == "":
|
2020-12-23 16:28:38 +01:00
|
|
|
errors.append(
|
2020-12-23 17:08:43 +01:00
|
|
|
_("Valeur manquante dans la ligne {} : 'login'.").format(line_nb)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
if line[0] in users:
|
|
|
|
errors.append(
|
|
|
|
_("Doublon dans les logins : lignes {} et {}.").format(
|
|
|
|
line_nb, users[line[0]]
|
|
|
|
)
|
2020-12-23 16:28:38 +01:00
|
|
|
)
|
2020-12-23 17:08:43 +01:00
|
|
|
else:
|
|
|
|
users[line[0]] = line_nb
|
|
|
|
if line[1] == "":
|
|
|
|
errors.append(
|
|
|
|
_("Valeur manquante dans la ligne {} : 'nom'.").format(line_nb)
|
2020-12-23 16:28:38 +01:00
|
|
|
)
|
|
|
|
try:
|
|
|
|
validate_email(line[2])
|
|
|
|
except ValidationError:
|
|
|
|
errors.append(
|
|
|
|
_("Adresse mail invalide à la ligne {} : '{}'.").format(
|
|
|
|
line_nb, line[2]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
return errors
|
|
|
|
|
|
|
|
|
2021-08-20 00:45:33 +02:00
|
|
|
def send_mail(election, subject, body, reply_to):
|
2020-12-23 16:28:38 +01:00
|
|
|
"""Envoie le mail d'annonce de l'élection avec identifiants et mot de passe
|
|
|
|
aux votant·e·s, le mdp est généré en même temps que le mail est envoyé.
|
|
|
|
"""
|
2021-05-29 12:05:47 +02:00
|
|
|
User = get_user_model()
|
2021-03-19 11:48:38 +01:00
|
|
|
|
2021-08-20 00:45:33 +02:00
|
|
|
# On n'envoie le mail qu'aux personnes qui n'en n'ont pas déjà reçu un
|
|
|
|
voters = list(election.registered_voters.exclude(has_valid_email=True))
|
2021-04-11 19:27:47 +02:00
|
|
|
e_url = reverse("election.view", args=[election.id])
|
2021-05-24 16:33:22 +02:00
|
|
|
url = f"https://vote.eleves.ens.fr{e_url}"
|
2020-12-24 00:41:29 +01:00
|
|
|
messages = []
|
|
|
|
for v in voters:
|
|
|
|
password = generate_password()
|
|
|
|
v.password = make_password(password)
|
|
|
|
messages.append(
|
2021-08-20 00:45:33 +02:00
|
|
|
(
|
|
|
|
EmailMessage(
|
|
|
|
subject=subject,
|
|
|
|
body=body.format(
|
|
|
|
full_name=v.full_name,
|
|
|
|
election_url=url,
|
|
|
|
username=v.base_username,
|
|
|
|
password=password,
|
|
|
|
),
|
|
|
|
to=[v.email],
|
|
|
|
reply_to=[reply_to],
|
2021-12-14 10:17:05 +01:00
|
|
|
# On modifie l'adresse de retour d'erreur
|
|
|
|
headers={"Return-Path": reply_to},
|
2020-12-24 00:41:29 +01:00
|
|
|
),
|
2021-08-20 00:45:33 +02:00
|
|
|
v,
|
2020-12-24 00:41:29 +01:00
|
|
|
)
|
|
|
|
)
|
2021-08-20 00:45:33 +02:00
|
|
|
|
|
|
|
for (m, v) in messages:
|
|
|
|
try:
|
|
|
|
m.send()
|
|
|
|
except smtplib.SMTPException:
|
|
|
|
v.has_valid_email = False
|
|
|
|
else:
|
|
|
|
v.has_valid_email = True
|
|
|
|
|
|
|
|
User.objects.bulk_update(voters, ["password", "has_valid_email"])
|