70 lines
1.9 KiB
Python
70 lines
1.9 KiB
Python
from rest_framework.viewsets import GenericViewSet # type: ignore
|
|
from rest_framework.decorators import action # type: ignore
|
|
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
|
|
IsAuthenticated
|
|
)
|
|
|
|
from django_core.mixins import BaseViewSetMixin # type: ignore
|
|
|
|
from core.apps.companies.serializers import (
|
|
RetrieveCompanySerializer,
|
|
CreateCompanySerializer,
|
|
)
|
|
from core.apps.companies.models import (
|
|
CompanyModel,
|
|
CompanyAccountModel
|
|
)
|
|
|
|
from django.db import transaction
|
|
|
|
|
|
class MeCompanyView(BaseViewSetMixin, GenericViewSet):
|
|
permission_classes = [IsAuthenticated]
|
|
|
|
action_permission_classes = {}
|
|
action_serializer_class = {
|
|
"create": CreateCompanySerializer,
|
|
"list": RetrieveCompanySerializer,
|
|
}
|
|
|
|
def list(
|
|
self,
|
|
request: HttpRequest,
|
|
*args: object,
|
|
**kwargs: object
|
|
) -> Response:
|
|
|
|
companies = CompanyModel.objects.filter(
|
|
accounts__user=request.user
|
|
)
|
|
|
|
return Response(
|
|
RetrieveCompanySerializer(instance=companies, many=True).data,
|
|
status=status.HTTP_200_OK
|
|
)
|
|
|
|
def create(
|
|
self,
|
|
request: HttpRequest,
|
|
*args: object,
|
|
**kwargs: object
|
|
) -> Response:
|
|
|
|
with transaction.atomic():
|
|
serializer = CreateCompanySerializer(data=request.data) # type: ignore
|
|
serializer.is_valid(raise_exception=True)
|
|
company = serializer.save() # type: ignore
|
|
|
|
account = CompanyAccountModel(
|
|
company=company,
|
|
user=request.user
|
|
)
|
|
account.save()
|
|
|
|
return Response(
|
|
data=serializer.data,
|
|
status=status.HTTP_201_CREATED
|
|
) |