diff --git a/docs/dev-guide/architecture.md b/docs/dev-guide/architecture.md index 58e2ef79..b884e8fa 100644 --- a/docs/dev-guide/architecture.md +++ b/docs/dev-guide/architecture.md @@ -68,6 +68,13 @@ user admin also blocks deleting a person who is the sole manager of any team. ## Team page +Signed-in users who have accepted the terms can choose **Create team** from +**My Teams**. They enter a name and description. The team URL is generated from +the name. If the name or URL is already in use, or the name cannot produce a +usable URL, the form shows an error on the name field. Successful submission +opens the new team's page, with the creator as its only manager. Inviting +members and promoting them to manager are separate from team creation. + `TeamDetailView` shows a team at `/teams//`. Access is checked with the team's Guardian `view_team` object permission, so only members (and superusers) can see it; anyone else gets a 404, so the page does not reveal whether a team diff --git a/main/forms.py b/main/forms.py index 1ba9800b..f2b1eec6 100644 --- a/main/forms.py +++ b/main/forms.py @@ -6,6 +6,7 @@ from crispy_forms.layout import HTML, Div, Layout, Submit from django import forms from django.core.exceptions import ValidationError +from django.db import IntegrityError from django.urls import reverse from django.utils import timezone from django.utils.html import format_html @@ -15,7 +16,8 @@ RegistrationFormUniqueEmail, ) -from .models import Profile, Skill, SkillLevel, SkillProfile +from .models import Profile, Skill, SkillLevel, SkillProfile, Team, User +from .team_services import create_team def _build_tos_form_label() -> str: @@ -69,6 +71,55 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.fields["tos"].label = _(_build_tos_form_label()) +class TeamCreateForm(forms.ModelForm[Team]): + """Collect the details a user can set when creating a team.""" + + class Meta: + """Use the team model's name and description fields.""" + + model = Team + fields = ("name", "description") + + def validate_unique(self) -> None: + """Report unusable team URLs on the name field, after checking the name.""" + super().validate_unique() + if "name" not in self.cleaned_data: + return + + # The model generates the slug during validation, but the form excludes it. + slug = self.instance.slug + if not slug: + self.add_error("name", _("Choose a name that can be used in a team URL.")) + return + + slug_field = Team._meta.get_field("slug") + try: + slug_field.run_validators(slug) + except ValidationError: + self.add_error("name", _("Choose a name that can be used in a team URL.")) + return + + if Team.objects.filter(slug=slug).exists(): + self.add_error( + "name", _("Choose a different name. The team URL is already in use.") + ) + + def create_for(self, user: User) -> Team | None: + """Create the team from valid input, or report a new name or URL conflict.""" + try: + return create_team( + user=user, + name=self.cleaned_data["name"], + description=self.cleaned_data["description"], + ) + except (ValidationError, IntegrityError): + # Another request may have claimed the name or slug since validation. + self.validate_unique() + if not self.has_error("name"): + raise + return None + + class SkillProfileForm(forms.Form): """Form for creating SkillProfiles for all skills in the database.""" diff --git a/main/templates/main/my-teams.html b/main/templates/main/my-teams.html index 860042f9..e94f7313 100644 --- a/main/templates/main/my-teams.html +++ b/main/templates/main/my-teams.html @@ -3,7 +3,10 @@ My Teams {% endblock title %} {% block content %} -

My Teams

+
+

My Teams

+ Create team +
{% for membership in memberships %}
diff --git a/main/templates/main/team-create-form.html b/main/templates/main/team-create-form.html new file mode 100644 index 00000000..4e587e4d --- /dev/null +++ b/main/templates/main/team-create-form.html @@ -0,0 +1,15 @@ +{% extends "main/base.account.html" %} +{% load crispy_forms_tags %} +{% block title %} + Create team +{% endblock title %} +{% block content %} +

Create team

+

You will be the team's first manager.

