Commit 151f9eb2 authored by okhin's avatar okhin

A lot of work for #1 and adding a Phone model to keep track of last phone valid

parent 79a691cd
Pipeline #95 failed with stage
in 1 minute and 9 seconds
from picampaign.campaign.models import (Campaign, CampaignContact,
Argumentary)
from picampaign.contact.models import Phone
from picampaign.organization.serializers import GroupSerializer
from rest_framework import serializers
......@@ -17,13 +18,18 @@ class CampaignSerializer(serializers.HyperlinkedModelSerializer):
model = Campaign
fields = ('id', 'title', 'description', 'start_date', 'end_date')
class PhoneSerializer(serializers.ModelSerializer):
class Meta:
model = Phone
fields = ('id', 'phone', 'valid')
class CampaignContactSerializer(serializers.HyperlinkedModelSerializer):
full_name = serializers.ReadOnlyField(source='contact.full_name')
first_name = serializers.ReadOnlyField(source='contact.first_name')
last_name = serializers.ReadOnlyField(source='contact.last_name')
phone = serializers.ReadOnlyField(source='contact.phone')
phones = PhoneSerializer(many=True, source='contact.phones')
groups = GroupSerializer(many=True, source='contact.groups')
contact_id = serializers.ReadOnlyField(source='contact.id')
photo = serializers.ReadOnlyField(source='contact.get_photo_url')
......@@ -31,4 +37,4 @@ class CampaignContactSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = CampaignContact
fields = ('id', 'weight', 'contact_id',
'full_name', 'first_name', 'last_name', 'phone', 'groups', 'photo')
'full_name', 'first_name', 'last_name', 'phones', 'groups', 'photo')
from django.contrib import admin
from picampaign.contact.models import Contact
from picampaign.contact.models import Contact, Phone
class ContactAdmin(admin.ModelAdmin):
list_display = ['full_name', 'mail', 'phone', 'twitter']
list_display = ['full_name', 'mail', 'twitter']
search_fields = ('first_name', 'last_name')
class PhoneAdmin(admin.ModelAdmin):
list_display = ['phone', 'valid', 'contact']
search_fields = ('phone',)
admin.site.register(Phone, PhoneAdmin)
admin.site.register(Contact, ContactAdmin)
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-08 12:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contact', '0006_auto_20160807_2057'),
]
operations = [
migrations.CreateModel(
name='Phone',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('phone', models.CharField(max_length=32)),
('valid', models.BooleanField(default=False)),
],
),
migrations.RemoveField(
model_name='contact',
name='phone',
),
migrations.AddField(
model_name='phone',
name='contact',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='phones', to='contact.Contact'),
),
]
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Contact(models.Model):
"""Contact model. Person to be called by users"""
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
birthdate = models.DateField(blank=True, null=True)
phone = models.CharField(max_length=32, blank=True)
twitter = models.CharField(max_length=64, blank=True)
mail = models.CharField(max_length=255, blank=True)
photo = models.ImageField(upload_to='contacts/photos', blank=True)
......@@ -22,8 +20,25 @@ class Contact(models.Model):
'lastname': self.last_name}
full_name.admin_order_field = 'first_name'
def set_valid_phone(self, valid_phone):
"""
We want to set a phone as valid - so we must invalidate all the other ones
"""
if isinstance(valid_phone, Phone):
Phone.objects.filter(contact=self).update(valid=False)
Phone.objects.get(id=valid_phone.id).update(valid=True)
def get_photo_url(self):
if self.photo:
return self.photo.url
return ''
class Phone(models.Model):
"""Phone model, sed to keep track of which phone is working."""
id = models.AutoField(primary_key=True)
phone = models.CharField(max_length=32)
contact = models.ForeignKey(Contact, related_name='phones')
valid = models.BooleanField(default=False)
def __str__(self):
return _(u'%(phone)s') % {'phone': self.phone}
......@@ -13,7 +13,7 @@ class ImporterAdmin(admin.ModelAdmin):
"""
for obj in queryset:
obj.handle()
self.message_user(request, _("Imported %(last_imported)s of %(last_imported)s contacts") % {
self.message_user(request, _("Imported %(last_imported)s of %(last_count)s contacts") % {
'last_imported': obj.last_imported,
'last_count': obj.last_count})
import_action.short_description = _("Run the selected importers")
......
......@@ -6,8 +6,8 @@ import re
from django.db import models
from django.utils.translation import ugettext_lazy as _
from picampaign.contact.models import Contact
from picampaign.campaign.models import Campaign
from picampaign.contact.models import Contact, Phone
from picampaign.campaign.models import Campaign, CampaignContact
from picampaign.organization.models import Group, GroupType, Organization
class Importer(models.Model):
......@@ -65,7 +65,7 @@ class Importer(models.Model):
if re.match(re_mandate, key):
# We have a mandate
for mandate in item[key].split(':'):
item['mandates'].append({'kind': key.split(':')[0], 'name': mandate})
item['mandates'].append({'group': {'kind': key.split(':')[0], 'name': mandate}})
item.delete(key)
import_data.append(item)
else:
......@@ -87,24 +87,38 @@ class Importer(models.Model):
for mandate in import_mep['mandates']:
# Parltrack gives us a date starting with 9999 if ends has not happens
# FranceData gives us an empty one
if 'end_date' in mandate and (mandate['end_date'] != '' or mandate['end_date'].startswith('9999')):
# This mandate has ended
end_date = mandate.get('end_date', None)
if end_date is None:
continue
else:
if not (end_date == '' or end_date.startswith('9999')):
# This mandate has ended
continue
#import ipdb; ipdb.set_trace()
groupType, added = GroupType.objects.get_or_create(organization = self.organization,
name = mandate['kind'])
group, added = Group.objects.get_or_create(name = mandate['name'],
type = groupType)
name = mandate['group']['kind'])
if 'abbreviation' in mandate['group']:
group, added = Group.objects.get_or_create(name = mandate['group']['abbreviation'],
type = groupType)
else:
group, added = Group.objects.get_or_create(name = mandate['group']['name'],
type = groupType)
updated_mep['groups'].append(group)
#import ipdb; ipdb.set_trace()
if updated_mep['groups'] == []:
del updated_mep['groups']
# The mep have no groups active, he is not to be bothered.
continue
# All groups are done
# If we have a contact item, we can go through it. Otherwise we probably have
# phone, twitter, etc fields.
phones = []
if 'contacts' in import_mep:
# Let's get the first phone
if import_mep['contacts']['phones'] != []:
updated_mep['phone'] = import_mep['contacts']['phones'][0]['number']
for phone in import_mep['contacts']['phones']:
if phone['kind'] == "office phone":
phones.append(phone['number'])
if import_mep['contacts']['emails'] != []:
updated_mep['mail'] = import_mep['contacts']['emails'][0]['email']
if import_mep['contacts']['websites'] != []:
......@@ -115,19 +129,26 @@ class Importer(models.Model):
else:
# We have phone, mail, twitter fields
if 'phone' in import_mep:
updated_mep['phone'] = import_mep['phone']
phones.append(import_mep['phone'])
if 'mail' in import_mep:
updated_mep['mail'] = import_mep['phone']
if 'twitter' in import_mep:
updated_mep['twitter'] = import_mep['twitter']
#import ipdb; ipdb.set_trace()
# Let's update_or_create the mep
mep, updated = Contact.objects.update_or_create(first_name=import_mep['first_name'],
last_name=import_mep['last_name'],
birthdate=import_mep['birth_date'],
defaults=updated_mep
)
# We want to create the phones
for phone in phones:
mep.phones.get_or_create(phone=phone)
# We want to link the mep to our current campaign
CampaignContact(campaign=self.campaign, contact=mep).save()
inserted += 1
self.last_imported = inserted
self.save()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment