Browse Source

add taken courses front end

dmr1725 4 years ago
parent
commit
fe6c405417

+ 2
- 2
client/App.js View File

32
 
32
 
33
         try {
33
         try {
34
           // login user in backend
34
           // login user in backend
35
-          let response = await fetch('http://ef32e7a10841.ngrok.io/rest-auth/google/', {
35
+          let response = await fetch('http://70eb11ac4839.ngrok.io/rest-auth/google/', {
36
             method: 'POST',
36
             method: 'POST',
37
             headers: {
37
             headers: {
38
               'content-type': 'application/json'
38
               'content-type': 'application/json'
53
           const token = await SecureStore.getItemAsync('token')
53
           const token = await SecureStore.getItemAsync('token')
54
 
54
 
55
           // storing our id
55
           // storing our id
56
-          let id = await fetch('http://ef32e7a10841.ngrok.io/api/get_user_id', {
56
+          let id = await fetch('http://70eb11ac4839.ngrok.io/api/get_user_id', {
57
             method: 'GET',
57
             method: 'GET',
58
             headers: {
58
             headers: {
59
               'content-type': 'application/json',
59
               'content-type': 'application/json',

+ 115
- 6
client/Screens/AddTakenCourse.js View File

1
 import axios from "axios";
1
 import axios from "axios";
2
 import React, { useState } from "react";
2
 import React, { useState } from "react";
3
-import { FlatList, SafeAreaView, StatusBar, StyleSheet, Text, TouchableOpacity, TextInput, View } from "react-native";
3
+import { FlatList, StatusBar, StyleSheet, Text, TouchableOpacity, TextInput, View, Button, ActivityIndicator } from "react-native";
4
 import * as SecureStore from 'expo-secure-store';
4
 import * as SecureStore from 'expo-secure-store';
5
+import Modal from 'react-native-modal';
6
+import {Picker} from '@react-native-community/picker';
5
 
7
 
6
 
8
 
7
 const Item = ({ item, onPress, style }) => (
9
 const Item = ({ item, onPress, style }) => (
28
   const [text, setText] = useState('')
30
   const [text, setText] = useState('')
29
   const [selectedId, setSelectedId] = useState(null);
31
   const [selectedId, setSelectedId] = useState(null);
30
   const [data, setData] = useState([])
32
   const [data, setData] = useState([])
33
+  const [modalVisible, setModalVisible] = useState(false)
34
+  const [grade, setGrade] = useState('A')
35
+  const [year, setYear] = useState('1')
36
+  const [semester, setSemester] = useState('1')
37
+  const [animating, setAnimating] = useState('')
38
+
39
+  const toggle = ()=>{
40
+    setModalVisible(!modalVisible)
41
+  }
42
+
43
+  const addCourse = async ()=>{
44
+      const token = await SecureStore.getItemAsync('token')
45
+      let id = await SecureStore.getItemAsync('id')
46
+      let user_id = parseInt(id)
47
+      console.log('year', year)
48
+      console.log('semester', semester)
49
+      console.log('grade', grade)
50
+
51
+
52
+      let response = await axios({
53
+        method: 'POST',
54
+        url: 'http://70eb11ac4839.ngrok.io/api/add_taken_course',
55
+        headers: {
56
+          'content-type': 'application/json',
57
+          Authorization: `Token ${token}`
58
+        },
59
+        data: {
60
+          semester: semester,
61
+          year: year,
62
+          user_id: user_id,
63
+          grade: grade,
64
+          course_id: selectedId
65
+        }
66
+      })
67
+
68
+      console.log(response.data)
69
+
70
+      setAnimating(true)
71
+
72
+      setTimeout(()=>{
73
+        setAnimating(false)
74
+        setModalVisible(false)
75
+        setSelectedId(null)
76
+        setData([])
77
+      }, 3000)
78
+  }
79
+
31
 
80
 
32
 
81
 
33
   const searchCourses = async(text)=>{
82
   const searchCourses = async(text)=>{
36
       const token = await SecureStore.getItemAsync('token')
85
       const token = await SecureStore.getItemAsync('token')
37
       const response = await axios({
86
       const response = await axios({
38
           method: 'GET',
87
           method: 'GET',
39
-          url: `http://ef32e7a10841.ngrok.io/api/find_course?code=${text}`,
88
+          url: `http://70eb11ac4839.ngrok.io/api/find_course?code=${text}`,
40
           headers: {
89
           headers: {
41
             'content-type': 'application/json',
90
             'content-type': 'application/json',
42
             Authorization: `Token ${token}`
91
             Authorization: `Token ${token}`
56
     return (
105
     return (
57
       <Item
106
       <Item
58
         item={item}
107
         item={item}
59
-        onPress={() => setSelectedId(item.id)}
108
+        onPress={() => {
109
+          setSelectedId(item.id)
110
+          setModalVisible(true)
111
+        }}
60
         style={{ backgroundColor }}
112
         style={{ backgroundColor }}
61
       />
113
       />
62
     );
114
     );
63
   };
115
   };
64
 
116
 
65
 
117
 
66
-  console.log(selectedId)
67
   return (
118
   return (
68
-    <View style={{padding: 10}}>
119
+    <View style={{flex: 1, padding: 10}}>
69
        <TextInput
120
        <TextInput
70
         style={styles.searchBar}
121
         style={styles.searchBar}
71
         placeholder="Search for a course that you've taken"
122
         placeholder="Search for a course that you've taken"
79
         extraData={selectedId}
130
         extraData={selectedId}
80
         ItemSeparatorComponent={renderSeparator}
131
         ItemSeparatorComponent={renderSeparator}
81
       />
132
       />
133
+      <Modal isVisible={modalVisible} style={{
134
+            backgroundColor: 'white',
135
+            flexDirection: 'row',
136
+            borderRadius: 20,
137
+            margin: 50,
138
+            padding: 10,
139
+        }}>
140
+            <View style={styles.modalItem}>
141
+                <Text>Grade</Text>
142
+                <Picker
143
+                    selectedValue={grade}
144
+                    style={{ width: 50}}
145
+                    onValueChange={(itemValue, itemIndex) => setGrade(itemValue) }>
146
+                    <Picker.Item label="A" value="A" />
147
+                    <Picker.Item label="B" value="B" />
148
+                    <Picker.Item label="C" value="C" />
149
+                    <Picker.Item label="D" value="D" />
150
+                    <Picker.Item label="F" value="F" />
151
+                </Picker>
152
+            </View>
153
+            <View style={styles.modalItem}>
154
+                <Text>Year</Text>
155
+                <Picker
156
+                    selectedValue={year}
157
+                    style={{ width: 50}}
158
+                    onValueChange={(itemValue, itemIndex) => setYear(itemValue) }>
159
+                    <Picker.Item label="1" value="1" />
160
+                    <Picker.Item label="2" value="2" />
161
+                    <Picker.Item label="3" value="3" />
162
+                    <Picker.Item label="4" value="4" />
163
+                    <Picker.Item label="5" value="5" />
164
+                    <Picker.Item label="6" value="6" />
165
+                </Picker>
166
+            </View>
167
+            <View style={styles.modalItem}>
168
+                <Text>Semester</Text>
169
+                <Picker
170
+                    selectedValue={semester}
171
+                    style={{ width: 50}}
172
+                    onValueChange={(itemValue, itemIndex) => setSemester(itemValue) }>
173
+                    <Picker.Item label="1" value="1" />
174
+                    <Picker.Item label="2" value="2" />
175
+                </Picker>
176
+            </View>
177
+           <View style={{flex: 1, justifyContent: 'center'}}>
178
+                <ActivityIndicator size="large" color="0000ff" animating={animating}/>
179
+                <View>
180
+                    <Button title="Submit" onPress={addCourse}/>
181
+                    <Button title="Close" onPress={toggle}/>
182
+                </View>
183
+           </View>
184
+        </Modal>
185
+     
82
     </View>
186
     </View>
83
   );
187
   );
84
 };
188
 };
101
     height: 40, 
205
     height: 40, 
102
     borderColor: '#000', 
206
     borderColor: '#000', 
103
     borderWidth: 1 
207
     borderWidth: 1 
104
-  }
208
+  },
209
+  modalItem: {
210
+    // width: '30%', // is 30% of container width
211
+    margin: 8 // 300
212
+}
213
+  
105
 });
214
 });
106
 
215
 
107
 export default AddTakenCourse;
216
 export default AddTakenCourse;

+ 1
- 1
client/Screens/HomeScreen.js View File

11
     console.log(token, id)
11
     console.log(token, id)
12
 
12
 
13
     let response = await Axios({
13
     let response = await Axios({
14
-      url: 'http://ef32e7a10841.ngrok.io/api/hello',
14
+      url: 'http://70eb11ac4839.ngrok.io/api/hello',
15
       method: 'GET',
15
       method: 'GET',
16
       headers: {
16
       headers: {
17
           Authorization: `Token ${token}`
17
           Authorization: `Token ${token}`

+ 2
- 2
client/Screens/SettingScreen.js View File

15
         let user_id = parseInt(id)
15
         let user_id = parseInt(id)
16
 
16
 
17
        try {
17
        try {
18
-        let response = await axios(`http://ef32e7a10841.ngrok.io/api/get_faculty_name?id=${user_id}`, {
18
+        let response = await axios(`http://70eb11ac4839.ngrok.io/api/get_faculty_name?id=${user_id}`, {
19
             method: 'GET',
19
             method: 'GET',
20
             headers: {
20
             headers: {
21
                 'content-type': 'application/json',
21
                 'content-type': 'application/json',
43
         try {
43
         try {
44
             let response = await axios({
44
             let response = await axios({
45
                 method: 'PATCH',
45
                 method: 'PATCH',
46
-                url: 'http://ef32e7a10841.ngrok.io/api/update_faculty',
46
+                url: 'http://70eb11ac4839.ngrok.io/api/update_faculty',
47
                 headers: {
47
                 headers: {
48
                     Authorization: `Token ${token}`
48
                     Authorization: `Token ${token}`
49
                 },
49
                 },

+ 17
- 0
client/package-lock.json View File

6540
         }
6540
         }
6541
       }
6541
       }
6542
     },
6542
     },
6543
+    "react-native-animatable": {
6544
+      "version": "1.3.3",
6545
+      "resolved": "https://registry.npmjs.org/react-native-animatable/-/react-native-animatable-1.3.3.tgz",
6546
+      "integrity": "sha512-2ckIxZQAsvWn25Ho+DK3d1mXIgj7tITkrS4pYDvx96WyOttSvzzFeQnM2od0+FUMzILbdHDsDEqZvnz1DYNQ1w==",
6547
+      "requires": {
6548
+        "prop-types": "^15.7.2"
6549
+      }
6550
+    },
6543
     "react-native-elements": {
6551
     "react-native-elements": {
6544
       "version": "3.0.0-alpha.1",
6552
       "version": "3.0.0-alpha.1",
6545
       "resolved": "https://registry.npmjs.org/react-native-elements/-/react-native-elements-3.0.0-alpha.1.tgz",
6553
       "resolved": "https://registry.npmjs.org/react-native-elements/-/react-native-elements-3.0.0-alpha.1.tgz",
6589
       "resolved": "https://registry.npmjs.org/react-native-iphone-x-helper/-/react-native-iphone-x-helper-1.3.1.tgz",
6597
       "resolved": "https://registry.npmjs.org/react-native-iphone-x-helper/-/react-native-iphone-x-helper-1.3.1.tgz",
6590
       "integrity": "sha512-HOf0jzRnq2/aFUcdCJ9w9JGzN3gdEg0zFE4FyYlp4jtidqU03D5X7ZegGKfT1EWteR0gPBGp9ye5T5FvSWi9Yg=="
6598
       "integrity": "sha512-HOf0jzRnq2/aFUcdCJ9w9JGzN3gdEg0zFE4FyYlp4jtidqU03D5X7ZegGKfT1EWteR0gPBGp9ye5T5FvSWi9Yg=="
6591
     },
6599
     },
6600
+    "react-native-modal": {
6601
+      "version": "11.5.6",
6602
+      "resolved": "https://registry.npmjs.org/react-native-modal/-/react-native-modal-11.5.6.tgz",
6603
+      "integrity": "sha512-APGNfbvgC4hXbJqcSADu79GLoMKIHUmgR3fDQ7rCGZNBypkStSP8imZ4PKK/OzIZZfjGU9aP49jhMgGbhY9KHA==",
6604
+      "requires": {
6605
+        "prop-types": "^15.6.2",
6606
+        "react-native-animatable": "1.3.3"
6607
+      }
6608
+    },
6592
     "react-native-ratings": {
6609
     "react-native-ratings": {
6593
       "version": "7.3.0",
6610
       "version": "7.3.0",
6594
       "resolved": "https://registry.npmjs.org/react-native-ratings/-/react-native-ratings-7.3.0.tgz",
6611
       "resolved": "https://registry.npmjs.org/react-native-ratings/-/react-native-ratings-7.3.0.tgz",

+ 1
- 0
client/package.json View File

23
     "react-native": "https://github.com/expo/react-native/archive/sdk-39.0.4.tar.gz",
23
     "react-native": "https://github.com/expo/react-native/archive/sdk-39.0.4.tar.gz",
24
     "react-native-elements": "^3.0.0-alpha.1",
24
     "react-native-elements": "^3.0.0-alpha.1",
25
     "react-native-gesture-handler": "~1.7.0",
25
     "react-native-gesture-handler": "~1.7.0",
26
+    "react-native-modal": "^11.5.6",
26
     "react-native-reanimated": "~1.13.0",
27
     "react-native-reanimated": "~1.13.0",
27
     "react-native-safe-area-context": "3.1.4",
28
     "react-native-safe-area-context": "3.1.4",
28
     "react-native-screens": "~2.10.1",
29
     "react-native-screens": "~2.10.1",

BIN
server/CompanionApp/__pycache__/models.cpython-38.pyc View File


BIN
server/CompanionApp/__pycache__/views.cpython-38.pyc View File


+ 17
- 0
server/CompanionApp/migrations/0009_remove_matricula_fecha.py View File

1
+# Generated by Django 3.0.8 on 2020-11-17 20:42
2
+
3
+from django.db import migrations
4
+
5
+
6
+class Migration(migrations.Migration):
7
+
8
+    dependencies = [
9
+        ('CompanionApp', '0008_auto_20201114_1935'),
10
+    ]
11
+
12
+    operations = [
13
+        migrations.RemoveField(
14
+            model_name='matricula',
15
+            name='fecha',
16
+        ),
17
+    ]

+ 18
- 0
server/CompanionApp/migrations/0010_user_credits_taken_score.py View File

1
+# Generated by Django 3.0.8 on 2020-11-17 22:05
2
+
3
+from django.db import migrations, models
4
+
5
+
6
+class Migration(migrations.Migration):
7
+
8
+    dependencies = [
9
+        ('CompanionApp', '0009_remove_matricula_fecha'),
10
+    ]
11
+
12
+    operations = [
13
+        migrations.AddField(
14
+            model_name='user',
15
+            name='credits_taken_score',
16
+            field=models.IntegerField(default=0),
17
+        ),
18
+    ]

BIN
server/CompanionApp/migrations/__pycache__/0009_remove_matricula_fecha.cpython-38.pyc View File


BIN
server/CompanionApp/migrations/__pycache__/0010_user_credits_taken_score.cpython-38.pyc View File


+ 2
- 1
server/CompanionApp/models.py View File

16
     gpa = models.DecimalField(default = 0, max_digits = 3, decimal_places = 2)
16
     gpa = models.DecimalField(default = 0, max_digits = 3, decimal_places = 2)
17
     fac_id = models.ForeignKey(Facultad, on_delete=models.CASCADE, default=1)
17
     fac_id = models.ForeignKey(Facultad, on_delete=models.CASCADE, default=1)
18
     credits_taken = models.IntegerField(default=0)
18
     credits_taken = models.IntegerField(default=0)
19
+    credits_taken_score = models.IntegerField(default=0)
19
 
20
 
20
 class Matricula(models.Model):
21
 class Matricula(models.Model):
21
     user_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
22
     user_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
24
     prof = models.CharField(max_length=150, null=True, blank=True)
25
     prof = models.CharField(max_length=150, null=True, blank=True)
25
     semestre = models.IntegerField(default=0, null=False, blank=False)
26
     semestre = models.IntegerField(default=0, null=False, blank=False)
26
     year = models.IntegerField(default=0, null=False, blank=False)
27
     year = models.IntegerField(default=0, null=False, blank=False)
27
-    fecha = models.CharField(max_length=150, null=False, blank=True)
28
+    # fecha = models.CharField(max_length=150, null=False, blank=True)
28
     grade = models.CharField(max_length=3, default = 'N')
29
     grade = models.CharField(max_length=3, default = 'N')
29
     salones =models.CharField(max_length=100,blank=True, null=True) 
30
     salones =models.CharField(max_length=100,blank=True, null=True) 
30
     horarios =models.CharField(max_length=150,blank=True, null=True) 
31
     horarios =models.CharField(max_length=150,blank=True, null=True) 

+ 29
- 22
server/CompanionApp/views.py View File

107
     if request.method == 'POST':
107
     if request.method == 'POST':
108
         # request params
108
         # request params
109
         user_id = int(request.data['user_id'])
109
         user_id = int(request.data['user_id'])
110
-        course_code = request.data['code'].upper()
110
+        course_id = int(request.data['course_id'])
111
         grade = request.data['grade'].upper()
111
         grade = request.data['grade'].upper()
112
         year = int(request.data['year'])
112
         year = int(request.data['year'])
113
         semester = int(request.data['semester'])
113
         semester = int(request.data['semester'])
114
-        fecha = request.data['fecha']
115
         repeating = False
114
         repeating = False
116
-        print(type(grade))
115
+        
117
 
116
 
118
         # set point of grade
117
         # set point of grade
119
         points = 0
118
         points = 0
130
         else:
129
         else:
131
             return JsonResponse({'msg': 'Insert A, B, C, D or F' }, status=status.HTTP_406_NOT_ACCEPTABLE)
130
             return JsonResponse({'msg': 'Insert A, B, C, D or F' }, status=status.HTTP_406_NOT_ACCEPTABLE)
132
 
131
 
133
-        # find course id and credits
132
+        # find course credits
134
         cursor = connection.cursor()
133
         cursor = connection.cursor()
135
-        cursor.execute(f'Select id, creditos from "CompanionApp_curso" where code =\'{course_code}\' ')
134
+        cursor.execute(f'Select creditos from "CompanionApp_curso" where id = {course_id} ')
136
         course = cursor.fetchone()
135
         course = cursor.fetchone()
137
-        course_id = int(course[0])
138
-        creditos = int(course[1])
136
+        creditos = int(course[0])
139
 
137
 
140
         # check if student already took that class in the same year and semester he/she is trying to post
138
         # check if student already took that class in the same year and semester he/she is trying to post
141
         cursor = connection.cursor()
139
         cursor = connection.cursor()
142
         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}')
140
         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}')
143
         check = cursor.fetchone()
141
         check = cursor.fetchone()
144
-        check = list(check)
145
-        print(check)
146
-        if int(check[0]) == semester and int(check[1]) == year and check[3] == course_id:
147
-            return JsonResponse({'msg': 'You already took the course that year and semester.' }, status=status.HTTP_406_NOT_ACCEPTABLE)
148
-        elif int(check[1]) != year:
149
-            pass
150
-        elif int(check[1] == year) and int(check[0]) != semester:
151
-            pass
152
-          
142
+        if check != None:
143
+            check = list(check)
144
+            if int(check[0]) == semester and int(check[1]) == year and check[3] == course_id:
145
+                return JsonResponse({'msg': 'You already took the course that year and semester.' }, status=status.HTTP_406_NOT_ACCEPTABLE)
146
+            elif int(check[1]) != year:
147
+                pass
148
+            elif int(check[1] == year) and int(check[0]) != semester:
149
+                pass
150
+            
153
         # matricular al estudiante
151
         # matricular al estudiante
154
         cursor = connection.cursor()
152
         cursor = connection.cursor()
155
-        cursor.execute(f'INSERT INTO "CompanionApp_matricula" (semestre, year, fecha, grade, user_id_id, course_id_id) VALUES ({semester}, {year}, \'{fecha}\', \'{grade}\', {user_id}, {course_id})')
153
+        cursor.execute(f'INSERT INTO "CompanionApp_matricula" (semestre, year, grade, user_id_id, course_id_id) VALUES ({semester}, {year}, \'{grade}\', {user_id}, {course_id})')
156
 
154
 
157
         # find credits taken
155
         # find credits taken
158
         cursor = connection.cursor()
156
         cursor = connection.cursor()
159
         cursor.execute(f'Select credits_taken from "CompanionApp_user" where id={user_id}')
157
         cursor.execute(f'Select credits_taken from "CompanionApp_user" where id={user_id}')
160
         credits_taken = cursor.fetchone()
158
         credits_taken = cursor.fetchone()
161
         credits_taken = int(credits_taken[0])
159
         credits_taken = int(credits_taken[0])
162
-        credits_taken += creditos
163
-        
160
+
161
+        # find last credits_taken_score
162
+        cursor = connection.cursor()
163
+        cursor.execute(f'Select credits_taken_score from "CompanionApp_user" where id={user_id}')
164
+        credits_taken_score = cursor.fetchone()
165
+        credits_taken_score = int(credits_taken_score[0])
166
+
164
         # update credits taken
167
         # update credits taken
168
+        credits_taken += creditos
165
         cursor = connection.cursor()
169
         cursor = connection.cursor()
166
         cursor.execute(f'UPDATE "CompanionApp_user" set credits_taken = {credits_taken} where id ={user_id}')
170
         cursor.execute(f'UPDATE "CompanionApp_user" set credits_taken = {credits_taken} where id ={user_id}')
167
 
171
 
168
-        credit_score = credits_taken * 4
169
-        credits_taken_score = credits_taken * points
170
-  
172
+        # update credits_taken_score
173
+        credits_taken_score = credits_taken_score + (creditos * points)
174
+        cursor = connection.cursor()
175
+        cursor.execute(f'UPDATE "CompanionApp_user" set credits_taken_score = {credits_taken_score} where id ={user_id}')
176
+
171
  
177
  
172
         # set GPA and insert it in user
178
         # set GPA and insert it in user
179
+        credit_score = credits_taken * 4
173
         gpa = (credits_taken_score / credit_score) * 4.0
180
         gpa = (credits_taken_score / credit_score) * 4.0
174
         gpa = float("{:.2f}".format(gpa))
181
         gpa = float("{:.2f}".format(gpa))
175
         cursor = connection.cursor()
182
         cursor = connection.cursor()