Files
trustme/core/apps/accounts/views/me.py

48 lines
1.9 KiB
Python

from rest_framework.generics import GenericAPIView # 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 core.utils.views import BaseApiViewMixin
from core.apps.companies.serializers import (
RetrieveCompanySerializer,
CreateCompanySerializer,
)
from core.apps.companies.models import (
CompanyModel,
CompanyAccountModel
)
from django.db import transaction
######################################################################
# @api-view | POST, GET - me/companies
######################################################################
class MeCompanyApiView(BaseApiViewMixin, GenericAPIView): # type: ignore
permission_classes = [IsAuthenticated]
method_permission_classes = {}
method_serializer_class = {
"post": CreateCompanySerializer,
"get": RetrieveCompanySerializer,
}
def get(self, request: HttpRequest, *args: object, **kwargs: object) -> Response:
companies = CompanyModel.objects.filter(accounts__user=request.user)
ser = RetrieveCompanySerializer(instance=companies, many=True)
return Response(ser.data, 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(serializer.data, status.HTTP_201_CREATED)