Merge branch 'master' into Production

This commit is contained in:
Martin Pépin 2017-09-09 22:03:32 +02:00
commit 937a485704
174 changed files with 8315 additions and 3617 deletions

5
.gitignore vendored
View file

@ -9,3 +9,8 @@ venv/
/src
media/
*.log
*.sqlite3
# PyCharm
.idea
.cache

118
README.md
View file

@ -66,119 +66,65 @@ car par défaut Django n'écoute que sur l'adresse locale de la machine virtuell
or vous voudrez accéder à GestioCOF depuis votre machine physique. L'url à
entrer dans le navigateur est `localhost:8000`.
#### Serveur de développement type production
Sur la VM Vagrant, un serveur apache est configuré pour servir GestioCOF de
façon similaire à la version en production : on utilise
Juste histoire de jouer, pas indispensable pour développer :
La VM Vagrant héberge en plus un serveur nginx configuré pour servir GestioCOF
comme en production : on utilise
[Daphne](https://github.com/django/daphne/) et `python manage.py runworker`
derrière un reverse-proxy apache. Le tout est monitoré par
[supervisor](http://supervisord.org/).
derrière un reverse-proxy nginx.
Ce serveur se lance tout seul et est accessible en dehors de la VM à l'url
`localhost:8080`. Toutefois il ne se recharge pas tout seul lorsque le code
change, il faut relancer le worker avec `sudo supervisorctl restart worker` pour
visualiser la dernière version du code.
`localhost:8080/gestion/`. Toutefois il ne se recharge pas tout seul lorsque le
code change, il faut relancer le worker avec `sudo systemctl restart
worker.service` pour visualiser la dernière version du code.
### Installation manuelle
Si vous optez pour une installation manuelle plutôt que d'utiliser Vagrant, il
est fortement conseillé d'utiliser un environnement virtuel pour Python.
Vous pouvez opter pour une installation manuelle plutôt que d'utiliser Vagrant,
il est fortement conseillé d'utiliser un environnement virtuel pour Python.
Il vous faudra installer pip, les librairies de développement de python, un
client et un serveur MySQL ainsi qu'un serveur redis ; sous Debian et dérivées
(Ubuntu, ...) :
Il vous faudra installer pip, les librairies de développement de python ainsi
que sqlite3, un moteur de base de données léger et simple d'utilisation. Sous
Debian et dérivées (Ubuntu, ...) :
sudo apt-get install python-pip python-dev libmysqlclient-dev redis-server
sudo apt-get install python3-pip python3-dev sqlite3
Si vous décidez d'utiliser un environnement virtuel Python (virtualenv;
fortement conseillé), déplacez-vous dans le dossier où est installé GestioCOF
(le dossier où se trouve ce README), et créez-le maintenant :
virtualenv env -p $(which python3)
python3 -m venv venv
L'option `-p` sert à préciser l'exécutable python à utiliser. Vous devez choisir
python3, si c'est la version de python par défaut sur votre système, ceci n'est
pas nécessaire. Pour l'activer, il faut faire
Pour l'activer, il faut faire
. env/bin/activate
. venv/bin/activate
dans le même dossier.
Vous pouvez maintenant installer les dépendances Python depuis le fichier
`requirements-devel.txt` :
pip install -U pip
pip install -r requirements-devel.txt
Copiez le fichier `cof/settings_dev.py` dans `cof/settings.py`.
Pour terminer, copier le fichier `cof/settings/secret_example.py` vers
`cof/settings/secret.py`. Sous Linux ou Mac, préférez plutôt un lien symbolique
pour profiter de façon transparente des mises à jour du fichier:
#### Installation avec MySQL
ln -s secret_example.py cof/settings/secret.py
Il faut maintenant installer MySQL. Si vous n'avez pas déjà MySQL installé sur
votre serveur, il faut l'installer ; sous Debian et dérivées (Ubuntu, ...) :
sudo apt-get install mysql-server
Il vous demandera un mot de passe pour le compte d'administration MySQL,
notez-le quelque part (ou n'en mettez pas, le serveur n'est accessible que
localement par défaut). Si vous utilisez une autre distribution, consultez la
documentation de votre distribution pour savoir comment changer ce mot de passe
et démarrer le serveur MySQL (c'est automatique sous Ubuntu).
Vous devez alors créer un utilisateur local et une base `cof_gestion`, avec le
mot de passe de votre choix (remplacez `mot_de_passe`) :
mysql -uroot -e "CREATE DATABASE cof_gestion; GRANT ALL PRIVILEGES ON cof_gestion.* TO 'cof_gestion'@'localhost' IDENTIFIER BY 'mot_de_passe'"
Éditez maintenant le fichier `cof/settings.py` pour y intégrer ces changements ;
la définition de `DATABASES` doit ressembler à (à nouveau, remplacez
`mot_de_passe` de façon appropriée) :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cof_gestion',
'USER': 'cof_gestion',
'PASSWORD': 'mot_de_passe',
}
}
#### Installation avec SQLite
GestioCOF est installé avec MySQL sur la VM COF, et afin d'avoir un
environnement de développement aussi proche que possible de ce qui tourne en
vrai pour éviter les mauvaises surprises, il est conseillé d'utiliser MySQL sur
votre machine de développement également. Toutefois, GestioCOF devrait
fonctionner avec d'autres moteurs SQL, et certains préfèrent utiliser SQLite
pour sa légèreté et facilité d'installation.
Si vous décidez d'utiliser SQLite, il faut l'installer ; sous Debian et dérivées :
sudo apt-get install sqlite3
puis éditer le fichier `cof/settings.py` pour que la définition de `DATABASES`
ressemble à :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
#### Fin d'installation
Il ne vous reste plus qu'à initialiser les modèles de Django avec la commande suivante :
Il ne vous reste plus qu'à initialiser les modèles de Django et peupler la base
de donnée avec les données nécessaires au bon fonctionnement de GestioCOF + des
données bidons bien pratiques pour développer avec la commande suivante :
python manage.py migrate
Charger les mails indispensables au bon fonctionnement de GestioCOF :
python manage.py syncmails
Une base de donnée pré-remplie est disponible en lançant les commandes :
python manage.py loaddata gestion sites accounts groups articles
python manage.py loaddevdata
bash provisioning/prepare_django.sh
Vous êtes prêts à développer ! Lancer GestioCOF en faisant
@ -188,7 +134,7 @@ Vous êtes prêts à développer ! Lancer GestioCOF en faisant
Pour mettre à jour les paquets Python, utiliser la commande suivante :
pip install --upgrade -r requirements.txt -r requirements-devel.txt
pip install --upgrade -r requirements-devel.txt
Pour mettre à jour les modèles après une migration, il faut ensuite faire :
@ -197,6 +143,6 @@ Pour mettre à jour les modèles après une migration, il faut ensuite faire :
## Documentation utilisateur
Une brève documentation utilisateur pour se familiariser plus vite avec l'outil
est accessible sur le
[wiki](https://git.eleves.ens.fr/cof-geek/gestioCOF/wikis/home).
Une brève documentation utilisateur est accessible sur le
[wiki](https://git.eleves.ens.fr/cof-geek/gestioCOF/wikis/home) pour avoir une
idée de la façon dont le COF utilise GestioCOF.

View file

@ -0,0 +1 @@

View file

@ -13,32 +13,76 @@ from bda.models import Spectacle, Salle, Participant, ChoixSpectacle,\
Attribution, Tirage, Quote, CategorieSpectacle, SpectacleRevente
class ReadOnlyMixin(object):
readonly_fields_update = ()
def get_readonly_fields(self, request, obj=None):
readonly_fields = super().get_readonly_fields(request, obj)
if obj is None:
return readonly_fields
else:
return readonly_fields + self.readonly_fields_update
class ChoixSpectacleInline(admin.TabularInline):
model = ChoixSpectacle
sortable_field_name = "priority"
class AttributionTabularAdminForm(forms.ModelForm):
listing = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
spectacles = Spectacle.objects.select_related('location')
if self.listing is not None:
spectacles = spectacles.filter(listing=self.listing)
self.fields['spectacle'].queryset = spectacles
class WithoutListingAttributionTabularAdminForm(AttributionTabularAdminForm):
listing = False
class WithListingAttributionTabularAdminForm(AttributionTabularAdminForm):
listing = True
class AttributionInline(admin.TabularInline):
model = Attribution
extra = 0
listing = None
def get_queryset(self, request):
qs = super(AttributionInline, self).get_queryset(request)
return qs.filter(spectacle__listing=False)
qs = super().get_queryset(request)
if self.listing is not None:
qs.filter(spectacle__listing=self.listing)
return qs
class AttributionInlineListing(admin.TabularInline):
model = Attribution
class WithListingAttributionInline(AttributionInline):
form = WithListingAttributionTabularAdminForm
listing = True
class WithoutListingAttributionInline(AttributionInline):
exclude = ('given', )
extra = 0
def get_queryset(self, request):
qs = super(AttributionInlineListing, self).get_queryset(request)
return qs.filter(spectacle__listing=True)
form = WithoutListingAttributionTabularAdminForm
listing = False
class ParticipantAdmin(admin.ModelAdmin):
inlines = [AttributionInline, AttributionInlineListing]
class ParticipantAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['choicesrevente'].queryset = (
Spectacle.objects
.select_related('location')
)
class ParticipantAdmin(ReadOnlyMixin, admin.ModelAdmin):
inlines = [WithListingAttributionInline, WithoutListingAttributionInline]
def get_queryset(self, request):
return Participant.objects.annotate(nb_places=Count('attributions'),
@ -65,6 +109,8 @@ class ParticipantAdmin(admin.ModelAdmin):
actions_on_bottom = True
list_per_page = 400
readonly_fields = ("total",)
readonly_fields_update = ('user', 'tirage')
form = ParticipantAdminForm
def send_attribs(self, request, queryset):
datatuple = []
@ -94,6 +140,20 @@ class ParticipantAdmin(admin.ModelAdmin):
class AttributionAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if 'spectacle' in self.fields:
self.fields['spectacle'].queryset = (
Spectacle.objects
.select_related('location')
)
if 'participant' in self.fields:
self.fields['participant'].queryset = (
Participant.objects
.select_related('user', 'tirage')
)
def clean(self):
cleaned_data = super(AttributionAdminForm, self).clean()
participant = cleaned_data.get("participant")
@ -106,7 +166,7 @@ class AttributionAdminForm(forms.ModelForm):
return cleaned_data
class AttributionAdmin(admin.ModelAdmin):
class AttributionAdmin(ReadOnlyMixin, admin.ModelAdmin):
def paid(self, obj):
return obj.participant.paid
paid.short_description = 'A payé'
@ -116,6 +176,7 @@ class AttributionAdmin(admin.ModelAdmin):
'participant__user__first_name',
'participant__user__last_name')
form = AttributionAdminForm
readonly_fields_update = ('spectacle', 'participant')
class ChoixSpectacleAdmin(admin.ModelAdmin):
@ -160,6 +221,24 @@ class SalleAdmin(admin.ModelAdmin):
search_fields = ('name', 'address')
class SpectacleReventeAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['answered_mail'].queryset = (
Participant.objects
.select_related('user', 'tirage')
)
self.fields['seller'].queryset = (
Participant.objects
.select_related('user', 'tirage')
)
self.fields['soldTo'].queryset = (
Participant.objects
.select_related('user', 'tirage')
)
class SpectacleReventeAdmin(admin.ModelAdmin):
"""
Administration des reventes de spectacles
@ -182,6 +261,7 @@ class SpectacleReventeAdmin(admin.ModelAdmin):
actions = ['transfer', 'reinit']
actions_on_bottom = True
form = SpectacleReventeAdminForm
def transfer(self, request, queryset):
"""

View file

@ -22,8 +22,7 @@ class Algorithm(object):
show.requests
- on crée des tables de demandes pour chaque personne, afin de
pouvoir modifier les rankings"""
self.max_group = \
2 * choices.aggregate(Max('priority'))['priority__max']
self.max_group = 2*max(choice.priority for choice in choices)
self.shows = []
showdict = {}
for show in shows:

View file

@ -1,35 +1,40 @@
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django import forms
from django.forms.models import BaseInlineFormSet
from django.utils import timezone
from bda.models import Attribution, Spectacle
class BaseBdaFormSet(BaseInlineFormSet):
def clean(self):
"""Checks that no two articles have the same title."""
super(BaseBdaFormSet, self).clean()
if any(self.errors):
# Don't bother validating the formset unless each form is valid on
# its own
return
spectacles = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
if not form.cleaned_data:
continue
spectacle = form.cleaned_data['spectacle']
delete = form.cleaned_data['DELETE']
if not delete and spectacle in spectacles:
raise forms.ValidationError(
"Vous ne pouvez pas vous inscrire deux fois pour le "
"même spectacle.")
spectacles.append(spectacle)
class InscriptionInlineFormSet(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self.instance is a Participant object
tirage = self.instance.tirage
# set once for all "spectacle" field choices
# - restrict choices to the spectacles of this tirage
# - force_choices avoid many db requests
spectacles = tirage.spectacle_set.select_related('location')
choices = [(sp.pk, str(sp)) for sp in spectacles]
self.force_choices('spectacle', choices)
def force_choices(self, name, choices):
"""Set choices of a field.
As ModelChoiceIterator (default use to get choices of a
ModelChoiceField), it appends an empty selection if requested.
"""
for form in self.forms:
field = form.fields[name]
if field.empty_label is not None:
field.choices = [('', field.empty_label)] + choices
else:
field.choices = choices
class TokenForm(forms.Form):
@ -38,7 +43,7 @@ class TokenForm(forms.Form):
class AttributionModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
return "%s" % obj.spectacle
return "%s" % str(obj.spectacle)
class ResellForm(forms.Form):
@ -50,9 +55,13 @@ class ResellForm(forms.Form):
def __init__(self, participant, *args, **kwargs):
super(ResellForm, self).__init__(*args, **kwargs)
self.fields['attributions'].queryset = participant.attribution_set\
.filter(spectacle__date__gte=timezone.now())\
self.fields['attributions'].queryset = (
participant.attribution_set
.filter(spectacle__date__gte=timezone.now())
.exclude(revente__seller=participant)
.select_related('spectacle', 'spectacle__location',
'participant__user')
)
class AnnulForm(forms.Form):
@ -64,11 +73,15 @@ class AnnulForm(forms.Form):
def __init__(self, participant, *args, **kwargs):
super(AnnulForm, self).__init__(*args, **kwargs)
self.fields['attributions'].queryset = participant.attribution_set\
self.fields['attributions'].queryset = (
participant.attribution_set
.filter(spectacle__date__gte=timezone.now(),
revente__isnull=False,
revente__notif_sent=False,
revente__soldTo__isnull=True)
.select_related('spectacle', 'spectacle__location',
'participant__user')
)
class InscriptionReventeForm(forms.Form):
@ -79,8 +92,11 @@ class InscriptionReventeForm(forms.Form):
def __init__(self, tirage, *args, **kwargs):
super(InscriptionReventeForm, self).__init__(*args, **kwargs)
self.fields['spectacles'].queryset = tirage.spectacle_set.filter(
date__gte=timezone.now())
self.fields['spectacles'].queryset = (
tirage.spectacle_set
.select_related('location')
.filter(date__gte=timezone.now())
)
class SoldForm(forms.Form):
@ -93,7 +109,9 @@ class SoldForm(forms.Form):
super(SoldForm, self).__init__(*args, **kwargs)
self.fields['attributions'].queryset = (
participant.attribution_set
.filter(revente__isnull=False,
revente__soldTo__isnull=False)
.exclude(revente__soldTo=participant)
.filter(revente__isnull=False,
revente__soldTo__isnull=False)
.exclude(revente__soldTo=participant)
.select_related('spectacle', 'spectacle__location',
'participant__user')
)

View file

@ -7,18 +7,30 @@ from custommail.shortcuts import send_mass_custom_mail
from django.contrib.sites.models import Site
from django.db import models
from django.db.models import Count
from django.contrib.auth.models import User
from django.conf import settings
from django.utils import timezone, formats
def get_generic_user():
generic, _ = User.objects.get_or_create(
username="bda_generic",
defaults={"email": "bda@ens.fr", "first_name": "Bureau des arts"}
)
return generic
class Tirage(models.Model):
title = models.CharField("Titre", max_length=300)
ouverture = models.DateTimeField("Date et heure d'ouverture du tirage")
fermeture = models.DateTimeField("Date et heure de fermerture du tirage")
tokens = models.TextField("Graine(s) du tirage", blank=True)
active = models.BooleanField("Tirage actif", default=False)
appear_catalogue = models.BooleanField("Tirage à afficher dans le catalogue", default=False)
appear_catalogue = models.BooleanField(
"Tirage à afficher dans le catalogue",
default=False
)
enable_do_tirage = models.BooleanField("Le tirage peut être lancé",
default=False)
@ -93,32 +105,29 @@ class Spectacle(models.Model):
Envoie un mail de rappel à toutes les personnes qui ont une place pour
ce spectacle.
"""
# On récupère la liste des participants
members = {}
for attr in Attribution.objects.filter(spectacle=self).all():
member = attr.participant.user
if member.id in members:
members[member.id][1] = 2
else:
members[member.id] = [member, 1]
# FIXME : faire quelque chose de ça, un utilisateur bda_generic ?
# # Pour le BdA
# members[0] = ['BdA', 1, 'bda@ens.fr']
# members[-1] = ['BdA', 2, 'bda@ens.fr']
# On récupère la liste des participants + le BdA
members = list(
User.objects
.filter(participant__attributions=self)
.annotate(nb_attr=Count("id")).order_by()
)
bda_generic = get_generic_user()
bda_generic.nb_attr = 1
members.append(bda_generic)
# On écrit un mail personnalisé à chaque participant
datatuple = [(
'bda-rappel',
{'member': member[0], 'nb_attr': member[1], 'show': self},
{'member': member, "nb_attr": member.nb_attr, 'show': self},
settings.MAIL_DATA['rappels']['FROM'],
[member[0].email])
for member in members.values()
[member.email])
for member in members
]
send_mass_custom_mail(datatuple)
# On enregistre le fait que l'envoi a bien eu lieu
self.rappel_sent = timezone.now()
self.save()
# On renvoie la liste des destinataires
return members.values()
return members
@property
def is_past(self):

View file

@ -3,41 +3,46 @@
{% block realcontent %}
<h2>Mails de rappels</h2>
{% if sent %}
<h3>Les mails de rappel pour le spectacle {{ show.title }} ont bien été envoyés aux personnes suivantes</h3>
<ul>
{% for member in members %}
<li>{{ member.get_full_name }} ({{ member.email }})</li>
{% endfor %}
</ul>
<h3>Les mails de rappel pour le spectacle {{ show.title }} ont bien été envoyés aux personnes suivantes</h3>
<ul>
{% for member in members %}
<li>{{ member.get_full_name }} ({{ member.email }})</li>
{% endfor %}
</ul>
{% else %}
<h3>Voulez vous envoyer les mails de rappel pour le spectacle
{{ show.title }}&nbsp;?</h3>
{% if show.rappel_sent %}
<p class="error">Attention, les mails ont déjà été envoyés le
{{ show.rappel_sent }}</p>
{% endif %}
<h3>Voulez vous envoyer les mails de rappel pour le spectacle {{ show.title }}&nbsp;?</h3>
{% endif %}
{% if not sent %}
<form action="" method="post">
{% csrf_token %}
<div class="pull-right">
<input class="btn btn-primary" type="submit" value="Envoyer" />
</div>
</form>
{% endif %}
<div class="empty-form">
{% if not sent %}
<form action="" method="post">
{% csrf_token %}
<div class="pull-right">
<input class="btn btn-primary" type="submit" value="Envoyer" />
</div>
</form>
{% endif %}
</div>
<hr \>
<p>
<em>Note :</em> le template de ce mail peut être modifié à
<a href="{% url 'admin:custommail_custommail_change' custommail.pk %}">cette adresse</a>
</p>
<hr \>
<br/>
<hr/>
<h3>Forme des mails</h3>
<h4>Une seule place</h4>
{% for part in exemple_mail_1place %}
<pre>{{ part }}</pre>
{% endfor %}
{% for part in exemple_mail_1place %}
<pre>{{ part }}</pre>
{% endfor %}
<h4>Deux places</h4>
{% for part in exemple_mail_2places %}
<pre>{{ part }}</pre>
<pre>{{ part }}</pre>
{% endfor %}
{% endblock %}

View file

@ -36,17 +36,26 @@
</tbody>
</table>
<h3><a href="{% url "admin:bda_attribution_add" %}?spectacle={{spectacle.id}}"><span class="glyphicon glyphicon-plus-sign"></span> Ajouter une attribution</a></h3>
<br>
<button class="btn btn-default" type="button" onclick="toggle('export-mails')">Afficher/Cacher mails participants</button>
<pre id="export-mails" style="display:none">
{%for participant in participants %}{{participant.email}}, {%endfor%}
</pre>
<br>
<button class="btn btn-default" type="button" onclick="toggle('export-salle')">Afficher/Cacher liste noms</button>
<pre id="export-salle" style="display:none">
<div>
<div>
<button class="btn btn-default" type="button" onclick="toggle('export-mails')">Afficher/Cacher mails participants</button>
<pre id="export-mails" style="display:none">{% spaceless %}
{% for participant in participants %}{{ participant.email }}, {% endfor %}
{% endspaceless %}</pre>
</div>
<div>
<button class="btn btn-default" type="button" onclick="toggle('export-salle')">Afficher/Cacher liste noms</button>
<pre id="export-salle" style="display:none">{% spaceless %}
{% for participant in participants %}{{participant.name}} : {{participant.nb_places}} places
{% endfor %}
</pre>
{% endspaceless %}</pre>
</div>
<div>
<a href="{% url 'bda-rappels' spectacle.id %}">Page d'envoi manuel des mails de rappel</a>
</div>
<script type="text/javascript"
src="{% static "js/joequery-Stupid-Table-Plugin/stupidtable.js" %}"></script>
<script>

View file

@ -4,6 +4,8 @@
{% block realcontent %}
<h2>Revente de place</h2>
{% with resell_attributions=resellform.attributions annul_attributions=annulform.attributions sold_attributions=soldform.attributions %}
{% if resellform.attributions %}
<h3>Places non revendues</h3>
<form class="form-horizontal" action="" method="post">
@ -15,14 +17,14 @@
</form>
{% endif %}
<br>
{% if annulform.attributions or overdue %}
{% if annul_attributions or overdue %}
<h3>Places en cours de revente</h3>
<form action="" method="post">
{% csrf_token %}
<div class='form-group'>
<div class='multiple-checkbox'>
<ul>
{% for attrib in annulform.attributions %}
{% for attrib in annul_attributions %}
<li>{{attrib.tag}} {{attrib.choice_label}}</li>
{% endfor %}
{% for attrib in overdue %}
@ -31,13 +33,13 @@
{{attrib.spectacle}}
</li>
{% endfor %}
{% if annulform.attributions %}
{% if annul_attributions %}
<input type="submit" class="btn btn-primary" name="annul" value="Annuler les reventes sélectionnées">
{% endif %}
</form>
{% endif %}
<br>
{% if soldform.attributions %}
{% if sold_attributions %}
<h3>Places revendues</h3>
<form action="" method="post">
{% csrf_token %}
@ -46,8 +48,9 @@
<button type="submit" class="btn btn-primary" name="reinit">Réinitialiser</button>
</form>
{% endif %}
{% if not resellform.attributions and not soldform.attributions and not overdue and not annulform.attributions %}
{% if not resell_attributions and not annul_attributions and not overdue and not sold_attributions %}
<p>Plus de reventes possibles !</p>
{% endif %}
{% endwith %}
{% endblock %}

View file

@ -1,22 +1,105 @@
# -*- coding: utf-8 -*-
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
import json
Replace this with more appropriate tests for your application.
"""
from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.utils import timezone
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .models import Tirage, Spectacle, Salle, CategorieSpectacle
from django.test import TestCase
class TestBdAViews(TestCase):
def setUp(self):
self.tirage = Tirage.objects.create(
title="Test tirage",
appear_catalogue=True,
ouverture=timezone.now(),
fermeture=timezone.now(),
)
self.category = CategorieSpectacle.objects.create(name="Category")
self.location = Salle.objects.create(name="here")
Spectacle.objects.bulk_create([
Spectacle(
title="foo", date=timezone.now(), location=self.location,
price=0, slots=42, tirage=self.tirage, listing=False,
category=self.category
),
Spectacle(
title="bar", date=timezone.now(), location=self.location,
price=1, slots=142, tirage=self.tirage, listing=False,
category=self.category
),
Spectacle(
title="baz", date=timezone.now(), location=self.location,
price=2, slots=242, tirage=self.tirage, listing=False,
category=self.category
),
])
self.bda_user = User.objects.create_user(
username="bda_user", password="bda4ever"
)
self.bda_user.profile.is_cof = True
self.bda_user.profile.is_buro = True
self.bda_user.profile.save()
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
def bda_participants(self):
"""The BdA participants views can be queried"""
client = Client()
show = self.tirage.spectacle_set.first()
client.login(self.bda_user.username, "bda4ever")
tirage_resp = client.get("/bda/spectacles/{}".format(self.tirage.id))
show_resp = client.get(
"/bda/spectacles/{}/{}".format(self.tirage.id, show.id)
)
reminder_url = "/bda/mails-rappel/{}".format(show.id)
reminder_get_resp = client.get(reminder_url)
reminder_post_resp = client.post(reminder_url)
self.assertEqual(200, tirage_resp.status_code)
self.assertEqual(200, show_resp.status_code)
self.assertEqual(200, reminder_get_resp.status_code)
self.assertEqual(200, reminder_post_resp.status_code)
def test_catalogue(self):
"""Test the catalogue JSON API"""
client = Client()
# The `list` hook
resp = client.get("/bda/catalogue/list")
self.assertJSONEqual(
resp.content.decode("utf-8"),
[{"id": self.tirage.id, "title": self.tirage.title}]
)
# The `details` hook
resp = client.get(
"/bda/catalogue/details?id={}".format(self.tirage.id)
)
self.assertJSONEqual(
resp.content.decode("utf-8"),
{
"categories": [{
"id": self.category.id,
"name": self.category.name
}],
"locations": [{
"id": self.location.id,
"name": self.location.name
}],
}
)
# The `descriptions` hook
resp = client.get(
"/bda/catalogue/descriptions?id={}".format(self.tirage.id)
)
raw = resp.content.decode("utf-8")
try:
results = json.loads(raw)
except ValueError:
self.fail("Not valid JSON: {}".format(raw))
self.assertEqual(len(results), 3)
self.assertEqual(
{(s["title"], s["price"], s["slots"]) for s in results},
{("foo", 0, 42), ("bar", 1, 142), ("baz", 2, 242)}
)

View file

@ -44,7 +44,10 @@ urlpatterns = [
url(r'^revente-immediat/(?P<tirage_id>\d+)$',
views.revente_shotgun,
name="bda-shotgun"),
url(r'^mails-rappel/(?P<spectacle_id>\d+)$', views.send_rappel),
url(r'^mails-rappel/(?P<spectacle_id>\d+)$',
views.send_rappel,
name="bda-rappels"
),
url(r'^descriptions/(?P<tirage_id>\d+)$', views.descriptions_spectacles,
name='bda-descriptions'),
url(r'^catalogue/(?P<request_type>[a-z]+)$', views.catalogue,

View file

@ -1,19 +1,19 @@
# -*- coding: utf-8 -*-
from collections import defaultdict
import random
import hashlib
import time
import json
from datetime import timedelta
from custommail.shortcuts import (
send_mass_custom_mail, send_custom_mail, render_custom_mail
)
from custommail.shortcuts import send_mass_custom_mail, send_custom_mail
from custommail.models import CustomMail
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db import models, transaction
from django.db import transaction
from django.core import serializers
from django.db.models import Count, Q, Sum
from django.db.models import Count, Q, Prefetch
from django.forms.models import inlineformset_factory
from django.http import (
HttpResponseBadRequest, HttpResponseRedirect, JsonResponse
@ -22,16 +22,15 @@ from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone, formats
from django.views.generic.list import ListView
from django.core.exceptions import ObjectDoesNotExist
from gestioncof.decorators import cof_required, buro_required
from bda.models import (
Spectacle, Participant, ChoixSpectacle, Attribution, Tirage,
SpectacleRevente, Salle, Quote, CategorieSpectacle
SpectacleRevente, Salle, CategorieSpectacle
)
from bda.algorithm import Algorithm
from bda.forms import (
BaseBdaFormSet, TokenForm, ResellForm, AnnulForm, InscriptionReventeForm,
SoldForm
TokenForm, ResellForm, AnnulForm, InscriptionReventeForm, SoldForm,
InscriptionInlineFormSet,
)
@ -45,39 +44,44 @@ def etat_places(request, tirage_id):
Et le total de toutes les demandes
"""
tirage = get_object_or_404(Tirage, id=tirage_id)
spectacles1 = ChoixSpectacle.objects \
.filter(spectacle__tirage=tirage) \
.filter(double_choice="1") \
.all() \
.values('spectacle', 'spectacle__title') \
.annotate(total=models.Count('spectacle'))
spectacles2 = ChoixSpectacle.objects \
.filter(spectacle__tirage=tirage) \
.exclude(double_choice="1") \
.all() \
.values('spectacle', 'spectacle__title') \
.annotate(total=models.Count('spectacle'))
spectacles = tirage.spectacle_set.all()
spectacles_dict = {}
total = 0
spectacles = tirage.spectacle_set.select_related('location')
spectacles_dict = {} # index of spectacle by id
for spectacle in spectacles:
spectacle.total = 0
spectacle.ratio = 0.0
spectacle.total = 0 # init total requests
spectacles_dict[spectacle.id] = spectacle
for spectacle in spectacles1:
spectacles_dict[spectacle["spectacle"]].total += spectacle["total"]
spectacles_dict[spectacle["spectacle"]].ratio = \
spectacles_dict[spectacle["spectacle"]].total / \
spectacles_dict[spectacle["spectacle"]].slots
total += spectacle["total"]
for spectacle in spectacles2:
spectacles_dict[spectacle["spectacle"]].total += 2*spectacle["total"]
spectacles_dict[spectacle["spectacle"]].ratio = \
spectacles_dict[spectacle["spectacle"]].total / \
spectacles_dict[spectacle["spectacle"]].slots
total += 2*spectacle["total"]
choices = (
ChoixSpectacle.objects
.filter(spectacle__in=spectacles)
.values('spectacle')
.annotate(total=Count('spectacle'))
)
# choices *by spectacles* whose only 1 place is requested
choices1 = choices.filter(double_choice="1")
# choices *by spectacles* whose 2 places is requested
choices2 = choices.exclude(double_choice="1")
for spectacle in choices1:
pk = spectacle['spectacle']
spectacles_dict[pk].total += spectacle['total']
for spectacle in choices2:
pk = spectacle['spectacle']
spectacles_dict[pk].total += 2*spectacle['total']
# here, each spectacle.total contains the number of requests
slots = 0 # proposed slots
total = 0 # requests
for spectacle in spectacles:
slots += spectacle.slots
total += spectacle.total
spectacle.ratio = spectacle.total / spectacle.slots
context = {
"proposed": tirage.spectacle_set.aggregate(Sum('slots'))['slots__sum'],
"proposed": slots,
"spectacles": spectacles,
"total": total,
'tirage': tirage
@ -95,11 +99,16 @@ def _hash_queryset(queryset):
@cof_required
def places(request, tirage_id):
tirage = get_object_or_404(Tirage, id=tirage_id)
participant, created = Participant.objects.get_or_create(
user=request.user, tirage=tirage)
places = participant.attribution_set.order_by(
"spectacle__date", "spectacle").all()
total = sum([place.spectacle.price for place in places])
participant, _ = (
Participant.objects
.get_or_create(user=request.user, tirage=tirage)
)
places = (
participant.attribution_set
.order_by("spectacle__date", "spectacle")
.select_related("spectacle", "spectacle__location")
)
total = sum(place.spectacle.price for place in places)
filtered_places = []
places_dict = {}
spectacles = []
@ -147,35 +156,31 @@ def inscription(request, tirage_id):
messages.error(request, "Le tirage n'est pas encore ouvert : "
"ouverture le {:s}".format(opening))
return render(request, 'bda/resume-inscription-tirage.html', {})
participant, _ = (
Participant.objects.select_related('tirage')
.get_or_create(user=request.user, tirage=tirage)
)
if timezone.now() > tirage.fermeture:
# Le tirage est fermé.
participant, created = Participant.objects.get_or_create(
user=request.user, tirage=tirage)
choices = participant.choixspectacle_set.order_by("priority").all()
choices = participant.choixspectacle_set.order_by("priority")
messages.error(request,
" C'est fini : tirage au sort dans la journée !")
return render(request, "bda/resume-inscription-tirage.html",
{"choices": choices})
def formfield_callback(f, **kwargs):
"""
Fonction utilisée par inlineformset_factory ci dessous.
Restreint les spectacles proposés aux spectacles du bo tirage.
"""
if f.name == "spectacle":
kwargs['queryset'] = tirage.spectacle_set
return f.formfield(**kwargs)
BdaFormSet = inlineformset_factory(
Participant,
ChoixSpectacle,
fields=("spectacle", "double_choice", "priority"),
formset=BaseBdaFormSet,
formfield_callback=formfield_callback)
participant, created = Participant.objects.get_or_create(
user=request.user, tirage=tirage)
formset=InscriptionInlineFormSet,
)
success = False
stateerror = False
if request.method == "POST":
# use *this* queryset
dbstate = _hash_queryset(participant.choixspectacle_set.all())
if "dbstate" in request.POST and dbstate != request.POST["dbstate"]:
stateerror = True
@ -188,9 +193,14 @@ def inscription(request, tirage_id):
formset = BdaFormSet(instance=participant)
else:
formset = BdaFormSet(instance=participant)
# use *this* queryset
dbstate = _hash_queryset(participant.choixspectacle_set.all())
total_price = 0
for choice in participant.choixspectacle_set.all():
choices = (
participant.choixspectacle_set
.select_related('spectacle')
)
for choice in choices:
total_price += choice.spectacle.price
if choice.double:
total_price += choice.spectacle.price
@ -219,9 +229,9 @@ def do_tirage(tirage_elt, token):
# Initialisation du dictionnaire data qui va contenir les résultats
start = time.time()
data = {
'shows': tirage_elt.spectacle_set.select_related().all(),
'shows': tirage_elt.spectacle_set.select_related('location'),
'token': token,
'members': tirage_elt.participant_set.all(),
'members': tirage_elt.participant_set.select_related('user'),
'total_slots': 0,
'total_losers': 0,
'total_sold': 0,
@ -234,7 +244,7 @@ def do_tirage(tirage_elt, token):
ChoixSpectacle.objects
.filter(spectacle__tirage=tirage_elt)
.order_by('participant', 'priority')
.select_related().all()
.select_related('participant', 'participant__user', 'spectacle')
)
results = Algorithm(data['shows'], data['members'], choices)(token)
@ -291,10 +301,31 @@ def do_tirage(tirage_elt, token):
])
# On inscrit à BdA-Revente ceux qui n'ont pas eu les places voulues
for (show, _, losers) in results:
for (loser, _, _, _) in losers:
loser.choicesrevente.add(show)
loser.save()
ChoixRevente = Participant.choicesrevente.through
# Suppression des reventes demandées/enregistrées
# (si le tirage est relancé)
(
ChoixRevente.objects
.filter(spectacle__tirage=tirage_elt)
.delete()
)
(
SpectacleRevente.objects
.filter(attribution__spectacle__tirage=tirage_elt)
.delete()
)
lost_by = defaultdict(set)
for show, _, losers in results:
for loser, _, _, _ in losers:
lost_by[loser].add(show)
ChoixRevente.objects.bulk_create(
ChoixRevente(participant=member, spectacle=show)
for member, shows in lost_by.items()
for show in shows
)
data["duration"] = time.time() - start
data["results"] = results
@ -459,7 +490,6 @@ def list_revente(request, tirage_id):
)
if min_resell is not None:
min_resell.answered_mail.add(participant)
min_resell.save()
inscrit_revente.append(spectacle)
success = True
else:
@ -497,13 +527,13 @@ def buy_revente(request, spectacle_id):
# Si l'utilisateur veut racheter une place qu'il est en train de revendre,
# on supprime la revente en question.
if reventes.filter(seller=participant).exists():
revente = reventes.filter(seller=participant)[0]
revente.delete()
own_reventes = reventes.filter(seller=participant)
if len(own_reventes) > 0:
own_reventes[0].delete()
return HttpResponseRedirect(reverse("bda-shotgun",
args=[tirage.id]))
reventes_shotgun = list(reventes.filter(shotgun=True).all())
reventes_shotgun = reventes.filter(shotgun=True)
if not reventes_shotgun:
return render(request, "bda-no-revente.html", {})
@ -535,16 +565,21 @@ def buy_revente(request, spectacle_id):
@login_required
def revente_shotgun(request, tirage_id):
tirage = get_object_or_404(Tirage, id=tirage_id)
spectacles = tirage.spectacle_set.filter(
date__gte=timezone.now())
shotgun = []
for spectacle in spectacles:
reventes = SpectacleRevente.objects.filter(
attribution__spectacle=spectacle,
shotgun=True,
soldTo__isnull=True)
if reventes.exists():
shotgun.append(spectacle)
spectacles = (
tirage.spectacle_set
.filter(date__gte=timezone.now())
.select_related('location')
.prefetch_related(Prefetch(
'attribues',
queryset=(
Attribution.objects
.filter(revente__shotgun=True,
revente__soldTo__isnull=True)
),
to_attr='shotguns',
))
)
shotgun = [sp for sp in spectacles if len(sp.shotguns) > 0]
return render(request, "bda-shotgun.html",
{"shotgun": shotgun})
@ -554,7 +589,10 @@ def revente_shotgun(request, tirage_id):
def spectacle(request, tirage_id, spectacle_id):
tirage = get_object_or_404(Tirage, id=tirage_id)
spectacle = get_object_or_404(Spectacle, id=spectacle_id, tirage=tirage)
attributions = spectacle.attribues.all()
attributions = (
spectacle.attribues
.select_related('participant', 'participant__user')
)
participants = {}
for attrib in attributions:
participant = attrib.participant
@ -573,7 +611,7 @@ def spectacle(request, tirage_id, spectacle_id):
participants_info = sorted(participants.values(),
key=lambda part: part['lastname'])
return render(request, "bda-participants.html",
return render(request, "bda/participants.html",
{"spectacle": spectacle, "participants": participants_info})
@ -583,7 +621,10 @@ class SpectacleListView(ListView):
def get_queryset(self):
self.tirage = get_object_or_404(Tirage, id=self.kwargs['tirage_id'])
categories = self.tirage.spectacle_set.all()
categories = (
self.tirage.spectacle_set
.select_related('location')
)
return categories
def get_context_data(self, **kwargs):
@ -596,9 +637,12 @@ class SpectacleListView(ListView):
@buro_required
def unpaid(request, tirage_id):
tirage = get_object_or_404(Tirage, id=tirage_id)
unpaid = tirage.participant_set \
.annotate(nb_attributions=Count('attribution')) \
.filter(paid=False, nb_attributions__gt=0).all()
unpaid = (
tirage.participant_set
.annotate(nb_attributions=Count('attribution'))
.filter(paid=False, nb_attributions__gt=0)
.select_related('user')
)
return render(request, "bda-unpaid.html", {"unpaid": unpaid})
@ -606,20 +650,24 @@ def unpaid(request, tirage_id):
def send_rappel(request, spectacle_id):
show = get_object_or_404(Spectacle, id=spectacle_id)
# Mails d'exemples
exemple_mail_1place = render_custom_mail('bda-rappel', {
custommail = CustomMail.objects.get(shortname="bda-rappel")
exemple_mail_1place = custommail.render({
'member': request.user,
'show': show,
'nb_attr': 1
})
exemple_mail_2places = render_custom_mail('bda-rappel', {
exemple_mail_2places = custommail.render({
'member': request.user,
'show': show,
'nb_attr': 2
})
# Contexte
ctxt = {'show': show,
'exemple_mail_1place': exemple_mail_1place,
'exemple_mail_2places': exemple_mail_2places}
ctxt = {
'show': show,
'exemple_mail_1place': exemple_mail_1place,
'exemple_mail_2places': exemple_mail_2places,
'custommail': custommail,
}
# Envoi confirmé
if request.method == 'POST':
members = show.send_rappel()
@ -628,12 +676,24 @@ def send_rappel(request, spectacle_id):
# Demande de confirmation
else:
ctxt['sent'] = False
if show.rappel_sent:
messages.warning(
request,
"Attention, un mail de rappel pour ce spectale a déjà été "
"envoyé le {}".format(formats.localize(
timezone.template_localtime(show.rappel_sent)
))
)
return render(request, "bda/mails-rappel.html", ctxt)
def descriptions_spectacles(request, tirage_id):
tirage = get_object_or_404(Tirage, id=tirage_id)
shows_qs = tirage.spectacle_set
shows_qs = (
tirage.spectacle_set
.select_related('location')
.prefetch_related('quote_set')
)
category_name = request.GET.get('category', '')
location_id = request.GET.get('location', '')
if category_name:
@ -644,7 +704,7 @@ def descriptions_spectacles(request, tirage_id):
except ValueError:
return HttpResponseBadRequest(
"La variable GET 'location' doit contenir un entier")
return render(request, 'descriptions.html', {'shows': shows_qs.all()})
return render(request, 'descriptions.html', {'shows': shows_qs})
def catalogue(request, request_type):
@ -657,29 +717,35 @@ def catalogue(request, request_type):
if request_type == "list":
# Dans ce cas on retourne la liste des tirages et de leur id en JSON
data_return = list(
Tirage.objects.filter(appear_catalogue=True).values('id', 'title'))
Tirage.objects.filter(appear_catalogue=True).values('id', 'title')
)
return JsonResponse(data_return, safe=False)
if request_type == "details":
# Dans ce cas on retourne une liste des catégories et des salles
tirage_id = request.GET.get('id', '')
try:
tirage = Tirage.objects.get(id=tirage_id)
except ObjectDoesNotExist:
tirage_id = request.GET.get('id', None)
if tirage_id is None:
return HttpResponseBadRequest(
"Aucun tirage correspondant à l'id "
+ tirage_id)
"Missing GET parameter: id <int>"
)
try:
tirage = get_object_or_404(Tirage, id=int(tirage_id))
except ValueError:
return HttpResponseBadRequest(
"Mauvais format d'identifiant : "
+ tirage_id)
"Bad format: int expected for `id`"
)
shows = tirage.spectacle_set.values_list("id", flat=True)
categories = list(
CategorieSpectacle.objects.filter(
spectacle__in=tirage.spectacle_set.all())
.distinct().values('id', 'name'))
CategorieSpectacle.objects
.filter(spectacle__in=shows)
.distinct()
.values('id', 'name')
)
locations = list(
Salle.objects.filter(
spectacle__in=tirage.spectacle_set.all())
.distinct().values('id', 'name'))
Salle.objects
.filter(spectacle__in=shows)
.distinct()
.values('id', 'name')
)
data_return = {'categories': categories, 'locations': locations}
return JsonResponse(data_return, safe=False)
if request_type == "descriptions":
@ -687,33 +753,39 @@ def catalogue(request, request_type):
# à la salle spécifiées
tirage_id = request.GET.get('id', '')
categories = request.GET.get('category', '[0]')
locations = request.GET.get('location', '[0]')
categories = request.GET.get('category', '[]')
locations = request.GET.get('location', '[]')
try:
category_id = json.loads(categories)
location_id = json.loads(locations)
tirage = Tirage.objects.get(id=tirage_id)
shows_qs = tirage.spectacle_set
if not(0 in category_id):
shows_qs = shows_qs.filter(
category__id__in=category_id)
if not(0 in location_id):
shows_qs = shows_qs.filter(
location__id__in=location_id)
except ObjectDoesNotExist:
return HttpResponseBadRequest(
"Impossible de trouver des résultats correspondant "
"à ces caractéristiques : "
+ "id = " + tirage_id
+ ", catégories = " + categories
+ ", salles = " + locations)
tirage_id = int(tirage_id)
categories_id = json.loads(categories)
locations_id = json.loads(locations)
# Integers expected
if not all(isinstance(id, int) for id in categories_id):
raise ValueError
if not all(isinstance(id, int) for id in locations_id):
raise ValueError
except ValueError: # Contient JSONDecodeError
return HttpResponseBadRequest(
"Impossible de parser les paramètres donnés : "
+ "id = " + request.GET.get('id', '')
+ ", catégories = " + request.GET.get('category', '[0]')
+ ", salles = " + request.GET.get('location', '[0]'))
"Parse error, please ensure the GET parameters have the "
"following types:\n"
"id: int, category: [int], location: [int]\n"
"Data received:\n"
"id = {}, category = {}, locations = {}"
.format(request.GET.get('id', ''),
request.GET.get('category', '[]'),
request.GET.get('location', '[]'))
)
tirage = get_object_or_404(Tirage, id=tirage_id)
shows_qs = (
tirage.spectacle_set
.select_related('location')
.prefetch_related('quote_set')
)
if categories_id:
shows_qs = shows_qs.filter(category__id__in=categories_id)
if locations_id:
shows_qs = shows_qs.filter(location__id__in=locations_id)
# On convertit les descriptions à envoyer en une liste facilement
# JSONifiable (il devrait y avoir un moyen plus efficace en
@ -728,14 +800,15 @@ def catalogue(request, request_type):
'vips': spectacle.vips,
'description': spectacle.description,
'slots_description': spectacle.slots_description,
'quotes': list(Quote.objects.filter(spectacle=spectacle).values(
'author', 'text')),
'quotes': [dict(author=quote.author,
text=quote.text)
for quote in spectacle.quote_set.all()],
'image': spectacle.getImgUrl(),
'ext_link': spectacle.ext_link,
'price': spectacle.price,
'slots': spectacle.slots
}
for spectacle in shows_qs.all()
for spectacle in shows_qs
]
return JsonResponse(data_return, safe=False)
# Si la requête n'est pas de la forme attendue, on quitte avec une erreur

