Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#929] Refactor contacts #348

Merged
merged 13 commits into from
Dec 6, 2022
35 changes: 8 additions & 27 deletions src/open_inwoner/accounts/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from open_inwoner.utils.mixins import UUIDAdminFirstInOrder

from .models import Action, Appointment, Contact, Document, Invite, Message, User
from .models import Action, Appointment, Document, Invite, Message, User


class ActionInlineAdmin(UUIDAdminFirstInOrder, admin.StackedInline):
Expand All @@ -25,7 +25,7 @@ class _UserAdmin(UserAdmin):
"first_name",
)
fieldsets = (
(None, {"fields": ("email", "password", "login_type")}),
(None, {"fields": ("uuid", "email", "password", "login_type")}),
(
_("Personal info"),
{
Expand Down Expand Up @@ -60,6 +60,10 @@ class _UserAdmin(UserAdmin):
),
},
),
(
_("Contacts - invites"),
{"fields": ("user_contacts", "contacts_for_approval")},
vaszig marked this conversation as resolved.
Show resolved Hide resolved
),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
add_fieldsets = (
Expand All @@ -71,7 +75,7 @@ class _UserAdmin(UserAdmin):
},
),
)
readonly_fields = ("bsn", "rsin", "is_prepopulated", "oidc_id")
readonly_fields = ("bsn", "rsin", "is_prepopulated", "oidc_id", "uuid")
list_display = (
"email",
"first_name",
Expand All @@ -83,6 +87,7 @@ class _UserAdmin(UserAdmin):
)
search_fields = ("first_name", "last_name", "email")
ordering = ("email",)
filter_horizontal = ("user_contacts", "contacts_for_approval")


@admin.register(Action)
Expand Down Expand Up @@ -128,30 +133,6 @@ def mark_not_deleted(self, request, queryset):
)


@admin.register(Contact)
class ContactAdmin(UUIDAdminFirstInOrder, admin.ModelAdmin):
readonly_fields = ("uuid",)
search_fields = (
"first_name",
"last_name",
"email",
"contact_user__email",
"created_by__email",
)
list_display = (
"first_name",
"last_name",
"email",
"contact_user",
"created_by",
"created_on",
)
list_filter = (
"contact_user",
"created_by",
)


@admin.register(Document)
class DocumentAdmin(UUIDAdminFirstInOrder, PrivateMediaMixin, admin.ModelAdmin):
readonly_fields = ("uuid",)
Expand Down
46 changes: 18 additions & 28 deletions src/open_inwoner/accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from open_inwoner.utils.forms import LimitedUploadFileField, PrivateFileWidget

from .choices import EmptyContactTypeChoices, EmptyStatusChoices, LoginTypeChoices
from .models import Action, Contact, Document, Invite, Message, User
from .models import Action, Document, Invite, Message, User


class CustomRegistrationForm(RegistrationForm):
Expand Down Expand Up @@ -53,6 +53,7 @@ class Meta:
fields = (
"first_name",
"last_name",
"phonenumber",
"birthday",
"street",
"housenumber",
Expand Down Expand Up @@ -120,41 +121,32 @@ class ContactFilterForm(forms.Form):
)


class ContactForm(forms.ModelForm):
def __init__(self, user, create, *args, **kwargs):
class ContactCreateForm(forms.Form):
first_name = forms.CharField(max_length=255)
last_name = forms.CharField(max_length=255)
email = forms.EmailField()

def __init__(self, user, *args, **kwargs):
self.user = user
self.create = create
super().__init__(*args, **kwargs)

class Meta:
model = Contact
fields = ("first_name", "last_name", "email", "phonenumber")

def clean(self):
cleaned_data = super().clean()
email = cleaned_data.get("email")

if self.create and email:
if (
self.user.contacts.filter(email=email).exists()
or self.user.assigned_contacts.filter(created_by__email=email).exists()
):
if email:
if self.user.user_contacts.filter(email=email).exists():
vaszig marked this conversation as resolved.
Show resolved Hide resolved
raise ValidationError(
_(
"Het ingevoerde e-mailadres komt al voor in uw contactpersonen. Pas de gegevens aan en probeer het opnieuw."
)
)

def save(self, commit=True):
if not self.instance.pk:
self.instance.created_by = self.user

if not self.instance.pk and self.instance.email:
contact_user = User.objects.filter(email=self.instance.email).first()
if contact_user:
self.instance.contact_user = contact_user

return super().save(commit=commit)
existing_user = User.objects.filter(email=email)
if existing_user and existing_user.get().is_not_active():
raise ValidationError(
_("The user cannot be added, their account has been deleted.")
)


class UserField(forms.ModelChoiceField):
Expand Down Expand Up @@ -305,12 +297,10 @@ def __init__(self, user, **kwargs):

super().__init__(**kwargs)

extended_contact_users = User.objects.get_extended_contact_users(self.user)
choices = [
[u.email, f"{u.first_name} {u.last_name}"] for u in extended_contact_users
]
contact_users = self.user.get_active_contacts()
choices = [[u.email, f"{u.first_name} {u.last_name}"] for u in contact_users]
vaszig marked this conversation as resolved.
Show resolved Hide resolved
self.fields["receiver"].choices = choices
self.fields["receiver"].queryset = extended_contact_users
self.fields["receiver"].queryset = contact_users

