No Description

views.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import sys
  2. import json
  3. sys.path.insert(1,'C:/Users/diego/Documents/companion_app_gh/organizar/')
  4. from organizar import files3
  5. from rest_auth.registration.views import SocialLoginView
  6. from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
  7. from django.db import connection
  8. from django.http.response import JsonResponse
  9. from rest_framework.parsers import JSONParser
  10. from rest_framework import status
  11. from .models import Facultad, Curso
  12. from .serializers import FacultadSerializer, CursoSerializer
  13. from rest_framework.decorators import api_view
  14. # clientID: 965339169610-8et02d4qpfk96vclngd0otths1rs8661.apps.googleusercontent.com
  15. # clientSecret: zeY8NoW6ORBHP8pDQLE2x_Z2
  16. # Create your views here.
  17. class GoogleLogin(SocialLoginView):
  18. adapter_class = GoogleOAuth2Adapter
  19. @api_view(['POST',])
  20. def insertarFacultades(request):
  21. faculties = [ 'Administración de Empresas', 'Administración de Empresas graduado', 'Arquitectura', 'Arquitectura Graduado', 'Asuntos Académicos',
  22. 'Ciencias Militares', 'Ciencias Naturales', 'Ciencias Naturales Graduado', 'Ciencias Sociales', 'Ciencias Sociales Graduado',
  23. 'Escuela de Comunicación', 'Escuela de Comunicación Graduada', 'Educación', 'Educación Continua (BEOF)', 'Educación Graduado',
  24. 'Escuela de Derecho', 'Escuela Graduada de Ciencias y Tecnologías de la Información', 'Estudios Generales', 'Humanidades',
  25. 'Humanidades Graduado', 'Planificación']
  26. if request.method == 'POST':
  27. for faculty in faculties:
  28. facultad_serializer = FacultadSerializer(data={'fname': faculty})
  29. if facultad_serializer.is_valid():
  30. facultad_serializer.save()
  31. return JsonResponse({"message": 'se crearon todas las facultades'}, status=status.HTTP_201_CREATED)
  32. @api_view(['POST',])
  33. def insertarTodosLosCursos(request):
  34. if request.method == 'POST':
  35. i = 1
  36. for file in files3:
  37. check = file['file'].split('.')
  38. path = "C:/Users/diego/Documents/companion_app_gh/segundo_sem" if check[0][-1] == '2' else "C:/Users/diego/Documents/companion_app_gh/primer_sem"
  39. with open(path + '/' + file['file']) as f:
  40. data = json.load(f)
  41. fac_id = file['num']
  42. for key in data:
  43. if key != 'Horario ':
  44. code = key
  45. name = data[key][0]
  46. creds = data[key][1]
  47. try:
  48. curso = Curso.objects.get(code = code)
  49. except Curso.DoesNotExist:
  50. curso = None
  51. if curso == None:
  52. curso_serializer = CursoSerializer(data={'name': name, 'code': code, 'creditos': creds, 'fac_id': fac_id})
  53. if curso_serializer.is_valid():
  54. curso_serializer.save()
  55. else:
  56. print('ya se creo', i)
  57. i += 1
  58. return JsonResponse({'message': 'se insertaron todos los cursos'}, status=status.HTTP_201_CREATED)
  59. @api_view(['PATCH',])
  60. def updateFaculty(request):
  61. if request.method == 'PATCH':
  62. # params from request
  63. fac_id = int(request.data['fac_id_id'])
  64. user_id = int(request.data['id'])
  65. print(type(fac_id))
  66. print('backend', fac_id)
  67. # update faculty
  68. cursor = connection.cursor()
  69. cursor.execute(f'UPDATE "CompanionApp_user" set fac_id_id = {fac_id} where id = {user_id}')
  70. return JsonResponse({'list': 'updated'}, status=status.HTTP_201_CREATED)
  71. # find courses in our Curso table
  72. @api_view(['GET',])
  73. def findCourse(request):
  74. # alternative to .filter
  75. # cursor = connection.cursor()
  76. # cursor.execute(f'SELECT id, code from "CompanionApp_curso" where code LIKE \'{course_code}%\' LIMIT 10')
  77. # courses = cursor.fetchall()
  78. if request.method == 'GET':
  79. course_code = request.query_params['code'].upper()
  80. courses = Curso.objects.filter(code__contains=course_code)[:10]
  81. courses = list(courses.values())
  82. return JsonResponse({'list': courses}, status=status.HTTP_200_OK)
  83. @api_view(['POST'])
  84. def addTakenCourse(request):
  85. if request.method == 'POST':
  86. # request params
  87. user_id = int(request.data['user_id'])
  88. course_id = int(request.data['course_id'])
  89. grade = request.data['grade'].upper()
  90. year = int(request.data['year'])
  91. semester = int(request.data['semester'])
  92. repeating = False
  93. # set point of grade
  94. points = 0
  95. if grade == 'A':
  96. points = 4
  97. elif grade == 'B':
  98. points = 3
  99. elif grade == 'C':
  100. points = 2
  101. elif grade == 'D':
  102. points = 1
  103. elif grade == 'F':
  104. points = 0
  105. else:
  106. return JsonResponse({'msg': 'Insert A, B, C, D or F' }, status=status.HTTP_406_NOT_ACCEPTABLE)
  107. # find course credits
  108. cursor = connection.cursor()
  109. cursor.execute(f'Select creditos from "CompanionApp_curso" where id = {course_id} ')
  110. course = cursor.fetchone()
  111. creditos = int(course[0])
  112. # check if student already took that class in the same year and semester he/she is trying to post
  113. cursor = connection.cursor()
  114. cursor.execute(f'select semestre, year, grade, course_id_id from "CompanionApp_matricula" where semestre = {semester} and year = {year} and course_id_id = {course_id} and user_id_id = {user_id}')
  115. check = cursor.fetchone()
  116. if check != None:
  117. check = list(check)
  118. if int(check[0]) == semester and int(check[1]) == year and check[3] == course_id:
  119. return JsonResponse({'msg': 'You already took the course that year and semester.' }, status=status.HTTP_406_NOT_ACCEPTABLE)
  120. elif int(check[1]) != year:
  121. pass
  122. elif int(check[1] == year) and int(check[0]) != semester:
  123. pass
  124. # matricular al estudiante
  125. cursor = connection.cursor()
  126. cursor.execute(f'INSERT INTO "CompanionApp_matricula" (semestre, year, grade, user_id_id, course_id_id) VALUES ({semester}, {year}, \'{grade}\', {user_id}, {course_id})')
  127. # find credits taken
  128. cursor = connection.cursor()
  129. cursor.execute(f'Select credits_taken from "CompanionApp_user" where id={user_id}')
  130. credits_taken = cursor.fetchone()
  131. credits_taken = int(credits_taken[0])
  132. # find last credits_taken_score
  133. cursor = connection.cursor()
  134. cursor.execute(f'Select credits_taken_score from "CompanionApp_user" where id={user_id}')
  135. credits_taken_score = cursor.fetchone()
  136. credits_taken_score = int(credits_taken_score[0])
  137. # update credits taken
  138. credits_taken += creditos
  139. cursor = connection.cursor()
  140. cursor.execute(f'UPDATE "CompanionApp_user" set credits_taken = {credits_taken} where id ={user_id}')
  141. # update credits_taken_score
  142. credits_taken_score = credits_taken_score + (creditos * points)
  143. cursor = connection.cursor()
  144. cursor.execute(f'UPDATE "CompanionApp_user" set credits_taken_score = {credits_taken_score} where id ={user_id}')
  145. # set GPA and insert it in user
  146. credit_score = credits_taken * 4
  147. gpa = (credits_taken_score / credit_score) * 4.0
  148. gpa = float("{:.2f}".format(gpa))
  149. cursor = connection.cursor()
  150. cursor.execute(f'UPDATE "CompanionApp_user" set gpa = {gpa} where id={user_id}')
  151. return JsonResponse({'list': 'se matriculo al estudiante'}, status=status.HTTP_201_CREATED)
  152. @api_view(['GET'])
  153. def getUserId(request):
  154. if request.method == 'GET':
  155. authorization = request.META.get('HTTP_AUTHORIZATION')
  156. authorization = authorization.split()
  157. token = authorization[1]
  158. cursor = connection.cursor()
  159. cursor.execute(f'SELECT user_id from "authtoken_token" where key = \'{token}\'')
  160. user_id = cursor.fetchone()
  161. user_id = user_id[0]
  162. return JsonResponse({'user_id': user_id}, status=status.HTTP_200_OK)
  163. @api_view(['GET'])
  164. def getFacultyUser(request):
  165. if request.method == 'GET':
  166. print(request.query_params)
  167. user_id = request.query_params['id']
  168. user_id = int(user_id)
  169. cursor = connection.cursor()
  170. cursor.execute(f'select fname from "CompanionApp_facultad" where id in (select fac_id_id from "CompanionApp_user" where id={user_id})')
  171. facultyName = cursor.fetchone()
  172. return JsonResponse({'FacultyName': facultyName}, status=status.HTTP_200_OK)
  173. @api_view(['GET'])
  174. def getAllCoursesUserHasTaken(request):
  175. if request.method == 'GET':
  176. user_id = int(request.query_params['user_id'])
  177. cursor = connection.cursor()
  178. cursor.execute(f'SELECT c.name, c.code, c.creditos, m.user_id_id, m.year, m.semestre, m.grade FROM "CompanionApp_curso" c INNER JOIN "CompanionApp_matricula" m ON (c.id = m.course_id_id) where m.user_id_id = {user_id} and m.grade <> \'N%\' order by m.year ASC, m.semestre ASC')
  179. fetchCourses = cursor.fetchall()
  180. courses = []
  181. # convert courses to an array of objects
  182. for i in range(0, len(fetchCourses)):
  183. dic = {'name': fetchCourses[i][0], 'code': fetchCourses[i][1], 'creditos': fetchCourses[i][2], 'year': fetchCourses[i][4], 'semestre': fetchCourses[i][5], 'grade': fetchCourses[i][6]}
  184. courses.append(dic)
  185. return JsonResponse({'list': courses}, status=status.HTTP_200_OK)
  186. @api_view(['GET'])
  187. def getAllCoursesBySemester(request):
  188. if request.method == 'GET':
  189. user_id = int(request.query_params['user_id'])
  190. year = int(request.query_params['year'])
  191. semestre = int(request.query_params['semestre'])
  192. cursor = connection.cursor()
  193. cursor.execute(f'SELECT c.name, c.code, c.creditos, m.user_id_id, m.year, m.semestre, m.grade FROM "CompanionApp_curso" c INNER JOIN "CompanionApp_matricula" m ON (c.id = m.course_id_id) where m.user_id_id = {user_id} and m.year = {year} and m.semestre = {semestre} and m.grade <> \'N%\' ')
  194. fetchCourses = cursor.fetchall()
  195. courses = []
  196. # convert courses to an array of objects
  197. for i in range(0, len(fetchCourses)):
  198. dic = {'name': fetchCourses[i][0], 'code': fetchCourses[i][1], 'creditos': fetchCourses[i][2], 'year': fetchCourses[i][4], 'semestre': fetchCourses[i][5], 'grade': fetchCourses[i][6]}
  199. courses.append(dic)
  200. return JsonResponse({'list': courses}, status=status.HTTP_200_OK)
  201. @api_view(['GET', 'POST'])
  202. def hello_world(request):
  203. # if request.user.is_authenticated:
  204. if request.method == 'GET':
  205. return JsonResponse({'msg': request.user.email}, status = status.HTTP_200_OK)
  206. return JsonResponse({'msg': 'no'})