No Description

views.py 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import sys
  2. import json
  3. sys.path.insert(1,'C:/Users/diego/Documents/companion_app/organizar/')
  4. from organizar import files3, proxSemFiles
  5. from rest_auth.registration.views import SocialLoginView
  6. from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
  7. from allauth.account.views import LogoutView
  8. from django.db import connection
  9. from django.http.response import JsonResponse
  10. from rest_framework.parsers import JSONParser
  11. from rest_framework import status
  12. from .models import Facultad, Curso, ProximoSemestre
  13. from .serializers import FacultadSerializer, CursoSerializer
  14. from rest_framework.decorators import api_view
  15. # clientID: 965339169610-8et02d4qpfk96vclngd0otths1rs8661.apps.googleusercontent.com
  16. # clientSecret: zeY8NoW6ORBHP8pDQLE2x_Z2
  17. # Create your views here.
  18. class GoogleLogin(SocialLoginView):
  19. adapter_class = GoogleOAuth2Adapter
  20. @api_view(['POST',])
  21. def insertarFacultades(request):
  22. faculties = [ 'Administración de Empresas', 'Administración de Empresas graduado', 'Arquitectura', 'Arquitectura Graduado', 'Asuntos Académicos',
  23. 'Ciencias Militares', 'Ciencias Naturales', 'Ciencias Naturales Graduado', 'Ciencias Sociales', 'Ciencias Sociales Graduado',
  24. 'Escuela de Comunicación', 'Escuela de Comunicación Graduada', 'Educación', 'Educación Continua (BEOF)', 'Educación Graduado',
  25. 'Escuela de Derecho', 'Escuela Graduada de Ciencias y Tecnologías de la Información', 'Estudios Generales', 'Humanidades',
  26. 'Humanidades Graduado', 'Planificación']
  27. if request.method == 'POST':
  28. for faculty in faculties:
  29. facultad_serializer = FacultadSerializer(data={'fname': faculty})
  30. if facultad_serializer.is_valid():
  31. facultad_serializer.save()
  32. return JsonResponse({"message": 'se crearon todas las facultades'}, status=status.HTTP_201_CREATED)
  33. @api_view(['POST',])
  34. def insertarTodosLosCursos(request):
  35. if request.method == 'POST':
  36. i = 1
  37. for file in files3:
  38. check = file['file'].split('.')
  39. path = "C:/Users/diego/Documents/companion_app/segundo_sem" if check[0][-1] == '2' else "C:/Users/diego/Documents/companion_app/primer_sem"
  40. with open(path + '/' + file['file']) as f:
  41. data = json.load(f)
  42. fac_id = file['num']
  43. for key in data:
  44. if key != 'Horario ':
  45. code = key
  46. name = data[key][0]
  47. creds = data[key][1]
  48. # si la clase es un laboratorio de 0 creditos
  49. if 'LAB' in key and (name == 'LABORATORIO' or name == 'LABORATORIO ' or name == 'TALLER' or name == 'TALLER ' or name == 'CONFERENCIA' or name == 'CONFERENCIA '):
  50. creds = 0
  51. try:
  52. curso = Curso.objects.get(code = code)
  53. except Curso.DoesNotExist:
  54. curso = None
  55. if curso == None:
  56. curso_serializer = CursoSerializer(data={'name': name, 'code': code, 'creditos': creds, 'fac_id': fac_id})
  57. if curso_serializer.is_valid():
  58. curso_serializer.save()
  59. else:
  60. print('ya se creo del lab', i)
  61. i += 1
  62. elif 'LAB' in key and (name != 'LABORATORIO' or name != 'LABORATORIO ' or name != 'TALLER' or name != 'TALLER ' or name != 'CONFERENCIA' or name != 'CONFERENCIA '):
  63. continue
  64. # todas las otras clases que no tengan _LAB en su codigo
  65. else:
  66. try:
  67. curso = Curso.objects.get(code = code)
  68. except Curso.DoesNotExist:
  69. curso = None
  70. if curso == None:
  71. curso_serializer = CursoSerializer(data={'name': name, 'code': code, 'creditos': creds, 'fac_id': fac_id})
  72. if curso_serializer.is_valid():
  73. curso_serializer.save()
  74. else:
  75. print('ya se creo', i)
  76. i += 1
  77. return JsonResponse({'message': 'se insertaron todos los cursos'}, status=status.HTTP_201_CREATED)
  78. @api_view(['POST',])
  79. def insertarTodosLosCursosProxSemestre(request):
  80. if request.method == 'POST':
  81. for file in proxSemFiles:
  82. path = "C:/Users/diego/Documents/companion_app/Miupi Parser"
  83. with open(path + '/' + file['file']) as f:
  84. data = json.load(f)
  85. fac_id = file["num"] # this id comes from the file organizar. If the course does not exist in table Curso, use this id
  86. for course in data:
  87. name = course["Nombre"]
  88. code = course["Curso"]
  89. creditos = int(course["Creditos"])
  90. section = course["Seccion"]
  91. prof = course["Profesor"]
  92. hours = course["Horario"]
  93. days = course["Dias"]
  94. rooms = course["Salones"]
  95. # seeing if course from json file already exists in table Curso
  96. cursor = connection.cursor()
  97. cursor.execute(f'SELECT id from "CompanionApp_curso" where code = \'{code}\'')
  98. course_id = cursor.fetchone()
  99. # if course does not exist in table Curso, create the course in table Course and create the course in table ProximoSemestre
  100. if course_id == None:
  101. print('hola')
  102. # create course
  103. cursor = connection.cursor()
  104. cursor.execute(f'INSERT INTO "CompanionApp_curso" (name, code, creditos, fac_id_id) VALUES (\'{name}\', \'{code}\', {creditos}, {fac_id})')
  105. # once created the course, fetch the course_id
  106. cursor = connection.cursor()
  107. cursor.execute(f'SELECT id from "CompanionApp_curso" where code = \'{code}\'')
  108. course_id = cursor.fetchone()
  109. # getting course_id from line 128 or 116
  110. course_id = course_id[0]
  111. # before inserting course, check if that course with section is already in the table ProximoSemestre
  112. cursor = connection.cursor()
  113. cursor.execute(f'Select id from "CompanionApp_proximosemestre" where code=\'{code}\' and section=\'{section}\'')
  114. prox_sem_id = cursor.fetchone() # id from table
  115. # if course with section does not exist, insert it in the table ProximoSemestre
  116. if prox_sem_id == None:
  117. cursor = connection.cursor()
  118. cursor.execute(f'INSERT INTO "CompanionApp_proximosemestre" (name, code, creditos, section, prof, hours, days, rooms, course_id_id) VALUES (\'{name}\', \'{code}\', {creditos}, \'{section}\', \'{prof}\', \'{hours}\', \'{days}\', \'{rooms}\', {course_id})')
  119. return JsonResponse({'message': 'se insertaron todos los cursos'}, status=status.HTTP_201_CREATED)
  120. @api_view(['PATCH',])
  121. def updateFaculty(request):
  122. if request.method == 'PATCH':
  123. # params from request
  124. fac_id = int(request.data['fac_id_id'])
  125. user_id = int(request.data['id'])
  126. print(type(fac_id))
  127. print('backend', fac_id)
  128. # update faculty
  129. cursor = connection.cursor()
  130. cursor.execute(f'UPDATE "CompanionApp_user" set fac_id_id = {fac_id} where id = {user_id}')
  131. return JsonResponse({'list': 'updated'}, status=status.HTTP_201_CREATED)
  132. # find courses in our Curso table
  133. @api_view(['GET',])
  134. def findCourse(request):
  135. # alternative to .filter
  136. # cursor = connection.cursor()
  137. # cursor.execute(f'SELECT id, code from "CompanionApp_curso" where code LIKE \'{course_code}%\' LIMIT 10')
  138. # courses = cursor.fetchall()
  139. if request.method == 'GET':
  140. course_code = request.query_params['code'].upper()
  141. courses = Curso.objects.filter(code__contains=course_code)[:10]
  142. courses = list(courses.values())
  143. return JsonResponse({'list': courses}, status=status.HTTP_200_OK)
  144. # find courses in our ProximoSemestre table
  145. @api_view(['GET',])
  146. def selectCourseProxSemestre(request):
  147. if request.method == 'GET':
  148. course_code = request.query_params['code'].upper()
  149. courses = ProximoSemestre.objects.filter(code__contains=course_code)[:10]
  150. courses = list(courses.values())
  151. return JsonResponse({'list': courses}, status=status.HTTP_200_OK)
  152. @api_view(['POST'])
  153. def addTakenCourse(request):
  154. if request.method == 'POST':
  155. # request params
  156. user_id = int(request.data['user_id'])
  157. course_id = int(request.data['course_id'])
  158. grade = request.data['grade'].upper()
  159. year = int(request.data['year'])
  160. semester = int(request.data['semester'])
  161. repeating = False
  162. # set point of grade
  163. points = 0
  164. if grade == 'A':
  165. points = 4
  166. elif grade == 'B':
  167. points = 3
  168. elif grade == 'C':
  169. points = 2
  170. elif grade == 'D':
  171. points = 1
  172. elif grade == 'F':
  173. points = 0
  174. else:
  175. return JsonResponse({'msg': 'Insert A, B, C, D or F' }, status=status.HTTP_200_OK)
  176. # find course credits
  177. cursor = connection.cursor()
  178. cursor.execute(f'Select creditos from "CompanionApp_curso" where id = {course_id} ')
  179. course = cursor.fetchone()
  180. creditos = int(course[0])
  181. # check if student already took that class in the same year and semester he/she is trying to post
  182. cursor = connection.cursor()
  183. 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}')
  184. check = cursor.fetchone()
  185. if check != None:
  186. check = list(check)
  187. if int(check[0]) == semester and int(check[1]) == year and check[3] == course_id:
  188. return JsonResponse({'msg': 'You already took the course that year and semester.' }, status=status.HTTP_200_OK)
  189. elif int(check[1]) != year:
  190. pass
  191. elif int(check[1] == year) and int(check[0]) != semester:
  192. pass
  193. # matricular al estudiante
  194. cursor = connection.cursor()
  195. cursor.execute(f'INSERT INTO "CompanionApp_matricula" (semestre, year, grade, user_id_id, course_id_id) VALUES ({semester}, {year}, \'{grade}\', {user_id}, {course_id})')
  196. # find credits taken
  197. cursor = connection.cursor()
  198. cursor.execute(f'Select credits_taken from "CompanionApp_user" where id={user_id}')
  199. credits_taken = cursor.fetchone()
  200. credits_taken = int(credits_taken[0])
  201. # find last credits_taken_score
  202. cursor = connection.cursor()
  203. cursor.execute(f'Select credits_taken_score from "CompanionApp_user" where id={user_id}')
  204. credits_taken_score = cursor.fetchone()
  205. credits_taken_score = int(credits_taken_score[0])
  206. # update credits taken
  207. credits_taken += creditos
  208. cursor = connection.cursor()
  209. cursor.execute(f'UPDATE "CompanionApp_user" set credits_taken = {credits_taken} where id ={user_id}')
  210. # update credits_taken_score
  211. credits_taken_score = credits_taken_score + (creditos * points)
  212. cursor = connection.cursor()
  213. cursor.execute(f'UPDATE "CompanionApp_user" set credits_taken_score = {credits_taken_score} where id ={user_id}')
  214. # set GPA and insert it in user
  215. credit_score = credits_taken * 4
  216. gpa = (credits_taken_score / credit_score) * 4.0
  217. gpa = float("{:.2f}".format(gpa))
  218. cursor = connection.cursor()
  219. cursor.execute(f'UPDATE "CompanionApp_user" set gpa = {gpa} where id={user_id}')
  220. print('ya')
  221. return JsonResponse({'msg': 'Ok, you can see that course in your curriculum'}, status=status.HTTP_201_CREATED)
  222. @api_view(['GET'])
  223. def getUserId(request):
  224. if request.method == 'GET':
  225. authorization = request.META.get('HTTP_AUTHORIZATION')
  226. authorization = authorization.split()
  227. token = authorization[1]
  228. cursor = connection.cursor()
  229. cursor.execute(f'SELECT user_id from "authtoken_token" where key = \'{token}\'')
  230. user_id = cursor.fetchone()
  231. user_id = user_id[0]
  232. return JsonResponse({'user_id': user_id}, status=status.HTTP_200_OK)
  233. @api_view(['GET'])
  234. def getFacultyUser(request):
  235. if request.method == 'GET':
  236. print(request.query_params)
  237. user_id = request.query_params['id']
  238. user_id = int(user_id)
  239. cursor = connection.cursor()
  240. cursor.execute(f'select fname from "CompanionApp_facultad" where id in (select fac_id_id from "CompanionApp_user" where id={user_id})')
  241. facultyName = cursor.fetchone()
  242. return JsonResponse({'FacultyName': facultyName}, status=status.HTTP_200_OK)
  243. @api_view(['GET'])
  244. def getAllCoursesUserHasTaken(request):
  245. if request.method == 'GET':
  246. user_id = int(request.query_params['user_id'])
  247. cursor = connection.cursor()
  248. cursor.execute(f'SELECT c.name, c.code, c.creditos, m.user_id_id, m.year, m.semestre, m.grade, c.id 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')
  249. fetchCourses = cursor.fetchall()
  250. courses = []
  251. # convert courses to an array of objects
  252. for i in range(0, len(fetchCourses)):
  253. 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], 'course_id': fetchCourses[i][7]}
  254. courses.append(dic)
  255. return JsonResponse({'list': courses}, status=status.HTTP_200_OK)
  256. @api_view(['GET'])
  257. def getAllCoursesBySemester(request):
  258. if request.method == 'GET':
  259. user_id = int(request.query_params['user_id'])
  260. year = int(request.query_params['year'])
  261. semestre = int(request.query_params['semestre'])
  262. cursor = connection.cursor()
  263. cursor.execute(f'SELECT c.name, c.code, c.creditos, m.user_id_id, m.year, m.semestre, m.grade, c.id 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%\' ')
  264. fetchCourses = cursor.fetchall()
  265. courses = []
  266. # convert courses to an array of objects
  267. for i in range(0, len(fetchCourses)):
  268. 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], 'course_id': fetchCourses[i][7]}
  269. courses.append(dic)
  270. return JsonResponse({'list': courses}, status=status.HTTP_200_OK)
  271. @api_view(['POST',])
  272. def seeGPA(request):
  273. if request.method == 'POST':
  274. user_id = int(request.data['user_id'])
  275. cursor = connection.cursor()
  276. cursor.execute(f'SELECT gpa from "CompanionApp_user" where id={user_id}')
  277. GPA = cursor.fetchone()
  278. return JsonResponse({'gpa': GPA}, status = status.HTTP_200_OK)
  279. @api_view(['POST',])
  280. def matricularProxSemestre(request):
  281. if request.method == 'POST':
  282. # data from request
  283. user_id = int(request.data['user_id'])
  284. isSummer = request.data['isSummer']
  285. course_id = int(request.data['course_id'])
  286. # selecting current year and current semester of user from database
  287. cursor = connection.cursor()
  288. cursor.execute(f'Select current_year, current_semester from "CompanionApp_user" where id = {user_id} ')
  289. info = cursor.fetchone()
  290. current_year = info[0]
  291. current_semester = info[1]
  292. # determining next semester and next year
  293. if (current_semester == 2 and isSummer == 'false') or current_semester == 3:
  294. next_semester = 1
  295. next_year = current_year + 1
  296. elif (current_semester == 2 and isSummer == 'true'):
  297. next_semester = current_semester + 1 # 3
  298. next_year = current_year # stays the same
  299. elif current_semester == 1:
  300. next_semester = current_semester + 1 # 2
  301. next_year = current_year
  302. # selecting all attributes of course from course_id
  303. cursor = connection.cursor()
  304. cursor.execute(f'Select * from "CompanionApp_proximosemestre" where id = {course_id} ')
  305. info = cursor.fetchone()
  306. course_name = info[1]
  307. course_code = info[2]
  308. course_section = info[4]
  309. course_prof = info[5]
  310. course_hours = info[6]
  311. course_days = info[7]
  312. course_rooms = info[8]
  313. course_id = info[9] # course_id in "CompanionApp_curso"
  314. course_grade = 'N' # N de none, por ahora no hay nota
  315. # see if student already enrolled for the class
  316. cursor = connection.cursor()
  317. cursor.execute(f'Select id from "CompanionApp_matricula" where course_id_id={course_id} and section=\'{course_section}\' and prof=\'{course_prof}\' and horarios=\'{course_hours}\' and dias=\'{course_days}\' and salones=\'{course_rooms}\' and semestre={next_semester} and year={next_year} and user_id_id={user_id}')
  318. info = cursor.fetchone()
  319. print(info)
  320. if info != None:
  321. return JsonResponse({'msg': 'Ya estabas matriculado'}, status=status.HTTP_201_CREATED)
  322. else:
  323. # enroll student
  324. cursor = connection.cursor()
  325. cursor.execute(f'INSERT INTO "CompanionApp_matricula" (section, prof, semestre, year, grade, salones, horarios, dias, course_id_id, user_id_id) VALUES (\'{course_section}\',\'{course_prof}\', {next_semester}, {next_year}, \'{course_grade}\', \'{course_rooms}\', \'{course_hours}\', \'{course_days}\', {course_id}, {user_id})')
  326. return JsonResponse({'msg': 'te matriculaste a ' + course_code + '-' + course_section}, status=status.HTTP_201_CREATED)
  327. @api_view(['POST',])
  328. def getMyCurrentCourses(request):
  329. if request.method == 'POST':
  330. user_id = int(request.data['user_id'])
  331. current_courses = []
  332. # find current year of student
  333. cursor = connection.cursor()
  334. cursor.execute(f'select max(year) from "CompanionApp_matricula" where user_id_id={user_id}')
  335. current_year = cursor.fetchone()
  336. if current_year[0] == None:
  337. return JsonResponse({'msg': 'No tienes cursos'}, status = status.HTTP_200_OK)
  338. else:
  339. current_year = int(current_year[0])
  340. # find current semester of student, based on the current_year
  341. cursor = connection.cursor()
  342. cursor.execute(f'select max(semestre) from "CompanionApp_matricula" where year = {current_year} and user_id_id = {user_id}')
  343. current_semester = cursor.fetchone()
  344. current_semester = int(current_semester[0])
  345. # find current courses based on current_semester and current_year
  346. cursor = connection.cursor()
  347. cursor.execute(f'select c.id, c.name, c.code, m.year, m.semestre, m.section, m.prof, m.salones, m.horarios, m.dias from "CompanionApp_matricula" m INNER JOIN "CompanionApp_curso" c on c.id = m.course_id_id where m.year = {current_year} and m.semestre={current_semester} and m.user_id_id={user_id}')
  348. fetchCourses = cursor.fetchall()
  349. # convert courses array into dictionary
  350. for i in range(0, len(fetchCourses)):
  351. # if fetchCourses[i][2] == None, this means that the rest of the array will also be none.
  352. # The reason for this is that when users AddTakenCourses, they just add the course code
  353. if fetchCourses[i][5] == None:
  354. dic = {'id': fetchCourses[i][0], 'name': fetchCourses[i][1], 'code': fetchCourses[i][2], 'year': fetchCourses[i][3], 'semestre': fetchCourses[i][4]}
  355. # here we have all the elements because users enrolled from the courses in table ProximoSemestre
  356. else:
  357. dic = {'id': fetchCourses[i][0], 'name': fetchCourses[i][1], 'code': fetchCourses[i][2], 'year': fetchCourses[i][3], 'semestre': fetchCourses[i][4], 'section': fetchCourses[i][5], 'prof': fetchCourses[i][6], 'salones': fetchCourses[i][7], 'horarios': fetchCourses[i][8], 'dias': fetchCourses[i][9]}
  358. current_courses.append(dic)
  359. return JsonResponse({'list': current_courses}, status = status.HTTP_200_OK)
  360. @api_view(['PATCH',])
  361. def updateGradeAndGPA(request):
  362. if request.method == 'PATCH':
  363. new_grade = request.data['grade']
  364. course_id = int(request.data['course_id'])
  365. year = int(request.data['year'])
  366. semestre = int(request.data['semestre'])
  367. user_id = int(request.data['user_id'])
  368. current_points = 0 # to deal with current_grade
  369. new_points = 0 # to deal with new_grade
  370. # points of new_grade
  371. if new_grade == 'A':
  372. new_points = 4
  373. elif new_grade == 'B':
  374. new_points = 3
  375. elif new_grade == 'C':
  376. new_points = 2
  377. elif new_grade == 'D':
  378. new_points = 1
  379. elif new_grade == 'F':
  380. new_points = 0
  381. # get credits from the course
  382. cursor = connection.cursor()
  383. cursor.execute(f'select creditos from "CompanionApp_curso" where id={course_id}')
  384. creditos = cursor.fetchone()
  385. creditos = creditos[0]
  386. # select current grade
  387. cursor = connection.cursor()
  388. cursor.execute(f'select grade from "CompanionApp_matricula" where course_id_id={course_id} and user_id_id={user_id} and year={year} and semestre={semestre}')
  389. current_grade = cursor.fetchone()
  390. current_grade = current_grade[0]
  391. print(current_grade)
  392. # this means that the credits for this course had not been added to the column credits_taken from table "CompanionApp_curso"
  393. if current_grade == 'N':
  394. # get credits_taken. Then add the courses credits to credits_taken
  395. cursor = connection.cursor()
  396. cursor.execute(f'select credits_taken from "CompanionApp_user" where id={user_id}')
  397. credits_taken = cursor.fetchone()
  398. credits_taken = credits_taken[0]
  399. new_credits_taken = credits_taken + creditos
  400. print(new_credits_taken, 'New credits taken')
  401. # get credits_taken_score. Then multiply credits * new_points and add it to credits_taken_score
  402. cursor = connection.cursor()
  403. cursor.execute(f'select credits_taken_score from "CompanionApp_user" where id={user_id}')
  404. credits_taken_score = cursor.fetchone()
  405. credits_taken_score = credits_taken_score[0]
  406. new_credits_taken_score = credits_taken_score + (new_points * creditos)
  407. print(new_credits_taken_score, 'New credits taken score')
  408. # update gpa, credits_taken, credits_taken_score
  409. gpa = (new_credits_taken_score / new_credits_taken)
  410. gpa = float("{:.2f}".format(gpa))
  411. print(gpa, 'new gpa')
  412. cursor = connection.cursor()
  413. cursor.execute(f'UPDATE "CompanionApp_user" set gpa = {gpa}, credits_taken = {new_credits_taken}, credits_taken_score={new_credits_taken_score} where id={user_id}')
  414. # update grade in table CompanionApp_matricula
  415. cursor = connection.cursor()
  416. cursor.execute(f'UPDATE "CompanionApp_matricula" set grade=\'{new_grade}\' where user_id_id={user_id} and semestre={semestre} and year={year} and course_id_id={course_id} ')
  417. return JsonResponse({'msg': 'Your GPA was updated to ' + str(gpa)}, status = status.HTTP_202_ACCEPTED)
  418. # else student already has a grade and wants to replace it
  419. else:
  420. if current_grade == 'A':
  421. current_points = 4
  422. elif current_grade == 'B':
  423. current_points = 3
  424. elif current_grade == 'C':
  425. current_points = 2
  426. elif current_grade == 'D':
  427. current_points = 1
  428. elif current_grade == 'F':
  429. current_points = 0
  430. # get credits_taken_score and credits_taken. Then substract (creditos * current_points) to credits_taken_score. Then add (creditos * new_points) to credits_taken_score
  431. cursor = connection.cursor()
  432. cursor.execute(f'select credits_taken_score, credits_taken from "CompanionApp_user" where id={user_id}')
  433. results = cursor.fetchone()
  434. credits_taken_score = results[0]
  435. credits_taken = results[1]
  436. new_credits_taken_score = credits_taken_score - (creditos * current_points)
  437. new_credits_taken_score = new_credits_taken_score + (creditos * new_points)
  438. print(new_credits_taken_score, 'new credits taken score')
  439. print(credits_taken, 'credits taken')
  440. # update gpa and credits_taken_score. credits_taken stays the same
  441. gpa = (new_credits_taken_score / credits_taken)
  442. gpa = float("{:.2f}".format(gpa))
  443. print(gpa, 'new gpa')
  444. cursor = connection.cursor()
  445. cursor.execute(f'UPDATE "CompanionApp_user" set gpa = {gpa}, credits_taken_score={new_credits_taken_score} where id={user_id}')
  446. # update grade in table CompanionApp_matricula
  447. cursor = connection.cursor()
  448. cursor.execute(f'UPDATE "CompanionApp_matricula" set grade=\'{new_grade}\' where user_id_id={user_id} and semestre={semestre} and year={year} and course_id_id={course_id} ')
  449. return JsonResponse({'msg': 'Your GPA was updated to ' + str(gpa)}, status = status.HTTP_202_ACCEPTED)
  450. @api_view(['DELETE',])
  451. def deleteCourse(request):
  452. if request.method == 'DELETE':
  453. course_id = int(request.data['course_id'])
  454. year = int(request.data['year'])
  455. semestre = int(request.data['semestre'])
  456. user_id = int(request.data['user_id'])
  457. # get credits from the course
  458. cursor = connection.cursor()
  459. cursor.execute(f'select creditos from "CompanionApp_curso" where id={course_id}')
  460. creditos = cursor.fetchone()
  461. creditos = creditos[0]
  462. print(creditos)
  463. # select current grade
  464. cursor = connection.cursor()
  465. cursor.execute(f'select grade from "CompanionApp_matricula" where course_id_id={course_id} and user_id_id={user_id} and year={year} and semestre={semestre}')
  466. current_grade = cursor.fetchone()
  467. current_grade = current_grade[0]
  468. print(current_grade)
  469. if current_grade == 'N':
  470. # just delete course from table CompanionApp_matricula
  471. cursor = connection.cursor()
  472. cursor.execute(f'DELETE from "CompanionApp_matricula" where user_id_id={user_id} and course_id_id = {course_id} and year={year} and semestre={semestre}')
  473. return JsonResponse({'msg': 'SUCCESS' }, status = status.HTTP_202_ACCEPTED)
  474. else:
  475. # update credits_taken, credits_taken_score and gpa
  476. current_points = 0
  477. if current_grade == 'A':
  478. current_points = 4
  479. elif current_grade == 'B':
  480. current_points = 3
  481. elif current_grade == 'C':
  482. current_points = 2
  483. elif current_grade == 'D':
  484. current_points = 1
  485. elif current_grade == 'F':
  486. current_points = 0
  487. # get credits_taken_score and credits_taken. Then, substract (creditos * current_points) to credits_taken_score and substract creditos to credits_taken
  488. cursor = connection.cursor()
  489. cursor.execute(f'select credits_taken_score, credits_taken from "CompanionApp_user" where id={user_id}')
  490. results = cursor.fetchone()
  491. credits_taken_score = results[0]
  492. credits_taken = results[1]
  493. new_credits_taken_score = credits_taken_score - (current_points * creditos)
  494. new_credits_taken = credits_taken - creditos
  495. if new_credits_taken == 0:
  496. gpa = 0.00
  497. else:
  498. gpa = new_credits_taken_score / new_credits_taken
  499. gpa = float("{:.2f}".format(gpa))
  500. print(new_credits_taken, 'credits taken')
  501. print(new_credits_taken_score, 'credits taken score')
  502. # update gpa, credits_taken and credits_taken_score
  503. cursor = connection.cursor()
  504. cursor.execute(f'UPDATE "CompanionApp_user" set gpa = {gpa}, credits_taken = {new_credits_taken}, credits_taken_score={new_credits_taken_score} where id={user_id}')
  505. # delete course from "CompanionApp_matricula"
  506. cursor = connection.cursor()
  507. cursor.execute(f'DELETE from "CompanionApp_matricula" where user_id_id={user_id} and course_id_id = {course_id} and year={year} and semestre={semestre}')
  508. return JsonResponse({'msg': 'SUCCESS' }, status = status.HTTP_202_ACCEPTED)
  509. @api_view(['PATCH',])
  510. def updateSemesterAndYear(request):
  511. if request.method == 'PATCH':
  512. user_id = int(request.data['user_id'])
  513. year = int(request.data['year'])
  514. semestre = int(request.data['semester'])
  515. # update semestre and year for user. This is for knowing which year and semester he/she is currently in
  516. cursor = connection.cursor()
  517. cursor.execute(f'UPDATE "CompanionApp_user" set current_year={year}, current_semester={semestre} where id={user_id}')
  518. return JsonResponse({'msg': 'SUCCESS' }, status = status.HTTP_202_ACCEPTED)
  519. @api_view(['POST',])
  520. def getSemesterAndYear(request):
  521. if request.method == 'POST':
  522. user_id = int(request.data['user_id'])
  523. cursor = connection.cursor()
  524. cursor.execute(f'select current_year, current_semester from "CompanionApp_user" where id={user_id}')
  525. info = cursor.fetchone()
  526. year = info[0]
  527. semestre = info[1]
  528. return JsonResponse({'msg': {'year': year, 'semestre': semestre} }, status = status.HTTP_202_ACCEPTED)
  529. @api_view(['POST',])
  530. def logout(request):
  531. request.user.auth_token.delete()
  532. return JsonResponse({"success": "Successfully logged out."}, status=status.HTTP_200_OK)
  533. @api_view(['GET', 'POST'])
  534. def hello_world(request):
  535. # if request.user.is_authenticated:
  536. if request.method == 'GET':
  537. return JsonResponse({'msg': request.user.email}, status = status.HTTP_200_OK)
  538. return JsonResponse({'msg': 'no'})
  539. # delete course and update credits_takenv