🎨(models) extract invitation converter in a proper method

Improved code readability, by extracting this well-scoped unit of
logic in a dedicated method. Also, rename active_invitations to match
'valid' vocabulary used elsewhere in the doc. If no valid invitation
exists, early return to avoid nesting.
This commit is contained in:
Lebaud Antoine
2024-03-21 13:54:42 +01:00
committed by aleb_the_flash
parent 159f112713
commit 0141aa220f

View File

@@ -286,28 +286,11 @@ class Identity(BaseModel):
def save(self, *args, **kwargs):
"""
Saves identity, ensuring users always have exactly one main identity.
Also converts valid invitations to accesses upon creating an identity.
If it's a new identity, give its user access to the relevant teams.
"""
# If new identity, convert all valid invitations to team accesses.
# Expired invitations are ignored.
if self._state.adding:
active_invitations = Invitation.objects.filter(
email=self.email,
created_at__gte=timezone.now()
- timedelta(seconds=settings.INVITATION_VALIDITY_DURATION),
).select_related("team")
if active_invitations.exists():
TeamAccess.objects.bulk_create(
[
TeamAccess(
user=self.user, team=invitation.team, role=invitation.role
)
for invitation in active_invitations
]
)
active_invitations.delete()
self._convert_valid_invitations()
super().save(*args, **kwargs)
@@ -315,6 +298,31 @@ class Identity(BaseModel):
if self.is_main is True:
self.user.identities.exclude(id=self.id).update(is_main=False)
def _convert_valid_invitations(self):
"""
Convert valid invitations to team accesses.
Expired invitations are ignored.
"""
valid_invitations = Invitation.objects.filter(
email=self.email,
created_at__gte=(
timezone.now()
- timedelta(seconds=settings.INVITATION_VALIDITY_DURATION)
),
).select_related("team")
if not valid_invitations.exists():
return
TeamAccess.objects.bulk_create(
[
TeamAccess(user=self.user, team=invitation.team, role=invitation.role)
for invitation in valid_invitations
]
)
valid_invitations.delete()
def clean(self):
"""Normalize the email field and clean the 'is_main' field."""
if self.email: