Example #1
0
    def bulk(self, request: request.Request, **kwargs) -> response.Response:
        data = cast(Any, request.data)
        if not isinstance(data, list):
            raise exceptions.ValidationError("This endpoint needs an array of data for bulk invite creation.")
        if len(data) > 20:
            raise exceptions.ValidationError(
                "A maximum of 20 invites can be sent in a single request.", code="max_length",
            )

        serializer = OrganizationInviteSerializer(
            data=data, many=True, context={**self.get_serializer_context(), "bulk_create": True}
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()

        organization = Organization.objects.get(id=self.organization_id)
        report_bulk_invited(
            cast(User, self.request.user),
            invitee_count=len(serializer.validated_data),
            name_count=sum(1 for invite in serializer.validated_data if invite.get("first_name")),
            current_invite_count=organization.active_invites.count(),
            current_member_count=organization.memberships.count(),
            email_available=is_email_available(),
        )

        return response.Response(serializer.data, status=status.HTTP_201_CREATED)
Example #2
0
    def create(self, validated_data: Dict[str, Any]) -> Dict[str, Any]:
        output = []
        organization = Organization.objects.get(
            id=self.context["organization_id"])

        with transaction.atomic():
            for invite in validated_data["invites"]:
                self.context["bulk_create"] = True
                serializer = OrganizationInviteSerializer(data=invite,
                                                          context=self.context)
                serializer.is_valid(raise_exception=False
                                    )  # Don't raise, already validated before
                output.append(serializer.save())

        report_bulk_invited(
            self.context["request"].user.distinct_id,
            invitee_count=len(validated_data["invites"]),
            name_count=sum(1 for invite in validated_data["invites"]
                           if invite["first_name"]),
            current_invite_count=organization.active_invites.count(),
            current_member_count=organization.memberships.count(),
            email_available=is_email_available(),
        )

        return {"invites": output}