|
| 1 | +""" |
| 2 | +New manager registration form |
| 3 | +""" |
| 4 | + |
| 5 | +import django.contrib.auth.models |
| 6 | +import django.forms as forms |
| 7 | +from django.contrib.auth.forms import UserCreationForm |
| 8 | +from invitations.models import Invitation |
| 9 | + |
| 10 | +from home.services import organisation_service |
| 11 | +from home.models import Organisation |
| 12 | +from home.constants import ROLE_PROJECT_MANAGER |
| 13 | + |
| 14 | +User = django.contrib.auth.get_user_model() |
| 15 | + |
| 16 | + |
| 17 | +class ManagerSignupForm(UserCreationForm): |
| 18 | + """ |
| 19 | + A form to register a new user (a new manager) who was invited by |
| 20 | + an existing manager of an organisation. |
| 21 | + """ |
| 22 | + |
| 23 | + class Meta: |
| 24 | + model = User |
| 25 | + fields = ("password1", "password2") |
| 26 | + |
| 27 | + # Secret key for the invitation (hidden form field) |
| 28 | + key = forms.CharField(required=False, disabled=True, widget=forms.HiddenInput, label="") |
| 29 | + |
| 30 | + @property |
| 31 | + def invitation(self) -> Invitation: |
| 32 | + """ |
| 33 | + The invitation that the existing manager send to the new user. |
| 34 | + """ |
| 35 | + return Invitation.objects.get(key=self.data["key"]) |
| 36 | + |
| 37 | + @property |
| 38 | + def inviter(self) -> User: |
| 39 | + """ |
| 40 | + The user (manager) who invited this new manager. |
| 41 | + """ |
| 42 | + return User.objects.get(pk=self.invitation.inviter_id) |
| 43 | + |
| 44 | + @property |
| 45 | + def organisation(self) -> Organisation: |
| 46 | + """ |
| 47 | + The organisation that the new user was invited to join. |
| 48 | + """ |
| 49 | + organisation = organisation_service.get_user_organisation(user=self.inviter) |
| 50 | + if organisation is None: |
| 51 | + raise forms.ValidationError("This user is not a manager of an organisation") |
| 52 | + return organisation |
| 53 | + |
| 54 | + @property |
| 55 | + def email(self) -> str: |
| 56 | + """ |
| 57 | + The email address of the new user that received the invitation email. |
| 58 | + """ |
| 59 | + return self.invitation.email |
| 60 | + |
| 61 | + def save(self, commit=True): |
| 62 | + user = super().save(commit=False) |
| 63 | + user.email = self.email |
| 64 | + user.username = user.email |
| 65 | + if commit: |
| 66 | + user.save() |
| 67 | + |
| 68 | + # Add user to organisation |
| 69 | + organisation_service.add_user_to_organisation( |
| 70 | + user_to_add=user, |
| 71 | + organisation=self.organisation, |
| 72 | + user=self.inviter, |
| 73 | + role=ROLE_PROJECT_MANAGER, |
| 74 | + ) |
| 75 | + |
| 76 | + return user |
0 commit comments