utils.py 7.46 KB
Newer Older
luxcem's avatar
luxcem committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# This file is part of django-representives.
#
# compotista 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.
#
# compotista 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 Foobar.
# If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2013 Laurent Peuch <cortex@worlddomination.be>
# Copyright (C) 2015 Arnaud Fabre <af@laquadrature.net>

# coding: utf-8

22 23 24 25 26
import sys

from django.db import transaction
from datetime import datetime

luxcem's avatar
luxcem committed
27
from representatives.models import Representative, Country, Group, Constituency
28 29

PERSONAL_FIELDS = ("first_name", "last_name", "full_name", "birth_place", "cv", "photo")
30 31 32 33 34 35 36
GENDER_DICT = dict(Representative.GENDER)


def export_a_representative(representative):
    reps = {"id": representative.remote_id}
    reps["personal"] = {field: getattr(representative, field) for field in PERSONAL_FIELDS}
    reps["personal"]["gender"] = GENDER_DICT[representative.gender]
luxcem's avatar
luxcem committed
37
    reps["personal"]["birth_date"] = representative.birth_date.isoformat().split('T')[0] if representative.birth_date else None
38 39

    reps["contact"] = {}
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

    reps["contact"]["emails"] = [{
        "email": email.email,
        "type": email.kind
    } for email in representative.email_set.all()]

    reps["contact"]["websites"] = [{
        "website": website.url,
        "type": website.kind
    } for website in representative.website_set.all()]

    reps["contact"]["phones"] = [{
        "phone": phone.number,
        "type": phone.kind, "address":
        phone.address_id,
        "id": phone.id
    } for phone in representative.phone_set.all()]
57 58

    reps["contact"]["address"] = [{
Bram's avatar
Bram committed
59
       "id": address.id,
60 61 62 63 64 65 66 67 68 69 70 71 72
       "country": {"name": address.country.name, "code": address.country.code},
       "city": address.city,
       "street": address.street,
       "number": address.number,
       "postcode": address.postcode,
       "floor": address.floor,
       "office_number": address.office_number,
       "type": address.kind,
       "geo": None,
       "phones": [phone.id for phone in address.phone_set.all()],
    } for address in representative.address_set.all()]

    reps["mandates"] = [{
73 74 75
        "name": mandate.group.name,
        "type": mandate.group.kind,
        "short_id": mandate.group.abbreviation,
76
        "url_official": mandate.url,
77
        "constituency": mandate.constituency.name,
78
        "role": mandate.role,
luxcem's avatar
luxcem committed
79 80 81
        "begin_date": mandate.begin_date.isoformat().split('T')[0] if mandate.begin_date else None,
        "end_date": mandate.end_date.isoformat().split('T')[0] if mandate.end_date else None,
        # "current": mandate.active,
82 83 84 85 86 87 88
    } for mandate in representative.mandate_set.all()]

    return reps


def export_all_representatives():
    return [export_a_representative(representative) for representative in Representative.objects.all()]
89

luxcem's avatar
luxcem committed
90 91 92
def export_active_representatives():
    return [export_a_representative(representative) for representative in Representative.objects.filter(active=True)]

93 94 95 96
def import_representatives_from_format(data, verbose=False):
    reverted_gender_dict = {x[1]: x[0] for x in Representative.GENDER}
    a = 0
    end = len(data)
luxcem's avatar
luxcem committed
97 98

    with transaction.atomic():
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        for reps in data:
            a += 1
            if verbose:
                sys.stdout.write("%s/%s\r" % (a, end))
                sys.stdout.flush()
            remote_id = reps["id"]
            representative = Representative.objects.filter(remote_id=remote_id)
            if representative:
                representative = representative[0]
            else:
                representative = Representative()
                representative.remote_id = remote_id

            representative.first_name = reps["personal"]["first_name"]
            representative.last_name = reps["personal"]["last_name"]
            representative.full_name = reps["personal"]["full_name"]
            representative.birth_place = reps["personal"]["birth_place"]
116 117 118
            representative.cv = reps["personal"]["cv"]
            representative.photo = reps["personal"]["photo"]

luxcem's avatar
luxcem committed
119 120 121 122 123
            if reps["personal"]["birth_date"]:
                representative.birth_date = datetime.strptime(reps["personal"]["birth_date"], "%Y-%m-%d")
            else:
                representative.birth_date = None

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
            representative.gender = reverted_gender_dict[reps["personal"]["gender"]]

            representative.save()

            representative.email_set.all().delete()
            for email in reps["contact"]["emails"]:
                representative.email_set.create(
                    email=email["email"],
                    kind=email["type"],
                )

            representative.website_set.all().delete()
            for website in reps["contact"]["websites"]:
                representative.website_set.create(
                    url=website["website"],
                    kind=website["type"],
                )

            addresses = {}
            representative.address_set.all().delete()
            for address in reps["contact"]["address"]:
                country = Country.objects.filter(code=address["country"]["code"])
luxcem's avatar
luxcem committed
146

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
                if not country:
                    country = Country.objects.create(
                        name=address["country"]["name"],
                        code=address["country"]["code"]
                    )
                else:
                    country = country[0]

                address_in_db = representative.address_set.create(
                    city=address["city"],
                    street=address["street"],
                    number=address["number"],
                    postcode=address["postcode"],
                    floor=address["floor"],
                    office_number=address["office_number"],
                    kind=address["type"],
                    country=country
                )

                for phone in address["phones"]:
                    addresses[phone] = address_in_db

            representative.phone_set.all().delete()
            for phone in reps["contact"]["phones"]:
                representative.phone_set.create(
                    number=phone["phone"],
                    kind=phone["type"],
                    address=addresses[phone["id"]]
                )

            representative.mandate_set.all().delete()
            for mandate in reps["mandates"]:
179

luxcem's avatar
luxcem committed
180 181 182
                constituency, created = Constituency.objects.get_or_create(
                    name=mandate['constituency']
                )
183

luxcem's avatar
luxcem committed
184 185 186 187 188
                group, created = Group.objects.get_or_create(
                    name=mandate['name'],
                    abbreviation=mandate['short_id'],
                    kind=mandate['type']
                )
189

190
                representative.mandate_set.create(
191 192
                    group=group,
                    constituency=constituency,
193 194 195 196
                    url=mandate["url_official"],
                    role=mandate["role"],
                    begin_date=mandate["begin_date"],
                    end_date=mandate["end_date"],
luxcem's avatar
luxcem committed
197
                    # active=mandate["current"],
198 199 200 201 202 203
                )

            representative.save()

    if verbose:
        sys.stdout.write("\n")