mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-08-25 21:59:40 +00:00
Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
f3478c972e | |||
bc18c67527 | |||
ffb99f5099 | |||
8183edf319 | |||
8f214d11a7 | |||
b5a89df59a | |||
5524eeed64 | |||
aeaa7d7ab8 | |||
69be3bb2ac | |||
be9f600bcc | |||
65d0932893 | |||
9b14eedb18 | |||
6c96ea0820 | |||
a93dc83bd1 | |||
116fb00358 | |||
20fa6e43da | |||
2cffc4e128 | |||
7b75a3233c |
@ -1,7 +1,7 @@
|
||||
{% extends "templated_email/email_base.email" %}
|
||||
|
||||
{% block subject %}
|
||||
{{subject}}
|
||||
Support Mail
|
||||
{% endblock %}
|
||||
|
||||
{% block plain %}
|
||||
|
@ -1,6 +1,6 @@
|
||||
"""Account utils"""
|
||||
from celery import shared_task
|
||||
|
||||
import random
|
||||
"""Import django"""
|
||||
from django.conf import settings
|
||||
from rest_framework import viewsets, status
|
||||
@ -167,7 +167,7 @@ def user_device_details(user, device_id):
|
||||
return False
|
||||
|
||||
|
||||
def send_support_email(name, sender, subject, message):
|
||||
def send_support_email(name, sender, message):
|
||||
"""Send otp on email with template"""
|
||||
to_email = [settings.EMAIL_FROM_ADDRESS]
|
||||
from_email = settings.DEFAULT_ADDRESS
|
||||
@ -179,7 +179,6 @@ def send_support_email(name, sender, subject, message):
|
||||
context={
|
||||
'name': name.title(),
|
||||
'sender': sender,
|
||||
'subject': subject,
|
||||
'message': message
|
||||
}
|
||||
)
|
||||
@ -191,7 +190,8 @@ def custom_response(detail, data=None, response_status=status.HTTP_200_OK, count
|
||||
if not data:
|
||||
"""when data is none"""
|
||||
data = None
|
||||
return Response({"data": data, "message": detail, "status": "success", "code": response_status, "count": count})
|
||||
return Response({"data": data, "message": detail, "status": "success",
|
||||
"code": response_status, "count": count})
|
||||
|
||||
|
||||
def custom_error_response(detail, response_status):
|
||||
@ -288,3 +288,42 @@ def get_user_full_name(user_obj):
|
||||
to get user's full name
|
||||
"""
|
||||
return f"{user_obj.first_name} {user_obj.last_name}" if user_obj.first_name or user_obj.last_name else "User"
|
||||
|
||||
|
||||
def make_special_password(length=10):
|
||||
"""
|
||||
to make secured password
|
||||
:param length:
|
||||
:return:
|
||||
"""
|
||||
# Define character sets
|
||||
lowercase_letters = string.ascii_lowercase
|
||||
uppercase_letters = string.ascii_uppercase
|
||||
digits = string.digits
|
||||
special_characters = '!@#$%^&*()_-+=<>?/[]{}|'
|
||||
|
||||
# Combine character sets
|
||||
all_characters = lowercase_letters + uppercase_letters + digits + special_characters
|
||||
|
||||
# Create a password with random characters
|
||||
password = (
|
||||
secrets.choice(lowercase_letters) +
|
||||
secrets.choice(uppercase_letters) +
|
||||
secrets.choice(digits) +
|
||||
secrets.choice(special_characters) +
|
||||
''.join(secrets.choice(all_characters) for _ in range(length - 4))
|
||||
)
|
||||
|
||||
# Shuffle the characters to make it more random
|
||||
password_list = list(password)
|
||||
random.shuffle(password_list)
|
||||
return ''.join(password_list)
|
||||
|
||||
def task_status_fun(status_value):
|
||||
"""task status"""
|
||||
task_status_value = ['1']
|
||||
if str(status_value) == '2':
|
||||
task_status_value = ['2', '4']
|
||||
elif str(status_value) == '3':
|
||||
task_status_value = ['3', '5', '6']
|
||||
return task_status_value
|
||||
|
@ -689,11 +689,10 @@ class SendSupportEmail(views.APIView):
|
||||
def post(self, request):
|
||||
name = request.data.get('name')
|
||||
sender = request.data.get('email')
|
||||
subject = request.data.get('subject')
|
||||
message = request.data.get('message')
|
||||
if name and sender and subject and message:
|
||||
if name and sender and message:
|
||||
try:
|
||||
send_support_email(name, sender, subject, message)
|
||||
send_support_email(name, sender, message)
|
||||
return custom_response(SUCCESS_CODE['3019'], response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
@ -111,7 +111,10 @@ ERROR_CODE = {
|
||||
"2080": "Can not add App version",
|
||||
"2081": "A junior can only be associated with a maximum of 3 guardian",
|
||||
# guardian code not exist
|
||||
"2082": "Guardian code does not exist"
|
||||
"2082": "Guardian code does not exist",
|
||||
"2083": "You can not start this task because guardian is not associate with you",
|
||||
"2084": "You can not complete this task because guardian is not associate with you",
|
||||
"2085": "You can not take action on this task because junior is not associate with you"
|
||||
|
||||
}
|
||||
"""Success message code"""
|
||||
@ -122,11 +125,11 @@ SUCCESS_CODE = {
|
||||
# Success code for Thank you
|
||||
"3002": "Thank you for contacting us! Our Consumer Experience Team will reach out to you shortly.",
|
||||
# Success code for account activation
|
||||
"3003": "Log in successful",
|
||||
"3003": "Log in successful.",
|
||||
# Success code for password reset
|
||||
"3004": "Password reset link has been sent to your email address",
|
||||
"3004": "Password reset link has been sent to your email address.",
|
||||
# Success code for link verified
|
||||
"3005": "Your account is deleted successfully.",
|
||||
"3005": "Your account has been deleted successfully.",
|
||||
# Success code for password reset
|
||||
"3006": "Password reset successful. You can now log in with your new password.",
|
||||
# Success code for password update
|
||||
@ -134,11 +137,11 @@ SUCCESS_CODE = {
|
||||
# Success code for valid link
|
||||
"3008": "You have a valid link.",
|
||||
# Success code for logged out
|
||||
"3009": "You have successfully logged out!",
|
||||
"3009": "You have successfully logged out.",
|
||||
# Success code for check all fields
|
||||
"3010": "All fields are valid",
|
||||
"3011": "Email OTP Verified successfully",
|
||||
"3012": "Phone OTP Verified successfully",
|
||||
"3010": "All fields are valid.",
|
||||
"3011": "Email OTP has been verified successfully.",
|
||||
"3012": "Phone OTP has been verified successfully.",
|
||||
"3013": "Valid Guardian code",
|
||||
"3014": "Password has been updated successfully.",
|
||||
"3015": "Verification code has been sent on your email.",
|
||||
@ -147,39 +150,39 @@ SUCCESS_CODE = {
|
||||
"3018": "Task created successfully",
|
||||
"3019": "Support Email sent successfully",
|
||||
"3020": "Logged out successfully.",
|
||||
"3021": "Added junior successfully",
|
||||
"3022": "Removed junior successfully",
|
||||
"3023": "Junior is approved successfully",
|
||||
"3024": "Junior request is rejected successfully",
|
||||
"3025": "Task is approved successfully",
|
||||
"3026": "Task is rejected successfully",
|
||||
"3021": "Junior has been added successfully.",
|
||||
"3022": "Junior has been removed successfully.",
|
||||
"3023": "Junior has been approved successfully.",
|
||||
"3024": "Junior request is rejected successfully.",
|
||||
"3025": "Task is approved successfully.",
|
||||
"3026": "Task is rejected successfully.",
|
||||
"3027": "Article has been created successfully.",
|
||||
"3028": "Article has been updated successfully.",
|
||||
"3029": "Article has been deleted successfully.",
|
||||
"3030": "Article Card has been removed successfully.",
|
||||
"3031": "Article Survey has been removed successfully.",
|
||||
"3032": "Task request sent successfully",
|
||||
"3033": "Valid Referral code",
|
||||
"3034": "Invite guardian successfully",
|
||||
"3035": "Task started successfully",
|
||||
"3036": "Task reassign successfully",
|
||||
"3032": "Task request sent successfully.",
|
||||
"3033": "Valid Referral code.",
|
||||
"3034": "Invite guardian successfully.",
|
||||
"3035": "Task started successfully.",
|
||||
"3036": "Task reassign successfully.",
|
||||
"3037": "Profile has been updated successfully.",
|
||||
"3038": "Status has been changed successfully.",
|
||||
# notification read
|
||||
"3039": "Notification read successfully",
|
||||
"3039": "Notification read successfully.",
|
||||
# start article
|
||||
"3040": "Start article successfully",
|
||||
"3040": "Start article successfully.",
|
||||
# complete article
|
||||
"3041": "Article completed successfully",
|
||||
"3041": "Article completed successfully.",
|
||||
# submit assessment successfully
|
||||
"3042": "Assessment completed successfully",
|
||||
"3042": "Assessment completed successfully.",
|
||||
# read article
|
||||
"3043": "Read article card successfully",
|
||||
"3043": "Read article card successfully.",
|
||||
# remove guardian code request
|
||||
"3044": "Remove guardian code request successfully",
|
||||
"3044": "Remove guardian code request successfully.",
|
||||
# create faq
|
||||
"3045": "Create FAQ data",
|
||||
"3046": "Add App version successfully"
|
||||
"3045": "Create FAQ data.",
|
||||
"3046": "Add App version successfully."
|
||||
|
||||
}
|
||||
"""status code error"""
|
||||
|
Binary file not shown.
39
docker-compose-prod.yml
Normal file
39
docker-compose-prod.yml
Normal file
@ -0,0 +1,39 @@
|
||||
version: '3'
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./nginx:/etc/nginx/conf.d
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- web
|
||||
web:
|
||||
build: .
|
||||
container_name: prod_django
|
||||
restart: always
|
||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.7
|
||||
container_name: prod_rabbitmq
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
ports:
|
||||
- 5673:5673
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: celery
|
||||
container_name: prod_celery
|
||||
restart: "always"
|
||||
command: bash -c " celery -A zod_bank.celery worker --concurrency=1 -B -l DEBUG -E"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- broker
|
39
docker-compose-qa.yml
Normal file
39
docker-compose-qa.yml
Normal file
@ -0,0 +1,39 @@
|
||||
version: '3'
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./nginx:/etc/nginx/conf.d
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- web
|
||||
web:
|
||||
build: .
|
||||
container_name: qa_django
|
||||
restart: always
|
||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.7
|
||||
container_name: qa_rabbitmq
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
ports:
|
||||
- 5673:5673
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: celery
|
||||
container_name: qa_celery
|
||||
restart: "always"
|
||||
command: bash -c " celery -A zod_bank.celery worker --concurrency=1 -B -l DEBUG -E"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- broker
|
39
docker-compose-stage.yml
Normal file
39
docker-compose-stage.yml
Normal file
@ -0,0 +1,39 @@
|
||||
version: '3'
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./nginx:/etc/nginx/conf.d
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- web
|
||||
web:
|
||||
build: .
|
||||
container_name: stage_django
|
||||
restart: always
|
||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.7
|
||||
container_name: stage_rabbitmq
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
ports:
|
||||
- 5673:5673
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: celery
|
||||
container_name: stage_celery
|
||||
restart: "always"
|
||||
command: bash -c " celery -A zod_bank.celery worker --concurrency=1 -B -l DEBUG -E"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- broker
|
@ -28,7 +28,7 @@ from base.constants import NUMBER, JUN, ZOD, GRD, Already_register_user, GUARDIA
|
||||
from junior.models import Junior, JuniorPoints, JuniorGuardianRelationship
|
||||
from .utils import real_time, convert_timedelta_into_datetime, update_referral_points
|
||||
# notification's constant
|
||||
from notifications.constants import TASK_APPROVED, TASK_REJECTED
|
||||
from notifications.constants import TASK_APPROVED, TASK_REJECTED, TASK_ASSIGNED
|
||||
# send notification function
|
||||
from notifications.utils import send_notification
|
||||
from django.core.exceptions import ValidationError
|
||||
@ -229,20 +229,22 @@ class TaskSerializer(serializers.ModelSerializer):
|
||||
return value
|
||||
def create(self, validated_data):
|
||||
"""create default task image data"""
|
||||
guardian = Guardian.objects.filter(user=self.context['user']).last()
|
||||
guardian = self.context['guardian']
|
||||
# update image of the task
|
||||
images = self.context['image']
|
||||
junior_ids = self.context['junior_data']
|
||||
junior_data = junior_ids[0].split(',')
|
||||
junior_data = self.context['junior_data']
|
||||
tasks_created = []
|
||||
|
||||
for junior_id in junior_data:
|
||||
for junior in junior_data:
|
||||
# create task
|
||||
task_data = validated_data.copy()
|
||||
task_data['guardian'] = guardian
|
||||
task_data['default_image'] = images
|
||||
task_data['junior'] = Junior.objects.filter(id=junior_id).last()
|
||||
task_data['junior'] = junior
|
||||
instance = JuniorTask.objects.create(**task_data)
|
||||
tasks_created.append(instance)
|
||||
send_notification.delay(TASK_ASSIGNED, guardian.user.id, GUARDIAN,
|
||||
junior.auth.id, {'task_id': instance.id})
|
||||
return instance
|
||||
|
||||
class GuardianDetailSerializer(serializers.ModelSerializer):
|
||||
|
@ -1,4 +1,5 @@
|
||||
"""Views of Guardian"""
|
||||
import math
|
||||
|
||||
# django imports
|
||||
# Import IsAuthenticated
|
||||
@ -16,6 +17,7 @@ from base.constants import guardian_code_tuple
|
||||
from rest_framework.filters import SearchFilter
|
||||
from django.utils import timezone
|
||||
|
||||
from base.pagination import CustomPageNumberPagination
|
||||
# Import guardian's model,
|
||||
# Import junior's model,
|
||||
# Import account's model,
|
||||
@ -36,7 +38,7 @@ from .models import Guardian, JuniorTask
|
||||
from junior.models import Junior, JuniorPoints, JuniorGuardianRelationship
|
||||
from account.models import UserEmailOtp, UserNotification, UserDeviceDetails
|
||||
from .tasks import generate_otp
|
||||
from account.utils import custom_response, custom_error_response, OTP_EXPIRY, send_otp_email
|
||||
from account.utils import custom_response, custom_error_response, send_otp_email, task_status_fun
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
||||
from base.constants import NUMBER, GUARDIAN_CODE_STATUS, GUARDIAN
|
||||
from .utils import upload_image_to_alibaba
|
||||
@ -135,7 +137,8 @@ class TaskListAPIView(viewsets.ModelViewSet):
|
||||
Params
|
||||
status
|
||||
search
|
||||
page"""
|
||||
page
|
||||
junior"""
|
||||
serializer_class = TaskDetailsSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
filter_backends = (SearchFilter,)
|
||||
@ -145,8 +148,8 @@ class TaskListAPIView(viewsets.ModelViewSet):
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = JuniorTask.objects.filter(guardian__user=self.request.user
|
||||
).prefetch_related('junior', 'junior__auth'
|
||||
).order_by('due_date', 'created_at')
|
||||
).select_related('junior', 'junior__auth'
|
||||
).order_by('due_date', 'created_at')
|
||||
|
||||
queryset = self.filter_queryset(queryset)
|
||||
return queryset
|
||||
@ -154,15 +157,19 @@ class TaskListAPIView(viewsets.ModelViewSet):
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""Create guardian profile"""
|
||||
status_value = self.request.GET.get('status')
|
||||
junior = self.request.GET.get('junior')
|
||||
queryset = self.get_queryset()
|
||||
if status_value and status_value != '0':
|
||||
queryset = queryset.filter(task_status=status_value)
|
||||
paginator = self.pagination_class()
|
||||
task_status = task_status_fun(status_value)
|
||||
if status_value:
|
||||
queryset = queryset.filter(task_status__in=task_status)
|
||||
if junior:
|
||||
queryset = queryset.filter(junior=int(junior))
|
||||
paginator = CustomPageNumberPagination()
|
||||
# use Pagination
|
||||
paginated_queryset = paginator.paginate_queryset(queryset, request)
|
||||
# use TaskDetailsSerializer serializer
|
||||
serializer = self.serializer_class(paginated_queryset, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
return paginator.get_paginated_response(serializer.data)
|
||||
|
||||
|
||||
class CreateTaskAPIView(viewsets.ModelViewSet):
|
||||
@ -177,48 +184,52 @@ class CreateTaskAPIView(viewsets.ModelViewSet):
|
||||
"""
|
||||
try:
|
||||
image = request.data['default_image']
|
||||
juniors = request.data['junior'].split(',')
|
||||
for junior in juniors:
|
||||
junior_id = Junior.objects.filter(id=junior).last()
|
||||
if junior_id:
|
||||
guardian_data = Guardian.objects.filter(user=request.user).last()
|
||||
index = junior_id.guardian_code.index(guardian_data.guardian_code)
|
||||
status_index = junior_id.guardian_code_status[index]
|
||||
junior_ids = request.data['junior'].split(',')
|
||||
|
||||
invalid_junior_ids = [junior_id for junior_id in junior_ids if not junior_id.isnumeric()]
|
||||
if invalid_junior_ids:
|
||||
# At least one junior value is not an integer
|
||||
return custom_error_response(ERROR_CODE['2047'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
allowed_extensions = ['.jpg', '.jpeg', '.png']
|
||||
if not any(extension in str(image) for extension in allowed_extensions):
|
||||
return custom_error_response(ERROR_CODE['2048'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
if 'https' in str(image):
|
||||
image_data = image
|
||||
else:
|
||||
filename = f"images/{image}"
|
||||
if image and image.size == NUMBER['zero']:
|
||||
return custom_error_response(ERROR_CODE['2035'],
|
||||
response_status=status.HTTP_400_BAD_REQUEST)
|
||||
image_data = upload_image_to_alibaba(image, filename)
|
||||
request.data.pop('default_image')
|
||||
|
||||
guardian = Guardian.objects.filter(user=request.user).select_related('user').last()
|
||||
junior_data = Junior.objects.filter(id__in=junior_ids,
|
||||
guardian_code__contains=[guardian.guardian_code]
|
||||
).select_related('auth')
|
||||
if junior_data:
|
||||
for junior in junior_data:
|
||||
index = junior.guardian_code.index(guardian.guardian_code)
|
||||
status_index = junior.guardian_code_status[index]
|
||||
if status_index == str(NUMBER['three']):
|
||||
return custom_error_response(ERROR_CODE['2078'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
allowed_extensions = ['.jpg', '.jpeg', '.png']
|
||||
if not any(extension in str(image) for extension in allowed_extensions):
|
||||
return custom_error_response(ERROR_CODE['2048'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
if not junior.isnumeric():
|
||||
"""junior value must be integer"""
|
||||
return custom_error_response(ERROR_CODE['2047'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
data = request.data
|
||||
if 'https' in str(image):
|
||||
image_data = image
|
||||
else:
|
||||
filename = f"images/{image}"
|
||||
if image and image.size == NUMBER['zero']:
|
||||
return custom_error_response(ERROR_CODE['2035'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
image_url = upload_image_to_alibaba(image, filename)
|
||||
image_data = image_url
|
||||
data.pop('default_image')
|
||||
junior_data = data.pop('junior')
|
||||
# use TaskSerializer serializer
|
||||
serializer = TaskSerializer(context={"user":request.user, "image":image_data,
|
||||
"junior_data":junior_data}, data=data)
|
||||
if serializer.is_valid():
|
||||
# save serializer
|
||||
task = serializer.save()
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE['2047'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
send_notification.delay(TASK_ASSIGNED, request.auth.payload['user_id'], GUARDIAN,
|
||||
junior_id.auth.id, {'task_id': task.id})
|
||||
return custom_response(SUCCESS_CODE['3018'], response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE['2047'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
# use TaskSerializer serializer
|
||||
serializer = TaskSerializer(context={"guardian": guardian, "image": image_data,
|
||||
"junior_data": junior_data}, data=request.data)
|
||||
if serializer.is_valid():
|
||||
# save serializer
|
||||
serializer.save()
|
||||
# removed send notification method and used in serializer
|
||||
return custom_response(SUCCESS_CODE['3018'], response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class SearchTaskListAPIView(viewsets.ModelViewSet):
|
||||
"""Filter task"""
|
||||
serializer_class = TaskDetailsSerializer
|
||||
@ -347,6 +358,8 @@ class ApproveTaskAPIView(viewsets.ModelViewSet):
|
||||
task_queryset = JuniorTask.objects.filter(id=self.request.data.get('task_id'),
|
||||
guardian=guardian,
|
||||
junior=self.request.data.get('junior_id')).last()
|
||||
if task_queryset and guardian.guardian_code not in task_queryset.junior.guardian_code:
|
||||
return custom_error_response(ERROR_CODE['2084'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
if task_queryset and (task_queryset.junior.is_deleted or not task_queryset.junior.is_active):
|
||||
return custom_error_response(ERROR_CODE['2072'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
# use ApproveJuniorSerializer serializer
|
||||
|
@ -11,7 +11,7 @@ from django.utils import timezone
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
# local imports
|
||||
from account.utils import send_otp_email, generate_code
|
||||
from account.utils import send_otp_email, generate_code, make_special_password
|
||||
from junior.models import Junior, JuniorPoints, JuniorGuardianRelationship, JuniorArticlePoints, FAQ
|
||||
from guardian.tasks import generate_otp
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
||||
@ -297,8 +297,8 @@ class AddJuniorSerializer(serializers.ModelSerializer):
|
||||
user_data = User.objects.create(username=email, email=email,
|
||||
first_name=self.context['first_name'],
|
||||
last_name=self.context['last_name'])
|
||||
password = User.objects.make_random_password()
|
||||
user_data.set_password(password)
|
||||
special_password = make_special_password()
|
||||
user_data.set_password(special_password)
|
||||
user_data.save()
|
||||
junior_data = Junior.objects.create(auth=user_data, gender=validated_data.get('gender'),
|
||||
image=profile_image,
|
||||
@ -321,7 +321,7 @@ class AddJuniorSerializer(serializers.ModelSerializer):
|
||||
# add push notification
|
||||
UserNotification.objects.get_or_create(user=user_data)
|
||||
"""Notification email"""
|
||||
junior_notification_email.delay(email, full_name, email, password)
|
||||
junior_notification_email.delay(email, full_name, email, special_password)
|
||||
# push notification
|
||||
send_notification.delay(ASSOCIATE_JUNIOR, None, None, junior_data.auth.id, {})
|
||||
return junior_data
|
||||
|
@ -12,6 +12,10 @@ import datetime
|
||||
import requests
|
||||
|
||||
from rest_framework.viewsets import GenericViewSet, mixins
|
||||
import math
|
||||
|
||||
from base.pagination import CustomPageNumberPagination
|
||||
|
||||
"""Django app import"""
|
||||
from drf_yasg.utils import swagger_auto_schema
|
||||
from drf_yasg import openapi
|
||||
@ -43,7 +47,7 @@ from guardian.models import Guardian, JuniorTask
|
||||
from guardian.serializers import TaskDetailsSerializer, TaskDetailsjuniorSerializer
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
||||
from base.constants import NUMBER, ARTICLE_STATUS, none, GUARDIAN
|
||||
from account.utils import custom_response, custom_error_response
|
||||
from account.utils import custom_response, custom_error_response, task_status_fun
|
||||
from guardian.utils import upload_image_to_alibaba
|
||||
from .utils import update_positions_based_on_points
|
||||
from notifications.utils import send_notification
|
||||
@ -353,8 +357,8 @@ class JuniorTaskListAPIView(viewsets.ModelViewSet):
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = JuniorTask.objects.filter(junior__auth=self.request.user
|
||||
).prefetch_related('junior', 'junior__auth'
|
||||
).order_by('due_date', 'created_at')
|
||||
).select_related('junior', 'junior__auth'
|
||||
).order_by('due_date', 'created_at')
|
||||
|
||||
queryset = self.filter_queryset(queryset)
|
||||
return queryset
|
||||
@ -367,14 +371,15 @@ class JuniorTaskListAPIView(viewsets.ModelViewSet):
|
||||
try:
|
||||
status_value = self.request.GET.get('status')
|
||||
queryset = self.get_queryset()
|
||||
if status_value and status_value != '0':
|
||||
queryset = queryset.filter(task_status=status_value)
|
||||
paginator = self.pagination_class()
|
||||
task_status = task_status_fun(status_value)
|
||||
if status_value:
|
||||
queryset = queryset.filter(task_status__in=task_status)
|
||||
paginator = CustomPageNumberPagination()
|
||||
# use Pagination
|
||||
paginated_queryset = paginator.paginate_queryset(queryset, request)
|
||||
# use TaskDetails juniorSerializer serializer
|
||||
serializer = self.serializer_class(paginated_queryset, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
return paginator.get_paginated_response(serializer.data)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@ -403,10 +408,12 @@ class CompleteJuniorTaskAPIView(views.APIView):
|
||||
task_queryset = JuniorTask.objects.filter(id=task_id, junior__auth__email=self.request.user
|
||||
).select_related('guardian', 'junior').last()
|
||||
if task_queryset:
|
||||
if task_queryset.junior.is_deleted or not task_queryset.junior.is_active:
|
||||
if task_queryset.guardian.guardian_code not in task_queryset.junior.guardian_code:
|
||||
return custom_error_response(ERROR_CODE['2085'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
elif task_queryset.junior.is_deleted or not task_queryset.junior.is_active:
|
||||
return custom_error_response(ERROR_CODE['2074'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
# use CompleteTaskSerializer serializer
|
||||
if task_queryset.task_status in [str(NUMBER['four']), str(NUMBER['five'])]:
|
||||
elif task_queryset.task_status in [str(NUMBER['four']), str(NUMBER['five'])]:
|
||||
"""Already request send """
|
||||
return custom_error_response(ERROR_CODE['2049'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
serializer = CompleteTaskSerializer(task_queryset, data={'image': image_url}, partial=True)
|
||||
@ -511,7 +518,10 @@ class StartTaskAPIView(views.APIView):
|
||||
try:
|
||||
task_id = self.request.data.get('task_id')
|
||||
task_queryset = JuniorTask.objects.filter(id=task_id, junior__auth__email=self.request.user).last()
|
||||
print("task_queryset==>",task_queryset)
|
||||
if task_queryset and task_queryset.task_status == str(NUMBER['one']):
|
||||
if task_queryset.guardian.guardian_code not in task_queryset.junior.guardian_code:
|
||||
return custom_error_response(ERROR_CODE['2083'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
# use StartTaskSerializer serializer
|
||||
serializer = StartTaskSerializer(task_queryset, data=request.data, partial=True)
|
||||
if serializer.is_valid():
|
||||
|
@ -22,7 +22,7 @@ ARTICLE_REWARD_POINTS = 17
|
||||
REMOVE_JUNIOR = 18
|
||||
|
||||
TEST_NOTIFICATION = 99
|
||||
|
||||
# notification dictionary
|
||||
NOTIFICATION_DICT = {
|
||||
REGISTRATION: {
|
||||
"title": "Successfully registered!",
|
||||
|
@ -31,11 +31,16 @@ class RegisterDevice(serializers.Serializer):
|
||||
|
||||
class NotificationListSerializer(serializers.ModelSerializer):
|
||||
"""List of notification"""
|
||||
badge = serializers.SerializerMethodField()
|
||||
|
||||
class Meta(object):
|
||||
"""meta info"""
|
||||
model = Notification
|
||||
fields = ['id', 'data', 'is_read', 'created_at']
|
||||
fields = ['id', 'data', 'badge', 'is_read', 'created_at']
|
||||
|
||||
@staticmethod
|
||||
def get_badge(obj):
|
||||
return Notification.objects.filter(notification_to=obj.notification_to, is_read=False).count()
|
||||
|
||||
|
||||
class ReadNotificationSerializer(serializers.ModelSerializer):
|
||||
|
@ -15,6 +15,7 @@ from notifications.utils import send_notification_multiple_user
|
||||
from web_admin.models import Article, ArticleCard, SurveyOption, ArticleSurvey, DefaultArticleCardImage
|
||||
from web_admin.utils import pop_id, get_image_url
|
||||
from junior.models import JuniorArticlePoints, JuniorArticle
|
||||
|
||||
USER = get_user_model()
|
||||
|
||||
|
||||
@ -90,10 +91,9 @@ class ArticleSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
article_cards = attrs.get('article_cards', None)
|
||||
article_survey = attrs.get('article_survey', None)
|
||||
if article_cards is None or len(article_cards) > int(MAX_ARTICLE_CARD):
|
||||
if not 0 < len(article_cards) <= int(MAX_ARTICLE_CARD):
|
||||
raise serializers.ValidationError({'details': ERROR_CODE['2039']})
|
||||
if article_survey is None or len(article_survey) < int(MIN_ARTICLE_SURVEY) or int(
|
||||
MAX_ARTICLE_SURVEY) < len(article_survey):
|
||||
if not int(MIN_ARTICLE_SURVEY) <= len(article_survey) <= int(MAX_ARTICLE_SURVEY):
|
||||
raise serializers.ValidationError({'details': ERROR_CODE['2040']})
|
||||
return attrs
|
||||
|
||||
@ -185,6 +185,28 @@ class ArticleSerializer(serializers.ModelSerializer):
|
||||
return instance
|
||||
|
||||
|
||||
class ArticleStatusChangeSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
Article status change serializer
|
||||
"""
|
||||
class Meta:
|
||||
"""
|
||||
meta class
|
||||
"""
|
||||
model = Article
|
||||
fields = ('is_published', )
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
"""
|
||||
:param instance: article object
|
||||
:param validated_data:
|
||||
:return:
|
||||
"""
|
||||
instance.is_published = validated_data['is_published']
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
|
||||
class DefaultArticleCardImageSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
Article Card serializer
|
||||
@ -221,6 +243,7 @@ class DefaultArticleCardImageSerializer(serializers.ModelSerializer):
|
||||
card_image = DefaultArticleCardImage.objects.create(**validated_data)
|
||||
return card_image
|
||||
|
||||
|
||||
class ArticleListSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
serializer for article API
|
||||
@ -234,13 +257,14 @@ class ArticleListSerializer(serializers.ModelSerializer):
|
||||
meta class
|
||||
"""
|
||||
model = Article
|
||||
fields = ('id', 'title', 'description','image', 'total_points', 'is_completed')
|
||||
fields = ('id', 'title', 'description', 'image', 'total_points', 'is_completed')
|
||||
|
||||
def get_image(self, obj):
|
||||
"""article image"""
|
||||
if obj.article_cards.first():
|
||||
return obj.article_cards.first().image_url
|
||||
return None
|
||||
|
||||
def get_total_points(self, obj):
|
||||
"""total points of article"""
|
||||
return obj.article_survey.all().count() * NUMBER['five']
|
||||
@ -253,6 +277,7 @@ class ArticleListSerializer(serializers.ModelSerializer):
|
||||
return junior_article.is_completed
|
||||
return False
|
||||
|
||||
|
||||
class ArticleQuestionSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
article survey serializer
|
||||
@ -263,7 +288,6 @@ class ArticleQuestionSerializer(serializers.ModelSerializer):
|
||||
correct_answer = serializers.SerializerMethodField('get_correct_answer')
|
||||
attempted_answer = serializers.SerializerMethodField('get_attempted_answer')
|
||||
|
||||
|
||||
def get_is_attempt(self, obj):
|
||||
"""attempt question or not"""
|
||||
context_data = self.context.get('user')
|
||||
@ -295,6 +319,7 @@ class ArticleQuestionSerializer(serializers.ModelSerializer):
|
||||
model = ArticleSurvey
|
||||
fields = ('id', 'question', 'options', 'points', 'is_attempt', 'correct_answer', 'attempted_answer')
|
||||
|
||||
|
||||
class StartAssessmentSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
serializer for article API
|
||||
@ -310,6 +335,7 @@ class StartAssessmentSerializer(serializers.ModelSerializer):
|
||||
if data:
|
||||
return data.current_que_page if data.current_que_page < total_count else data.current_que_page - 1
|
||||
return NUMBER['zero']
|
||||
|
||||
class Meta(object):
|
||||
"""
|
||||
meta class
|
||||
@ -318,7 +344,6 @@ class StartAssessmentSerializer(serializers.ModelSerializer):
|
||||
fields = ('article_survey', 'current_page')
|
||||
|
||||
|
||||
|
||||
class ArticleCardlistSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
Article Card serializer
|
||||
|
@ -17,7 +17,7 @@ from web_admin.models import Article, ArticleCard, ArticleSurvey, DefaultArticle
|
||||
from web_admin.permission import AdminPermission
|
||||
from web_admin.serializers.article_serializer import (ArticleSerializer, ArticleCardSerializer,
|
||||
DefaultArticleCardImageSerializer, ArticleListSerializer,
|
||||
ArticleCardlistSerializer)
|
||||
ArticleCardlistSerializer, ArticleStatusChangeSerializer)
|
||||
|
||||
USER = get_user_model()
|
||||
|
||||
@ -32,7 +32,6 @@ class ArticleViewSet(GenericViewSet, mixins.CreateModelMixin, mixins.UpdateModel
|
||||
queryset = Article
|
||||
filter_backends = (SearchFilter,)
|
||||
search_fields = ['title']
|
||||
http_method_names = ['get', 'post', 'put', 'delete']
|
||||
|
||||
def get_queryset(self):
|
||||
article = self.queryset.objects.filter(is_deleted=False).prefetch_related(
|
||||
@ -130,21 +129,22 @@ class ArticleViewSet(GenericViewSet, mixins.CreateModelMixin, mixins.UpdateModel
|
||||
return custom_response(SUCCESS_CODE["3029"])
|
||||
return custom_error_response(ERROR_CODE["2041"], status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
@action(methods=['get'], url_name='status-change', url_path='status-change',
|
||||
detail=True)
|
||||
@action(methods=['patch'], url_name='status-change', url_path='status-change',
|
||||
detail=True, serializer_class=ArticleStatusChangeSerializer)
|
||||
def article_status_change(self, request, *args, **kwargs):
|
||||
"""
|
||||
article un-publish or publish api method
|
||||
:param request: article id
|
||||
:param request: article id and
|
||||
{
|
||||
"is_published": true/false
|
||||
}
|
||||
:return: success message
|
||||
"""
|
||||
try:
|
||||
article = Article.objects.filter(id=kwargs['pk']).first()
|
||||
article.is_published = False if article.is_published else True
|
||||
article.save(update_fields=['is_published'])
|
||||
return custom_response(SUCCESS_CODE["3038"])
|
||||
except AttributeError:
|
||||
return custom_error_response(ERROR_CODE["2041"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
article = Article.objects.filter(id=kwargs['pk']).first()
|
||||
serializer = self.serializer_class(article, data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
serializer.save()
|
||||
return custom_response(SUCCESS_CODE["3038"])
|
||||
|
||||
@action(methods=['get'], url_name='remove-card', url_path='remove-card',
|
||||
detail=True)
|
||||
@ -230,7 +230,7 @@ class DefaultArticleCardImagesViewSet(GenericViewSet, mixins.CreateModelMixin, m
|
||||
:param request:
|
||||
:return: default article card images
|
||||
"""
|
||||
queryset = self.queryset
|
||||
queryset = self.get_queryset()
|
||||
serializer = self.serializer_class(queryset, many=True)
|
||||
return custom_response(None, data=serializer.data)
|
||||
|
||||
|
@ -35,19 +35,28 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = os.getenv('DEBUG')
|
||||
ENV = os.getenv('ENV')
|
||||
|
||||
# cors allow setting
|
||||
CORS_ORIGIN_ALLOW_ALL = False
|
||||
|
||||
# Allow specific origins
|
||||
CORS_ALLOWED_ORIGINS = [
|
||||
"https://dev-api.zodqaapp.com",
|
||||
"https://qa-api.zodqaapp.com",
|
||||
"https://stage-api.zodqaapp.com",
|
||||
# Add more trusted origins as needed
|
||||
]
|
||||
# if DEBUG:
|
||||
# CORS_ALLOWED_ORIGINS += ["http://localhost:3000"]
|
||||
if ENV in ['dev', 'qa', 'stage']:
|
||||
CORS_ALLOWED_ORIGINS = [
|
||||
# backend base url
|
||||
"https://dev-api.zodqaapp.com",
|
||||
"https://qa-api.zodqaapp.com",
|
||||
"https://stage-api.zodqaapp.com",
|
||||
|
||||
# frontend url
|
||||
"http://localhost:3000",
|
||||
"https://zod-dev.zodqaapp.com",
|
||||
"https://zod-qa.zodqaapp.com",
|
||||
"https://zod-stage.zodqaapp.com",
|
||||
# Add more trusted origins as needed
|
||||
]
|
||||
if ENV == "prod":
|
||||
CORS_ALLOWED_ORIGINS = []
|
||||
|
||||
# allow all host
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
Reference in New Issue
Block a user