91 lines
2.7 KiB
Python
91 lines
2.7 KiB
Python
import uuid
|
|
|
|
from drf_spectacular.utils import extend_schema
|
|
|
|
from rest_framework.generics import GenericAPIView # type: ignore
|
|
from rest_framework.decorators import action # type: ignore
|
|
from rest_framework.permissions import IsAdminUser
|
|
from rest_framework import status # type: ignore
|
|
from rest_framework.request import HttpRequest # type: ignore
|
|
from rest_framework.response import Response # type: ignore
|
|
from rest_framework.permissions import ( # type: ignore
|
|
IsAdminUser,
|
|
)
|
|
|
|
from rest_framework.generics import get_object_or_404 # type: ignore
|
|
from django.contrib.auth import get_user_model
|
|
from django.db import transaction
|
|
|
|
from core.utils.views import BaseApiViewMixin
|
|
from core.apps.companies.serializers import (
|
|
CreateCompanySerializer,
|
|
RetrieveCompanySerializer,
|
|
BaseCompanySerializer,
|
|
)
|
|
from core.apps.companies.models import (
|
|
CompanyModel,
|
|
CompanyAccountModel,
|
|
)
|
|
|
|
UserModel = get_user_model()
|
|
|
|
|
|
######################################################################
|
|
# /users/{id}/companies
|
|
######################################################################
|
|
@extend_schema(tags=["User Companies"])
|
|
class UserCompanyApiView(BaseApiViewMixin, GenericAPIView): # type: ignore
|
|
queryset = UserModel.objects.all()
|
|
permission_classes = [IsAdminUser]
|
|
serializer_class = BaseCompanySerializer
|
|
|
|
method_permission_classes = {
|
|
"get": [IsAdminUser],
|
|
"post": [IsAdminUser],
|
|
}
|
|
method_serializer_class = {
|
|
"get": RetrieveCompanySerializer,
|
|
"post": CreateCompanySerializer,
|
|
}
|
|
|
|
@extend_schema(
|
|
summary="Get List Of Companies For User",
|
|
description="Get List Of Companies For User",
|
|
)
|
|
def get(
|
|
self,
|
|
request: HttpRequest,
|
|
pk: uuid.UUID,
|
|
*args: object,
|
|
**kwargs: object,
|
|
) -> Response:
|
|
companies = CompanyModel.objects.filter(accounts__user__pk=pk)
|
|
return Response(
|
|
data=RetrieveCompanySerializer(instance=companies, many=True),
|
|
status=status.HTTP_200_OK
|
|
)
|
|
|
|
|
|
@extend_schema(
|
|
summary="Create Company For User",
|
|
description="Create Company For User",
|
|
)
|
|
def post(
|
|
self,
|
|
request: HttpRequest,
|
|
pk: uuid.UUID,
|
|
*args: object,
|
|
**kwargs: object,
|
|
) -> Response:
|
|
with transaction.atomic():
|
|
ser = CreateCompanySerializer(data=request.data) # type: ignore
|
|
ser.is_valid(raise_exception=True)
|
|
company = ser.save() # type: ignore
|
|
|
|
user = get_object_or_404(UserModel, pk=pk)
|
|
|
|
account = CompanyAccountModel(company=company, user=user)
|
|
account.save()
|
|
|
|
return Response(data=ser.data, status=status.HTTP_201_CREATED)
|