Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get all user list , Job Application , Get Job status, Job Application Acceptance, Reject API #79

Closed
wants to merge 16 commits into from
14 changes: 14 additions & 0 deletions furbaby/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from rest_framework import serializers
from .models import Users, Locations, Pets
from .models import Users, Applications
from .models import Users, Locations
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ValidationError

Expand Down Expand Up @@ -47,6 +49,18 @@ class UserLoginSerializer(serializers.Serializer):
password = serializers.CharField(min_length=8, write_only=True)


class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = "__all__"


class ApplicationsSerializer(serializers.ModelSerializer):
class Meta:
model = Applications
fields = "__all__"


class UserLocationSerializer(serializers.Serializer):
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
address = serializers.CharField(max_length=200)
Expand Down
23 changes: 20 additions & 3 deletions furbaby/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@
include("django_rest_passwordreset.urls", namespace="password_reset"),
),
path("api/user", views.user_view, name="user-info"),
path("user-list/", views.UserList.as_view(), name="user-list"),
path(
"jobs/<uuid:job_id>/apply/",
views.ApplyForJobView.as_view(),
name="apply_for_job",
),
path("get-job-status/<uuid:job_id>", views.GetJobStatus.as_view()),
path(
"api/user/profile_picture",
views.handle_profile_picture,
Expand All @@ -40,8 +47,18 @@
path("api/user/locations", views.user_location_view, name="user-location"),
path("pets/", PetListCreateView.as_view(), name="pet-list-create"),
path(
"pets/<uuid:pk>/",
PetRetrieveUpdateDeleteView.as_view(),
name="pet-retrieve-update-delete",
"pets/<uuid:pk>/", PetRetrieveUpdateDeleteView.as_view(), name="pet-retrieve-update-delete"
),
path("api/user/locations", views.user_location_view, name="user-location"),
path(
"jobs/<uuid:job_id>/applications/<uuid:application_id>/accept/",
views.accept_application,
name="accept_application",
),
path(
"jobs/<uuid:job_id>/applications/<uuid:application_id>/reject/",
views.reject_application,
name="reject_application",
),
path("/get-previously-completed-jobs", views.GetPetSitterJobHistory.as_view()),
]
170 changes: 166 additions & 4 deletions furbaby/api/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
import os
from django.http import JsonResponse, HttpResponse
import json
from django.http import JsonResponse
from django.contrib.auth import login, logout
from drf_standardized_errors.handler import exception_handler
from rest_framework import status
Expand All @@ -22,6 +22,8 @@
UserLocationSerializer,
UserLoginSerializer,
PetSerializer,
ApplicationsSerializer,
CustomUserSerializer,
)

from django.core.mail import EmailMultiAlternatives
Expand All @@ -33,6 +35,9 @@
from django.views.decorators.csrf import csrf_protect
from django.core.serializers import serialize

from .models import Users, Jobs, Pets, Applications
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import ValidationError
import boto3
from botocore.exceptions import ClientError

Expand Down Expand Up @@ -162,7 +167,7 @@ def user_view(request):
return email_backend.get_user_info(request, request.user.email)

if request.method in ["PUT", "PATCH"]:
return __update_user_info__(request)
return _update_user_info_(request)

if request.method == "DELETE":
return email_backend.delete_user(request, request.user.email)
Expand All @@ -173,7 +178,7 @@ def user_view(request):
)


