migratemembers.py 12.8 KB
Newer Older
1 2 3 4 5
import json
import os

import requests
from bs4 import BeautifulSoup
6
from django.conf import settings
7
from django.contrib.auth.models import User
8
from django.core.exceptions import ImproperlyConfigured
9
from django.core.files.base import ContentFile
10
from django.core.management.base import BaseCommand
11
from django.utils.dateparse import parse_date
12
from django.utils.translation import activate
13

14 15
from activemembers.models import (Board, Committee,
                                  CommitteeMembership, Mentorship)
Joost Rijneveld's avatar
Joost Rijneveld committed
16
from members.models import Member, Membership
17 18 19 20 21 22 23 24 25 26 27


def imagefield_from_url(imagefield, url):
    file = ContentFile(requests.get(url).content)
    imagefield.save(os.path.basename(url), file)


class Command(BaseCommand):
    help = "Migrates members and related committees / memberships"

    def handle(self, *args, **options):
28
        activate('en')
29 30 31 32 33
        if not settings.MIGRATION_KEY:
            raise ImproperlyConfigured("MIGRATION_KEY not specified")
        url = "https://thalia.nu/api/members_export.php?apikey={}".format(
            settings.MIGRATION_KEY
        )
34
        print("Querying concrete5.. this may take a while")
35 36
        data = json.loads(requests.get(url).text)

37
        groups = {}
38
        mentorgroups = {}
39

40 41 42 43
        board_url = "https://thalia.nu/board/2015-2016"
        soup = BeautifulSoup(requests.get(board_url).text, 'lxml')
        default_board_photo = ("https://thalia.nu/application/files/"
                               "6614/3560/3446/site_logo_board.png")
44
        print("Migrating boards..")
45
        for board in data['boards']:
46 47
            obj, cr = Board.objects.get_or_create(name_nl=board['name'])
            obj.name_en = board['name']
48 49 50
            year = int(board['name'][-9:-5])
            obj.since = parse_date('{}-09-01'.format(year))
            obj.until = parse_date('{}-08-31'.format(year+1))
51
            print(obj.name_en)
52
            groups[board['gID']] = obj
53 54 55 56 57
            img = soup.find("img", {"alt": board['name'][8:]})
            if img:
                imagefield_from_url(obj.photo, img['src'])
            else:
                imagefield_from_url(obj.photo, default_board_photo)
58
            obj.save()
59

60 61 62 63
        for mentorgroup in data['mentors']:
            mentorgroups[mentorgroup['gID']] = int(mentorgroup['name'][-4:])

        print("Migrating committees..")
64 65 66 67 68
        committee_url = "https://thalia.nu/committees"
        soup = BeautifulSoup(requests.get(committee_url).text, 'lxml')
        anchors = soup.find('ul', {'class': 'row committees'}).find_all('a')
        links = {anchor.find('h2').text: anchor['href'] for anchor in anchors}
        for committee in data['committees']:
69 70 71
            obj, cr = Committee.objects.get_or_create(
                name_nl=committee['name'])
            obj.name_en = committee['name']
72 73
            # Committees are active by default
            obj.active = True
74
            print(obj.name_en)
75 76
            groups[committee['gID']] = obj
            obj.save()
77 78 79 80 81
            if committee['name'] not in links:
                continue
            src = requests.get(links[committee['name']]).text
            soup = BeautifulSoup(src, 'lxml')
            div = soup.find('div', {'id': 'committee-div'})
82 83
            obj.description_en = div.find('p').text
            obj.description_nl = div.find('p').text
84 85 86
            img = div.find('img')
            imagefield_from_url(obj.photo, "https://thalia.nu" + img['src'])

87
        for memberno, member in enumerate(data['members']):
88
            user, cr = User.objects.get_or_create(username=member['username'])
89 90 91
            print("Migrating {} ({}/{})".format(member['username'],
                                                memberno,
                                                len(data['members'])))
92 93 94 95 96
            user.username = member['username']
            user.email = member['email']
            # Concrete5 uses bcrypt passwords, which django can rehash
            user.password = 'bcrypt$' + member['password']
            user.first_name = member['first_name']
Joost Rijneveld's avatar
Joost Rijneveld committed
97
            user.last_name = ' '.join([member['infix'],
98
                                       member['surname']]).strip()[:30]
99
            user.save()
100 101 102
            try:
                user.member
            except Member.DoesNotExist:
103 104
                user.member = Member()
            user.member.programme = {
105
                'Computer Science': 'computingscience',
106 107
                'Information Science': 'informationscience',
                'Other': None,
108
                '': None,
109 110
            }[member['study']]
            if member['student_number']:
111 112 113
                if not len(member['student_number']) == 8:
                    member['student_number'] = 's' + member['student_number']
                user.member.student_number = member['student_number']
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
            if member['member_since']:
                # This is as best as we can do, although this may be incorrect
                user.member.starting_year = member['member_since']
            user.member.address_street = member['address1']
            if member['address2']:
                user.member.address_street2 = member['address2']
            user.member.address_city = member['city']
            user.member.address_postal_code = member['postalcode']
            if member['mobile_number']:
                user.member.phone_number = member['mobile_number']
            elif member['phone_number']:
                user.member.phone_number = member['phone_number']
            if member['phone_number_parents']:
                user.member.emergency_contact = '[default: Parents]'
                user.member.emergency_contact_phone_number = (
                    member['phone_number_parents'])
            if member['birthday']:
                user.member.birthday = member['birthday'].split(' ')[0]
132 133 134 135 136
                if user.member.birthday == "0000-00-00":
                    user.member.birthday = None
                elif user.member.birthday[:3] == "201":  # Likely incorrect!
                    user.member.birthday = None