View file

@ -1,3 +1,6 @@
from kfet.routing import channel_routing as kfet_channel_routings
from channels.routing import include
channel_routing = kfet_channel_routings
routing = [
include('kfet.routing.routing', path=r'^/ws/k-fet'),
]

1
cof/settings/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
secret.py

View file

@ -1,32 +1,59 @@
# -*- coding: utf-8 -*-
"""
Django settings for cof project.
Django common settings for cof project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
Everything which is supposed to be identical between the production server and
the local development server should be here.
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
try:
from . import secret
except ImportError:
raise ImportError(
"The secret.py file is missing.\n"
"For a development environment, simply copy secret_example.py"
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
def import_secret(name):
"""
Shorthand for importing a value from the secret module and raising an
informative exception if a secret is missing.
"""
try:
return getattr(secret, name)
except AttributeError:
raise RuntimeError("Secret missing: {}".format(name))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q()(zn4m63i%5cp4)f+ww4-28_w+ly3q9=6imw2ciu&_(5_4ah'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
SECRET_KEY = import_secret("SECRET_KEY")
ADMINS = import_secret("ADMINS")
SERVER_EMAIL = import_secret("SERVER_EMAIL")
DBNAME = import_secret("DBNAME")
DBUSER = import_secret("DBUSER")
DBPASSWD = import_secret("DBPASSWD")
REDIS_PASSWD = import_secret("REDIS_PASSWD")
REDIS_DB = import_secret("REDIS_DB")
REDIS_HOST = import_secret("REDIS_HOST")
REDIS_PORT = import_secret("REDIS_PORT")
RECAPTCHA_PUBLIC_KEY = import_secret("RECAPTCHA_PUBLIC_KEY")
RECAPTCHA_PRIVATE_KEY = import_secret("RECAPTCHA_PRIVATE_KEY")
KFETOPEN_TOKEN = import_secret("KFETOPEN_TOKEN")
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
# Application definition
INSTALLED_APPS = (
INSTALLED_APPS = [
'gestioncof',
'django.contrib.auth',
'django.contrib.contenttypes',
@ -41,16 +68,32 @@ INSTALLED_APPS = (
'autocomplete_light',
'captcha',
'django_cas_ng',
'debug_toolbar',
'bootstrapform',
'kfet',
'kfet.open',
'channels',
'widget_tweaks',
'custommail',
)
'djconfig',
'wagtail.wagtailforms',
'wagtail.wagtailredirects',
'wagtail.wagtailembeds',
'wagtail.wagtailsites',
'wagtail.wagtailusers',
'wagtail.wagtailsnippets',
'wagtail.wagtaildocs',
'wagtail.wagtailimages',
'wagtail.wagtailsearch',
'wagtail.wagtailadmin',
'wagtail.wagtailcore',
'wagtail.contrib.modeladmin',
'wagtailmenus',
'modelcluster',
'taggit',
'kfet.cms',
]
MIDDLEWARE_CLASSES = (
'debug_toolbar.middleware.DebugToolbarMiddleware',
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
@ -60,7 +103,10 @@ MIDDLEWARE_CLASSES = (
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
'djconfig.middleware.DjConfigMiddleware',
'wagtail.wagtailcore.middleware.SiteMiddleware',
'wagtail.wagtailredirects.middleware.RedirectMiddleware',
]
ROOT_URLCONF = 'cof.urls'
@ -78,24 +124,22 @@ TEMPLATES = [
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'wagtailmenus.context_processors.wagtailmenus',
'djconfig.context_processors.config',
'gestioncof.shared.context_processor',
'kfet.context_processors.auth',
'kfet.context_processors.config',
],
},
},
]
# WSGI_APPLICATION = 'cof.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ['DBNAME'],
'USER': os.environ['DBUSER'],
'PASSWORD': os.environ['DBPASSWD'],
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': DBNAME,
'USER': DBUSER,
'PASSWORD': DBPASSWD,
'HOST': os.environ.get('DBHOST', 'localhost'),
}
}
@ -114,19 +158,6 @@ USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/static/'
# Media upload (through ImageField, SiteField)
# https://docs.djangoproject.com/en/1.9/ref/models/fields/
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
# Various additional settings
SITE_ID = 1
@ -150,51 +181,52 @@ LOGIN_URL = "cof-login"
LOGIN_REDIRECT_URL = "home"
CAS_SERVER_URL = 'https://cas.eleves.ens.fr/'
CAS_VERSION = '3'
CAS_LOGIN_MSG = None
CAS_IGNORE_REFERER = True
CAS_REDIRECT_URL = '/'
CAS_EMAIL_FORMAT = "%s@clipper.ens.fr"
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'gestioncof.shared.COFCASBackend',
'kfet.backends.GenericTeamBackend',
)
# LDAP_SERVER_URL = 'ldaps://ldap.spi.ens.fr:636'
# EMAIL_HOST="nef.ens.fr"
RECAPTCHA_PUBLIC_KEY = "DUMMY"
RECAPTCHA_PRIVATE_KEY = "DUMMY"
RECAPTCHA_USE_SSL = True
# Cache settings
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': 'redis://:{passwd}@{host}:{port}/db'
.format(passwd=REDIS_PASSWD, host=REDIS_HOST,
port=REDIS_PORT, db=REDIS_DB),
}
}
# Channels settings
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [(os.environ.get("REDIS_HOST", "localhost"), 6379)],
"hosts": [(
"redis://:{passwd}@{host}:{port}/{db}"
.format(passwd=REDIS_PASSWD, host=REDIS_HOST,
port=REDIS_PORT, db=REDIS_DB)
)],
},
"ROUTING": "cof.routing.channel_routing",
"ROUTING": "cof.routing.routing",
}
}
def show_toolbar(request):
"""
On ne veut pas la vérification de INTERNAL_IPS faite par la debug-toolbar
car cela interfère avec l'utilisation de Vagrant. En effet, l'adresse de la
machine physique n'est pas forcément connue, et peut difficilement être
mise dans les INTERNAL_IPS.
"""
if not DEBUG:
return False
if request.is_ajax():
return False
return True
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': show_toolbar,
}
FORMAT_MODULE_PATH = 'cof.locale'
# Wagtail settings
WAGTAIL_SITE_NAME = 'GestioCOF'
WAGTAIL_ENABLE_UPDATE_CHECK = False
TAGGIT_CASE_INSENSITIVE = True

46
cof/settings/dev.py Normal file
View file

@ -0,0 +1,46 @@
"""
Django development settings for the cof project.
The settings that are not listed here are imported from .common
"""
from .common import * # NOQA
from .common import INSTALLED_APPS, MIDDLEWARE_CLASSES
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEBUG = True
# ---
# Apache static/media config
# ---
STATIC_URL = '/static/'
STATIC_ROOT = '/srv/gestiocof/static/'
MEDIA_ROOT = '/srv/gestiocof/media/'
MEDIA_URL = '/media/'
# ---
# Debug tool bar
# ---
def show_toolbar(request):
"""
On ne veut pas la vérification de INTERNAL_IPS faite par la debug-toolbar
car cela interfère avec l'utilisation de Vagrant. En effet, l'adresse de la
machine physique n'est pas forcément connue, et peut difficilement être
mise dans les INTERNAL_IPS.
"""
return DEBUG
INSTALLED_APPS += ["debug_toolbar", "debug_panel"]
MIDDLEWARE_CLASSES = (
["debug_panel.middleware.DebugPanelMiddleware"]
+ MIDDLEWARE_CLASSES
)
DEBUG_TOOLBAR_CONFIG = {
'SHOW_TOOLBAR_CALLBACK': show_toolbar,
}

36
cof/settings/local.py Normal file
View file

@ -0,0 +1,36 @@
"""
Django local settings for the cof project.
The settings that are not listed here are imported from .common
"""
import os
from .dev import * # NOQA
from .dev import BASE_DIR
# Use sqlite for local development
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3")
}
}
# Use the default cache backend for local development
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache"
}
}
# Use the default in memory asgi backend for local development
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgiref.inmemory.ChannelLayer",
"ROUTING": "cof.routing.routing",
}
}
# No need to run collectstatic -> unset STATIC_ROOT
STATIC_ROOT = None

29
cof/settings/prod.py Normal file
View file

@ -0,0 +1,29 @@
"""
Django development settings for the cof project.
The settings that are not listed here are imported from .common
"""
import os
from .common import * # NOQA
from .common import BASE_DIR
DEBUG = False
ALLOWED_HOSTS = [
"cof.ens.fr",
"www.cof.ens.fr",
"dev.cof.ens.fr"
]
STATIC_ROOT = os.path.join(
os.path.dirname(os.path.dirname(BASE_DIR)),
"public",
"static",
)
STATIC_URL = "/gestion/static/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
MEDIA_URL = "/gestion/media/"

View file

@ -0,0 +1,20 @@
SECRET_KEY = 'q()(zn4m63i%5cp4)f+ww4-28_w+ly3q9=6imw2ciu&_(5_4ah'
ADMINS = None
SERVER_EMAIL = "root@vagrant"
DBUSER = "cof_gestion"
DBNAME = "cof_gestion"
DBPASSWD = "4KZt3nGPLVeWSvtBZPSM3fSzXpzEU4"
REDIS_PASSWD = "dummy"
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_HOST = "127.0.0.1"
RECAPTCHA_PUBLIC_KEY = "DUMMY"
RECAPTCHA_PRIVATE_KEY = "DUMMY"
EMAIL_HOST = None
KFETOPEN_TOKEN = "plop"
LDAP_SERVER_URL = None

View file

@ -14,6 +14,10 @@ from django.views.generic.base import TemplateView
from django.contrib.auth import views as django_views
from django_cas_ng import views as django_cas_views
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailcore import urls as wagtail_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from gestioncof import views as gestioncof_views, csv_views
from gestioncof.urls import export_patterns, petitcours_patterns, \
surveys_patterns, events_patterns, calendar_patterns, \
@ -48,7 +52,7 @@ urlpatterns = [
url(r'^outsider/login$', gestioncof_views.login_ext),
url(r'^outsider/logout$', django_views.logout, {'next_page': 'home'}),
url(r'^login$', gestioncof_views.login, name="cof-login"),
url(r'^logout$', gestioncof_views.logout),
url(r'^logout$', gestioncof_views.logout, name="cof-logout"),
# Infos persos
url(r'^profile$', gestioncof_views.profile),
url(r'^outsider/password-change$', django_views.password_change),
@ -82,6 +86,10 @@ urlpatterns = [
url(r'^utile_cof/diff_cof$', gestioncof_views.liste_diffcof),
url(r'^utile_bda/bda_revente$', gestioncof_views.liste_bdarevente),
url(r'^k-fet/', include('kfet.urls')),
url(r'^cms/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
# djconfig
url(r"^config", gestioncof_views.ConfigUpdate.as_view()),
]
if 'debug_toolbar' in settings.INSTALLED_APPS:
@ -90,7 +98,13 @@ if 'debug_toolbar' in settings.INSTALLED_APPS:
url(r'^__debug__/', include(debug_toolbar.urls)),
]
if settings.DEBUG:
# Si on est en production, MEDIA_ROOT est servi par Apache.
# Il faut dire à Django de servir MEDIA_ROOT lui-même en développement.
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
# Wagtail for uncatched
urlpatterns += [
url(r'', include(wagtail_urls)),
]

View file

@ -0,0 +1 @@
default_app_config = 'gestioncof.apps.GestioncofConfig'

View file

@ -1,9 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django import forms
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
@ -18,13 +12,12 @@ from django.contrib.auth.admin import UserAdmin
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django.db.models import Q
import django.utils.six as six
import autocomplete_light
def add_link_field(target_model='', field='', link_text=six.text_type,
desc_text=six.text_type):
def add_link_field(target_model='', field='', link_text=str,
desc_text=str):
def add_link(cls):
reverse_name = target_model or cls.model.__name__.lower()
@ -139,7 +132,6 @@ def ProfileInfo(field, short_description, boolean=False):
User.profile_login_clipper = FkeyLookup("profile__login_clipper",
"Login clipper")
User.profile_num = FkeyLookup("profile__num", "Numéro")
User.profile_phone = ProfileInfo("phone", "Téléphone")
User.profile_occupation = ProfileInfo("occupation", "Occupation")
User.profile_departement = ProfileInfo("departement", "Departement")
@ -166,10 +158,12 @@ class UserProfileAdmin(UserAdmin):
is_cof.short_description = 'Membre du COF'
is_cof.boolean = True
list_display = ('profile_num',) + UserAdmin.list_display \
list_display = (
UserAdmin.list_display
+ ('profile_login_clipper', 'profile_phone', 'profile_occupation',
'profile_mailing_cof', 'profile_mailing_bda',
'profile_mailing_bda_revente', 'is_cof', 'is_buro', )
)
list_display_links = ('username', 'email', 'first_name', 'last_name')
list_filter = UserAdmin.list_filter \
+ ('profile__is_cof', 'profile__is_buro', 'profile__mailing_cof',
@ -215,21 +209,17 @@ class UserProfileAdmin(UserAdmin):
# FIXME: This is absolutely horrible.
def user_unicode(self):
def user_str(self):
if self.first_name and self.last_name:
return "%s %s (%s)" % (self.first_name, self.last_name, self.username)
return "{} ({})".format(self.get_full_name(), self.username)
else:
return self.username
if six.PY2:
User.__unicode__ = user_unicode
else:
User.__str__ = user_unicode
User.__str__ = user_str
class EventRegistrationAdmin(admin.ModelAdmin):
form = autocomplete_light.modelform_factory(EventRegistration, exclude=[])
list_display = ('__unicode__' if six.PY2 else '__str__', 'event', 'user',
'paid')
list_display = ('__str__', 'event', 'user', 'paid')
list_filter = ('paid',)
search_fields = ('user__username', 'user__first_name', 'user__last_name',
'user__email', 'event__title')

15
gestioncof/apps.py Normal file
View file

@ -0,0 +1,15 @@
from django.apps import AppConfig
class GestioncofConfig(AppConfig):
name = 'gestioncof'
verbose_name = "Gestion des adhérents du COF"
def ready(self):
from . import signals
self.register_config()
def register_config(self):
import djconfig
from .forms import GestioncofConfigForm
djconfig.register(GestioncofConfigForm)

View file

@ -1,20 +1,14 @@
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.forms.widgets import RadioSelect, CheckboxSelectMultiple
from django.forms.formsets import BaseFormSet, formset_factory
from django.db.models import Max
from djconfig.forms import ConfigForm
from gestioncof.models import CofProfile, EventCommentValue, \
CalendarSubscription, Club
from gestioncof.widgets import TriStateCheckbox
from gestioncof.shared import lock_table, unlock_table
from bda.models import Spectacle
@ -239,7 +233,6 @@ class RegistrationProfileForm(forms.ModelForm):
self.fields['mailing_cof'].initial = True
self.fields['mailing_bda'].initial = True
self.fields['mailing_bda_revente'].initial = True
self.fields['num'].widget.attrs['readonly'] = True
self.fields.keyOrder = [
'login_clipper',
@ -247,7 +240,6 @@ class RegistrationProfileForm(forms.ModelForm):
'occupation',
'departement',
'is_cof',
'num',
'type_cotiz',
'mailing_cof',
'mailing_bda',
@ -255,24 +247,9 @@ class RegistrationProfileForm(forms.ModelForm):
'comments'
]
def save(self, *args, **kw):
instance = super(RegistrationProfileForm, self).save(*args, **kw)
if instance.is_cof and not instance.num:
# Generate new number
try:
lock_table(CofProfile)
aggregate = CofProfile.objects.aggregate(Max('num'))
instance.num = aggregate['num__max'] + 1
instance.save()
self.cleaned_data['num'] = instance.num
self.data['num'] = instance.num
finally:
unlock_table(CofProfile)
return instance
class Meta:
model = CofProfile
fields = ("login_clipper", "num", "phone", "occupation",
fields = ("login_clipper", "phone", "occupation",
"departement", "is_cof", "type_cotiz", "mailing_cof",
"mailing_bda", "mailing_bda_revente", "comments")
@ -399,3 +376,16 @@ class ClubsForm(forms.Form):
queryset=Club.objects.all(),
widget=forms.CheckboxSelectMultiple,
required=False)
# ---
# Announcements banner
# TODO: move this to the `gestion` app once the supportBDS branch is merged
# ---
class GestioncofConfigForm(ConfigForm):
gestion_banner = forms.CharField(
label=_("Announcements banner"),
help_text=_("An empty banner disables annoucements"),
max_length=2048
)

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('gestioncof', '0010_delete_custommail'),
]
operations = [
migrations.RemoveField(
model_name='cofprofile',
name='num',
),
]

View file

@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestioncof', '0011_remove_cofprofile_num'),
('gestioncof', '0011_longer_clippers'),
]
operations = [
]

View file

@ -1,11 +1,7 @@
# -*- coding: utf-8 -*-
from django.db import models
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
import django.utils.six as six
from django.db.models.signals import post_save, post_delete
from gestioncof.petits_cours_models import choices_length
@ -35,14 +31,12 @@ TYPE_COMMENT_FIELD = (
)
@python_2_unicode_compatible
class CofProfile(models.Model):
user = models.OneToOneField(User, related_name="profile")
login_clipper = models.CharField(
"Login clipper", max_length=32, blank=True
)
is_cof = models.BooleanField("Membre du COF", default=False)
num = models.IntegerField("Numéro d'adhérent", blank=True, default=0)
phone = models.CharField("Téléphone", max_length=20, blank=True)
occupation = models.CharField(_("Occupation"),
default="1A",
@ -74,7 +68,7 @@ class CofProfile(models.Model):
verbose_name_plural = "Profils COF"
def __str__(self):
return six.text_type(self.user.username)
return self.user.username
@receiver(post_save, sender=User)
@ -88,7 +82,6 @@ def post_delete_user(sender, instance, *args, **kwargs):
instance.user.delete()
@python_2_unicode_compatible
class Club(models.Model):
name = models.CharField("Nom", max_length=200, unique=True)
description = models.TextField("Description", blank=True)
@ -100,7 +93,6 @@ class Club(models.Model):
return self.name
@python_2_unicode_compatible
class Event(models.Model):
title = models.CharField("Titre", max_length=200)
location = models.CharField("Lieu", max_length=200)
@ -117,10 +109,9 @@ class Event(models.Model):
verbose_name = "Événement"
def __str__(self):
return six.text_type(self.title)
return self.title
@python_2_unicode_compatible
class EventCommentField(models.Model):
event = models.ForeignKey(Event, related_name="commentfields")
name = models.CharField("Champ", max_length=200)
@ -132,10 +123,9 @@ class EventCommentField(models.Model):
verbose_name = "Champ"
def __str__(self):
return six.text_type(self.name)
return self.name
@python_2_unicode_compatible
class EventCommentValue(models.Model):
commentfield = models.ForeignKey(EventCommentField, related_name="values")
registration = models.ForeignKey("EventRegistration",
@ -146,7 +136,6 @@ class EventCommentValue(models.Model):
return "Commentaire de %s" % self.commentfield
@python_2_unicode_compatible
class EventOption(models.Model):
event = models.ForeignKey(Event, related_name="options")
name = models.CharField("Option", max_length=200)
@ -156,10 +145,9 @@ class EventOption(models.Model):
verbose_name = "Option"
def __str__(self):
return six.text_type(self.name)
return self.name
@python_2_unicode_compatible
class EventOptionChoice(models.Model):
event_option = models.ForeignKey(EventOption, related_name="choices")
value = models.CharField("Valeur", max_length=200)
@ -169,10 +157,9 @@ class EventOptionChoice(models.Model):
verbose_name_plural = "Choix"
def __str__(self):
return six.text_type(self.value)
return self.value
@python_2_unicode_compatible
class EventRegistration(models.Model):
user = models.ForeignKey(User)
event = models.ForeignKey(Event)
@ -186,11 +173,9 @@ class EventRegistration(models.Model):
unique_together = ("user", "event")
def __str__(self):
return "Inscription de %s à %s" % (six.text_type(self.user),
six.text_type(self.event.title))
return "Inscription de {} à {}".format(self.user, self.event.title)
@python_2_unicode_compatible
class Survey(models.Model):
title = models.CharField("Titre", max_length=200)
details = models.TextField("Détails", blank=True)
@ -201,10 +186,9 @@ class Survey(models.Model):
verbose_name = "Sondage"
def __str__(self):
return six.text_type(self.title)
return self.title
@python_2_unicode_compatible
class SurveyQuestion(models.Model):
survey = models.ForeignKey(Survey, related_name="questions")
question = models.CharField("Question", max_length=200)
@ -214,10 +198,9 @@ class SurveyQuestion(models.Model):
verbose_name = "Question"
def __str__(self):
return six.text_type(self.question)
return self.question
@python_2_unicode_compatible
class SurveyQuestionAnswer(models.Model):
survey_question = models.ForeignKey(SurveyQuestion, related_name="answers")
answer = models.CharField("Réponse", max_length=200)
@ -226,10 +209,9 @@ class SurveyQuestionAnswer(models.Model):
verbose_name = "Réponse"
def __str__(self):
return six.text_type(self.answer)
return self.answer
@python_2_unicode_compatible
class SurveyAnswer(models.Model):
user = models.ForeignKey(User)
survey = models.ForeignKey(Survey)
@ -246,7 +228,6 @@ class SurveyAnswer(models.Model):
self.survey.title)
@python_2_unicode_compatible
class CalendarSubscription(models.Model):
token = models.UUIDField()
user = models.OneToOneField(User)

View file

@ -12,28 +12,34 @@ from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db import transaction
from gestioncof.models import CofProfile
from gestioncof.petits_cours_models import (
PetitCoursDemande, PetitCoursAttribution, PetitCoursAttributionCounter,
PetitCoursAbility, PetitCoursSubject
PetitCoursAbility
)
from gestioncof.petits_cours_forms import DemandeForm, MatieresFormSet
from gestioncof.decorators import buro_required
from gestioncof.shared import lock_table, unlock_tables
class DemandeListView(ListView):
model = PetitCoursDemande
queryset = (
PetitCoursDemande.objects
.prefetch_related('matieres')
.order_by('traitee', '-id')
)
template_name = "petits_cours_demandes_list.html"
paginate_by = 20
def get_queryset(self):
return PetitCoursDemande.objects.order_by('traitee', '-id').all()
class DemandeDetailView(DetailView):
model = PetitCoursDemande
queryset = (
PetitCoursDemande.objects
.prefetch_related('petitcoursattribution_set',
'matieres')
)
template_name = "gestioncof/details_demande_petit_cours.html"
context_object_name = "demande"
@ -268,17 +274,17 @@ def _traitement_post(request, demande):
headers={'Reply-To': replyto}))
connection = mail.get_connection(fail_silently=False)
connection.send_messages(mails_to_send)
lock_table(PetitCoursAttributionCounter, PetitCoursAttribution, User)
for matiere in proposals:
for rank, user in enumerate(proposals[matiere]):
counter = PetitCoursAttributionCounter.objects.get(user=user,
matiere=matiere)
counter.count += 1
counter.save()
attrib = PetitCoursAttribution(user=user, matiere=matiere,
demande=demande, rank=rank + 1)
attrib.save()
unlock_tables()
with transaction.atomic():
for matiere in proposals:
for rank, user in enumerate(proposals[matiere]):
counter = PetitCoursAttributionCounter.objects.get(
user=user, matiere=matiere
)
counter.count += 1
counter.save()
attrib = PetitCoursAttribution(user=user, matiere=matiere,
demande=demande, rank=rank + 1)
attrib.save()
demande.traitee = True
demande.traitee_par = request.user
demande.processed = datetime.now()
@ -303,17 +309,15 @@ def inscription(request):
profile.petits_cours_accept = "receive_proposals" in request.POST
profile.petits_cours_remarques = request.POST["remarques"]
profile.save()
lock_table(PetitCoursAttributionCounter, PetitCoursAbility, User,
PetitCoursSubject)
abilities = (
PetitCoursAbility.objects.filter(user=request.user).all()
)
for ability in abilities:
PetitCoursAttributionCounter.get_uptodate(
ability.user,
ability.matiere
with transaction.atomic():
abilities = (
PetitCoursAbility.objects.filter(user=request.user).all()
)
unlock_tables()
for ability in abilities:
PetitCoursAttributionCounter.get_uptodate(
ability.user,
ability.matiere
)
success = True
formset = MatieresFormSet(instance=request.user)
else:

View file

@ -1,69 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.contrib.sites.models import Site
from django.conf import settings
from django.contrib.sites.models import Site
from django_cas_ng.backends import CASBackend
from django_cas_ng.utils import get_cas_client
from django.contrib.auth import get_user_model
from django.db import connection
from gestioncof.models import CofProfile
User = get_user_model()
class COFCASBackend(CASBackend):
def authenticate_cas(self, ticket, service, request):
"""Verifies CAS ticket and gets or creates User object"""
client = get_cas_client(service_url=service)
username, attributes, _ = client.verify_ticket(ticket)
if attributes:
request.session['attributes'] = attributes
if not username:
return None
def clean_username(self, username):
# Le CAS de l'ENS accepte les logins avec des espaces au début
# et à la fin, ainsi quavec une casse variable. On normalise pour
# éviter les doublons.
username = username.strip().lower()
return username.strip().lower()
profiles = CofProfile.objects.filter(login_clipper=username)
if len(profiles) > 0:
profile = profiles.order_by('-is_cof')[0]
user = profile.user
return user
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# user will have an "unusable" password
user = User.objects.create_user(username, '')
user.save()
return user
def authenticate(self, ticket, service, request):
"""Authenticates CAS ticket and retrieves user data"""
user = self.authenticate_cas(ticket, service, request)
if user is None:
return user
try:
profile = user.profile
except CofProfile.DoesNotExist:
profile, created = CofProfile.objects.get_or_create(user=user)
profile.save()
if not profile.login_clipper:
profile.login_clipper = user.username
profile.save()
if not user.email:
user.email = settings.CAS_EMAIL_FORMAT % profile.login_clipper
user.save()
if profile.is_buro and not user.is_staff:
user.is_staff = True
user.save()
def configure_user(self, user):
clipper = user.username
user.profile.login_clipper = clipper
user.profile.save()
user.email = settings.CAS_EMAIL_FORMAT % clipper
user.save()
return user
@ -74,25 +30,3 @@ def context_processor(request):
"site": Site.objects.get_current(),
}
return data
def lock_table(*models):
query = "LOCK TABLES "
for i, model in enumerate(models):
table = model._meta.db_table
if i > 0:
query += ", "
query += "%s WRITE" % table
cursor = connection.cursor()
cursor.execute(query)
row = cursor.fetchone()
return row
def unlock_tables(*models):
cursor = connection.cursor()
cursor.execute("UNLOCK TABLES")
row = cursor.fetchone()
return row
unlock_table = unlock_tables

23
gestioncof/signals.py Normal file
View file

@ -0,0 +1,23 @@
from django.contrib import messages
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django_cas_ng.signals import cas_user_authenticated
@receiver(user_logged_in)
def messages_on_out_login(request, user, **kwargs):
if user.backend.startswith('django.contrib.auth'):
msg = _('Connexion à GestioCOF réussie. Bienvenue {}.').format(
user.get_short_name(),
)
messages.success(request, msg)
@receiver(cas_user_authenticated)
def mesagges_on_cas_login(request, user, **kwargs):
msg = _('Connexion à GestioCOF par CAS réussie. Bienvenue {}.').format(
user.get_short_name(),
)
messages.success(request, msg)

View file

@ -40,8 +40,9 @@ a {
background: transparent;
}
div.empty-form {
padding-bottom: 2em;
}
a:hover {
color: #444;
@ -341,10 +342,12 @@ fieldset legend {
font-weight: 700;
font-size: large;
color:#DE826B;
padding-bottom: .5em;
}
#main-content h4 {
color:#DE826B;
padding-bottom: .5em;
}
#main-content h2,
@ -778,6 +781,17 @@ header .open > .dropdown-toggle.btn-default {
border-color: white;
}
/* Announcements banner ------------------ */
#banner {
background-color: #d86b01;
width: 100%;
text-align: center;
padding: 10px;
color: white;
font-size: larger;
}
/* FORMS --------------------------------- */

View file

@ -8,13 +8,13 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
{# CSS #}
{# CSS #}
<link type="text/css" rel="stylesheet" href="{% static "css/bootstrap.min.css" %}" />
<link type="text/css" rel="stylesheet" href="{% static "css/cof.css" %}" />
<link href="https://fonts.googleapis.com/css?family=Dosis|Dosis:700|Raleway|Roboto:300,300i,700" rel="stylesheet">
<link rel="stylesheet" href="{% static "font-awesome/css/font-awesome.min.css" %}">
{# JS #}
{# JS #}
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
{% block extra_head %}{% endblock %}

View file

@ -0,0 +1,23 @@
{% extends "base_title.html" %}
{% load bootstrap %}
{% load i18n %}
{% block page_size %}col-sm-8{%endblock%}
{% block realcontent %}
<h2>{% trans "Global configuration" %}</h2>
<form id="profile form-horizontal" method="post" action="">
<div class="row" style="margin: 0 15%;">
{% csrf_token %}
<fieldset"center-block">
{% for field in form %}
{{ field | bootstrap }}
{% endfor %}
</fieldset>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary pull-right"
value={% trans "Save" %} />
</div>
</form>
{% endblock %}

View file

@ -16,6 +16,14 @@
<h2 class="member-status">{% if user.first_name %}{{ user.first_name }}{% else %}<tt>{{ user.username }}</tt>{% endif %}, {% if user.profile.is_cof %}<tt class="user-is-cof">au COF{% else %}<tt class="user-is-not-cof">non-COF{% endif %}</tt></h2>
</div><!-- /.container -->
</header>
{% if config.gestion_banner %}
<div id="banner" class="container">
<span class="glyphicon glyphicon-bullhorn"></span>
<span>{{ config.gestion_banner }}</span>
</div>
{% endif %}
{% if messages %}
{% for message in messages %}
<div class="messages">

View file

@ -1,4 +1,5 @@
{% extends "gestioncof/base_header.html" %}
{% load wagtailcore_tags %}
{% block homelink %}
{% endblock %}
@ -55,7 +56,8 @@
<h3 class="block-title">K-Fêt<span class="pull-right"><i class="fa fa-coffee"></i></span></h3>
<div class="hm-block">
<ul>
<li><a href="{% url "kfet.home" %}">Page d'accueil</a></li>
{# TODO: Since Django 1.9, we can store result with "as", allowing proper value management (if None) #}
<li><a href="{% slugurl "k-fet" %}">Page d'accueil</a></li>
<li><a href="https://www.cof.ens.fr/k-fet/calendrier">Calendrier</a></li>
{% if perms.kfet.is_team %}
<li><a href="{% url 'kfet.kpsul' %}">K-Psul</a></li>

View file

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
import unicodecsv
import uuid
from datetime import timedelta
@ -9,12 +7,18 @@ from custommail.shortcuts import send_custom_mail
from django.shortcuts import redirect, get_object_or_404, render
from django.http import Http404, HttpResponse, HttpResponseForbidden
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login as django_login_view
from django.contrib.auth.views import (
login as django_login_view, logout as django_logout_view,
)
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
import django.utils.six as six
from django_cas_ng.views import logout as cas_logout_view
from gestioncof.models import Survey, SurveyAnswer, SurveyQuestion, \
SurveyQuestionAnswer
@ -24,10 +28,11 @@ from gestioncof.models import EventCommentField, EventCommentValue, \
CalendarSubscription
from gestioncof.models import CofProfile, Club
from gestioncof.decorators import buro_required, cof_required
from gestioncof.forms import UserProfileForm, EventStatusFilterForm, \
SurveyForm, SurveyStatusFilterForm, RegistrationUserForm, \
RegistrationProfileForm, EventForm, CalendarForm, EventFormset, \
RegistrationPassUserForm, ClubsForm
from gestioncof.forms import (
UserProfileForm, EventStatusFilterForm, SurveyForm, SurveyStatusFilterForm,
RegistrationUserForm, RegistrationProfileForm, EventForm, CalendarForm,
EventFormset, RegistrationPassUserForm, ClubsForm, GestioncofConfigForm
)
from bda.models import Tirage, Spectacle
@ -81,20 +86,29 @@ def login_ext(request):
@login_required
def logout(request):
try:
profile = request.user.profile
except CofProfile.DoesNotExist:
profile, created = CofProfile.objects.get_or_create(user=request.user)
if profile.login_clipper:
return redirect("django_cas_ng.views.logout")
def logout(request, next_page=None):
if next_page is None:
next_page = request.GET.get('next', None)
profile = getattr(request.user, 'profile', None)
if profile and profile.login_clipper:
msg = _('Déconnexion de GestioCOF et CAS réussie. À bientôt {}.')
logout_view = cas_logout_view
else:
return redirect("django.contrib.auth.views.logout")
msg = _('Déconnexion de GestioCOF réussie. À bientôt {}.')
logout_view = django_logout_view
messages.success(request, msg.format(request.user.get_short_name()))
return logout_view(request, next_page=next_page)
@login_required
def survey(request, survey_id):
survey = get_object_or_404(Survey, id=survey_id)
survey = get_object_or_404(
Survey.objects.prefetch_related('questions', 'questions__answers'),
id=survey_id,
)
if not survey.survey_open or survey.old:
raise Http404
success = False
@ -399,12 +413,8 @@ def registration_form2(request, login_clipper=None, username=None,
def registration(request):
if request.POST:
request_dict = request.POST.copy()
# num ne peut pas être défini manuellement
if "num" in request_dict:
del request_dict["num"]
member = None
login_clipper = None
success = False
# -----
# Remplissage des formulaires
@ -439,7 +449,6 @@ def registration(request):
member = user_form.save()
profile, _ = CofProfile.objects.get_or_create(user=member)
was_cof = profile.is_cof
request_dict["num"] = profile.num
# Maintenant on remplit le formulaire de profil
profile_form = RegistrationProfileForm(request_dict,
instance=profile)
@ -493,16 +502,18 @@ def registration(request):
for club in clubs_form.cleaned_data['clubs']:
club.membres.add(member)
club.save()
success = True
# Messages
if success:
msg = ("L'inscription de {:s} (<tt>{:s}</tt>) a été "
"enregistrée avec succès"
.format(member.get_full_name(), member.email))
if member.profile.is_cof:
msg += "Il est désormais membre du COF n°{:d} !".format(
member.profile.num)
messages.success(request, msg, extra_tags='safe')
# ---
# Success
# ---
msg = ("L'inscription de {:s} (<tt>{:s}</tt>) a été "
"enregistrée avec succès."
.format(member.get_full_name(), member.email))
if profile.is_cof:
msg += "\nIl est désormais membre du COF n°{:d} !".format(
member.profile.id)
messages.success(request, msg, extra_tags='safe')
return render(request, "gestioncof/registration_post.html",
{"user_form": user_form,
"profile_form": profile_form,
@ -566,10 +577,10 @@ def export_members(request):
writer = unicodecsv.writer(response)
for profile in CofProfile.objects.filter(is_cof=True).all():
user = profile.user
bits = [profile.num, user.username, user.first_name, user.last_name,
bits = [profile.id, user.username, user.first_name, user.last_name,
user.email, profile.phone, profile.occupation,
profile.departement, profile.type_cotiz]
writer.writerow([six.text_type(bit) for bit in bits])
writer.writerow([str(bit) for bit in bits])
return response
@ -585,10 +596,10 @@ def csv_export_mega(filename, qs):
comments = "---".join(
[comment.content for comment in reg.comments.all()])
bits = [user.username, user.first_name, user.last_name, user.email,
profile.phone, profile.num,
profile.phone, profile.id,
profile.comments if profile.comments else "", comments]
writer.writerow([six.text_type(bit) for bit in bits])
writer.writerow([str(bit) for bit in bits])
return response
@ -607,8 +618,8 @@ def export_mega_remarksonly(request):
user = reg.user
profile = user.profile
bits = [user.username, user.first_name, user.last_name, user.email,
profile.phone, profile.num, profile.comments, val.content]
writer.writerow([six.text_type(bit) for bit in bits])
profile.phone, profile.id, profile.comments, val.content]
writer.writerow([str(bit) for bit in bits])
return response
@ -760,3 +771,18 @@ def calendar_ics(request, token):
response = HttpResponse(content=vcal.to_ical())
response['Content-Type'] = "text/calendar"
return response
class ConfigUpdate(FormView):
form_class = GestioncofConfigForm
template_name = "gestioncof/banner_update.html"
success_url = reverse_lazy("home")
def dispatch(self, request, *args, **kwargs):
if request.user is None or not request.user.is_superuser:
raise Http404
return super().dispatch(request, *args, **kwargs)
def form_valid(self, form):
form.save()
return super().form_valid(form)

View file

@ -12,3 +12,9 @@ class KFetConfig(AppConfig):
def ready(self):
import kfet.signals
self.register_config()
def register_config(self):
import djconfig
from kfet.forms import KFetConfigForm
djconfig.register(KFetConfigForm)

View file

@ -1,15 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import hashlib
from django.contrib.auth.models import User, Permission
from gestioncof.models import CofProfile
from kfet.models import Account, GenericTeamToken
class KFetBackend(object):
def authenticate(self, request):
password = request.POST.get('KFETPASSWORD', '')
@ -18,13 +15,15 @@ class KFetBackend(object):
return None
try:
password_sha256 = hashlib.sha256(password.encode('utf-8')).hexdigest()
password_sha256 = (
hashlib.sha256(password.encode('utf-8'))
.hexdigest()
)
account = Account.objects.get(password=password_sha256)
user = account.cofprofile.user
return account.cofprofile.user
except Account.DoesNotExist:
return None
return user
class GenericTeamBackend(object):
def authenticate(self, username=None, token=None):
@ -46,6 +45,10 @@ class GenericTeamBackend(object):
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
return (
User.objects
.select_related('profile__account_kfet')
.get(pk=user_id)
)
except User.DoesNotExist:
return None

1
kfet/cms/__init__.py Normal file
View file

@ -0,0 +1 @@
default_app_config = 'kfet.cms.apps.KFetCMSAppConfig'

10
kfet/cms/apps.py Normal file
View file

@ -0,0 +1,10 @@
from django.apps import AppConfig
class KFetCMSAppConfig(AppConfig):
name = 'kfet.cms'
label = 'kfetcms'
verbose_name = 'CMS K-Fêt'
def ready(self):
from . import hooks

View file

@ -0,0 +1,20 @@
from kfet.models import Article
def get_articles(request=None):
articles = (
Article.objects
.filter(is_sold=True, hidden=False)
.select_related('category')
.order_by('category__name', 'name')
)
pressions, others = [], []
for article in articles:
if article.category.name == 'Pression':
pressions.append(article)
else:
others.append(article)
return {
'pressions': pressions,
'articles': others,
}

File diff suppressed because one or more lines are too long

12
kfet/cms/hooks.py Normal file
View file

@ -0,0 +1,12 @@
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.html import format_html
from wagtail.wagtailcore import hooks
@hooks.register('insert_editor_css')
def editor_css():
return format_html(
'<link rel="stylesheet" href="{}">',
static('kfetcms/css/editor.css'),
)

View file

@ -0,0 +1,35 @@
from django.contrib.auth.models import Group
from django.core.management import call_command
from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page, Site
class Command(BaseCommand):
help = "Importe des données pour Wagtail"
def add_arguments(self, parser):
parser.add_argument('--file', default='kfet_wagtail_17_05')
def handle(self, *args, **options):
self.stdout.write("Import des données wagtail")
# Nettoyage des données initiales posées par Wagtail dans la migration
# wagtailcore/0002
Group.objects.filter(name__in=('Moderators', 'Editors')).delete()
try:
homepage = Page.objects.get(
title="Welcome to your new Wagtail site!"
)
homepage.delete()
Site.objects.filter(root_page=homepage).delete()
except Page.DoesNotExist:
pass
# Import des données
# Par défaut, il s'agit d'une copie du site K-Fêt (17-05)
call_command('loaddata', options['file'])

View file

@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import wagtail.wagtailsnippets.blocks
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import django.db.models.deletion
import kfet.cms.models
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0033_remove_golive_expiry_help_text'),
('wagtailimages', '0019_delete_filter'),
]
operations = [
migrations.CreateModel(
name='KFetPage',
fields=[
('page_ptr', models.OneToOneField(serialize=False, primary_key=True, parent_link=True, auto_created=True, to='wagtailcore.Page')),
('no_header', models.BooleanField(verbose_name='Sans en-tête', help_text="Coché, l'en-tête (avec le titre) de la page n'est pas affiché.", default=False)),
('content', wagtail.wagtailcore.fields.StreamField((('rich', wagtail.wagtailcore.blocks.RichTextBlock(label='Éditeur')), ('carte', kfet.cms.models.MenuBlock()), ('group_team', wagtail.wagtailcore.blocks.StructBlock((('show_only', wagtail.wagtailcore.blocks.IntegerBlock(help_text='Nombre initial de membres affichés. Laisser vide pour tou-te-s les afficher.', required=False, label='Montrer seulement')), ('members', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailsnippets.blocks.SnippetChooserBlock(kfet.cms.models.MemberTeam), classname='team-group', label='K-Fêt-eux-ses'))))), ('group', wagtail.wagtailcore.blocks.StreamBlock((('rich', wagtail.wagtailcore.blocks.RichTextBlock(label='Éditeur')), ('carte', kfet.cms.models.MenuBlock()), ('group_team', wagtail.wagtailcore.blocks.StructBlock((('show_only', wagtail.wagtailcore.blocks.IntegerBlock(help_text='Nombre initial de membres affichés. Laisser vide pour tou-te-s les afficher.', required=False, label='Montrer seulement')), ('members', wagtail.wagtailcore.blocks.ListBlock(wagtail.wagtailsnippets.blocks.SnippetChooserBlock(kfet.cms.models.MemberTeam), classname='team-group', label='K-Fêt-eux-ses')))))), label='Contenu groupé'))), verbose_name='Contenu')),
('layout', models.CharField(max_length=255, choices=[('kfet/base_col_1.html', 'Une colonne : centrée sur la page'), ('kfet/base_col_2.html', 'Deux colonnes : fixe à gauche, contenu à droite'), ('kfet/base_col_mult.html', 'Contenu scindé sur plusieurs colonnes')], help_text='Comment cette page devrait être affichée ?', verbose_name='Template', default='kfet/base_col_mult.html')),
('main_size', models.CharField(max_length=255, blank=True, verbose_name='Taille de la colonne de contenu')),
('col_count', models.CharField(max_length=255, blank=True, verbose_name='Nombre de colonnes', help_text="S'applique au page dont le contenu est scindé sur plusieurs colonnes")),
],
options={
'verbose_name': 'page K-Fêt',
'verbose_name_plural': 'pages K-Fêt',
},
bases=('wagtailcore.page',),
),
migrations.CreateModel(
name='MemberTeam',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('first_name', models.CharField(blank=True, max_length=255, verbose_name='Prénom', default='')),
('last_name', models.CharField(blank=True, max_length=255, verbose_name='Nom', default='')),
('nick_name', models.CharField(verbose_name='Alias', blank=True, default='', max_length=255)),
('photo', models.ForeignKey(null=True, related_name='+', on_delete=django.db.models.deletion.SET_NULL, verbose_name='Photo', blank=True, to='wagtailimages.Image')),
],
options={
'verbose_name': 'K-Fêt-eux-se',
},
),
]

View file

@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfetcms', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='kfetpage',
name='col_count',
field=models.CharField(blank=True, max_length=255, verbose_name='Nombre de colonnes', help_text="S'applique au page dont le contenu est scindé sur plusieurs colonnes."),
),
]

View file

174
kfet/cms/models.py Normal file
View file

@ -0,0 +1,174 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.edit_handlers import (
FieldPanel, FieldRowPanel, MultiFieldPanel, StreamFieldPanel
)
from wagtail.wagtailcore import blocks
from wagtail.wagtailcore.fields import StreamField
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
from wagtail.wagtailsnippets.blocks import SnippetChooserBlock
from wagtail.wagtailsnippets.models import register_snippet
from kfet.cms.context_processors import get_articles
@register_snippet
class MemberTeam(models.Model):
first_name = models.CharField(
verbose_name=_('Prénom'),
blank=True, default='', max_length=255,
)
last_name = models.CharField(
verbose_name=_('Nom'),
blank=True, default='', max_length=255,
)
nick_name = models.CharField(
verbose_name=_('Alias'),
blank=True, default='', max_length=255,
)
photo = models.ForeignKey(
'wagtailimages.Image',
verbose_name=_('Photo'),
on_delete=models.SET_NULL,
null=True, blank=True,
related_name='+',
)
class Meta:
verbose_name = _('K-Fêt-eux-se')
panels = [
FieldPanel('first_name'),
FieldPanel('last_name'),
FieldPanel('nick_name'),
ImageChooserPanel('photo'),
]
def __str__(self):
return self.get_full_name()
def get_full_name(self):
return '{} {}'.format(self.first_name, self.last_name).strip()
class MenuBlock(blocks.StaticBlock):
class Meta:
icon = 'list-ul'
label = _('Carte')
template = 'kfetcms/block_menu.html'
def get_context(self, *args, **kwargs):
context = super().get_context(*args, **kwargs)
context.update(get_articles())
return context
class GroupTeamBlock(blocks.StructBlock):
show_only = blocks.IntegerBlock(
label=_('Montrer seulement'),
required=False,
help_text=_(
'Nombre initial de membres affichés. Laisser vide pour tou-te-s '
'les afficher.'
),
)
members = blocks.ListBlock(
SnippetChooserBlock(MemberTeam),
label=_('K-Fêt-eux-ses'),
classname='team-group',
)
class Meta:
icon = 'group'
label = _('Groupe de K-Fêt-eux-ses')
template = 'kfetcms/block_teamgroup.html'
class ChoicesStreamBlock(blocks.StreamBlock):
rich = blocks.RichTextBlock(label=_('Éditeur'))
carte = MenuBlock()
group_team = GroupTeamBlock()
class KFetStreamBlock(ChoicesStreamBlock):
group = ChoicesStreamBlock(label=_('Contenu groupé'))
class KFetPage(Page):
content = StreamField(KFetStreamBlock, verbose_name=_('Contenu'))
# Layout fields
TEMPLATE_COL_1 = 'kfet/base_col_1.html'
TEMPLATE_COL_2 = 'kfet/base_col_2.html'
TEMPLATE_COL_MULT = 'kfet/base_col_mult.html'
no_header = models.BooleanField(
verbose_name=_('Sans en-tête'),
default=False,
help_text=_(
"Coché, l'en-tête (avec le titre) de la page n'est pas affiché."
),
)
layout = models.CharField(
verbose_name=_('Template'),
choices=[
(TEMPLATE_COL_1, _('Une colonne : centrée sur la page')),
(TEMPLATE_COL_2, _('Deux colonnes : fixe à gauche, contenu à droite')),
(TEMPLATE_COL_MULT, _('Contenu scindé sur plusieurs colonnes')),
],
default=TEMPLATE_COL_MULT, max_length=255,
help_text=_(
"Comment cette page devrait être affichée ?"
),
)
main_size = models.CharField(
verbose_name=_('Taille de la colonne de contenu'),
blank=True, max_length=255,
)
col_count = models.CharField(
verbose_name=_('Nombre de colonnes'),
blank=True, max_length=255,
help_text=_(
"S'applique au page dont le contenu est scindé sur plusieurs colonnes."
),
)
# Panels
content_panels = Page.content_panels + [
StreamFieldPanel('content'),
]
layout_panel = [
FieldPanel('no_header'),
FieldPanel('layout'),
FieldRowPanel([
FieldPanel('main_size'),
FieldPanel('col_count'),
]),
]
settings_panels = [
MultiFieldPanel(layout_panel, _('Affichage'))
] + Page.settings_panels
# Base template
template = "kfetcms/base.html"
class Meta:
verbose_name = _('page K-Fêt')
verbose_name_plural = _('pages K-Fêt')
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
page = context['page']
if not page.seo_title:
page.seo_title = page.title
return context

View file

@ -0,0 +1,93 @@
.main.cms {
padding: 20px 15px;
}
@media (min-width: 768px) {
.main.cms {
padding: 35px 30px;
}
}
.cms {
text-align: justify;
font-size: 1.1em;
}
@media (min-width:768px) {
.cms {
font-size: 1.2em;
line-height: 1.6em;
}
}
/* Titles */
.cms h2, .cms h3 {
clear: both;
margin: 0 0 15px;
padding-bottom: 10px;
border-bottom: 1px solid #c8102e;
text-align: left;
font-weight: bold;
}
@media (min-width: 768px) {
.cms h2, .cms h3 {
padding-bottom: 15px;
}
}
/* Paragraphs */
.cms p {
margin-bottom: 20px;
text-indent: 2em;
}
.cms p + :not(h2):not(h3):not(div) {
margin-top: -10px;
}
@media (min-width: 768px) {
.cms p {
padding-bottom: 15px;
}
.cms p + :not(h2):not(h3):not(div) {
margin-top: -30px;
}
}
/* Lists */
.cms ol, .cms ul {
padding: 0 0 0 15px;
margin: 0 0 10px;
}
.cms ul {
list-style-type: square;
}
.cms ol > li, .cms ul > li {
padding-left: 5px;
}
/* Images */
.cms .richtext-image {
max-height: 100%;
margin: 5px 0 15px;
}
.cms .richtext-image.left {
float: left;
margin-right: 30px;
}
.cms .richtext-image.right {
float: right;
margin-left: 30px;
}

View file

@ -0,0 +1,18 @@
.snippets.listing thead, .snippets.listing thead tr {
border: 0;
}
.snippets.listing tbody {
display: block;
column-count: 2;
}
.snippets.listing tbody tr {
display: block;
}
@media (min-width: 992px) {
.snippets.listing tbody {
column-count: 3;
}
}

View file

@ -0,0 +1,3 @@
@import url("base.css");
@import url("menu.css");
@import url("team.css");

View file

@ -0,0 +1,58 @@
.carte {
margin-bottom: 15px;
font-family: "Roboto Slab";
}
.carte .carte-title {
padding-top: 0;
margin-top: 0;
margin-bottom: 0;
}
.carte .carte-list {
width: 100%;
padding: 15px;
list-style-type: none;
}
.carte .carte-item {
position: relative;
text-align: right;
white-space: nowrap;
padding: 0;
}
.carte .carte-item .filler {
position: absolute;
left: 0;
right: 0;
border-bottom: 2px dotted #333;
height: 75%;
}
.carte .carte-item > span {
position: relative;
}
.carte .carte-item .carte-label {
background: white;
float: left;
padding-right: 10px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.carte .carte-item .carte-ukf {
padding: 0 10px;
background: #ffdbc7;
}
.carte-inverted .carte-list,
.carte-inverted .carte-item .carte-label {
background: #ffdbc7;
}
.carte-inverted .carte-item .carte-ukf {
background: white;
}

View file

@ -0,0 +1,47 @@
.team-group {
margin-bottom: 20px;
}
.team-group .col-btn {
margin-bottom: 20px;
}
.team-group .member-more {
display: none;
}
.team-member {
padding: 0;
margin-bottom: 20px;
min-height: 190px;
background-color: inherit;
border: 0;
}
.team-member img {
max-width: 100%;
max-height: 125px;
width: auto;
height: auto;
display: block;
}
.team-member .infos {
height: 50px;
margin-top: 15px;
}
@media (min-width: 768px) {
.team-group {
margin-left: 20px;
margin-right: 20px;
}
.team-member {
min-height: 215px;
}
.team-member img {
max-height: 150px;
}
}

View file

@ -0,0 +1,41 @@
{% extends page.layout %}
{% load static wagtailcore_tags wagtailuserbar %}
{# CSS/JS #}
{% block extra_head %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "kfetcms/css/index.css" %}">
{% endblock %}
{# Titles #}
{% block title %}{{ page.seo_title }}{% endblock %}
{% block header-title %}{{ page.title }}{% endblock %}
{# Layout #}
{% block main-size %}{{ page.main_size|default:block.super }}{% endblock %}
{% block mult-count %}{{ page.col_count|default:block.super }}{% endblock %}
{% block main-class %}cms main-bg{% endblock %}
{# Content #}
{% block main %}
{% for block in page.content %}
<div class="{% if block.block_type == "rich" or block.block_type == "group" %}unbreakable{% endif %}">
{% include_block block %}
</div>
{% endfor %}
{% wagtailuserbar %}
{% endblock %}
{# Footer #}
{% block footer %}
{% include "kfet/base_footer.html" %}
{% endblock %}

View file

@ -0,0 +1,11 @@
{% load static %}
{% if pressions %}
{% include "kfetcms/block_menu_category.html" with title="Pressions du moment" articles=pressions class="carte-inverted" %}
{% endif %}
{% regroup articles by category as categories %}
{% for category in categories %}
{% include "kfetcms/block_menu_category.html" with title=category.grouper.name articles=category.list %}
{% endfor %}

View file

@ -0,0 +1,12 @@
<div class="carte {{ class }} unbreakable">
<h3 class="carte-title">{{ title }}</h3>
<ul class="carte-list">
{% for article in articles %}
<li class="carte-item">
<div class="filler"></div>
<span class="carte-label">{{ article.name }}</span>
<span class="carte-ukf">{{ article.price_ukf }} UKF</span>
</li>
{% endfor %}
</ul>
</div>

View file

@ -0,0 +1,66 @@
{% load wagtailcore_tags wagtailimages_tags %}
{% with groupteam=value len=value.members|length %}
<div class="team-group row">
{% if len == 2 %}
<div class="visible-sm col-sm-3"></div>
{% endif %}
{% for member in groupteam.members %}
<div class="
{% if len == 1 %}
col-xs-12
{% else %}
col-xs-6
{% if len == 3 %}
col-sm-4
{% elif len == 2 %}
col-sm-3 col-md-6
{% else %}
col-sm-3 col-md-4 col-lg-3
{% endif %}
{% endif %}
{% if groupteam.show_only != None and forloop.counter0 >= groupteam.show_only %}
member-more
{% endif %}
">
<div class="team-member thumbnail text-center">
{% image member.photo max-200x500 %}
<div class="infos">
<b>{{ member.get_full_name }}</b>
<br>
{% if member.nick_name %}
<i>alias</i> {{ member.nick_name }}
{% endif %}
</div>
</div>
</div>
{% endfor %}
{% if groupteam.show_only != None and len > groupteam.show_only %}
<div class="col-xs-12 col-btn text-center">
<button class="btn btn-primary btn-lg more">
{% if groupteam.show_only %}
Y'en a plus !
{% else %}
Les voir
{% endif %}
</button>
</div>
{% endif %}
</div>
{% endwith %}
<script type="text/javascript">
$( function() {
$('.more').click( function() {
$(this).closest('.col-btn').hide();
$(this).closest('.team-group').children('.member-more').show();
});
});
</script>

71
kfet/config.py Normal file
View file

@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.db import models
from djconfig import config
class KFetConfig(object):
"""kfet app configuration.
Enhance isolation with backend used to store config.
Usable after DjConfig middleware was called.
"""
prefix = 'kfet_'
def __getattr__(self, key):
if key == 'subvention_cof':
# Allows accessing to the reduction as a subvention
# Other reason: backward compatibility
reduction_mult = 1 - self.reduction_cof/100
return (1/reduction_mult - 1) * 100
return getattr(config, self._get_dj_key(key))
def list(self):
"""Get list of kfet app configuration.
Returns:
(key, value) for each configuration entry as list.
"""
# prevent circular imports
from kfet.forms import KFetConfigForm
return [(field.label, getattr(config, name), )
for name, field in KFetConfigForm.base_fields.items()]
def _get_dj_key(self, key):
return '{}{}'.format(self.prefix, key)
def set(self, **kwargs):
"""Update configuration value(s).
Args:
**kwargs: Keyword arguments. Keys must be in kfet config.
Config entries are updated to given values.
"""
# prevent circular imports
from kfet.forms import KFetConfigForm
# get old config
new_cfg = KFetConfigForm().initial
# update to new config
for key, value in kwargs.items():
dj_key = self._get_dj_key(key)
if isinstance(value, models.Model):
new_cfg[dj_key] = value.pk
else:
new_cfg[dj_key] = value
# save new config
cfg_form = KFetConfigForm(new_cfg)
if cfg_form.is_valid():
cfg_form.save()
else:
raise ValidationError(
'Invalid values in kfet_config.set: %(fields)s',
params={'fields': list(cfg_form.errors)})
kfet_config = KFetConfig()

View file

@ -1,26 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from .utils import DjangoJsonWebsocketConsumer, PermConsumerMixin
from channels import Group
from channels.generic.websockets import JsonWebsocketConsumer
class KPsul(JsonWebsocketConsumer):
# Set to True if you want them, else leave out
strict_ordering = False
slight_ordering = False
def connection_groups(self, **kwargs):
return ['kfet.kpsul']
def connect(self, message, **kwargs):
pass
def receive(self, content, **kwargs):
pass
def disconnect(self, message, **kwargs):
pass
class KPsul(PermConsumerMixin, DjangoJsonWebsocketConsumer):
groups = ['kfet.kpsul']
perms_connect = ['kfet.is_team']

View file

@ -1,11 +1,10 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from django.contrib.auth.context_processors import PermWrapper
from kfet.config import kfet_config
def auth(request):
if hasattr(request, 'real_user'):
return {
@ -13,3 +12,7 @@ def auth(request):
'perms': PermWrapper(request.real_user),
}
return {}
def config(request):
return {'kfet_config': kfet_config}

View file

@ -1,35 +1,40 @@
# -*- coding: utf-8 -*-
from datetime import timedelta
from decimal import Decimal
from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.forms import modelformset_factory
from django.forms import modelformset_factory, widgets
from django.utils import timezone
from djconfig.forms import ConfigForm
from kfet.models import (
Account, Checkout, Article, OperationGroup, Operation,
CheckoutStatement, ArticleCategory, Settings, AccountNegative, Transfer,
CheckoutStatement, ArticleCategory, AccountNegative, Transfer,
TransferGroup, Supplier)
from gestioncof.models import CofProfile
# -----
# Widgets
# -----
class DateTimeWidget(forms.DateTimeInput):
def __init__(self, attrs = None):
super(DateTimeWidget, self).__init__(attrs)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.attrs['format'] = '%Y-%m-%d %H:%M'
class Media:
css = {
'all': ('kfet/css/bootstrap-datetimepicker.min.css',)
}
js = (
'kfet/js/moment.js',
'kfet/js/moment-fr.js',
'kfet/js/bootstrap-datetimepicker.min.js',
)
'all': ('kfet/css/bootstrap-datetimepicker.min.css',)
}
js = ('kfet/js/bootstrap-datetimepicker.min.js',)
# -----
# Account forms
# -----
@ -122,6 +127,7 @@ class UserRestrictTeamForm(UserForm):
class Meta(UserForm.Meta):
fields = ['first_name', 'last_name', 'email']
class UserGroupForm(forms.ModelForm):
groups = forms.ModelMultipleChoiceField(
Group.objects.filter(name__icontains='K-Fêt'),
@ -129,20 +135,33 @@ class UserGroupForm(forms.ModelForm):
required=False)
def clean_groups(self):
groups = self.cleaned_data.get('groups')
# Si aucun groupe, on le dénomme
if not groups:
groups = self.instance.groups.exclude(name__icontains='K-Fêt')
return groups
kfet_groups = self.cleaned_data.get('groups')
other_groups = self.instance.groups.exclude(name__icontains='K-Fêt')
return list(kfet_groups) + list(other_groups)
class Meta:
model = User
model = User
fields = ['groups']
class KFetPermissionsField(forms.ModelMultipleChoiceField):
def __init__(self, *args, **kwargs):
queryset = Permission.objects.filter(
content_type__in=ContentType.objects.filter(app_label="kfet"),
)
super().__init__(
queryset=queryset,
widget=widgets.CheckboxSelectMultiple,
*args, **kwargs
)
def label_from_instance(self, obj):
return obj.name
class GroupForm(forms.ModelForm):
permissions = forms.ModelMultipleChoiceField(
queryset= Permission.objects.filter(content_type__in=
ContentType.objects.filter(app_label='kfet')))
permissions = KFetPermissionsField()
def clean_name(self):
name = self.cleaned_data['name']
@ -316,12 +335,20 @@ class KPsulAccountForm(forms.ModelForm):
}),
}
class KPsulCheckoutForm(forms.Form):
checkout = forms.ModelChoiceField(
queryset=Checkout.objects.filter(
is_protected=False, valid_from__lte=timezone.now(),
valid_to__gte=timezone.now()),
widget=forms.Select(attrs={'id':'id_checkout_select'}))
queryset=(
Checkout.objects
.filter(
is_protected=False,
valid_from__lte=timezone.now(),
valid_to__gte=timezone.now(),
)
),
widget=forms.Select(attrs={'id': 'id_checkout_select'}),
)
class KPsulOperationForm(forms.ModelForm):
article = forms.ModelChoiceField(
@ -383,44 +410,53 @@ class AddcostForm(forms.Form):
self.cleaned_data['amount'] = 0
super(AddcostForm, self).clean()
# -----
# Settings forms
# -----
class SettingsForm(forms.ModelForm):
class Meta:
model = Settings
fields = ['value_decimal', 'value_account', 'value_duration']
def clean(self):
name = self.instance.name
value_decimal = self.cleaned_data.get('value_decimal')
value_account = self.cleaned_data.get('value_account')
value_duration = self.cleaned_data.get('value_duration')
class KFetConfigForm(ConfigForm):
type_decimal = ['SUBVENTION_COF', 'ADDCOST_AMOUNT', 'OVERDRAFT_AMOUNT']
type_account = ['ADDCOST_FOR']
type_duration = ['OVERDRAFT_DURATION', 'CANCEL_DURATION']
kfet_reduction_cof = forms.DecimalField(
label='Réduction COF', initial=Decimal('20'),
max_digits=6, decimal_places=2,
help_text="Réduction, à donner en pourcentage, appliquée lors d'un "
"achat par un-e membre du COF sur le montant en euros.",
)
kfet_addcost_amount = forms.DecimalField(
label='Montant de la majoration (en €)', initial=Decimal('0'),
required=False,
max_digits=6, decimal_places=2,
)
kfet_addcost_for = forms.ModelChoiceField(
label='Destinataire de la majoration', initial=None, required=False,
help_text='Laissez vide pour désactiver la majoration.',
queryset=(Account.objects
.select_related('cofprofile', 'cofprofile__user')
.all()),
)
kfet_overdraft_duration = forms.DurationField(
label='Durée du découvert autorisé par défaut',
initial=timedelta(days=1),
)
kfet_overdraft_amount = forms.DecimalField(
label='Montant du découvert autorisé par défaut (en €)',
initial=Decimal('20'),
max_digits=6, decimal_places=2,
)
kfet_cancel_duration = forms.DurationField(
label='Durée pour annuler une commande sans mot de passe',
initial=timedelta(minutes=5),
)
self.cleaned_data['name'] = name
if name in type_decimal:
if not value_decimal:
raise ValidationError('Renseignez une valeur décimale')
self.cleaned_data['value_account'] = None
self.cleaned_data['value_duration'] = None
elif name in type_account:
self.cleaned_data['value_decimal'] = None
self.cleaned_data['value_duration'] = None
elif name in type_duration:
if not value_duration:
raise ValidationError('Renseignez une durée')
self.cleaned_data['value_decimal'] = None
self.cleaned_data['value_account'] = None
super(SettingsForm, self).clean()
class FilterHistoryForm(forms.Form):
checkouts = forms.ModelMultipleChoiceField(queryset = Checkout.objects.all())
accounts = forms.ModelMultipleChoiceField(queryset = Account.objects.all())
checkouts = forms.ModelMultipleChoiceField(queryset=Checkout.objects.all())
accounts = forms.ModelMultipleChoiceField(queryset=Account.objects.all())
from_date = forms.DateTimeField(widget=DateTimeWidget)
to_date = forms.DateTimeField(widget=DateTimeWidget)
# -----
# Transfer forms
@ -499,11 +535,7 @@ class OrderArticleForm(forms.Form):
self.category = kwargs['initial']['category']
self.category_name = kwargs['initial']['category__name']
self.box_capacity = kwargs['initial']['box_capacity']
self.v_s1 = kwargs['initial']['v_s1']
self.v_s2 = kwargs['initial']['v_s2']
self.v_s3 = kwargs['initial']['v_s3']
self.v_s4 = kwargs['initial']['v_s4']
self.v_s5 = kwargs['initial']['v_s5']
self.v_all = kwargs['initial']['v_all']
self.v_moy = kwargs['initial']['v_moy']
self.v_et = kwargs['initial']['v_et']
self.v_prev = kwargs['initial']['v_prev']

View file

@ -14,7 +14,8 @@ from kfet.models import (Account, Article, OperationGroup, Operation,
class Command(BaseCommand):
help = "Crée des opérations réparties uniformément sur une période de temps"
help = ("Crée des opérations réparties uniformément "
"sur une période de temps")
def add_arguments(self, parser):
# Nombre d'opérations à créer
@ -29,7 +30,6 @@ class Command(BaseCommand):
parser.add_argument('--transfers', type=int, default=0,
help='Number of transfers to create (default 0)')
def handle(self, *args, **options):
self.stdout.write("Génération d'opérations")
@ -44,6 +44,7 @@ class Command(BaseCommand):
# Convert to seconds
time = options['days'] * 24 * 3600
now = timezone.now()
checkout = Checkout.objects.first()
articles = Article.objects.all()
accounts = Account.objects.exclude(trigramme='LIQ')
@ -55,6 +56,13 @@ class Command(BaseCommand):
except Account.DoesNotExist:
con_account = random.choice(accounts)
# use to fetch OperationGroup pk created by bulk_create
at_list = []
# use to lazy set OperationGroup pk on Operation objects
ope_by_grp = []
# OperationGroup objects to bulk_create
opegroup_list = []
for i in range(num_ops):
# Randomly pick account
@ -64,8 +72,7 @@ class Command(BaseCommand):
account = liq_account
# Randomly pick time
at = timezone.now() - timedelta(
seconds=random.randint(0, time))
at = now - timedelta(seconds=random.randint(0, time))
# Majoration sur compte 'concert'
if random.random() < 0.2:
@ -78,13 +85,6 @@ class Command(BaseCommand):
# Initialize opegroup amount
amount = Decimal('0')
opegroup = OperationGroup.objects.create(
on_acc=account,
checkout=checkout,
at=at,
is_cof=account.cofprofile.is_cof
)
# Generating operations
ope_list = []
for j in range(random.randint(1, 4)):
@ -94,25 +94,26 @@ class Command(BaseCommand):
# 0.1 probability to have a charge
if typevar > 0.9 and account != liq_account:
ope = Operation(
group=opegroup,
type=Operation.DEPOSIT,
is_checkout=(random.random() > 0.2),
amount=Decimal(random.randint(1, 99)/10)
)
# 0.1 probability to have a withdrawal
# 0.05 probability to have a withdrawal
elif typevar > 0.85 and account != liq_account:
ope = Operation(
type=Operation.WITHDRAW,
amount=-Decimal(random.randint(1, 99)/10)
)
# 0.05 probability to have an edition
elif typevar > 0.8 and account != liq_account:
ope = Operation(
group=opegroup,
type=Operation.WITHDRAW,
is_checkout=(random.random() > 0.2),
amount=-Decimal(random.randint(1, 99)/10)
type=Operation.EDIT,
amount=Decimal(random.randint(1, 99)/10)
)
else:
article = random.choice(articles)
nb = random.randint(1, 5)
ope = Operation(
group=opegroup,
type=Operation.PURCHASE,
amount=-article.price*nb,
article=article,
@ -129,17 +130,44 @@ class Command(BaseCommand):
ope_list.append(ope)
amount += ope.amount
Operation.objects.bulk_create(ope_list)
opes_created += len(ope_list)
opegroup.amount = amount
opegroup.save()
opegroup_list.append(OperationGroup(
on_acc=account,
checkout=checkout,
at=at,
is_cof=account.cofprofile.is_cof,
amount=amount,
))
at_list.append(at)
ope_by_grp.append((at, ope_list, ))
OperationGroup.objects.bulk_create(opegroup_list)
# Fetch created OperationGroup objects pk by at
opegroups = (OperationGroup.objects
.filter(at__in=at_list)
.values('id', 'at'))
opegroups_by = {grp['at']: grp['id'] for grp in opegroups}
all_ope = []
for _ in range(num_ops):
at, ope_list = ope_by_grp.pop()
for ope in ope_list:
ope.group_id = opegroups_by[at]
all_ope.append(ope)
Operation.objects.bulk_create(all_ope)
opes_created = len(all_ope)
# Transfer generation
transfer_by_grp = []
transfergroup_list = []
at_list = []
for i in range(num_transfers):
# Randomly pick time
at = timezone.now() - timedelta(
seconds=random.randint(0, time))
at = now - timedelta(seconds=random.randint(0, time))
# Choose whether to have a comment
if random.random() > 0.5:
@ -147,24 +175,40 @@ class Command(BaseCommand):
else:
comment = ""
transfergroup = TransferGroup.objects.create(
transfergroup_list.append(TransferGroup(
at=at,
comment=comment,
valid_by=random.choice(accounts)
)
valid_by=random.choice(accounts),
))
at_list.append(at)
# Randomly generate transfer
transfer_list = []
for i in range(random.randint(1, 4)):
transfer_list.append(Transfer(
group=transfergroup,
from_acc=random.choice(accounts),
to_acc=random.choice(accounts),
amount=Decimal(random.randint(1, 99)/10)
))
Transfer.objects.bulk_create(transfer_list)
transfers += len(transfer_list)
transfer_by_grp.append((at, transfer_list, ))
TransferGroup.objects.bulk_create(transfergroup_list)
transfergroups = (TransferGroup.objects
.filter(at__in=at_list)
.values('id', 'at'))
transfergroups_by = {grp['at']: grp['id'] for grp in transfergroups}
all_transfer = []
for _ in range(num_transfers):
at, transfer_list = transfer_by_grp.pop()
for transfer in transfer_list:
transfer.group_id = transfergroups_by[at]
all_transfer.append(transfer)
Transfer.objects.bulk_create(all_transfer)
transfers += len(all_transfer)
self.stdout.write(
"- {:d} opérations créées dont {:d} commandes d'articles"

View file

@ -147,3 +147,9 @@ class Command(MyBaseCommand):
# ---
call_command('createopes', '100', '7', '--transfers=20')
# ---
# Wagtail CMS
# ---
call_command('kfet_loadwagtail')

View file

@ -1,15 +1,27 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from django.contrib.auth.models import User
from django.http import HttpResponseForbidden
from kfet.backends import KFetBackend
from kfet.models import Account
class KFetAuthenticationMiddleware(object):
"""Authenticate another user for this request if KFetBackend succeeds.
By the way, if a user is authenticated, we refresh its from db to add
values from CofProfile and Account of this user.
"""
def process_request(self, request):
if request.user.is_authenticated():
# avoid multiple db accesses in views and templates
user_pk = request.user.pk
request.user = (
User.objects
.select_related('profile__account_kfet')
.get(pk=user_pk)
)
kfet_backend = KFetBackend()
temp_request_user = kfet_backend.authenticate(request)
if temp_request_user:

View file

@ -0,0 +1,58 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from kfet.forms import KFetConfigForm
def adapt_settings(apps, schema_editor):
Settings = apps.get_model('kfet', 'Settings')
db_alias = schema_editor.connection.alias
obj = Settings.objects.using(db_alias)
cfg = {}
def try_get(new, old, type_field):
try:
value = getattr(obj.get(name=old), type_field)
cfg[new] = value
except Settings.DoesNotExist:
pass
try:
subvention = obj.get(name='SUBVENTION_COF').value_decimal
subvention_mult = 1 + subvention/100
reduction = (1 - 1/subvention_mult) * 100
cfg['kfet_reduction_cof'] = reduction
except Settings.DoesNotExist:
pass
try_get('kfet_addcost_amount', 'ADDCOST_AMOUNT', 'value_decimal')
try_get('kfet_addcost_for', 'ADDCOST_FOR', 'value_account')
try_get('kfet_overdraft_duration', 'OVERDRAFT_DURATION', 'value_duration')
try_get('kfet_overdraft_amount', 'OVERDRAFT_AMOUNT', 'value_decimal')
try_get('kfet_cancel_duration', 'CANCEL_DURATION', 'value_duration')
cfg_form = KFetConfigForm(initial=cfg)
if cfg_form.is_valid():
cfg_form.save()
class Migration(migrations.Migration):
dependencies = [
('kfet', '0053_created_at'),
('djconfig', '0001_initial'),
]
operations = [
migrations.RunPython(adapt_settings),
migrations.RemoveField(
model_name='settings',
name='value_account',
),
migrations.DeleteModel(
name='Settings',
),
]

View file

@ -0,0 +1,81 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def forwards_perms(apps, schema_editor):
"""Safely delete content type for old kfet.GlobalPermissions model.
Any permissions (except defaults) linked to this content type are updated
to link at its new content type.
Then, delete the content type. This will delete the three defaults
permissions which are assumed unused.
"""
ContentType = apps.get_model('contenttypes', 'contenttype')
try:
ctype_global = ContentType.objects.get(
app_label="kfet", model="globalpermissions",
)
except ContentType.DoesNotExist:
# We are not migrating from existing data, nothing to do.
return
perms = {
'account': (
'is_team', 'manage_perms', 'manage_addcosts',
'edit_balance_account', 'change_account_password',
'special_add_account',
),
'accountnegative': ('view_negs',),
'inventory': ('order_to_inventory',),
'operation': (
'perform_deposit', 'perform_negative_operations',
'override_frozen_protection', 'cancel_old_operations',
'perform_commented_operations',
),
}
Permission = apps.get_model('auth', 'permission')
global_perms = Permission.objects.filter(content_type=ctype_global)
for modelname, codenames in perms.items():
model = apps.get_model('kfet', modelname)
ctype = ContentType.objects.get_for_model(model)
(
global_perms
.filter(codename__in=codenames)
.update(content_type=ctype)
)
ctype_global.delete()
class Migration(migrations.Migration):
dependencies = [
('kfet', '0054_delete_settings'),
('contenttypes', '__latest__'),
('auth', '__latest__'),
]
operations = [
migrations.AlterModelOptions(
name='account',
options={'permissions': (('is_team', 'Is part of the team'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('edit_balance_account', "Modifier la balance d'un compte"), ('change_account_password', "Modifier le mot de passe d'une personne de l'équipe"), ('special_add_account', 'Créer un compte avec une balance initiale'))},
),
migrations.AlterModelOptions(
name='accountnegative',
options={'permissions': (('view_negs', 'Voir la liste des négatifs'),)},
),
migrations.AlterModelOptions(
name='inventory',
options={'ordering': ['-at'], 'permissions': (('order_to_inventory', "Générer un inventaire à partir d'une commande"),)},
),
migrations.AlterModelOptions(
name='operation',
options={'permissions': (('perform_deposit', 'Effectuer une charge'), ('perform_negative_operations', 'Enregistrer des commandes en négatif'), ('override_frozen_protection', "Forcer le gel d'un compte"), ('cancel_old_operations', 'Annuler des commandes non récentes'), ('perform_commented_operations', 'Enregistrer des commandes avec commentaires'))},
),
migrations.RunPython(forwards_perms),
]

View file

@ -0,0 +1,18 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0055_move_permissions'),
]
operations = [
migrations.AlterModelOptions(
name='account',
options={'permissions': (('is_team', 'Is part of the team'), ('manage_perms', 'Gérer les permissions K-Fêt'), ('manage_addcosts', 'Gérer les majorations'), ('edit_balance_account', "Modifier la balance d'un compte"), ('change_account_password', "Modifier le mot de passe d'une personne de l'équipe"), ('special_add_account', 'Créer un compte avec une balance initiale'), ('can_force_close', 'Fermer manuellement la K-Fêt'))},
),
]

View file

@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kfet', '0056_change_account_meta'),
('kfet', '0054_update_promos'),
]
operations = [
]

View file

@ -1,12 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from django.db import models
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied, ValidationError
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
from gestioncof.models import CofProfile
@ -15,11 +10,13 @@ from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.db import transaction
from django.db.models import F
from django.core.cache import cache
from datetime import date, timedelta
from datetime import date
import re
import hashlib
from .config import kfet_config
from .utils import to_ukf
def choices_length(choices):
return reduce(lambda m, choice: max(m, len(choice[0])), choices, 0)
@ -27,8 +24,19 @@ def default_promo():
now = date.today()
return now.month <= 8 and now.year-1 or now.year
@python_2_unicode_compatible
class AccountManager(models.Manager):
"""Manager for Account Model."""
def get_queryset(self):
"""Always append related data to this Account."""
return super().get_queryset().select_related('cofprofile__user',
'negative')
class Account(models.Model):
objects = AccountManager()
cofprofile = models.OneToOneField(
CofProfile, on_delete = models.PROTECT,
related_name = "account_kfet")
@ -56,10 +64,23 @@ class Account(models.Model):
unique = True,
blank = True, null = True, default = None)
class Meta:
permissions = (
('is_team', 'Is part of the team'),
('manage_perms', 'Gérer les permissions K-Fêt'),
('manage_addcosts', 'Gérer les majorations'),
('edit_balance_account', "Modifier la balance d'un compte"),
('change_account_password',
"Modifier le mot de passe d'une personne de l'équipe"),
('special_add_account',
"Créer un compte avec une balance initiale"),
('can_force_close', "Fermer manuellement la K-Fêt"),
)
def __str__(self):
return '%s (%s)' % (self.trigramme, self.name)
# Propriétés pour accéder aux attributs de user et cofprofile et user
# Propriétés pour accéder aux attributs de cofprofile et user
@property
def user(self):
return self.cofprofile.user
@ -83,9 +104,13 @@ class Account(models.Model):
return self.cofprofile.is_cof
# Propriétés supplémentaires
@property
def balance_ukf(self):
return to_ukf(self.balance, is_cof=self.is_cof)
@property
def real_balance(self):
if (hasattr(self, 'negative')):
if hasattr(self, 'negative') and self.negative.balance_offset:
return self.balance - self.negative.balance_offset
return self.balance
@ -101,6 +126,14 @@ class Account(models.Model):
def need_comment(self):
return self.trigramme == '#13'
@property
def readable(self):
return self.trigramme != 'GNR'
@property
def is_team(self):
return self.has_perm('kfet.is_team')
@staticmethod
def is_validandfree(trigramme):
data = { 'is_valid' : False, 'is_free' : False }
@ -113,8 +146,8 @@ class Account(models.Model):
return data
def perms_to_perform_operation(self, amount):
overdraft_duration_max = Settings.OVERDRAFT_DURATION()
overdraft_amount_max = Settings.OVERDRAFT_AMOUNT()
overdraft_duration_max = kfet_config.overdraft_duration
overdraft_amount_max = kfet_config.overdraft_amount
perms = set()
stop_ope = False
# Checking is cash account
@ -214,31 +247,79 @@ class Account(models.Model):
def delete(self, *args, **kwargs):
pass
def update_negative(self):
if self.real_balance < 0:
if hasattr(self, 'negative') and not self.negative.start:
self.negative.start = timezone.now()
self.negative.save()
elif not hasattr(self, 'negative'):
self.negative = (
AccountNegative.objects.create(
account=self, start=timezone.now(),
)
)
elif hasattr(self, 'negative'):
# self.real_balance >= 0
balance_offset = self.negative.balance_offset
if balance_offset:
(
Account.objects
.filter(pk=self.pk)
.update(balance=F('balance')-balance_offset)
)
self.refresh_from_db()
self.negative.delete()
class UserHasAccount(Exception):
def __init__(self, trigramme):
self.trigramme = trigramme
class AccountNegativeManager(models.Manager):
"""Manager for AccountNegative model."""
def get_queryset(self):
return (
super().get_queryset()
.select_related('account__cofprofile__user')
)
class AccountNegative(models.Model):
objects = AccountNegativeManager()
account = models.OneToOneField(
Account, on_delete = models.PROTECT,
related_name = "negative")
start = models.DateTimeField(
blank = True, null = True, default = None)
Account, on_delete=models.PROTECT,
related_name="negative",
)
start = models.DateTimeField(blank=True, null=True, default=None)
balance_offset = models.DecimalField(
"décalage de balance",
help_text="Montant non compris dans l'autorisation de négatif",
max_digits = 6, decimal_places = 2,
blank = True, null = True, default = None)
max_digits=6, decimal_places=2,
blank=True, null=True, default=None,
)
authz_overdraft_amount = models.DecimalField(
"négatif autorisé",
max_digits = 6, decimal_places = 2,
blank = True, null = True, default = None)
max_digits=6, decimal_places=2,
blank=True, null=True, default=None,
)
authz_overdraft_until = models.DateTimeField(
"expiration du négatif",
blank = True, null = True, default = None)
comment = models.CharField("commentaire", max_length = 255, blank = True)
blank=True, null=True, default=None,
)
comment = models.CharField("commentaire", max_length=255, blank=True)
class Meta:
permissions = (
('view_negs', 'Voir la liste des négatifs'),
)
@property
def until_default(self):
return self.start + kfet_config.overdraft_duration
@python_2_unicode_compatible
class Checkout(models.Model):
created_by = models.ForeignKey(
Account, on_delete = models.PROTECT,
@ -390,6 +471,10 @@ class Article(models.Model):
def get_absolute_url(self):
return reverse('kfet.article.read', kwargs={'pk': self.pk})
def price_ukf(self):
return to_ukf(self.price)
class ArticleRule(models.Model):
article_on = models.OneToOneField(
Article, on_delete = models.PROTECT,
@ -416,6 +501,10 @@ class Inventory(models.Model):
class Meta:
ordering = ['-at']
permissions = (
('order_to_inventory', "Générer un inventaire à partir d'une commande"),
)
class InventoryArticle(models.Model):
inventory = models.ForeignKey(
@ -592,6 +681,17 @@ class Operation(models.Model):
max_digits=6, decimal_places=2,
blank=True, null=True, default=None)
class Meta:
permissions = (
('perform_deposit', 'Effectuer une charge'),
('perform_negative_operations',
'Enregistrer des commandes en négatif'),
('override_frozen_protection', "Forcer le gel d'un compte"),
('cancel_old_operations', 'Annuler des commandes non récentes'),
('perform_commented_operations',
'Enregistrer des commandes avec commentaires'),
)
@property
def is_checkout(self):
return (self.type == Operation.DEPOSIT or
@ -612,136 +712,5 @@ class Operation(models.Model):
amount=self.amount)
class GlobalPermissions(models.Model):
class Meta:
managed = False
permissions = (
('is_team', 'Is part of the team'),
('perform_deposit', 'Effectuer une charge'),
('perform_negative_operations',
'Enregistrer des commandes en négatif'),
('override_frozen_protection', "Forcer le gel d'un compte"),
('cancel_old_operations', 'Annuler des commandes non récentes'),
('manage_perms', 'Gérer les permissions K-Fêt'),
('manage_addcosts', 'Gérer les majorations'),
('perform_commented_operations', 'Enregistrer des commandes avec commentaires'),
('view_negs', 'Voir la liste des négatifs'),
('order_to_inventory', "Générer un inventaire à partir d'une commande"),
('edit_balance_account', "Modifier la balance d'un compte"),
('change_account_password', "Modifier le mot de passe d'une personne de l'équipe"),
('special_add_account', "Créer un compte avec une balance initiale")
)
class Settings(models.Model):
name = models.CharField(
max_length = 45,
unique = True,
db_index = True)
value_decimal = models.DecimalField(
max_digits = 6, decimal_places = 2,
blank = True, null = True, default = None)
value_account = models.ForeignKey(
Account, on_delete = models.PROTECT,
blank = True, null = True, default = None)
value_duration = models.DurationField(
blank = True, null = True, default = None)
@staticmethod
def setting_inst(name):
return Settings.objects.get(name=name)
@staticmethod
def SUBVENTION_COF():
subvention_cof = cache.get('SUBVENTION_COF')
if subvention_cof:
return subvention_cof
try:
subvention_cof = Settings.setting_inst("SUBVENTION_COF").value_decimal
except Settings.DoesNotExist:
subvention_cof = 0
cache.set('SUBVENTION_COF', subvention_cof)
return subvention_cof
@staticmethod
def ADDCOST_AMOUNT():
try:
return Settings.setting_inst("ADDCOST_AMOUNT").value_decimal
except Settings.DoesNotExist:
return 0
@staticmethod
def ADDCOST_FOR():
try:
return Settings.setting_inst("ADDCOST_FOR").value_account
except Settings.DoesNotExist:
return None;
@staticmethod
def OVERDRAFT_DURATION():
overdraft_duration = cache.get('OVERDRAFT_DURATION')
if overdraft_duration:
return overdraft_duration
try:
overdraft_duration = Settings.setting_inst("OVERDRAFT_DURATION").value_duration
except Settings.DoesNotExist:
overdraft_duration = timedelta()
cache.set('OVERDRAFT_DURATION', overdraft_duration)
return overdraft_duration
@staticmethod
def OVERDRAFT_AMOUNT():
overdraft_amount = cache.get('OVERDRAFT_AMOUNT')
if overdraft_amount:
return overdraft_amount
try:
overdraft_amount = Settings.setting_inst("OVERDRAFT_AMOUNT").value_decimal
except Settings.DoesNotExist:
overdraft_amount = 0
cache.set('OVERDRAFT_AMOUNT', overdraft_amount)
return overdraft_amount
@staticmethod
def CANCEL_DURATION():
cancel_duration = cache.get('CANCEL_DURATION')
if cancel_duration:
return cancel_duration
try:
cancel_duration = Settings.setting_inst("CANCEL_DURATION").value_duration
except Settings.DoesNotExist:
cancel_duration = timedelta()
cache.set('CANCEL_DURATION', cancel_duration)
return cancel_duration
@staticmethod
def create_missing():
s, created = Settings.objects.get_or_create(name='SUBVENTION_COF')
if created:
s.value_decimal = 25
s.save()
s, created = Settings.objects.get_or_create(name='ADDCOST_AMOUNT')
if created:
s.value_decimal = 0.5
s.save()
s, created = Settings.objects.get_or_create(name='ADDCOST_FOR')
s, created = Settings.objects.get_or_create(name='OVERDRAFT_DURATION')
if created:
s.value_duration = timedelta(days=1) # 24h
s.save()
s, created = Settings.objects.get_or_create(name='OVERDRAFT_AMOUNT')
if created:
s.value_decimal = 20
s.save()
s, created = Settings.objects.get_or_create(name='CANCEL_DURATION')
if created:
s.value_duration = timedelta(minutes=5) # 5min
s.save()
@staticmethod
def empty_cache():
cache.delete_many([
'SUBVENTION_COF', 'OVERDRAFT_DURATION', 'OVERDRAFT_AMOUNT',
'CANCEL_DURATION', 'ADDCOST_AMOUNT', 'ADDCOST_FOR',
])
class GenericTeamToken(models.Model):
token = models.CharField(max_length = 50, unique = True)

1
kfet/open/__init__.py Normal file
View file

@ -0,0 +1 @@
from .open import OpenKfet, kfet_open # noqa

25
kfet/open/consumers.py Normal file
View file

@ -0,0 +1,25 @@
from ..decorators import kfet_is_team
from ..utils import DjangoJsonWebsocketConsumer, PermConsumerMixin
from .open import kfet_open
class OpenKfetConsumer(PermConsumerMixin, DjangoJsonWebsocketConsumer):
"""Consumer for K-Fêt Open.
WS groups:
kfet.open.base: Only carries the values visible for all users.
kfet.open.team: Carries all values (raw status...).
"""
def connection_groups(self, user, **kwargs):
"""Select which group the user should be connected."""
if kfet_is_team(user):
return ['kfet.open.team']
return ['kfet.open.base']
def connect(self, message, *args, **kwargs):
"""Send current status on connect."""
super().connect(message, *args, **kwargs)
self.send(kfet_open.export(message.user))

109
kfet/open/open.py Normal file
View file

@ -0,0 +1,109 @@
from datetime import timedelta
from django.utils import timezone
from ..decorators import kfet_is_team
from ..utils import CachedMixin
class OpenKfet(CachedMixin, object):
"""Manage "open" status of a place.
Stores raw data (e.g. sent by raspberry), and user-set values
(as force_close).
Setting differents `cache_prefix` allows different places management.
Current state persists through cache.
"""
# status is unknown after this duration
time_unknown = timedelta(minutes=15)
# status
OPENED = 'opened'
CLOSED = 'closed'
UNKNOWN = 'unknown'
# admin status
FAKE_CLOSED = 'fake_closed'
# cached attributes config
cached = {
'_raw_open': False,
'_last_update': None,
'force_close': False,
}
cache_prefix = 'kfetopen'
@property
def raw_open(self):
"""Defined as property to update `last_update` on `raw_open` update."""
return self._raw_open
@raw_open.setter
def raw_open(self, value):
self._last_update = timezone.now()
self._raw_open = value
@property
def last_update(self):
"""Prevent `last_update` to be set."""
return self._last_update
@property
def is_open(self):
"""Take into account force_close."""
return False if self.force_close else self.raw_open
def status(self):
if (self.last_update is None or
timezone.now() - self.last_update >= self.time_unknown):
return self.UNKNOWN
return self.OPENED if self.is_open else self.CLOSED
def admin_status(self, status=None):
if status is None:
status = self.status()
if status == self.CLOSED and self.raw_open:
return self.FAKE_CLOSED
return status
def _export(self):
"""Export internal state.
Used by WS initialization and updates.
Returns:
(tuple): (base, team)
- team for team users.
- base for others.
"""
status = self.status()
base = {
'status': status,
}
restrict = {
'admin_status': self.admin_status(status),
'force_close': self.force_close,
}
return base, {**base, **restrict}
def export(self, user):
"""Export internal state for a given user.
Returns:
(dict): Internal state. Only variables visible for the user are
exported, according to its permissions.
"""
base, team = self._export()
return team if kfet_is_team(user) else base
def send_ws(self):
"""Send internal state to websocket channels."""
from .consumers import OpenKfetConsumer
base, team = self._export()
OpenKfetConsumer.group_send('kfet.open.base', base)
OpenKfetConsumer.group_send('kfet.open.team', team)
kfet_open = OpenKfet()

8
kfet/open/routing.py Normal file
View file

@ -0,0 +1,8 @@
from channels.routing import route_class
from . import consumers
routing = [
route_class(consumers.OpenKfetConsumer)
]

View file

@ -0,0 +1,50 @@
.kfetopen-st-opened .bullet { background: #73C252; }
.kfetopen-st-closed .bullet { background: #B42B26; }
.kfetopen-st-unknown .bullet { background: #D4BE4C; }
.kfetopen-st-fake_closed .bullet {
background: repeating-linear-gradient(
45deg,
#73C252, #73C252 5px, #B42B26 5px, #B42B26 10px
);
}
.kfetopen {
float: left;
}
.kfetopen .base {
height: 50px;
padding: 15px;
display: inline-flex;
align-items: center;
}
.kfetopen .details {
margin: 0;
padding: 10px !important;
min-width: 200px;
font-family: "Roboto Slab";
font-size: 16px;
color: black;
}
.kfetopen .bullet {
width: 10px;
height: 10px;
border-radius: 50%;
transition: background 0.15s;
}
.kfetopen .warning {
margin-left: 15px;
}
.kfetopen .status-text {
text-transform: uppercase;
}
.kfetopen .force-close-btn {
width: 100%;
margin-top: 5px;
}

View file

@ -0,0 +1,113 @@
var OpenWS = new KfetWebsocket({
relative_url: "open/"
});
var OpenKfet = function(force_close_url, admin) {
this.force_close_url = force_close_url;
this.admin = admin;
this.status = this.UNKNOWN;
this.dom = {
status_text: $('.kfetopen .status-text'),
force_close_btn: $('.kfetopen .force-close-btn'),
warning: $('.kfetopen .warning')
},
this.dom.force_close_btn.click( () => this.toggle_force_close() );
setInterval( () => this.refresh(), this.refresh_interval * 1000);
OpenWS.add_handler( data => this.refresh(data) );
};
OpenKfet.prototype = {
// Status is unknown after . minutes without update.
time_unknown: 15,
// Maximum interval (seconds) between two UI refresh.
refresh_interval: 20,
// Prefix for classes describing place status.
class_prefix: 'kfetopen-st-',
// Set status-classes on this dom element.
target: 'body',
// Status
OPENED: "opened",
CLOSED: "closed",
UNKNOWN: "unknown",
// Admin status
FAKE_CLOSED: "fake_closed",
// Display values
status_text: {
opened: "ouverte",
closed: "fermée",
unknown: "_____"
},
force_text: {
activate: "Fermer manuellement",
deactivate: "Réouvrir la K-Fêt"
},
get is_recent() {
return this.last_update && moment().diff(this.last_update, 'minute') <= this.time_unknown;
},
refresh: function(data) {
if (data) {
$.extend(this, data);
this.last_update = moment();
}
if (!this.is_recent)
this.status = this.UNKNOWN;
this.refresh_dom();
},
refresh_dom: function() {
let status = this.status;
this.clear_class();
this.add_class(status);
this.dom.status_text.html(this.status_text[status]);
// admin specific
if (this.admin) {
this.add_class(this.admin_status);
if (this.force_close) {
this.dom.warning.addClass('in');
this.dom.force_close_btn.html(this.force_text['deactivate']);
} else {
this.dom.warning.removeClass('in');
this.dom.force_close_btn.html(this.force_text['activate']);
}
}
},
toggle_force_close: function(password) {
$.post({
url: this.force_close_url,
data: {force_close: !this.force_close},
beforeSend: function ($xhr) {
$xhr.setRequestHeader("X-CSRFToken", csrftoken);
if (password !== undefined)
$xhr.setRequestHeader("KFetPassword", password);
}
})
.fail(function($xhr) {
switch ($xhr.status) {
case 403:
requestAuth({'errors': {}}, this.toggle_force_close);
break;
}
});
},
clear_class: function() {
let re = new RegExp('(^|\\s)' + this.class_prefix + '\\S+', 'g');
$(this.target).attr('class', (i, c) => c ? c.replace(re, '') : '');
},
add_class: function(status) {
$(this.target).addClass(this.class_prefix + status);
}
};

View file

@ -0,0 +1,13 @@
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static "kfetopen/kfet-open.css" %}">
<script type="text/javascript" src="{% static "kfetopen/kfet-open.js" %}"></script>
<script type="text/javascript">
$( function() {
kfet_open = new OpenKfet(
"{% url "kfet.open.edit_force_close" %}",
{{ perms.kfet.is_team|yesno:"true,false" }}
);
});
</script>

322
kfet/open/tests.py Normal file
View file

@ -0,0 +1,322 @@
import json
from datetime import timedelta
from django.contrib.auth.models import AnonymousUser, Permission, User
from django.test import Client
from django.utils import timezone
from channels.channel import Group
from channels.test import ChannelTestCase, WSClient
from . import kfet_open, OpenKfet
from .consumers import OpenKfetConsumer
class OpenKfetTest(ChannelTestCase):
"""OpenKfet object unit-tests suite."""
def setUp(self):
self.kfet_open = OpenKfet()
def tearDown(self):
self.kfet_open.clear_cache()
def test_defaults(self):
"""Default values."""
self.assertFalse(self.kfet_open.raw_open)
self.assertIsNone(self.kfet_open.last_update)
self.assertFalse(self.kfet_open.force_close)
self.assertFalse(self.kfet_open.is_open)
def test_raw_open(self):
"""Get and set raw_open; last_update is renewed."""
for raw_open in [True, False]:
prev_update = self.kfet_open.last_update
self.kfet_open.raw_open = raw_open
self.assertEqual(raw_open, self.kfet_open.raw_open)
self.assertNotEqual(prev_update, self.kfet_open.last_update)
def test_force_close(self):
"""Get and set force_close."""
for force_close in [True, False]:
self.kfet_open.force_close = force_close
self.assertEqual(force_close, self.kfet_open.force_close)
def test_is_open(self):
"""If force_close is disabled, is_open is raw_open."""
self.kfet_open.force_close = False
for raw_open in [True, False]:
self.kfet_open.raw_open = raw_open
self.assertEqual(raw_open, self.kfet_open.is_open)
def test_is_open_force_close(self):
"""If force_close is enabled, is_open is False."""
self.kfet_open.force_close = True
for raw_open in [True, False]:
self.kfet_open.raw_open = raw_open
self.assertFalse(self.kfet_open.is_open)
def test_status(self):
# (raw_open, force_close, expected status, expected admin)
cases = [
(False, False, OpenKfet.CLOSED, OpenKfet.CLOSED),
(False, True, OpenKfet.CLOSED, OpenKfet.CLOSED),
(True, False, OpenKfet.OPENED, OpenKfet.OPENED),
(True, True, OpenKfet.CLOSED, OpenKfet.FAKE_CLOSED),
]
for raw_open, force_close, exp_stat, exp_adm_stat in cases:
self.kfet_open.raw_open = raw_open
self.kfet_open.force_close = force_close
self.assertEqual(exp_stat, self.kfet_open.status())
self.assertEqual(exp_adm_stat, self.kfet_open.admin_status())
def test_status_unknown(self):
self.kfet_open.raw_open = True
self.kfet_open._last_update = timezone.now() - timedelta(days=30)
self.assertEqual(OpenKfet.UNKNOWN, self.kfet_open.status())
def test_export_user(self):
"""Export is limited for an anonymous user."""
export = self.kfet_open.export(AnonymousUser())
self.assertSetEqual(
set(['status']),
set(export),
)
def test_export_team(self):
"""Export all values for a team member."""
user = User.objects.create_user('team', '', 'team')
user.user_permissions.add(Permission.objects.get(codename='is_team'))
export = self.kfet_open.export(user)
self.assertSetEqual(
set(['status', 'admin_status', 'force_close']),
set(export),
)
def test_send_ws(self):
Group('kfet.open.base').add('test.open.base')
Group('kfet.open.team').add('test.open.team')
self.kfet_open.send_ws()
recv_base = self.get_next_message('test.open.base', require=True)
base = json.loads(recv_base['text'])
self.assertSetEqual(
set(['status']),
set(base),
)
recv_admin = self.get_next_message('test.open.team', require=True)
admin = json.loads(recv_admin['text'])
self.assertSetEqual(
set(['status', 'admin_status', 'force_close']),
set(admin),
)
class OpenKfetViewsTest(ChannelTestCase):
"""OpenKfet views unit-tests suite."""
def setUp(self):
# get some permissions
perms = {
'kfet.is_team': Permission.objects.get(codename='is_team'),
'kfet.can_force_close': Permission.objects.get(codename='can_force_close'),
}
# authenticated user and its client
self.u = User.objects.create_user('user', '', 'user')
self.c = Client()
self.c.login(username='user', password='user')
# team user and its clients
self.t = User.objects.create_user('team', '', 'team')
self.t.user_permissions.add(perms['kfet.is_team'])
self.c_t = Client()
self.c_t.login(username='team', password='team')
# admin user and its client
self.a = User.objects.create_user('admin', '', 'admin')
self.a.user_permissions.add(
perms['kfet.is_team'], perms['kfet.can_force_close'],
)
self.c_a = Client()
self.c_a.login(username='admin', password='admin')
def tearDown(self):
kfet_open.clear_cache()
def test_door(self):
"""Edit raw_status."""
for sent, expected in [(1, True), (0, False)]:
resp = Client().post('/k-fet/open/raw_open', {
'raw_open': sent,
'token': 'plop',
})
self.assertEqual(200, resp.status_code)
self.assertEqual(expected, kfet_open.raw_open)
def test_force_close(self):
"""Edit force_close."""
for sent, expected in [(1, True), (0, False)]:
resp = self.c_a.post('/k-fet/open/force_close', {'force_close': sent})
self.assertEqual(200, resp.status_code)
self.assertEqual(expected, kfet_open.force_close)
def test_force_close_forbidden(self):
"""Can't edit force_close without kfet.can_force_close permission."""
clients = [Client(), self.c, self.c_t]
for client in clients:
resp = client.post('/k-fet/open/force_close', {'force_close': 0})
self.assertEqual(403, resp.status_code)
class OpenKfetConsumerTest(ChannelTestCase):
"""OpenKfet consumer unit-tests suite."""
def test_standard_user(self):
"""Lambda user is added to kfet.open.base group."""
# setup anonymous client
c = WSClient()
# connect
c.send_and_consume('websocket.connect', path='/ws/k-fet/open',
fail_on_none=True)
# initialization data is replied on connection
self.assertIsNotNone(c.receive())
# client belongs to the 'kfet.open' group...
OpenKfetConsumer.group_send('kfet.open.base', {'test': 'plop'})
self.assertEqual(c.receive(), {'test': 'plop'})
# ...but not to the 'kfet.open.admin' one
OpenKfetConsumer.group_send('kfet.open.team', {'test': 'plop'})
self.assertIsNone(c.receive())
def test_team_user(self):
"""Team user is added to kfet.open.team group."""
# setup team user and its client
t = User.objects.create_user('team', '', 'team')
t.user_permissions.add(
Permission.objects.get(codename='is_team')
)
c = WSClient()
c.force_login(t)
# connect
c.send_and_consume('websocket.connect', path='/ws/k-fet/open',
fail_on_none=True)
# initialization data is replied on connection
self.assertIsNotNone(c.receive())
# client belongs to the 'kfet.open.admin' group...
OpenKfetConsumer.group_send('kfet.open.team', {'test': 'plop'})
self.assertEqual(c.receive(), {'test': 'plop'})
# ... but not to the 'kfet.open' one
OpenKfetConsumer.group_send('kfet.open.base', {'test': 'plop'})
self.assertIsNone(c.receive())
class OpenKfetScenarioTest(ChannelTestCase):
"""OpenKfet functionnal tests suite."""
def setUp(self):
# anonymous client (for views)
self.c = Client()
# anonymous client (for websockets)
self.c_ws = WSClient()
# root user
self.r = User.objects.create_superuser('root', '', 'root')
# its client (for views)
self.r_c = Client()
self.r_c.login(username='root', password='root')
# its client (for websockets)
self.r_c_ws = WSClient()
self.r_c_ws.force_login(self.r)
def tearDown(self):
kfet_open.clear_cache()
def ws_connect(self, ws_client):
ws_client.send_and_consume(
'websocket.connect', path='/ws/k-fet/open',
fail_on_none=True,
)
return ws_client.receive(json=True)
def test_scenario_0(self):
"""Clients connect."""
# test for anonymous user
msg = self.ws_connect(self.c_ws)
self.assertSetEqual(
set(['status']),
set(msg),
)
# test for root user
msg = self.ws_connect(self.r_c_ws)
self.assertSetEqual(
set(['status', 'admin_status', 'force_close']),
set(msg),
)
def test_scenario_1(self):
"""Clients connect, door opens, enable force close."""
self.ws_connect(self.c_ws)
self.ws_connect(self.r_c_ws)
# door sent "I'm open!"
self.c.post('/k-fet/open/raw_open', {
'raw_open': True,
'token': 'plop',
})
# anonymous user agree
msg = self.c_ws.receive(json=True)
self.assertEqual(OpenKfet.OPENED, msg['status'])
# root user too
msg = self.r_c_ws.receive(json=True)
self.assertEqual(OpenKfet.OPENED, msg['status'])
self.assertEqual(OpenKfet.OPENED, msg['admin_status'])
# admin says "no it's closed"
self.r_c.post('/k-fet/open/force_close', {'force_close': True})
# so anonymous user see it's closed
msg = self.c_ws.receive(json=True)
self.assertEqual(OpenKfet.CLOSED, msg['status'])
# root user too
msg = self.r_c_ws.receive(json=True)
self.assertEqual(OpenKfet.CLOSED, msg['status'])
# but root knows things
self.assertEqual(OpenKfet.FAKE_CLOSED, msg['admin_status'])
self.assertTrue(msg['force_close'])
def test_scenario_2(self):
"""Starting falsely closed, clients connect, disable force close."""
kfet_open.raw_open = True
kfet_open.force_close = True
msg = self.ws_connect(self.c_ws)
self.assertEqual(OpenKfet.CLOSED, msg['status'])
msg = self.ws_connect(self.r_c_ws)
self.assertEqual(OpenKfet.CLOSED, msg['status'])
self.assertEqual(OpenKfet.FAKE_CLOSED, msg['admin_status'])
self.assertTrue(msg['force_close'])
self.r_c.post('/k-fet/open/force_close', {'force_close': False})
msg = self.c_ws.receive(json=True)
self.assertEqual(OpenKfet.OPENED, msg['status'])
msg = self.r_c_ws.receive(json=True)
self.assertEqual(OpenKfet.OPENED, msg['status'])
self.assertEqual(OpenKfet.OPENED, msg['admin_status'])
self.assertFalse(msg['force_close'])