+
+ {% csrf_token %} + {{ form|crispy }} + + Cancel +
+{% endblock content %} diff --git a/main/urls.py b/main/urls.py index 12d5056c..5a6ae3d9 100644 --- a/main/urls.py +++ b/main/urls.py @@ -47,6 +47,7 @@ path("profile/", views.UserUpdateView.as_view(), name="profile"), path("overview/", views.AccountOverviewView.as_view(), name="account-overview"), path("teams/", views.MyTeamsPageView.as_view(), name="my_teams"), + path("teams/create/", views.TeamCreateView.as_view(), name="team-create"), path( "download-skills-data/csv/", views.DownloadSkillProfileDataCsvView.as_view(), diff --git a/main/views/team_views.py b/main/views/team_views.py index 5819a657..9e03c059 100644 --- a/main/views/team_views.py +++ b/main/views/team_views.py @@ -1,4 +1,4 @@ -"""Views for team membership actions.""" +"""Views for teams and team membership.""" from http import HTTPStatus from json import dumps @@ -6,11 +6,12 @@ from django.core.exceptions import ValidationError from django.http import Http404, HttpRequest, HttpResponse -from django.shortcuts import get_object_or_404, render +from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse -from django.views.generic import DetailView, TemplateView +from django.views.generic import DetailView, FormView, TemplateView from guardian.mixins import PermissionRequiredMixin +from ..forms import TeamCreateForm from ..models import SkillLevel, Team, TeamMembership from ..tables import TeamMembershipTable from ..team_services import ( @@ -25,6 +26,21 @@ from ..models import User as UserType +class TeamCreateView(TermsAcceptedMixin, FormView[TeamCreateForm]): + """Let a signed-in user create a team and become its first manager.""" + + request: AuthenticatedHttpRequest + form_class = TeamCreateForm + template_name = "main/team-create-form.html" + + def form_valid(self, form: TeamCreateForm) -> HttpResponse: + """Create the team and take its manager to the team page.""" + team = form.create_for(self.request.user) + if team is None: + return self.form_invalid(form) + return redirect("team-detail", slug=team.slug) + + class TeamDetailView(TermsAcceptedMixin, PermissionRequiredMixin, DetailView[Team]): """Show a team to its members.""" diff --git a/tests/main/views/test_account_views.py b/tests/main/views/test_account_views.py index e70c9635..445b8536 100644 --- a/tests/main/views/test_account_views.py +++ b/tests/main/views/test_account_views.py @@ -356,6 +356,13 @@ def test_shows_an_empty_state_when_the_user_has_no_teams( assert "You are not a member of any teams yet." in page_text assert "Astronomy team" not in page_text + @pytest.mark.django_db + def test_user_without_teams_can_open_team_creation(self, auth_soup) -> None: + """My Teams links to team creation even before the user has a team.""" + create_link = auth_soup.find(tag_with_text_filter("a", "Create team")) + assert create_link is not None + assert create_link["href"] == reverse("team-create") + @pytest.mark.parametrize("is_manager", [False, True], ids=["member", "manager"]) @pytest.mark.django_db def test_does_not_show_other_members_or_their_assessments( diff --git a/tests/main/views/test_team_views.py b/tests/main/views/test_team_views.py index b80a7588..58dd52e0 100644 --- a/tests/main/views/test_team_views.py +++ b/tests/main/views/test_team_views.py @@ -6,6 +6,7 @@ import pytest from django.urls import reverse +from pytest_django.asserts import assertContains from main.models import SkillProfile, TeamMembership, User from main.team_services import create_team, generate_invitation_token @@ -18,6 +19,87 @@ ) +class TestTeamCreateView(LoginRequiredMixin, TemplateOkMixin, BS4Mixin): + """Test team creation through the account form.""" + + _template_name = "main/team-create-form.html" + + def _get_url(self, **kwargs) -> str: + return reverse("team-create") + + @pytest.mark.django_db + def test_user_creates_team_as_its_only_manager( + self, client_logged_in, user + ) -> None: + """A user with no teams or assessments can create a team and see its roster.""" + response = client_logged_in.post( + self._get_url(), + {"name": "Research team", "description": "A team for planning research."}, + follow=True, + ) + + assert response.redirect_chain == [ + (reverse("team-detail", kwargs={"slug": "research-team"}), HTTPStatus.FOUND) + ] + assertContains(response, "

Research team

", html=True) + assertContains(response, "A team for planning research.") + assertContains(response, "test user") + assertContains(response, "Manager") + + @pytest.mark.django_db + def test_cancel_returns_to_my_teams(self, auth_soup) -> None: + """The create form provides a link back to My Teams.""" + cancel_link = auth_soup.find(tag_with_text_filter("a", "Cancel")) + + assert cancel_link is not None + assert cancel_link["href"] == reverse("my_teams") + + @pytest.mark.parametrize("method", ["get", "post"]) + @pytest.mark.django_db + def test_user_must_accept_terms_before_creating_a_team( + self, client, user, method + ) -> None: + """Users who have not accepted the terms cannot open or submit the form.""" + user.agreed_to_tos = False + user.save(update_fields=["agreed_to_tos"]) + client.force_login(user) + + response = getattr(client, method)( + self._get_url(), + {"name": "Research team", "description": "A team for planning research."}, + ) + + assert response.status_code == HTTPStatus.FOUND + assert response.url == reverse("terms_acceptance") + + @pytest.mark.parametrize( + ("name", "expected_error"), + [ + ("Imaging Lab", "Team with this Name already exists."), + ("Imaging-Lab", "Choose a different name. The team URL is already in use."), + ("!!!", "Choose a name that can be used in a team URL."), + ("\ufb03" * 100, "Choose a name that can be used in a team URL."), + ], + ids=["duplicate-name", "duplicate-url", "empty-url", "long-url"], + ) + @pytest.mark.django_db + def test_rejected_name_keeps_the_description( + self, client_logged_in, django_user_model, name, expected_error + ) -> None: + """Tell the user what is wrong with the name without losing their work.""" + other_user = django_user_model.objects.create_user(username="other-manager") + create_team(user=other_user, name="Imaging Lab", description="Another team.") + + response = client_logged_in.post( + self._get_url(), {"name": name, "description": "Keep these details."} + ) + + assert response.status_code == HTTPStatus.OK + assert response.context["form"].errors["name"] == [expected_error] + assert response.context["form"]["description"].value() == "Keep these details." + assertContains(response, expected_error) + + @pytest.mark.django_db class TestTeamInvitationLinkView(LoginRequiredMixin, TemplateOkMixin): """Test the manager's team invitation-link page."""