137 138 139 140 141 142
            user.member.show_birthday = bool(member['show_birthday'])
            if member['website']:
                user.member.website = member['website']
            if member['about']:
                user.member.profile_description = member['about']
            if member['nickname']:
143
                user.member.nickname = member['nickname'][:30]
144 145 146 147 148
            if member['initials']:
                user.member.initials = member['initials']
            user.member.display_name_preference = {
                'Full name': 'full',
                'Initials and last name': 'initials',
149
                'First name': 'firstname',
150 151 152
                'Nickname': 'nickname',
                'First name + nickname + last name': 'fullnick',
                'Nickname + last name': 'nicklast',
153
                '': 'full',
154 155 156 157 158
            }[member['display_name']]
            if member['avatar']:
                imagefield_from_url(user.member.photo, member['avatar'])
            if member['language']:
                user.member.language = member['language']
159
            user.member.receive_optin = bool(member['receive_optin_mail'])
160 161 162 163
            user.member.direct_debit_authorized = (
                member['payment_authorised'] == 'Authorised')
            if member['payment_iban']:
                user.member.bank_account = member['payment_iban']
164
            user.member.save()
165

Joost Rijneveld's avatar
Joost Rijneveld committed
166 167 168 169 170 171 172 173 174 175 176 177
            membership = Membership()
            membership.user = user
            if member['membership_type'] == 'Benefactor':
                membership.type = 'supporter'
                membership.until = parse_date("2017-09-01")
            if member['membership_type'] == 'Yearly Membership':
                membership.type = 'member'
                membership.until = parse_date("2017-09-01")
            if member['membership_type'] == 'Study Membership':
                membership.type = 'member'
            if member['membership_type'] == 'Honorary Member':
                membership.type = 'honorary'
178 179 180

            if membership.type is not None and membership.type != '':
                membership.save()
Joost Rijneveld's avatar
Joost Rijneveld committed
181

182 183
            for membership in member['memberships']:
                mdata = membership['membership']
184 185 186 187 188
                if not mdata['begindate'] or mdata['begindate'][:4] == '0000':
                    mdata['begindate'] = '1970-01-01'  # Manually fix this
                for p in membership['presidencies'] + membership['roles']:
                    if not p['begindate'] or p['begindate'][:4] == '0000':
                        p['begindate'] = '1970-01-01'
189

190 191 192 193 194
                if mdata['gID'] in mentorgroups:
                    m, cr = Mentorship.objects.get_or_create(
                                year=mentorgroups[mdata['gID']],
                                member=user.member)
                    m.save()
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
                if mdata['gID'] not in groups:
                    continue  # These are concrete5 groups (Admin, etc..)
                group = groups[mdata['gID']]
                dates = ([p['begindate'] for p in membership['presidencies']] +
                         [p['enddate'] for p in membership['presidencies']] +
                         [r['begindate'] for r in membership['roles']] +
                         [r['enddate'] for r in membership['roles']] +
                         [mdata['begindate']])
                dates = set(dates)
                try:
                    dates.remove(mdata['enddate'])
                    dates.remove(None)
                except KeyError:
                    pass  # Silence if enddate or None do not appear
                if not dates:
                    dates = {'1970-01-01'}  # Manually fix where this appears
                newmship = None
                for date in sorted(dates):
                    if newmship:
                        newmship.until = parse_date(date)
                        newmship.save()
                    newmship = CommitteeMembership()
                    newmship.member = user.member
                    newmship.committee = group
                    newmship.since = parse_date(date)
                    presidencies = [p for p in membership['presidencies']
                                    if p['begindate'] >= date and
                                    (not p['enddate'] or date < p['enddate'])]
                    if len(presidencies) >= 1:
                        newmship.chair = True
                    roles = [r['role'] for r in membership['roles']
                             if r['begindate'] >= date and
                             (not r['enddate'] or date < r['enddate'])]
                    if len(roles) >= 1:
                        newmship.role_nl = ' / '.join(roles)
                        newmship.role_en = ' / '.join(roles)
                if mdata['enddate'] is not None:
                    if newmship.since != parse_date(mdata['enddate']):
                        newmship.until = parse_date(mdata['enddate'])
                        newmship.save()
                else:
                    newmship.save()
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

            for m in CommitteeMembership.objects.filter(member=user.member):
                ms = (CommitteeMembership.objects
                                         .filter(committee_id=m.committee_id,
                                                 member_id=m.member_id,
                                                 since=m.until,
                                                 chair=m.chair,
                                                 role_en=m.role_en,
                                                 role_nl=m.role_nl,
                                                 ))
                if not ms:
                    continue
                if len(ms) > 1:
                    raise Exception("Could not merge more than one membership")
                m.until = ms[0].until
                m.save()
                ms[0].delete()

        print("Sanitizing board memberships")
        for m in CommitteeMembership.objects.all():
            try:
                if m.committee.board:
                    m.since = parse_date(
                        '{}-09-01'.format(m.committee.name_nl[8:12]))
                    m.until = parse_date(
                        '{}-09-01'.format(m.committee.name_nl[13:17]))
                    m.save()
            except Board.DoesNotExist:
                pass

        # remove duplicates to be sure
        print("Cleaning up duplicates")
        for m in CommitteeMembership.objects.all():
            if (CommitteeMembership.objects
                                   .filter(committee_id=m.committee_id,
                                           member_id=m.member_id,
                                           since=m.since,
                                           chair=m.chair,
                                           role_en=m.role_en,
                                           role_nl=m.role_nl)
                                   .count()) > 1:
                m.delete()