def clean(self):
cleaned_data = super().clean()
Expand Down
18 changes: 0 additions & 18 deletions src/open_inwoner/accounts/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,24 +68,6 @@ def create_superuser(self, email, password, **extra_fields):

return self._create_user(email, password, **extra_fields)

def get_active_contact_users(self, me):
active_contacts = me.get_active_contacts().values_list(
"contact_user__id", flat=True
)
return self.get_queryset().filter(id__in=active_contacts)

def get_extended_contact_users(self, me):
"""returns active users from your contacts and active users who assigned you as a contact"""
active_contacts = me.get_active_contacts().values_list(
"contact_user__id", flat=True
)
assigned_contacts = me.get_assigned_active_contacts().values_list(
"created_by__id", flat=True
)
return self.get_queryset().filter(
id__in=list(active_contacts) + list(assigned_contacts)
)


class ActionQueryset(QuerySet):
def visible(self):
Expand Down
74 changes: 74 additions & 0 deletions src/open_inwoner/accounts/migrations/0048_auto_20221205_0921.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Generated by Django 3.2.15 on 2022-12-05 08:21

from django.conf import settings
from django.db import migrations, models
import open_inwoner.utils.validators


class Migration(migrations.Migration):

dependencies = [
("accounts", "0047_action_is_deleted"),
]

operations = [
migrations.AddField(
model_name="invite",
name="invitee_first_name",
field=models.CharField(
default="",
help_text="The first name of the invitee.",
max_length=250,
verbose_name="First name",
),
),
migrations.AddField(
model_name="invite",
name="invitee_last_name",
field=models.CharField(
default="",
help_text="The last name of the invitee",
max_length=250,
verbose_name="Last name",
),
),
migrations.AddField(
model_name="user",
name="contacts_for_approval",
field=models.ManyToManyField(
blank=True,
help_text="User's contacts waiting for approval. This field is used for existing users in the application",
to=settings.AUTH_USER_MODEL,
verbose_name="Contacts for approval",
),
),
migrations.AddField(
model_name="user",
name="phonenumber",
field=models.CharField(
blank=True,
default="",
max_length=15,
validators=[open_inwoner.utils.validators.validate_phone_number],
verbose_name="Phonenumber",
),
),
migrations.AddField(
model_name="user",
name="user_contacts",
field=models.ManyToManyField(
blank=True,
help_text="The contacts of the specific user",
related_name="_accounts_user_user_contacts_+",
to=settings.AUTH_USER_MODEL,
verbose_name="Contacts",
),
),
migrations.AddField(
model_name="user",
name="uuid",
field=models.UUIDField(
help_text="Unique identifier.", null=True, verbose_name="UUID"
),
),
]
46 changes: 46 additions & 0 deletions src/open_inwoner/accounts/migrations/0049_auto_20221205_0921.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Generated by Django 3.2.15 on 2022-12-05 08:21

import uuid

from django.db import migrations


def gen_user_uuid(apps, schema_editor):
MyModel = apps.get_model("accounts", "User")
for row in MyModel.objects.all():
row.uuid = uuid.uuid4()
row.save(update_fields=["uuid"])


def populate_user_contacts(apps, schema_editor):
MyModel = apps.get_model("accounts", "Contact")
for contact in MyModel.objects.exclude(contact_user__isnull=True):
if contact.created_by != contact.contact_user:
creator = contact.created_by
contact_user = contact.contact_user
creator.user_contacts.add(contact_user)


def populate_invite_names(apps, schema_editor):
MyModel = apps.get_model("accounts", "Invite")
for invite in MyModel.objects.filter(invitee__isnull=False):
invite.invitee_first_name = invite.invitee.first_name
invite.invitee_last_name = invite.invitee.last_name
invite.save()


class Migration(migrations.Migration):

dependencies = [
("accounts", "0048_auto_20221205_0921"),
]

operations = [
migrations.RunPython(gen_user_uuid, reverse_code=migrations.RunPython.noop),
migrations.RunPython(
populate_user_contacts, reverse_code=migrations.RunPython.noop
),
migrations.RunPython(
populate_invite_names, reverse_code=migrations.RunPython.noop
),
]
50 changes: 50 additions & 0 deletions src/open_inwoner/accounts/migrations/0050_auto_20221205_0924.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Generated by Django 3.2.15 on 2022-12-05 08:24

from django.db import migrations, models
import uuid


class Migration(migrations.Migration):

dependencies = [
("plans", "0011_remove_plan_contacts"),
("accounts", "0049_auto_20221205_0921"),
]

operations = [
migrations.RemoveField(
model_name="invite",
name="contact",
),
migrations.AlterField(
model_name="invite",
name="invitee_first_name",
field=models.CharField(
help_text="The first name of the invitee.",
max_length=250,
verbose_name="First name",
),
),
migrations.AlterField(
model_name="invite",
name="invitee_last_name",
field=models.CharField(
help_text="The last name of the invitee",
max_length=250,
verbose_name="Last name",
),
),
migrations.AlterField(
model_name="user",
name="uuid",
field=models.UUIDField(
default=uuid.uuid4,
help_text="Unique identifier.",
unique=True,
verbose_name="UUID",
),
),
migrations.DeleteModel(
name="Contact",
),
]
Loading