Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/dev-guide/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<slug>/`. 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
Expand Down
53 changes: 52 additions & 1 deletion main/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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."""

Expand Down
5 changes: 4 additions & 1 deletion main/templates/main/my-teams.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
My Teams
{% endblock title %}
{% block content %}
<h1>My Teams</h1>
<div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
<h1 class="mb-0">My Teams</h1>
<a class="btn btn-dark" href="{% url 'team-create' %}">Create team</a>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<a class="btn btn-dark" href="{% url 'team-create' %}">Create team</a>
<a class="btn btn-primary" href="{% url 'team-create' %}">Create team</a>

</div>
<div class="row row-cols-1 row-cols-sm-2 row-cols-xl-3 g-3">
{% for membership in memberships %}
<div class="col">
Expand Down
15 changes: 15 additions & 0 deletions main/templates/main/team-create-form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{% extends "main/base.account.html" %}
{% load crispy_forms_tags %}
{% block title %}
Create team
{% endblock title %}
{% block content %}
<h1>Create team</h1>
<p>You will be the team's first manager.</p>
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-dark">Create team</button>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<button type="submit" class="btn btn-dark">Create team</button>
<button type="submit" class="btn btn-primary">Create team</button>

<a class="btn btn-secondary" href="{% url 'my_teams' %}">Cancel</a>
</form>
{% endblock content %}
1 change: 1 addition & 0 deletions main/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
22 changes: 19 additions & 3 deletions main/views/team_views.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
"""Views for team membership actions."""
"""Views for teams and team membership."""

from http import HTTPStatus
from json import dumps
from typing import TYPE_CHECKING, Any, cast

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 (
Expand All @@ -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."""

Expand Down
7 changes: 7 additions & 0 deletions tests/main/views/test_account_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
82 changes: 82 additions & 0 deletions tests/main/views/test_team_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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, "<h1>Research team</h1>", 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."""
Expand Down