diff --git a/contracts/management/commands/import_old_contracts.py b/contracts/management/commands/import_old_contracts.py index 23f456c71d02661cf3a5bac7f2013887182c0995..4264bbb544f4e4907d429296bce6ffc2d195d7f4 100644 --- a/contracts/management/commands/import_old_contracts.py +++ b/contracts/management/commands/import_old_contracts.py @@ -7,6 +7,7 @@ from datetime import date, datetime import yaml from django.conf import settings from django.core.management.base import BaseCommand +from django.db import models from postal.parser import parse_address from git import Repo @@ -300,10 +301,12 @@ class Command(BaseCommand): "česká pirátkská strana", "česká pirátská stran", ): - instance = Contractee() + model = Contractee + instance = model() is_contractee = True else: - instance = Signee(name=name, address_country="Česká republika") + model = Signee + instance = model(name=name, address_country="Česká republika") for signing_party_key, signing_party_value in signing_party.items(): if isinstance(signing_party_value, str): @@ -352,7 +355,33 @@ class Command(BaseCommand): case "IČ": instance.ico_number = signing_party_value - instance.save() + # Do our best to merge signing parties together. + existing_instance = model.objects.filter( + ( + models.Q(name=instance.name) + & ( + ( + models.Q(address_street_with_number=instance.address_street_with_number) + if instance.address_street_with_number is not None + else models.Value(False) + ) | ( + models.Q(date_of_birth=instance.date_of_birth) + if model is Signee and instance.date_of_birth is not None + else models.Value(False) + ) + ) + ) + | ( + models.Q(ico_number=instance.ico_number) + if instance.ico_number is not None + else models.Value(False) + ) + ).first() + + if existing_instance is not None: + instance = existing_instance + else: + instance.save() return instance, is_contractee, issue_count