diff --git a/greg/management/commands/import_guests.py b/greg/management/commands/import_guests.py index fc766f0d385e341fc3804a55a457152108621cfd..3af001a582734d19c895daafa3879528d8abeb61 100644 --- a/greg/management/commands/import_guests.py +++ b/greg/management/commands/import_guests.py @@ -68,20 +68,32 @@ class Command(BaseCommand): ) def _find_person_from_ids(self, ids: dict) -> Optional[Person]: - """Match IDs to find person.""" + """ + Match IDs to find person. + + Tries to find a perfect match, returns matches for identifiers + of same type with same value from different source if present. + """ for id_type in self.ID_TYPES: matching_ids = [x for x in ids if x["id_type"] == id_type] for matching_id in matching_ids: - try: - greg_id = Identity.objects.get( - type=id_type, - value=matching_id["external_id"], - source=matching_id["source_system"], - ) - except Identity.DoesNotExist: + # Check without correct source + matches = Identity.objects.filter( + type=id_type, + value=matching_id["external_id"], + ) + if not matches: + # No match, check next id continue - else: - return greg_id.person + # Found one or more matches, check if a perfect match exists + perfect = matches.filter( + source=matching_id["source_system"], + ).first() + if perfect: + # Perfect match! Return it + return perfect.person + # No perfect match, return first match from other source + return matches.first().person # type: ignore return None def _find_orgunit_from_external_id( @@ -188,15 +200,12 @@ class Command(BaseCommand): def upsert_identity(self, person: Person, id_data: dict) -> Identity: """Add or update identity""" - try: - identity = Identity.objects.get( - person=person, - type=id_data["id_type"], - value=id_data["external_id"], - source=id_data["source_system"], - verified="automatic", - ) - except Identity.DoesNotExist: + match = Identity.objects.filter( + person=person, + type=id_data["id_type"], + value=id_data["external_id"], + ).first() + if not match: identity = Identity.objects.create( person=person, type=id_data["id_type"], @@ -208,7 +217,13 @@ class Command(BaseCommand): logger.info( "identity_added", identity=identity.id, identity_type=identity.type ) - + else: + identity = match + if not identity.verified_at: + identity.source = id_data["source_system"] + identity.verified = "automatic" + identity.verified_at = make_aware(datetime.datetime.now()) + identity.save() return identity def _has_required_id(self, id_data: dict) -> bool: