|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TypedDict |
| 4 | + |
1 | 5 | from rest_framework import serializers
|
2 | 6 | from rest_framework.serializers import ListField
|
3 | 7 |
|
4 | 8 | from sentry.api.fields.actor import ActorField
|
5 |
| -from sentry.api.serializers.rest_framework.mentions import MentionsMixin |
| 9 | +from sentry.models.organizationmember import OrganizationMember |
| 10 | +from sentry.models.team import Team |
| 11 | +from sentry.types.actor import Actor |
| 12 | + |
| 13 | + |
| 14 | +class _SeparatedActors(TypedDict): |
| 15 | + users: list[Actor] |
| 16 | + teams: list[Actor] |
| 17 | + |
| 18 | + |
| 19 | +def separate_actors(actors: list[Actor]) -> _SeparatedActors: |
| 20 | + users = [actor for actor in actors if actor.is_user] |
| 21 | + teams = [actor for actor in actors if actor.is_team] |
| 22 | + |
| 23 | + return {"users": users, "teams": teams} |
6 | 24 |
|
7 | 25 |
|
8 |
| -class NoteSerializer(serializers.Serializer, MentionsMixin): |
| 26 | +class NoteSerializer(serializers.Serializer[None]): |
9 | 27 | text = serializers.CharField()
|
10 | 28 | mentions = ListField(child=ActorField(), required=False)
|
11 | 29 | external_id = serializers.CharField(allow_null=True, required=False)
|
| 30 | + |
| 31 | + def validate_mentions(self, mentions: list[Actor]) -> list[Actor]: |
| 32 | + if mentions and "projects" in self.context: |
| 33 | + |
| 34 | + separated_actors = separate_actors(mentions) |
| 35 | + # Validate that all mentioned users exist and are on the project. |
| 36 | + users = separated_actors["users"] |
| 37 | + |
| 38 | + mentioned_user_ids = {user.id for user in users} |
| 39 | + |
| 40 | + projects = self.context["projects"] |
| 41 | + user_ids = list( |
| 42 | + OrganizationMember.objects.filter( |
| 43 | + teams__projectteam__project__in=[p.id for p in projects], |
| 44 | + user_id__in=mentioned_user_ids, |
| 45 | + ).values_list("user_id", flat=True) |
| 46 | + ) |
| 47 | + |
| 48 | + if len(mentioned_user_ids) > len(user_ids): |
| 49 | + raise serializers.ValidationError("Cannot mention a non team member") |
| 50 | + |
| 51 | + # Validate that all mentioned teams exist and are on the project. |
| 52 | + teams = separated_actors["teams"] |
| 53 | + mentioned_team_ids = {team.id for team in teams} |
| 54 | + if ( |
| 55 | + len(mentioned_team_ids) |
| 56 | + > Team.objects.filter( |
| 57 | + id__in=mentioned_team_ids, projectteam__project__in=projects |
| 58 | + ).count() |
| 59 | + ): |
| 60 | + raise serializers.ValidationError( |
| 61 | + "Mentioned team not found or not associated with project" |
| 62 | + ) |
| 63 | + |
| 64 | + return mentions |
0 commit comments