conscribosync.py 4.35 KB
Newer Older
1 2 3 4 5
import logging

from django.conf import settings
from django.core.management.base import BaseCommand
from django.template.defaultfilters import date
6
from django.utils import translation
7 8 9
from requests import HTTPError

from members.models import Member
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
10 11
from utils.conscribo.api import ConscriboApi
from utils.conscribo.objects import Command as ApiCommand, ResultException
12 13 14 15 16 17 18 19 20 21 22 23 24 25

logger = logging.getLogger(__name__)


class Command(BaseCommand):

    def handle(self, *args, **options):
        api = ConscriboApi(settings.CONSCRIBO_ACCOUNT,
                           settings.CONSCRIBO_USER,
                           settings.CONSCRIBO_PASSWORD)

        try:
            relations_response = api.single_request(
                'listRelations',
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
26
                entityType='lid_2',
27 28 29 30 31 32 33 34 35 36 37 38
                requestedFields={
                    'fieldName': ['website_id', 'code']
                },
            )
            relations_response.raise_for_status()
            relations_response = relations_response.data

            current_relations = {}
            if len(relations_response.get('relations')) > 0:
                current_relations = {
                    int(r.get('website_id')): r.get('code', None)
                    for r in relations_response.get('relations').values()
39
                    if r.get('website_id', '') != ''
40 41 42
                }

            replace_commands = []
43 44 45 46
            with translation.override('nl'):
                for member in Member.current_members.all():
                    code = current_relations.pop(member.pk, None)
                    profile = member.profile
47

48 49
                    if member.bank_accounts.exists():
                        account = member.bank_accounts.last()
50
                        mandate_no = account.mandate_no
51
                        mandate_date = date(account.created_at, 'Y-m-d')
52 53 54 55 56 57
                        bank_account = {
                            'name': account.name,
                            'bic': account.bic or '',
                            'iban': account.iban,
                        }
                    else:
58
                        mandate_no = ''
59
                        mandate_date = ''
60 61 62 63 64 65
                        bank_account = {
                            'name': '',
                            'bic': '',
                            'iban': '',
                        }

66 67 68 69 70 71 72 73 74 75 76 77
                    fields = {
                        'website_id': member.pk,
                        'voornaam': member.first_name,
                        'naam': member.last_name[:100],  # api maxlength: 100
                        'einddatum_lidmaatschap':
                            date(member.current_membership.until, 'Y-m-d'),
                        'e_mailadres': member.email,
                        'eerste_adresregel': profile.address_street,
                        'tweede_adresregel': profile.address_street2,
                        'postcode': profile.address_postal_code,
                        'plaats': profile.address_city,
                        'land': profile.get_address_country_display(),
78
                        'bankrekeningnummer': bank_account,
79 80
                        'machtigingskenmerk': mandate_no,
                        'machtigingsdatum': mandate_date
81
                    }
82

83 84 85 86 87 88
                    replace_commands.append(ApiCommand(
                        command='ReplaceRelation',
                        entityType='lid_2',
                        fields=fields,
                        code=code,
                    ))
89

90 91 92 93 94
            replace_responses = api.multi_request(replace_commands)
            for response in replace_responses:
                if not response.success:
                    logger.debug(response.notifications)

95
            delete_commands = []
96
            for code in current_relations.values():
97 98
                delete_commands.append(ApiCommand(
                    command='DeleteRelation',
99
                    entityType='lid_2',
100 101 102 103 104 105 106 107 108 109 110
                    code=code,
                ))

            delete_responses = api.multi_request(delete_commands)
            for response in delete_responses:
                if not response.success:
                    logger.debug(response.notifications)
        except HTTPError as e:
            logger.error('HTTP error syncing relations to Conscribo', e)
        except ResultException as e:
            logger.error('Server error syncing relations to Conscribo', e)