Commit 80479bde authored by Arnaud Fabre's avatar Arnaud Fabre
Browse files

updates legislature

parent 36b2b071
from __future__ import absolute_import
from django.contrib import admin from django.contrib import admin
from representatives.models import Email, WebSite, Address, Phone, Country, Constituency from representatives.models import Email, WebSite, Address, Phone, Country
from legislature.models import MMandate, MRepresentative, MGroup from .models import MemopolRepresentative
class EmailInline(admin.TabularInline): class EmailInline(admin.TabularInline):
...@@ -24,10 +26,15 @@ class PhoneInline(admin.TabularInline): ...@@ -24,10 +26,15 @@ class PhoneInline(admin.TabularInline):
extra = 0 extra = 0
class RepresentativeAdmin(admin.ModelAdmin): class CountryInline(admin.TabularInline):
list_display = ('full_name', 'gender', 'birth_place') model = Country
extra = 0
class MemopolRepresentativeAdmin(admin.ModelAdmin):
list_display = ('full_name', 'country', 'score')
search_fields = ('first_name', 'last_name', 'birth_place') search_fields = ('first_name', 'last_name', 'birth_place')
list_filter = ('gender', ) list_filter = ('gender', 'active')
inlines = [ inlines = [
PhoneInline, PhoneInline,
EmailInline, EmailInline,
...@@ -35,18 +42,18 @@ class RepresentativeAdmin(admin.ModelAdmin): ...@@ -35,18 +42,18 @@ class RepresentativeAdmin(admin.ModelAdmin):
AdressInline, AdressInline,
] ]
class MandateAdmin(admin.ModelAdmin): # class MandateAdmin(admin.ModelAdmin):
list_display = ('representative', 'group', 'role', 'constituency', 'begin_date', 'end_date', 'active') # list_display = ('representative', 'group', 'role', 'constituency', 'begin_date', 'end_date', 'active')
search_fields = ('representative', 'group', 'constituency') # search_fields = ('representative', 'group', 'constituency')
# list_filter = ('role',) # list_filter = ('role',)
admin.site.register(MRepresentative, RepresentativeAdmin) # admin.site.register(Representative, RepresentativeAdmin)
admin.site.register(MemopolRepresentative, MemopolRepresentativeAdmin)
# admin.site.register(Country) # admin.site.register(Country)
admin.site.register(MMandate, MandateAdmin) # admin.site.register(MemopolMandate, MandateAdmin)
admin.site.register(MGroup) # admin.site.register(MemopolGroup)
# admin.site.register(Constituency) # admin.site.register(Constituency)
import datetime
from django.core.management.base import BaseCommand
from representatives.models import Mandate
from django.db import transaction
class Command(BaseCommand):
@transaction.atomic
def handle(self, *args, **options):
date = datetime.datetime.now().date()
mandates = Mandate.objects.all()
n = len(mandates)
for i, mandate in enumerate(mandates):
mandate.active = mandate.end_date > date
mandate.save()
print("%s/%s\r" % (i, n)),
# import datetime from __future__ import absolute_import
from django.core.management.base import BaseCommand
from representatives import models
from legislature.models import MRepresentative, MMandate, MGroup
from django.db import transaction from django.db import transaction
from django.core.management.base import BaseCommand
import pyprind
class Command(BaseCommand): import representatives.models
import legislature.models
class Command(BaseCommand):
@transaction.atomic @transaction.atomic
def handle(self, *args, **options): def handle(self, *args, **options):
# Representatives bar = pyprind.ProgBar(representatives.models.Representative.objects.all().count())
print('Representatives') for i, representative in enumerate(representatives.models.Representative.objects.all()):
n = models.Representative.objects.all().count() try:
for i, representative in enumerate(models.Representative.objects.all()): memopol_representative = legislature.models.MemopolRepresentative.objects.get(
mrepresentative = MRepresentative(representative_ptr=representative) representative_remote_id = representative.remote_id
mrepresentative.__dict__.update(representative.__dict__) )
mrepresentative.save() except legislature.models.MemopolRepresentative.DoesNotExist:
print("%s/%s\r" % (i, n)), memopol_representative = legislature.models.MemopolRepresentative(
representative_remote_id = representative.remote_id
print('Mandates') )
for i, mrepresentative in enumerate(MRepresentative.objects.all()): memopol_representative.representative_ptr_id = representative.pk
representative = mrepresentative.representative_ptr
for mandate in representative.mandate_set.all(): memopol_representative.__dict__.update(representative.__dict__)
mmandate = MMandate(mandate_ptr=mandate) memopol_representative.save()
mmandate.__dict__.update(mandate.__dict__) memopol_representative.update_country()
mmandate.mrepresentative = mrepresentative
bar.update()
# Group creation
try: for i, group_item in enumerate(representatives.models.Group.objects.all()):
mgroup = MGroup.objects.get(group_ptr=mandate.group) memopol_group, _ = legislature.models.MemopolGroup.objects.get_or_create(
except MGroup.DoesNotExist: group = group_item
mgroup = MGroup(group_ptr=mandate.group) )
mgroup.__dict__.update(mandate.group.__dict__) memopol_group.__dict__.update(group_item.__dict__)
mgroup.save() memopol_group.update_active()
memopol_group.save()
mmandate.mgroup = mgroup
mmandate.save()
mmandate.update_active()
mrepresentative.update_country()
# mrepresentative.update_active()
mrepresentative.save()
print("%s/%s\r" % (i, n)),
print('Groups')
for i, mgroup in enumerate(MGroup.objects.all()):
mgroup.update_active()
import pyprind
from django.core.management.base import BaseCommand
from legislature.models import MemopolRepresentative
class Command(BaseCommand):
def handle(self, *args, **options):
bar = pyprind.ProgBar(MemopolRepresentative.objects.all().count())
for representative in MemopolRepresentative.objects.all():
representative.update_score()
bar.update(item_id = str(representative))
...@@ -7,14 +7,14 @@ from django.db import models, migrations ...@@ -7,14 +7,14 @@ from django.db import models, migrations
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
('representatives', '0007_auto_20150323_1017'), ('representatives', '0001_initial'),
] ]
operations = [ operations = [
migrations.CreateModel( migrations.CreateModel(
name='MGroup', name='MemopolGroup',
fields=[ fields=[
('group_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='representatives.Group')), ('group', models.OneToOneField(parent_link=True, primary_key=True, serialize=False, to='representatives.Group')),
('active', models.BooleanField(default=False)), ('active', models.BooleanField(default=False)),
], ],
options={ options={
...@@ -22,30 +22,15 @@ class Migration(migrations.Migration): ...@@ -22,30 +22,15 @@ class Migration(migrations.Migration):
bases=('representatives.group',), bases=('representatives.group',),
), ),
migrations.CreateModel( migrations.CreateModel(
name='MMandate', name='MemopolRepresentative',
fields=[
('mandate_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='representatives.Mandate')),
('active', models.BooleanField(default=False)),
('mgroup', models.ForeignKey(to='legislature.MGroup')),
],
options={
},
bases=('representatives.mandate',),
),
migrations.CreateModel(
name='MRepresentative',
fields=[ fields=[
('representative_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='representatives.Representative')), ('representative_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='representatives.Representative')),
('representative_remote_id', models.CharField(unique=True, max_length=255)),
('score', models.IntegerField(default=0)),
('country', models.ForeignKey(to='representatives.Country', null=True)), ('country', models.ForeignKey(to='representatives.Country', null=True)),
], ],
options={ options={
}, },
bases=('representatives.representative',), bases=('representatives.representative',),
), ),
migrations.AddField(
model_name='mmandate',
name='mrepresentative',
field=models.ForeignKey(to='legislature.MRepresentative'),
preserve_default=True,
),
] ]
from django.db import models # coding: utf-8
import representatives
import datetime
class MRepresentative(representatives.models.Representative): # This file is part of memopol.
# active = models.BooleanField(default=False) #
country = models.ForeignKey(representatives.models.Country, null=True) # memopol is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or any later version.
#
# memopol is distributed in the hope that it will
# be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU General Affero Public
# License along with django-representatives.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2015 Arnaud Fabre <af@laquadrature.net>
def active_mandates(self): from datetime import datetime
return self.mmandate_set.filter(active=True)
def former_mandates(self): from django.db import models
return self.mmandate_set.filter(active=False) from django.core.exceptions import ObjectDoesNotExist
def current_group_mandate(self):
return self.mmandate_set.get(
active=True,
group__kind='group'
)
def update_active(self): from representatives.models import Representative, Group, Country
# If a representative has at least one active manadate from representatives_votes.models import Vote
self.active = False
for mandate in self.mmandate_set.all():
if mandate.active:
self.active = True
break
class MemopolRepresentative(Representative):
representative_remote_id = models.CharField(max_length=255, unique=True)
country = models.ForeignKey(Country, null=True)
score = models.IntegerField(default=0)
def update_score(self):
score = 0
for vote in self.representative.votes.all():
proposal = vote.m_proposal
if proposal.recommendation:
recommendation = proposal.recommendation
if vote.position != recommendation.recommendation:
score -= recommendation.weight
else:
score += recommendation.weight
self.score = score
self.save() self.save()
def update_country(self): def update_country(self):
# Create a country if it does not exist # Create a country if it does'nt exist
# The representative's country is the one associated # The representative's country is the one associated
# with the last 'country' mandate # with the last 'country' mandate
country_mandate = self.mmandate_set.filter( try:
group__kind='country' country_mandate = self.mandates.filter(
).order_by('-begin_date')[0:1].get() group__kind='country'
).order_by('-begin_date')[0:1].get()
country, _ = Country.objects.get_or_create(
name=country_mandate.group.name,
code=country_mandate.group.abbreviation
)
self.country = country
self.save()
country, created = representatives.models.Country.objects.get_or_create( except ObjectDoesNotExist:
name=country_mandate.group.name, self.country = None
code=country_mandate.group.abbreviation self.save()
# @property
# def votes(self):
# return Vote.objects.filter(
# representative_remote_id = self.remote_id
# )
def active_mandates(self):
return self.mandates.filter(
end_date__gte=datetime.now()
) )
self.country = country
self.save()
def former_mandates(self):
return self.mandates.filter(
end_date__lte=datetime.now()
)
def current_group_mandate(self):
return self.mandates.get(
end_date__gte=datetime.now(),
group__kind='group'
)
class MGroup(representatives.models.Group): class MemopolGroup(Group):
group = models.OneToOneField(
Group,
parent_link = True
)
active = models.BooleanField(default=False) active = models.BooleanField(default=False)
def update_active(self): def update_active(self):
self.active = False self.active = False
for mandate in self.mmandate_set.all(): for mandate in self.mandates.all():
if mandate.active: if mandate.end_date > datetime.date(datetime.now()):
self.active = True self.active = True
break break
self.save() self.save()
class MMandate(representatives.models.Mandate):
active = models.BooleanField(default=False)
mgroup = models.ForeignKey(MGroup)
mrepresentative = models.ForeignKey(MRepresentative)
def update_active(self):
date = datetime.datetime.now().date()
self.active = self.end_date > date
self.save()
-# List representatives' groups
- extends 'base.html' - extends 'base.html'
- load by_mandate_url - load by_group_url
- block content - block content
%ul %ul
......
- load by_mandate_url - load by_group_url
%td %td
%a{'href': "{% url 'legislature:representative_view_by_name' representative.full_name %}"} %a{'href': "{% url 'legislature:representative_view_by_name' representative.full_name %}"}
...@@ -13,5 +13,5 @@ ...@@ -13,5 +13,5 @@
={representative.country.name} ={representative.country.name}
%td %td
%a{'href': "{{ representative.current_group_mandate|by_mandate_url }}"} %a{'href': "{{ representative.current_group_mandate|by_group_url }}"}
={representative.current_group_mandate.mgroup.abbreviation} ={representative.current_group_mandate.group.abbreviation}
-# List representatives
- extends 'base.html'
- load by_group_url
- block content
%p{:style => "float: left"}
%img{:src => "{{ representative.photo }}"}/
%h1= representative.full_name
%p
%strong
%a{:href => "{{ representative.current_group_mandate|by_group_url }}"}
{{ representative.current_group_mandate.role }} of
{{ representative.current_group_mandate.group.name }}
%p
Born in {{ representative.birth_place }} the
{{ representative.birth_date }} ({{ representative.get_gender_display }})
%p= representative.country.name
-# Mandates
%h2{:style => "clear: both"} Mandates
- for mandate in representative.active_mandates
.mandate
%h3
{{ mandate.group.name }}
%small= mandate.role
%p
{{ mandate.begin_date }} to {{ mandate.end_date }} <br>
%a{:href => "{{ mandate|by_group_url }}"}
%strong {{ mandate.group.kind }} :
%em {{ mandate.group.name }} ({{ mandate.group.abbreviation }}) <br>
Constituency : {{ mandate.constituency.name }} <br>
%hr/
-# Former mandates
%h2{:style => "clear: both"} Former mandates
- for mandate in representative.former_mandates
.mandate
%h3
{{ mandate.group.name }}
%small= mandate.role
%p
{{ mandate.begin_date }} to {{ mandate.end_date }} <br>
%a{:href => "{{ mandate|by_group_url }}"}
%strong {{ mandate.group.kind }} :
%em {{ mandate.group.name }} ({{ mandate.group.abbreviation }}) <br>
Constituency : {{ mandate.constituency.name }} <br>
%hr/
{% extends 'base.html' %}
{% load by_group_url %}
{% block content %}
<p style="float: left">
<img src="{{ representative.photo }}">
</p>
<h1>{{ representative.full_name }}</h1>
<p>
<strong>
<a href="{{ representative.current_group_mandate|by_mandate_url }}">
{{ representative.current_group_mandate.role }} of {{ representative.current_group_mandate.mgroup.name }}
</a>
</strong>
</p>
<p>Born in {{ representative.birth_place }} the {{ representative.birth_date }} ({{ representative.get_gender_display }})</p>
<p>{{ representative.country.name }}</p>
<h2 style="clear: both">Mandates</h2>
{% for mandate in representative.active_mandates %}
<div class="mandate">
<h3>
{{ mandate.group.name }}
<small>
{{ mandate.role }}
</small>
</h3>
<p>
{{ mandate.begin_date }} to {{ mandate.end_date }} <br>
<a href="{{ mandate|by_mandate_url }}">
<strong>{{ mandate.group.kind }}</strong> : <em>{{ mandate.group.name }} ({{ mandate.group.abbreviation }})</em>
</a>
<br>
Constituency : {{ mandate.constituency.name }} <br>
</p>
</div>
<hr>
{% endfor %}
<h2>Former mandates</h2>
{% for mandate in representative.former_mandates %}
<div class="mandate">
<h3>
{{ mandate.group.name }}
<small>
{{ mandate.role }}
</small>
</h3>
<p>
{{ mandate.begin_date }} to {{ mandate.end_date }} <br>
<strong>{{ mandate.group.kind }}</strong> : <em>{{ mandate.group.name }} ({{ mandate.group.abbreviation }})</em> <br>
Constituency : {{ mandate.constituency.name }} <br>
</p>
</div>
<hr>
{% endfor %}
{% endblock %}
from django import template from django import template
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from representatives.models import Mandate
register = template.Library() register = template.Library()
@register.filter @register.filter
def by_group_url(group): def by_group_url(group):
if isinstance(group, Mandate):
group = group.group
kwargs = {'group_kind': group.kind} kwargs = {'group_kind': group.kind}
if group.abbreviation: if group.abbreviation:
...@@ -13,12 +18,9 @@ def by_group_url(group): ...@@ -13,12 +18,9 @@ def by_group_url(group):
else: else:
kwargs['search'] = group.name kwargs['search'] = group.name