11
kfet/open/urls.py Normal file
View file

@ -0,0 +1,11 @@
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^raw_open$', views.raw_open,
name='kfet.open.edit_raw_open'),
url(r'^force_close$', views.force_close,
name='kfet.open.edit_force_close'),
]

32
kfet/open/views.py Normal file
View file

@ -0,0 +1,32 @@
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .open import kfet_open
TRUE_STR = ['1', 'True', 'true']
@csrf_exempt
@require_POST
def raw_open(request):
token = request.POST.get('token')
if token != settings.KFETOPEN_TOKEN:
raise PermissionDenied
raw_open = request.POST.get('raw_open') in TRUE_STR
kfet_open.raw_open = raw_open
kfet_open.send_ws()
return HttpResponse()
@permission_required('kfet.can_force_close', raise_exception=True)
@require_POST
def force_close(request):
force_close = request.POST.get('force_close') in TRUE_STR
kfet_open.force_close = force_close
kfet_open.send_ws()
return HttpResponse()

View file

@ -1,12 +1,11 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from channels.routing import include, route_class
from channels.routing import route, route_class
from kfet import consumers
from . import consumers
channel_routing = [
route_class(consumers.KPsul, path=r"^/ws/k-fet/k-psul/$"),
routing = [
route_class(consumers.KPsul, path=r'^/k-psul/$'),
include('kfet.open.routing.routing', path=r'^/open'),
]

View file

@ -1,16 +1,21 @@
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from django.contrib import messages
from django.contrib.auth.signals import user_logged_in
from django.core.urlresolvers import reverse
from django.dispatch import receiver
from django.utils.safestring import mark_safe
@receiver(user_logged_in)
def messages_on_login(sender, request, user, **kwargs):
if (not user.username == 'kfet_genericteam'
and user.has_perm('kfet.is_team')):
messages.info(request, '<a href="%s">Connexion en utilisateur partagé ?</a>' % reverse('kfet.login.genericteam'), extra_tags='safe')
if (not user.username == 'kfet_genericteam' and
user.has_perm('kfet.is_team') and
hasattr(request, 'GET') and
'k-fet' in request.GET.get('next', '')):
messages.info(request, mark_safe(
'<a href="{}" class="genericteam" target="_blank">'
' Connexion en utilisateur partagé ?'
'</a>'
.format(reverse('kfet.login.genericteam'))
))

View file

@ -0,0 +1,88 @@
/* General ------------------------- */
.btn {
border: 0;
outline: none !important;
transition: background-color, border, color, opacity;
transition-duration: 0.15s;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-family: "Roboto Slab";
}
.btn, .btn-lg, .btn-group-lg>.btn {
border-radius:0;
}
/* Default ------------------------- */
.btn-default {
background-color: transparent !important;
color: #555;
}
.btn-default:hover,
.btn-default.focus, .btn-default:focus {
color: #c8102e;
}
.btn-default[disabled]:hover, .btn-default.disabled:hover {
color: inherit !important;
}
/* Primary ------------------------- */
.btn-primary {
background-color:#c63b52;
color:#FFF;
}
.btn-primary:hover,
.btn-primary.focus, .btn-primary:focus,
.btn-primary.active.focus, .btn-primary.active:focus, .btn-primary.active:hover,
.btn-primary:active.focus, .btn-primary:active:focus, .btn-primary:active:hover {
background-color:#c8102e;
color:#FFF;
}
/* Primary + White background ------ */
.btn-primary-w {
background: white;
color: black;
}
.btn-primary-w:hover {
background: #c63b52;
color: white;
}
.btn-primary-w.focus, .btn-primary-w:focus,
.btn-primary-w.active.focus, .btn-primary-w.active:focus, .btn-primary-w.active:hover,
.btn-primary-w:active.focus, .btn-primary-w:active:focus, .btn-primary-w:active:hover {
background: #c8102e;
color: white;
}
/* Nav ----------------------------- */
.btn-nav {
background-color: transparent !important;
color: inherit;
border-bottom: 1px solid #ddd;
}
.btn-nav:hover,
.btn-nav.focus, .btn-nav:focus,
.btn-nav.active.focus, .btn-nav.active:focus, .btn-nav.active:hover,
.btn-nav:active.focus, .btn-nav:active:focus, .btn-nav:active:hover {
border-bottom: 1px solid #c8102e;
}

View file

@ -0,0 +1,151 @@
.fixed > * + * {
margin-top: 15px;
}
/* Aside --------------------------- */
/* Aside - Block */
aside {
background: white;
padding: 15px;
}
aside > * + * {
margin-top: 15px;
}
/* Aside - Misc */
aside .glyphicon-question-sign {
font-size: 0.8;
}
aside h4 {
font-weight: bold;
}
/* Aside - Heading */
aside .heading {
font-family: "Roboto Slab";
font-size: 25px;
font-weight: bold;
line-height: 1.1;
text-align: center;
}
aside .heading .big {
font-size: 2em;
}
aside .heading .sub {
font-size: 0.7em;
font-weight: normal;
}
@media (min-width: 992px) {
aside .heading {
font-size: 32px;
line-height: 1.3;
}
}
/* Aside - Buttons */
aside .buttons {
margin-left: -15px;
margin-right: -15px;
}
aside .buttons > * {
flex: 0 1 auto !important;
}
/* Aside - Text */
aside .text {
line-height: 1.3;
font-size: 14px;
}
@media (min-width: 992px) {
aside .text {
line-height: 1.6;
font-size: 16px;
}
}
aside .text ul {
margin-bottom: 0;
}
/* Buttons ------------------------- */
.fixed .buttons {
display: flex;
flex-flow: row wrap;
justify-content: center;
text-align: center;
}
.fixed .buttons > * {
flex: 0 1 auto;
overflow: hidden;
}
.fixed .buttons > .solo {
flex: 1 100%;
}
@media (min-width: 768px) {
.fixed .buttons > * {
flex: 1 auto;
}
.fixed .buttons > .full > * {
width: 100%;
}
}
.fixed .buttons .btn {
padding: 8px 12px;
}
@media (min-width: 992px) {
.fixed .buttons .btn {
font-size: 16px;
}
}
/* Tabs ---------------------------- */
.fixed .tabs-buttons {
margin-bottom: -5px;
}
.fixed .tabs-buttons > * {
margin-bottom: 5px;
}
.fixed .tabs-buttons .glyphicon-chevron-right {
margin-left: 5px;
line-height: 1.4;
color: white;
}
@media (min-width: 768px) {
.fixed .tabs-buttons {
text-align: right;
justify-content: flex-end;
}
.fixed .tabs-buttons > * {
flex: 1 100%;
}
}

View file

@ -0,0 +1,18 @@
.footer {
line-height: 40px;
background: #c63b52;
color: white;
text-align: center;
font-size: 14px;
font-family: Roboto;
}
.footer a {
color: inherit !important;
}
.footer a:hover, .footer a:focus {
text-decoration: underline;
}

View file

@ -0,0 +1,138 @@
/* Global layout ------------------- */
.main-col, .fixed-col {
padding: 0 0 15px;
}
@media (min-width: 768px) {
.fixed-col {
position: sticky;
top: 35px;
padding-top: 15px;
}
.fixed-col + .main-col {
padding: 15px 0 15px 15px;
}
}
@media (min-width: 992px) {
.main-col {
padding: 15px;
}
}
.main-col-mult {
column-gap: 45px;
}
.main-bg {
background: white;
}
.main-padding {
padding: 15px;
}
@media (min-width: 768px) {
.main-padding {
padding: 30px;
}
}
/* Section ------------------------- */
section {
margin-bottom: 15px;
position:relative;
}
section:last-child {
margin-bottom: 0;
}
/* Section - Elements -------------- */
section > * {
background: white;
padding: 15px;
}
section > .full,
section > table,
section > .table-responsive {
padding: 0 !important;
margin-left: 0 !important;
margin-right: 0 !important;
}
section .full {
margin-left: -15px;
margin-right: -15px;
}
@media (min-width: 992px) {
section > * {
padding: 30px;
}
section .full {
margin-left: -30px;
margin-right: -30px;
}
}
section .row > div:last-child {
margin-bottom: 0 !important;
}
@media (max-width: 768px) {
section .row > div {
margin-bottom: 10px;
}
}
@media (max-width: 1200px) {
section .row > div {
margin-bottom: 20px;
}
}
section ul ul {
padding-left: 30px;
}
/* Titles & Heading */
section h2,
section .heading {
background: transparent;
margin: 20px 15px 15px;
padding: 0;
border-bottom: 3px solid #c8102e;
font-family: "Roboto Slab";
font-size: 40px;
line-height: 1.1;
}
section h3 {
border-bottom: 2px solid #c8102e;
margin: 0 0 10px;
padding: 10px 0 10px;
font-size: 25px;
font-weight: bold;
}
section .heading .buttons {
opacity: 0.7;
top: 10px;
float: right;
}
section h2:first-child,
section h3:first-child {
padding-top: 0;
margin-top: 0;
}

View file

@ -0,0 +1,36 @@
.messages .alert {
padding:10px 15px;
margin:0;
border:0;
border-radius:0;
}
.messages .alert:last-child {
margin-bottom: 15px;
}
.messages .alert .close {
top:0;
right:0;
}
.messages .alert-info {
color:inherit;
background-color:#ccc;
}
.messages .alert-error {
color: white;
background-color: #c63b52;
}
.messages .alert-success {
color: white;
background: #3d9947;
}
.messages a {
font-weight: bold;
text-decoration: none;
}

View file

@ -0,0 +1,118 @@
/* General ------------------------- */
body {
margin-top:50px;
font-family:Roboto;
background:#ddd;
}
.glyphicon + span, span + .glyphicon {
margin-left: 10px;
}
/* Titles */
h1,h2,h3,h4,h5,h6 {
font-family:"Roboto Slab";
}
/* Links */
a {
color:#C8202E;
}
a:focus, a:hover {
color:#C8102E;
}
/* Inputs */
:focus {
outline:none;
}
textarea {
font-family:'Roboto Mono';
border-radius:0 !important;
}
/* Lists */
ul, ol {
padding-left: 30px;
}
ul {
list-style-type: square;
}
/* Tables */
.table {
margin-bottom:0;
border-bottom:1px solid #ddd;
width:100%;
background-color: #FFF;
}
.table td {
vertical-align:middle !important;
}
.table td.no-padding {
padding:0;
}
.table thead {
background:#c8102e;
color:#fff;
font-weight:bold;
font-size:16px;
}
.table thead td {
padding:8px !important;
}
.table tr.section {
background: #c63b52 !important;
color:#fff;
font-weight:bold;
}
.table tr.section td {
border-top:0;
font-size:16px;
padding:8px 30px;
}
.table tr.more td {
padding: 0;
}
.table-responsive {
border: 0;
margin-bottom: 0;
}
/* Toggle on hover ----------------- */
.toggle:not(:hover) .hover {
display: none;
}
.toggle:hover .base {
display: none;
}
/* Spinning animation -------------- */
.glyphicon.spinning {
animation: spin 1s infinite linear;
}
@keyframes spin {
from { transform: scale(1) rotate(0deg); }
to { transform: scale(1) rotate(360deg); }
}

View file

@ -0,0 +1,151 @@
.navbar {
background: #000;
color: #DDD;
border: 0;
font-family: Roboto;
}
.navbar .navbar-header {
float: left;
display: none;
margin-left: -15px;
margin-right: 0;
}
.navbar .navbar-brand {
padding: 3px 0;
margin: 0 15px !important;
}
.navbar .navbar-brand img {
height: 44px;
}
.navbar .navbar-toggle {
border: 0;
border-radius: 0;
padding: 18px 15px;
margin: 0;
min-width: auto;
}
.navbar .navbar-toggle .icon-bar {
background: #fff;
}
.navbar-nav {
font-size: 14px;
margin: 0 0 0 -15px;
float: left;
}
@media (min-width: 460px) {
.navbar .navbar-header {
display: block;
}
.navbar-nav {
margin-left: 0;
}
.navbar-nav .nav-pages.dropdown .dropdown-menu > li:first-child {
display: none;
}
}
.navbar-right {
float: right !important;
margin: 0 -15px 0 0;
}
.navbar-nav a {
transition: background-color, box-shadow, color;
transition-duration: 0.15s;
}
.navbar-nav > li {
float: left;
text-align: center;
}
.navbar-nav > li > a {
min-width: 50px;
padding: 15px 10px;
color: #FFF;
}
.navbar-nav > .divider {
height: 1px;
background: rgba(255, 255, 255, 0.1);
}
@media (min-width: 1200px) {
.navbar-nav > li > a {
padding-left: 15px;
padding-right: 15px;
}
}
.navbar-nav > li > a:hover, .navbar-nav > li > a:focus,
.nav .open > a:hover, .nav .open > a:focus,
.navbar-nav > li.active > a,
.navbar-nav .dropdown:hover > a, .navbar-nav .dropdown:focus > a {
background-color: #C8102E;
color: #FFF;
box-shadow: inset 0 3px 3px -4px #000;
}
.navbar-nav .dropdown .dropdown-menu {
padding: 0;
border: 0;
border-radius: 0;
background-color: #FFF;
font-size: 14px;
/* override max-width: 767px of bs */
position: absolute;
float: left;
box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
.navbar-nav .dropdown .dropdown-menu > li > a {
padding: 8px 10px;
line-height: inherit;
color: #000;
}
.navbar-nav .dropdown .dropdown-menu > li > a:hover,
.navbar-nav .dropdown .dropdown-menu > li > a:focus {
color: #c8102e;
background-color: transparent;
}
.navbar-nav .dropdown .dropdown-menu .divider {
margin: 0;
}
.navbar-nav .dropdown .dropdown-menu {
display: block;
visibility: hidden;
opacity: 0;
transition: opacity 0.15s;
}
.navbar-nav .dropdown:hover > .dropdown-menu,
.navbar-nav .dropdown:focus > .dropdown-menu,
.navbar-nav .dropdown.open > .dropdown-menu {
visibility: visible;
opacity: 1;
}
@media (min-width: 992px) {
.navbar-nav .dropdown .dropdown-menu > li > a {
padding-left: 20px;
padding-right: 20px;
}
}
.nav-app .dropdown-menu {
right: 0;
left: auto;
}

View file

@ -9,17 +9,21 @@
#history .day {
height:40px;
line-height:40px;
background-color:#c8102e;
background-color:rgba(200,16,46,1);
color:#fff;
padding-left:20px;
font-family:"Roboto Slab";
font-size:16px;
font-weight:bold;
position:sticky;
top:50px;
z-index:10;
}
#history .opegroup {
height:30px;
line-height:30px;
background-color:rgba(200,16,46,0.85);
background-color: #c63b52;
color:#fff;
font-weight:bold;
padding-left:20px;

View file

@ -1,54 +0,0 @@
ul.carte {
width: 100%;
list-style-type: none;
padding-left: 15px;
padding-right: 15px;
display: inline-block;
*display: inline;
zoom: 1;
position: relative;
clip: auto;
overflow: hidden;
}
/*
ul.carte > li {
border-style: none none solid none;
border-width: 1px;
border-color: #DDD;
}
*/
li.carte-line {
position: relative;
text-align: right;
white-space: nowrap;
}
.filler {
position: absolute;
left: 0;
right: 0;
border-bottom: 3px dotted #333;
height: 70%;
}
.carte-label {
background: white;
float: left;
padding-right: 4px;
position: relative;
max-width: calc(100% - 40px);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.carte-ukf {
background: white;
padding-left: 4px;
position: relative;
}
.unbreakable.carte-inverted .carte-ukf,
.unbreakable.carte-inverted .carte-label,
.unbreakable.carte-inverted {
background: #FFDBC7;
}

View file

@ -1,254 +1,116 @@
@import url("nav.css");
/* Libs */
@import url("libs/columns.css");
/* Libs customizations */
@import url("libs/jconfirm-kfet.css");
@import url("libs/multiple-select-kfet.css");
/* Base */
@import url("base/misc.css");
@import url("base/buttons.css");
/* Blocks */
@import url("base/main.css");
@import url("base/nav.css");
@import url("base/messages.css");
@import url("base/fixed.css");
@import url("base/footer.css");
/* Components */
@import url("kpsul.css");
@import url("jconfirm-kfet.css");
@import url("history.css");
body {
margin-top:50px;
font-family:Roboto;
background:#ddd;
.header {
padding: 15px 20px;
background-color: rgba(200,16,46,1);
color: #FFF;
}
h1,h2,h3,h4,h5,h6 {
font-family:Oswald;
}
a {
color:#333;
}
a:focus, a:hover {
color:#C8102E;
}
:focus {
outline:none;
}
textarea {
font-family:'Roboto Mono';
border-radius:0 !important;
}
.table {
margin-bottom:0;
border-bottom:1px solid #ddd;
}
.table {
width:100%;
}
.table td {
vertical-align:middle !important;
}
.table td.no-padding {
padding:0;
}
.table thead {
background:#c8102e;
color:#fff;
font-weight:bold;
font-size:16px;
}
.table thead td {
padding:8px !important;
}
.table tr.section {
background:rgba(200,16,46,0.9);
color:#fff;
font-weight:bold;
}
.table tr.section td {
border-top:0;
font-size:16px;
padding:8px 30px;
}
.btn, .btn-lg, .btn-group-lg>.btn {
border-radius:0;
}
.btn-primary {
font-family:Oswald;
background-color:rgba(200,16,46,0.9);
color:#FFF;
border:0;
}
.btn-primary:hover, .btn-primary.focus, .btn-primary:focus {
background-color:#000;
color:#FFF;
}
.row-page-header {
background-color:rgba(200,16,46,1);
color:#FFF;
border-bottom:3px solid #000;
}
.page-header {
border:0;
padding:0;
margin:15px 20px;
text-transform:uppercase;
font-weight:bold;
.header h1 {
padding: 0;
margin: 0;
font-weight: bold;
}
.nopadding {
padding: 0 !important;
}
.panel-md-margin{
background-color: white;
overflow:hidden;
padding-left: 15px;
padding-right: 15px;
padding-bottom: 15px;
padding-top: 1px;
}
@media (min-width: 992px) {
.panel-md-margin{
margin:8px;
background-color: white;
}
}
.col-content-left, .col-content-right {
padding:0;
}
.content-left-top {
background:#fff;
padding:10px 30px;
}
.content-left .buttons {
background:#fff;
}
.content-left .buttons .btn {
display:block;
}
.content-left-top.frozen-account {
background:#000FBA;
.frozen-account {
background:#5072e0;
color:#fff;
}
.content-left .block {
padding-top:25px;
.main .table a:not(.btn) {
color: inherit;
}
.content-left .block .line {
font-size:16px;
line-height:30px;
.main .table a:not(.btn):focus ,
.main .table a:not(.btn):hover {
color: #C81022;
}
.content-left .line.line-big {
font-family:Oswald;
font-size:60px;
font-weight:bold;
text-align:center;
}
.content-left .line.line-bigsub {
font-size:25px;
font-weight:bold;
text-align:center;
}
.content-left .line.balance {
font-size:45px;
text-align:center;
}
.content-right {
margin:0 15px;
}
.content-right-block {
padding-bottom:5px;
position:relative;
}
.content-right-block:last-child {
padding-bottom:15px;
}
.content-right-block > div:not(.buttons-title) {
background:#fff;
}
.content-right-block-transparent > div:not(.buttons-title) {
background-color: transparent;
}
.content-right-block .buttons-title {
position:absolute;
top:8px;
right:20px;
}
.content-right-block > div.row {
margin:0;
}
.content-right-block h2 {
margin:20px 20px 15px;
padding-bottom:5px;
border-bottom:3px solid #c8102e;
font-size:40px;
}
.content-right-block h3 {
border-bottom: 1px solid #c8102e;
margin: 20px 15px 15px;
padding-bottom: 10px;
padding-left: 20px;
font-size:25px;
}
/*
* Pages tableaux seuls
*/
.content-center > div {
background:#fff;
}
.content-center tbody tr:not(.section) td {
padding:0px 5px !important;
}
.content-center .table .form-control {
.table .form-control {
padding: 1px 12px ;
height:28px;
margin:3px 0px;
background: transparent;
}
.content-center .auth-form {
margin:15px;
.table .form-control[disabled], .table .form-control[readonly] {
background: #f5f5f5;
}
.table-condensed-input tbody tr:not(.section) td {
padding:0px 5px;
}
.table-condensed input.form-control {
margin: 0 !important;
border-top: 0;
border-bottom: 0;
border-radius: 0;
}
.auth-form {
padding: 15px 0;
background: #d86c7e;
color: white;
}
.auth-form.form-horizontal {
padding: 0;
margin: 0;
}
.auth-form .form-group {
margin-bottom: 0;
}
.auth-form input {
box-shadow: none !important;
background: transparent;
color: white;
border: 0 !important;
border-radius: 0;
border-bottom: 1px solid white !important;
}
/*
* Pages formulaires seuls
*/
.form-only .content-form {
margin:15px;
background:#fff;
padding:15px;
}
.form-only .account_create #id_trigramme {
.account_create #id_trigramme {
display:block;
width:200px;
height:80px;
@ -310,38 +172,48 @@ textarea {
padding:5px 20px;
}
/*
* Messages
/* Account autocomplete window */
#account_results ul {
list-style-type:none;
background:rgba(255,255,255,0.9);
padding:0;
}
#account_results li {
display:block;
padding:5px 20px;
height:100%;
width:100%;
}
#account_results .hilight {
background:rgba(200,16,46,0.9);
color:#fff;
text-decoration:none;
}
/**
* Stats (graphs)
*/
.messages .alert {
padding:10px 15px;
margin:0;
border:0;
border-radius:0;
.stat-nav {
margin-bottom: 10px;
font-family: Roboto;
}
.messages .alert-dismissible {
padding-right:35px;
.stat-nav li {
float: left;
}
.messages .alert .close {
top:0;
right:0;
.stat-nav a {
opacity: 0.6;
font-family: Roboto;
}
.messages .alert-info {
color:inherit;
background-color:#ccc;
}
.messages .alert-error {
color:inherit;
background-color:rgba(200,16,46,0.2);
}
.messages .alert-success {
color:#333;
.stat-nav a:hover,
.stat-nav a.focus, .stat-nav a:focus {
opacity: 1;
}
/*
@ -364,7 +236,7 @@ textarea {
margin-top:30px;
padding-top:1px;
padding-bottom:15px;
background:rgba(51,51,51,0.7);
background:rgba(51,51,51,0.9);
color:#fff;
}
@ -401,171 +273,56 @@ thead .tooltip {
height: 100px;
}
/*
* Responsive Columns
*/
.unbreakable {
display:inline-block;
width: 100%;
}
.column-row {
padding: 15px 20px;
}
.column-xs-1,
.column-sm-1,
.column-md-1,
.column-lg-1,
.column-xs-2,
.column-sm-2,
.column-md-2,
.column-lg-2,
.column-xs-3,
.column-sm-3,
.column-md-3,
.column-lg-3,
.column-xs-4,
.column-sm-4,
.column-md-4,
.column-lg-4,
.column-xs-5,
.column-sm-5,
.column-md-5,
.column-lg-5 {
-webkit-column-count: 1; /* Chrome, Safari, Opera */
-moz-column-count: 1; /* Firefox */
column-count: 1;
}
.column-xs-1 {
-webkit-column-count: 1; /* Chrome, Safari, Opera */
-moz-column-count: 1; /* Firefox */
column-count: 1;
}
.column-xs-2 {
-webkit-column-count: 2; /* Chrome, Safari, Opera */
-moz-column-count: 2; /* Firefox */
column-count: 2;
}
.column-xs-3 {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
}
.column-xs-4 {
-webkit-column-count: 4; /* Chrome, Safari, Opera */
-moz-column-count: 4; /* Firefox */
column-count: 4;
}
.column-xs-5 {
-webkit-column-count: 5; /* Chrome, Safari, Opera */
-moz-column-count: 5; /* Firefox */
column-count: 5;
}
@media (min-width: 576px) {
.column-sm-1 {
-webkit-column-count: 1; /* Chrome, Safari, Opera */
-moz-column-count: 1; /* Firefox */
column-count: 1;
}
.column-sm-2 {
-webkit-column-count: 2; /* Chrome, Safari, Opera */
-moz-column-count: 2; /* Firefox */
column-count: 2;
}
.column-sm-3 {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
}
.column-sm-4 {
-webkit-column-count: 4; /* Chrome, Safari, Opera */
-moz-column-count: 4; /* Firefox */
column-count: 4;
}
.column-sm-5 {
-webkit-column-count: 5; /* Chrome, Safari, Opera */
-moz-column-count: 5; /* Firefox */
column-count: 5;
}
}
@media (min-width: 768px) {
.column-md-1 {
-webkit-column-count: 1; /* Chrome, Safari, Opera */
-moz-column-count: 1; /* Firefox */
column-count: 1;
}
.column-md-2 {
-webkit-column-count: 2; /* Chrome, Safari, Opera */
-moz-column-count: 2; /* Firefox */
column-count: 2;
}
.column-md-3 {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
}
.column-md-4 {
-webkit-column-count: 4; /* Chrome, Safari, Opera */
-moz-column-count: 4; /* Firefox */
column-count: 4;
}
.column-md-5 {
-webkit-column-count: 5; /* Chrome, Safari, Opera */
-moz-column-count: 5; /* Firefox */
column-count: 5;
}
}
@media (min-width: 992px) {
.column-lg-1 {
-webkit-column-count: 1; /* Chrome, Safari, Opera */
-moz-column-count: 1; /* Firefox */
column-count: 1;
}
.column-lg-2 {
-webkit-column-count: 2; /* Chrome, Safari, Opera */
-moz-column-count: 2; /* Firefox */
column-count: 2;
}
.column-lg-3 {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
}
.column-lg-4 {
-webkit-column-count: 4; /* Chrome, Safari, Opera */
-moz-column-count: 4; /* Firefox */
column-count: 4;
}
.column-lg-5 {
-webkit-column-count: 5; /* Chrome, Safari, Opera */
-moz-column-count: 5; /* Firefox */
column-count: 5;
}
}
.help-block {
padding-top: 15px;
}
/* Inventaires */
.table-condensed-input input[type=number] {
text-align: center;
}
.inventory_modified {
background:rgba(236,100,0,0.15);
}
.stock_diff {
padding-left: 5px;
color:#C8102E;
color:#C8102E;
}
.inventory_update {
display:none;
display: none;
width: 50px;
margin: 0 auto;
}
/* Checkbox select multiple */
.checkbox-select-multiple label {
font-weight: normal;
margin-bottom: 0;
}
/* Statement creation */
.statement-create-summary table {
margin: 0 auto;
}
.statement-create-summary tr td {
text-align: right;
}
.statement-create-summary tr td:first-child {
padding-right: 15px;
font-weight: bold;
}
.statement-create-summary tr td:last-child {
width: 80px;
}
#detail_taken table td,
#detail_balance table td {
padding: 0;
}

View file

@ -18,6 +18,17 @@ input[type=number]::-webkit-outer-spin-button {
100% { background: yellow; }
}
/* Announcements banner */
#banner {
background-color: #d86b01;
width: 100%;
text-align: center;
padding: 10px;
color: white;
font-size: larger;
}
/*
* Top row
*/
@ -143,9 +154,10 @@ input[type=number]::-webkit-outer-spin-button {
height:50px;
padding:0 15px;
background:#c8102e;
background:rgba(200,16,46,1);
color:#fff;
font-family:"Roboto Slab";
font-weight:bold;
font-size:18px;
}
@ -226,24 +238,17 @@ input[type=number]::-webkit-outer-spin-button {
height:40px;
}
#special_operations button {
height:100%;
width:25%;
#special_operations .btn {
height:40px;
float:left;
background:#c8102e;
color:#FFF;
font-size:18px;
font-size:15px;
font-weight:bold;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
#special_operations button:focus, #special_operations button:hover {
outline:none;
background:#000;
color:#fff;
}
/* Article autocomplete */
@ -256,15 +261,14 @@ input[type=number]::-webkit-outer-spin-button {
height:100%;
float:left;
border:0;
border-right:1px solid #c8102e;
border-bottom:1px solid #c8102e;
border-radius:0;
border-bottom: 1px solid rgba(200,16,46,0.9);
font-size:16px;
font-weight:bold;
}
#article_selection input+input #article_selection input+span {
border-right:0;
#article_selection input:first-child {
border-right: 1px dashed rgba(200,16,46,0.9);
}
#article_autocomplete {
@ -313,16 +317,22 @@ input[type=number]::-webkit-outer-spin-button {
font-size:14px;
}
#articles_data table tr.article>td:first-child {
#articles_data table tr.article td:first-child {
padding-left:10px;
}
#articles_data table tr.article td + td {
padding-right:10px;
text-align:right;
}
#articles_data table tr.category {
height:35px;
background-color:#c8102e;
font-family:"Roboto Slab";
font-size:16px;
color:#FFF;
font-weight:bold;
color:#FFF;
}
#articles_data table tr.category>td:first-child {
@ -423,3 +433,7 @@ input[type=number]::-webkit-outer-spin-button {
.kpsul_middle_right_col {
overflow:auto;
}
.kpsul_middle_right_col #history .day {
top: 0;
}

View file

@ -0,0 +1,43 @@
.unbreakable {
display:inline-block;
width: 100%;
}
.column-xs-1, .column-sm-1, .column-md-1, .column-lg-1,
.column-xs-2, .column-sm-2, .column-md-2, .column-lg-2,
.column-xs-3, .column-sm-3, .column-md-3, .column-lg-3,
.column-xs-4, .column-sm-4, .column-md-4, .column-lg-4,
.column-xs-5, .column-sm-5, .column-md-5, .column-lg-5 {
column-count: 1;
}
.column-xs-1 { column-count: 1; }
.column-xs-2 { column-count: 2; }
.column-xs-3 { column-count: 3; }
.column-xs-4 { column-count: 4; }
.column-xs-5 { column-count: 5; }
@media (min-width: 768px) {
.column-sm-1 { column-count: 1; }
.column-sm-2 { column-count: 2; }
.column-sm-3 { column-count: 3; }
.column-sm-4 { column-count: 4; }
.column-sm-5 { column-count: 5; }
}
@media (min-width: 992px) {
.column-md-1 { column-count: 1; }
.column-md-2 { column-count: 2; }
.column-md-3 { column-count: 3; }
.column-md-4 { column-count: 4; }
.column-md-5 { column-count: 5; }
}
@media (min-width: 1200px) {
.column-lg-1 { column-count: 1; }
.column-lg-2 { column-count: 2; }
.column-lg-3 { column-count: 3; }
.column-lg-4 { column-count: 4; }
.column-lg-5 { column-count: 5; }
}

View file

@ -5,7 +5,7 @@
.jconfirm .jconfirm-box {
padding:0;
border-radius:0 !important;
font-family:"Roboto Mono";
font-family:Roboto;
}
.jconfirm .jconfirm-box div.title-c .title {
@ -28,7 +28,6 @@
.jconfirm .jconfirm-box .content {
border-bottom:1px solid #ddd;
padding:5px 10px;
}
.jconfirm .jconfirm-box input {
@ -37,6 +36,7 @@
border:0;
font-family:"Roboto Mono";
font-size:40px;
text-align:center;
@ -49,6 +49,7 @@
}
.jconfirm .jconfirm-box .buttons button {
min-width:40px;
height:100%;
margin:0;
margin:0 !important;
@ -84,24 +85,3 @@
padding-right: 50px;
padding-left: 50px;
}
/* Account autocomplete window */
#account_results ul {
list-style-type:none;
background:rgba(255,255,255,0.9);
padding:0;
}
#account_results li {
display:block;
padding:5px 20px;
height:100%;
width:100%;
}
#account_results .hilight {
background:rgba(200,16,46,0.9);
color:#fff;
text-decoration:none;
}

View file

@ -0,0 +1,14 @@
/**
* Multiple Select plugin customizations
*/
.ms-choice {
height: 34px !important;
line-height: 34px !important;
border: 1px solid #ccc !important;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075) !important;
}
.ms-choice > div {
top: 4px !important;
}

View file

@ -1,67 +1,88 @@
nav {
background:#000;
color:#DDD;
font-family:Oswald;
.navbar {
background: #000;
color: #DDD;
font-family: Oswald;
border: 0;
}
.navbar-nav > li > .dropdown-menu {
border:0;
border-radius:0;
.navbar .navbar-brand {
padding: 3px 25px;
}
.navbar-fixed-top {
border:0;
.navbar .navbar-brand img {
height: 44px;
}
nav .navbar-brand {
padding:3px 25px;
}
nav .navbar-brand img {
height:44px;
}
nav .navbar-toggle .icon-bar {
background-color:#FFF;
}
nav a {
color:#DDD;
.navbar .navbar-toggle .icon-bar {
background-color: #FFF;
}
.navbar-nav {
font-weight:bold;
font-size:14px;
text-transform:uppercase;
font-weight: bold;
font-size: 14px;
text-transform: uppercase;
margin: 0 -15px;
}
.nav>li>a:focus, .nav>li>a:hover {
background-color:#C8102E;
color:#FFF;
}
.nav .open>a, .nav .open>a:focus, .nav .open>a:hover {
background-color:#C8102E;
}
.dropdown-menu {
padding:0;
}
.dropdown-menu>li>a {
padding:8px 20px;
}
.dropdown-menu .divider {
margin:0;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
background-color:#FFF;
}
@media (min-width: 768px) {
.navbar-nav {
margin:0 -15px;
margin: 0px;
}
.navbar-right {
margin-right: -15px;
}
}
.navbar-nav a {
transition: background-color, box-shadow, color;
transition-duration: 0.15s;
}
.navbar-nav > li > a {
color: #FFF;
}
.navbar-nav > li:hover > a,
.navbar-nav > li > a:focus,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #C8102E;
color: #FFF;
box-shadow: inset 0 5px 5px -5px #000;
}
.navbar .dropdown .dropdown-menu {
padding: 0;
border: 0;
border-radius: 0;
background-color: #FFF;
}
.navbar .dropdown .dropdown-menu > li > a {
padding: 8px 20px;
color: #000;
}
.navbar .dropdown .dropdown-menu > li > a:hover,
.navbar .dropdown .dropdown-meny > li > a:focus {
color: #c8102e;
background-color: transparent;
}
.navbar .dropdown .dropdown-menu .divider {
margin: 0;
}
@media (min-width: 768px) {
.navbar .dropdown .dropdown-menu {
display: block;
visibility: hidden;
opacity: 0;
transition: opacity 0.15s;
}
.navbar .dropdown:hover .dropdown-menu {
visibility: visible;
opacity: 1;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

View file

@ -1,14 +1,4 @@
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).width() >= 768 && $(this).scrollTop() > 72.6) {
$('.col-content-left').css({'position':'fixed', 'top':'50px'});
$('.col-content-right').addClass('col-sm-offset-4 col-md-offset-3');
} else {
$('.col-content-left').css({'position':'relative', 'top':'0'});
$('.col-content-right').removeClass('col-sm-offset-4 col-md-offset-3');
}
});
if (typeof Cookies !== 'undefined') {
// Retrieving csrf token
csrftoken = Cookies.get('csrftoken');
@ -34,19 +24,24 @@ $(document).ready(function() {
class KfetWebsocket {
static get defaults() {
return {"relative_url": "", "default_msg": {}, "handlers": []};
return {
relative_url: '',
default_msg: {},
handlers: [],
base_path: '/ws/k-fet/'
};
}
constructor(data) {
$.extend(this, this.constructor.defaults, data);
if (window.location.pathname.startsWith('/gestion/'))
this.base_path = '/gestion' + this.base_path;
}
get url() {
var websocket_protocol = window.location.protocol == 'https:' ? 'wss' : 'ws';
var location_host = window.location.host;
var location_url = window.location.pathname.startsWith('/gestion/') ? location_host + '/gestion' : location_host;
return websocket_protocol+"://" + location_url + this.relative_url ;
get url() {
var protocol = window.location.protocol == 'https:' ? 'wss' : 'ws';
var host = window.location.host;
return protocol + "://" + host + this.base_path + this.relative_url;
}
add_handler(handler) {
@ -70,7 +65,7 @@ class KfetWebsocket {
}
var OperationWebSocket = new KfetWebsocket({
'relative_url': '/ws/k-fet/k-psul/',
'relative_url': 'k-psul/',
'default_msg': {'opegroups':[],'opes':[],'checkouts':[],'articles':[]},
});
@ -194,3 +189,13 @@ function requestAuth(data, callback, focus_next = null) {
});
}
/**
* Setup jquery-confirm
*/
jconfirm.defaults = {
confirmButton: '<span class="glyphicon glyphicon-ok"></span>',
cancelButton: '<span class="glyphicon glyphicon-remove"></span>'
};

View file

@ -7,7 +7,7 @@
var self = this;
var element = $(target);
var content = $("<div>");
var content = $("<div class='full'>");
var buttons;
function dictToArray (dict, start) {
@ -61,13 +61,12 @@
var chart = charts[i];
// format the data
var chart_data = is_time_chart ? handleTimeChart(chart.values) : dictToArray(chart.values, 1);
var chart_data = is_time_chart ? handleTimeChart(chart.values) : dictToArray(chart.values, 0);
chart_datasets.push(
{
label: chart.label,
borderColor: chart.color,
backgroundColor: chart.color,
fill: is_time_chart,
lineTension: 0,
data: chart_data,
@ -132,7 +131,7 @@
type: 'line',
options: chart_options,
data: {
labels: (data.labels || []).slice(1),
labels: data.labels || [],
datasets: chart_datasets,
}
};
@ -154,9 +153,8 @@
// initialize the interface
function initialize (data) {
// creates the bar with the buttons
buttons = $("<div>",
{class: "btn-group btn-group-justified",
role: "group",
buttons = $("<ul>",
{class: "nav stat-nav",
"aria-label": "select-period"});
var to_click;
@ -164,11 +162,9 @@
for (var i = 0; i < context.length; i++) {
// creates the button
var btn_wrapper = $("<div>",
{class: "btn-group",
role:"group"});
var btn = $("<button>",
{class: "btn btn-primary",
var btn_wrapper = $("<li>", {role:"presentation"});
var btn = $("<a>",
{class: "btn btn-nav",
type: "button"})
.text(context[i].label)
.prop("stats_target_url", context[i].url)

Some files were not shown because too many files have changed in this diff Show more