Welcome To Our Shell

Mister Spy & Souheyl Bypass Shell

Current Path : /var/www/bavspeed/api/core/

Linux ift1.ift-informatik.de 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
Upload File :
Current File : /var/www/bavspeed/api/core/views.py

from rest_framework import viewsets, generics, status, permissions, serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework.parsers import MultiPartParser, FormParser

from django.shortcuts import get_object_or_404
from datetime import date
from dateutil.relativedelta import relativedelta
from django.http import Http404

from .models import User, Company, EmployeeProfile, Contribution, PlanRetraite
from .serializers import (
    UserSerializer, CompanySerializer, EmployeeProfileSerializer,
    ContributionSerializer, 
    CompanyUpdateSerializer, PensionSimulationSerializer,
    CustomTokenObtainPairSerializer, EmployeeProfileCreateSerializer,
    PlanRetraiteSerializer, UserRegistrationSerializer
)
from .permissions import IsCompanyOwner


# ------------------------- AUTH & USER -------------------------
class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer


class UserMeView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        data = UserSerializer(user).data
        try:
            if user.role == User.EMPLOYEE:
                employee_profile = EmployeeProfile.objects.get(user=user)
                data['employee_profile'] = EmployeeProfileSerializer(employee_profile).data
        except EmployeeProfile.DoesNotExist:
            data['employee_profile'] = None
        return Response(data)


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


# ------------------------- COMPANY -------------------------
class CompanyViewSet(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser] 
    
    def retrieve(self, request):
        """
        GET /company/ → Retourne les infos de l’entreprise de l’employeur connecté
        """
        if not request.user.company:
            return Response({"detail": "Aucune entreprise associée."}, status=status.HTTP_404_NOT_FOUND)

        serializer = CompanySerializer(request.user.company)
        return Response(serializer.data)

    def partial_update(self, request):
        """
        PATCH /company/ → Met à jour les infos de l’entreprise (inclut le logo)
        """
        company = request.user.company
        if not company:
            return Response({"detail": "Entreprise non trouvée."}, status=status.HTTP_404_NOT_FOUND)

        serializer = CompanySerializer(company, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class CompanyDetailView(generics.RetrieveUpdateAPIView):
    serializer_class = CompanyUpdateSerializer
    permission_classes = [IsAuthenticated, IsCompanyOwner]

    def get_object(self):
        return self.request.user.company


# ------------------------- PLAN RETRAITE -------------------------
class PlanRetraiteViewSet(viewsets.ModelViewSet):
    queryset = PlanRetraite.objects.all()
    serializer_class = PlanRetraiteSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        if self.request.user.role == User.EMPLOYER:
            return PlanRetraite.objects.filter(is_default=True) | PlanRetraite.objects.all()
        elif self.request.user.role == User.EMPLOYEE:
            return PlanRetraite.objects.filter(is_default=True)
        return PlanRetraite.objects.all()


# ------------------------- EMPLOYÉS -------------------------
class IsEmployer(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user.is_authenticated and request.user.role == User.EMPLOYER


class EmployeeProfileViewSet(viewsets.ModelViewSet):
    queryset = EmployeeProfile.objects.all()
    permission_classes = [IsAuthenticated, IsEmployer]

    def get_queryset(self):
        return EmployeeProfile.objects.filter(company=self.request.user.company)

    def get_serializer_class(self):
        if self.action in ['create', 'update', 'partial_update']:
            return EmployeeProfileCreateSerializer
        return EmployeeProfileSerializer

    def perform_create(self, serializer):
        user_id = self.request.data.get('user_id')
        if not user_id:
            raise serializers.ValidationError("user_id est requis")

        try:
            user = User.objects.get(id=user_id, role=User.EMPLOYEE)
        except User.DoesNotExist:
            raise serializers.ValidationError("Utilisateur employé introuvable")

        if hasattr(user, 'employee_profile'):
            raise serializers.ValidationError("Ce profil employé existe déjà")

        plan_id = self.request.data.get('plan_retraite')
        if not plan_id:
            raise serializers.ValidationError("Le plan de retraite est requis")

        try:
            plan = PlanRetraite.objects.get(id=plan_id)
        except PlanRetraite.DoesNotExist:
            raise serializers.ValidationError("Plan de retraite introuvable")

        serializer.save(user=user, company=self.request.user.company, plan_retraite=plan)


class EmployeeDetailView(generics.GenericAPIView):
    serializer_class = EmployeeProfileSerializer
    permission_classes = [IsAuthenticated, IsCompanyOwner]
    lookup_field = 'matricule'

    def get_queryset(self):
        return EmployeeProfile.objects.filter(company=self.request.user.company)

    def get(self, request, matricule=None):
        if matricule:
            try:
                employee = self.get_queryset().get(matricule=matricule)
                serializer = self.get_serializer(employee)
                return Response(serializer.data)
            except EmployeeProfile.DoesNotExist:
                return Response({"detail": "Employé introuvable."}, status=404)
        else:
            employees = self.get_queryset()
            serializer = self.get_serializer(employees, many=True)
            return Response(serializer.data)

    def post(self, request, *args, **kwargs):
        serializer = EmployeeProfileCreateSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            employee = serializer.save()
            return Response(EmployeeProfileSerializer(employee).data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, matricule=None, *args, **kwargs):
        try:
            employee = self.get_queryset().get(matricule=matricule)
        except EmployeeProfile.DoesNotExist:
            return Response({"detail": "Employé introuvable."}, status=404)

        serializer = EmployeeProfileCreateSerializer(
            employee, data=request.data, partial=True, context={'request': request}
        )
        if serializer.is_valid():
            employee = serializer.save()
            return Response(EmployeeProfileSerializer(employee).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# ------------------------- SIMULATION -------------------------
class PensionSimulationView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        if request.user.role != User.EMPLOYEE:
            raise PermissionDenied("Accès réservé aux employés")

        profile = request.user.employee_profile
        plan = profile.plan_retraite

        if not plan:
            raise ValidationError("Aucun plan de retraite associé à ce profil")

        years = relativedelta(date.today(), profile.hire_date).years
        pension = profile.salary * (plan.taux / 100) * years

        return Response({
            "pension": round(pension, 2),
            "years_of_service": years,
            "taux": plan.taux,
            "salaire": float(profile.salary),
            "plan_retraite": plan.nom
        })


# ------------------------- CONTRIBUTIONS -------------------------
class ContributionListView(generics.ListAPIView):
    serializer_class = ContributionSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        if self.request.user.role != User.EMPLOYEE:
            raise PermissionDenied("Accès réservé aux employés")
        return Contribution.objects.filter(employee=self.request.user.employee_profile)


# ------------------------- USER REGISTRATION -------------------------
class UserRegistrationView(APIView):
    def post(self, request):
        serializer = UserRegistrationSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({
                "id": user.id,
                "username": user.username,
                "role": user.role,
            }, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


bypass 1.0, Devloped By El Moujahidin (the source has been moved and devloped)
Email: contact@elmoujehidin.net bypass 1.0, Devloped By El Moujahidin (the source has been moved and devloped) Email: contact@elmoujehidin.net