Files
RasadDam_Backend/apps/herd/pos/api/v1/api.py

161 lines
5.1 KiB
Python

from django.db import transaction
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from apps.core.mixins.search_mixin import DynamicSearchMixin
from apps.herd.exception import DuplicateRancherException
from apps.herd.models import Herd, Rancher
from apps.herd.pos.api.v1.serializers import HerdSerializer, RancherSerializer
from apps.livestock.web.api.v1.serializers import LiveStockSerializer
from apps.pos_device.mixins.pos_device_mixin import POSDeviceMixin
from common.tools import CustomOperations
class HerdViewSet(viewsets.ModelViewSet):
""" Herd ViewSet """
queryset = Herd.objects.all()
serializer_class = HerdSerializer
permission_classes = [AllowAny]
@transaction.atomic
def create(self, request, *args, **kwargs):
""" create herd with user """
if 'rancher' in request.data.keys():
rancher = CustomOperations().custom_create(
request=request,
view=RancherViewSet(),
data=request.data['rancher']
)
request.data.update({'rancher': rancher['id']})
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN)
@action(
methods=['get'],
detail=False,
url_name='my_herds',
url_path='my_herds',
name='my_herds'
)
@transaction.atomic
def my_herds(self, request):
""" get current user herds """
serializer = self.serializer_class(self.queryset.filter(owner=request.user.id), many=True)
if serializer.data:
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_204_NO_CONTENT)
@action(
methods=['post'],
detail=True,
url_path='trash',
url_name='trash',
name='trash'
)
@transaction.atomic
def trash(self, request, pk=None):
""" Sent herd to trash """
try:
herd = self.queryset.get(id=pk)
herd.trash = True
herd.save()
return Response(status=status.HTTP_200_OK)
except APIException as e:
return Response(e, status=status.HTTP_204_NO_CONTENT)
@action(
methods=['post'],
detail=True,
url_path='delete',
url_name='delete',
name='delete'
)
@transaction.atomic
def delete(self, request, pk=None):
""" full delete of herd """
try:
herd = self.queryset.get(id=pk)
herd.delete()
return Response(status=status.HTTP_200_OK)
except APIException as e:
return Response(e, status=status.HTTP_204_NO_CONTENT)
@action(
methods=['get'],
detail=True,
url_path='live_stocks',
url_name='live_stocks',
name='live_stocks'
)
def live_stocks(self, request, pk=None):
""" list of herd live_stocks"""
herd = self.get_object()
queryset = herd.live_stock_herd.all() # get herd live_stocks
# paginate queryset
page = self.paginate_queryset(queryset)
if page is not None:
serializer = LiveStockSerializer(page, many=True)
return self.get_paginated_response(serializer.data)
class RancherViewSet(viewsets.ModelViewSet, DynamicSearchMixin, POSDeviceMixin):
queryset = Rancher.objects.all() # noqa
serializer_class = RancherSerializer
permission_classes = [AllowAny]
search_fields = [
"ranching_farm",
"first_name",
"last_name",
"mobile",
"national_code",
"birthdate",
"nationality",
"address",
"province__name",
"city__name",
]
@action(
methods=['post'],
detail=False,
url_name='check_national_code',
url_path='check_national_code',
name='check_national_code'
)
@transaction.atomic
def check_national_code(self, request):
""" check national code & existence of rancher """
rancher = self.queryset.filter(national_code=request.data['national_code'])
org = self.get_device_organization()
if len(rancher) > 1:
raise DuplicateRancherException()
if rancher.exists():
# if not RancherOrganizationLink.objects.filter(organization=org, rancher=rancher).exists():
# if org.purchase_policy == 'INTERNAL_ONLY':
# raise RancherOrganizationLinkException()
serializer = self.serializer_class(rancher.first())
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response({
"message": "دامدار با کد ملی مد نظر وجود ندارد" # noqa
}, status=status.HTTP_404_NOT_FOUND)