def __update_user_info__(request):
def _update_user_info_(request):
if not request.user.is_authenticated:
return json_response(
{
Expand Down Expand Up @@ -858,3 +863,160 @@ def user_location_view(request):
{"error": "incorrect request method supplied"},
status=status.HTTP_405_METHOD_NOT_ALLOWED,
)


class UserList(GenericAPIView):
def get(self, request, *args, **kwargs):
queryset = Users.objects.all()
try:
return json_response(data=list(queryset.values()), status=status.HTTP_200_OK)
except Exception as e:
return json_response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ApplyForJobView(GenericAPIView):
serializer_class = ApplicationsSerializer

def post(self, request, job_id):
print(request.user.user_type)
if "owner" in request.user.user_type:
return json_response(
"Pet Owner are not allowed to apply for Job", status=status.HTTP_400_BAD_REQUEST
)
print("JobID", job_id)
print("request", request)
try:
job = Jobs.objects.get(id=job_id)
print("Jobs", job.values())
except Jobs.DoesNotExist:
return json_response(
{"error": "Job not found or you do not have permission to access this job."},
status=status.HTTP_404_NOT_FOUND,
)
print("User data", request.data.get("user"))
user_serializer = CustomUserSerializer(data=request.data.get("user"))
if not user_serializer.is_valid():
return json_response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

application_data = {
"job_id": job_id,
"user": request.data.get("user"),
"status": "accepted",
"details": {},
}

application_serializer = self.get_serializer(data=application_data)
if application_serializer.is_valid():
application_serializer.save()
return json_response(application_serializer.data, status=status.HTTP_201_CREATED)
else:
return json_response(application_serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class GetJobStatus(APIView):
def get(self, request, job_id):
try:
job = Jobs.objects.get(id=job_id)
except Jobs.DoesNotExist:
return json_response({"error": "Job does not exist"}, status=status.HTTP_404_NOT_FOUND)

data = {"job_status": job.status}
return json_response(data, status=status.HTTP_200_OK)


@api_view(["POST"])
def accept_application(request, job_id, application_id):
try:
request.data["user_id"] = request.user.id
print(request.user.user_type)
if "owner" in request.user.user_type:
pet_id = request.data.get("pet")
try:
pet = Pets.objects.get(id=pet_id, owner=request.user)
except Pets.DoesNotExist:
raise ValidationError("Invalid pet ID or you do not own the pet.")

# return json_response({"error": "You do not have permission to accept the job for this pet."},
# status=status.HTTP_400_BAD_REQUEST)
# return json_response({"error": "You do not have permission to accept the job for this pet."},
# status=status.HTTP_400_BAD_REQUEST)

# Ensure that the pet owner is the one creating the job
if pet.owner != request.user:
raise BasePermission.PermissionDenied(
"You do not have permission to accept the job for this pet."
)
job = Jobs.objects.get(id=job_id)
application = Applications.objects.get(id=application_id, job=job)

if job.user != request.user: # Check if the requester is the job owner
return json_response(
{"error": "You are not authorized to perform this action"},
status=status.HTTP_401_UNAUTHORIZED,
)

# Mark the application as accepted
application.status = "accepted"
application.save()

return json_response({"message": "Application accepted successfully"})

except (Jobs.DoesNotExist, Applications.DoesNotExist):
return json_response(
{"error": "Job or application does not exist"}, status=status.HTTP_404_NOT_FOUND
)


@api_view(["POST"])
def reject_application(request, job_id, application_id):
try:
request.data["user_id"] = request.user.id
print(request.user.user_type)
if "owner" in request.user.user_type:
pet_id = request.data.get("pet")
try:
pet = Pets.objects.get(id=pet_id, owner=request.user)
except Pets.DoesNotExist:
raise ValidationError("Invalid pet ID or you do not own the pet.")

# Ensure that the pet owner is the one creating the job
if pet.owner != request.user:
raise BasePermission.PermissionDenied(
"You do not have permission to accept the job for this pet."
)
job = Jobs.objects.get(id=job_id)
application = Applications.objects.get(id=application_id, job=job)

if job.user != request.user: # Check if the requester is the job owner
return json_response(
{"error": "You are not authorized to perform this action"},
status=status.HTTP_401_UNAUTHORIZED,
)

# Mark the application as rejected or remove it as per your business logic
application.status = "rejected"
application.save()

# Additional logic: Notify the pet sitter about rejection

return json_response({"message": "Application rejected successfully"})
except (Jobs.DoesNotExist, Applications.DoesNotExist):
return json_response(
{"error": "Job or application does not exist"}, status=status.HTTP_404_NOT_FOUND
)


class GetPetSitterJobHistory(APIView):
def post(self, request):
if "owner" in request.user.user_type:
return json_response("Invalid User: Pet Owner", status=status.HTTP_400_BAD_REQUEST)

job_history = Jobs.objects.filter(user_id=request.user.id, status="job_complete").values(
"start", "end", "pet", "location", "pay"
)

response_message = "Completed jobs history fetched successfully"
if not job_history:
response_message = "No completed jobs history found for this pet " "sitter"
data = {"message": response_message, "job_history": job_history}
return json_response(data, status=status.HTTP_200_OK)
Loading