Browse Source

Generalice los queries en Confirm.js, cree el chat de la cita, borro la cita si me dicen que no, notifico al usuario. Anadi un field 'new' a appointments para saber cuales que appointments hay que halar en el screen de citas. Se pone en false si se acepta.

ErnestoOrtiz2 3 years ago
parent
commit
8790479dfe
4 changed files with 88 additions and 291 deletions
  1. 1
    196
      screens/main/Cita.js
  2. 76
    50
      screens/main/Confirm.js
  3. 9
    45
      screens/main/Home_page.js
  4. 2
    0
      screens/main/StateTime.js

+ 1
- 196
screens/main/Cita.js View File

15
 import Constants from 'expo-constants';
15
 import Constants from 'expo-constants';
16
 import * as Notifications from 'expo-notifications';
16
 import * as Notifications from 'expo-notifications';
17
 
17
 
18
-Notifications.setNotificationHandler({
19
-  handleNotification: async () => ({
20
-    shouldShowAlert: true,
21
-    shouldPlaySound: true,
22
-    shouldSetBadge: false,
23
-  }),
24
-});
25
 
18
 
26
 
19
 
27
 export function Cita({navigation}) {
20
 export function Cita({navigation}) {
28
-  const [threads, setThreads] = useState([]);  
29
-  const [loading, setLoading] = useState(true);
30
-  const [appointments, setAppointments] = useState([]); 
31
-
32
-  const [expoPushToken, setExpoPushToken] = useState('');
33
-  const [notification, setNotification] = useState(false);
34
-  const notificationListener = useRef();
35
-  const responseListener = useRef();
36
-
37
-  useEffect(() => {
38
-    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
39
-    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
40
-      setNotification(notification);
41
-    });
42
-
43
-    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
44
-      console.log(response);
45
-      navigation.navigate('Confirm');
46
-    });
47
-
48
-    const fire = firebase.firestore()
49
-    .collection('THREADS')
50
-    .where("members", "array-contains", firebase.auth().currentUser.uid)
51
-    .onSnapshot(querySnapshot => {
52
-      const threads = querySnapshot.docs.map(documentSnapshot => {
53
-        return{
54
-          _id:documentSnapshot.id,
55
-          name:'',
56
-          ...documentSnapshot.data()
57
-        };
58
-      });
59
-
60
-      setThreads(threads);
61
-      console.log(threads);
62
-
63
-      if(loading){
64
-        setLoading(false);
65
-      }
66
-    });
67
-
68
-    const cita = firebase.firestore().collection('APPOINTMENTS').where('Day', '==', 8).onSnapshot(snapShot => {
69
-      const appointments = snapShot.docs.map(docSnap => {
70
-        return{
71
-          _id:docSnap.id,
72
-          Day:'',
73
-          Month:'',
74
-          Time:'',
75
-          i_id:'',
76
-          uid1:'',
77
-          ...docSnap.data()
78
-        };
79
-      });
80
-      setAppointments(appointments);
81
-      console.log(appointments);
82
-    });
83
-      
84
-    return () => {
85
-      Notifications.removeNotificationSubscription(notificationListener.current);
86
-      Notifications.removeNotificationSubscription(responseListener.current);
87
-      fire();
88
-      cita();
89
-    }
90
-  }, []);
91
-  
92
-  if (loading) {
93
-    return <Loading />;
94
-  }
21
+   
95
 
22
 
96
   
23
   
97
-  function handleButtonPress() {
98
-      firebase.firestore()
99
-        .collection('THREADS')
100
-        .add({
101
-          name: 'PedroFecha',
102
-          members: [
103
-            firebase.auth().currentUser.uid,
104
-            '02yOZHxFcGUX4MNwjeEbAlCShdu1'
105
-          ]
106
-        })
107
-  }
108
 
24
 
109
   const dimensions = Dimensions.get('window');
25
   const dimensions = Dimensions.get('window');
110
   const screenWidth = dimensions.width;
26
   const screenWidth = dimensions.width;
112
   
28
   
113
   return (
29
   return (
114
       <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
30
       <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
115
-        <FlatList style={{
116
-             flex: 1,
117
-             width: screenWidth,
118
-         }}
119
-          data={threads}
120
-          keyExtractor = {item => item._id}
121
-          ItemSeparatorComponent={() => <Divider />}
122
-          renderItem = {({item}) => (
123
-          <TouchableOpacity
124
-            onPress={() => navigation.navigate('Room', {thread: item})}
125
-          >
126
-            <List.Item
127
-              title={item.name}
128
-              titleNumberOfLines={1}
129
-              titleStyle={styles.listTitle}
130
-              descriptionStyle={styles.listDescription}
131
-              descriptionNumberOfLines={1}
132
-            />
133
-          </TouchableOpacity>
134
-        )}
135
-        />
136
-        <FlatList style={{
137
-             flex: 1,
138
-             width: screenWidth,
139
-         }}
140
-          data={appointments}
141
-          keyExtractor = {item => item._id}
142
-          ItemSeparatorComponent={() => <Divider />}
143
-          renderItem = {({item}) => (
144
-          <TouchableOpacity
145
-          onPress={async () => {
146
-            await sendPushNotification(expoPushToken); //item.push_token
147
-          }}
148
-          >
149
-            <List.Item
150
-              title={item.Month}
151
-              titleNumberOfLines={1}
152
-              titleStyle={styles.listTitle}
153
-              descriptionStyle={styles.listDescription}
154
-              descriptionNumberOfLines={1}
155
-            />
156
-            <List.Item
157
-              title={item.Day}
158
-              titleNumberOfLines={1}
159
-              titleStyle={styles.listTitle}
160
-              descriptionStyle={styles.listDescription}
161
-              descriptionNumberOfLines={1}
162
-            />
163
-            <List.Item
164
-              title={item.Time}
165
-              titleNumberOfLines={1}
166
-              titleStyle={styles.listTitle}
167
-              descriptionStyle={styles.listDescription}
168
-              descriptionNumberOfLines={1}
169
-            />
170
-          </TouchableOpacity>
171
-        )}
172
-        />
173
       <Button
31
       <Button
174
         title ='Ver mapa'
32
         title ='Ver mapa'
175
         onPress= {() => navigation.navigate('Map')}
33
         onPress= {() => navigation.navigate('Map')}
181
         </ImageBackground>
39
         </ImageBackground>
182
     );
40
     );
183
   }
41
   }
184
-// Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
185
-async function sendPushNotification(expoPushToken) {
186
-  const message = {
187
-    to: expoPushToken,
188
-    sound: 'default',
189
-    title: 'Freehand',
190
-    body: 'Le solicitan una cita',
191
-    data: { someData: 'goes here' },
192
-  };
193
-
194
-  await fetch('https://exp.host/--/api/v2/push/send', {
195
-    method: 'POST',
196
-    headers: {
197
-      Accept: 'application/json',
198
-      'Accept-encoding': 'gzip, deflate',
199
-      'Content-Type': 'application/json',
200
-    },
201
-    body: JSON.stringify(message),
202
-  });
203
-}
204
-
205
-async function registerForPushNotificationsAsync() {
206
-  let token;
207
-  if (Constants.isDevice) {
208
-    const { status: existingStatus } = await Notifications.getPermissionsAsync();
209
-    let finalStatus = existingStatus;
210
-    if (existingStatus !== 'granted') {
211
-      const { status } = await Notifications.requestPermissionsAsync();
212
-      finalStatus = status;
213
-    }
214
-    if (finalStatus !== 'granted') {
215
-      alert('Failed to get push token for push notification!');
216
-      return;
217
-    }
218
-    token = (await Notifications.getExpoPushTokenAsync()).data;
219
-    console.log(token);
220
-  } else {
221
-    alert('Must use physical device for Push Notifications');
222
-  }
223
-
224
-  if (Platform.OS === 'android') {
225
-    Notifications.setNotificationChannelAsync('default', {
226
-      name: 'default',
227
-      importance: Notifications.AndroidImportance.MAX,
228
-      vibrationPattern: [0, 250, 250, 250],
229
-      lightColor: '#FF231F7C',
230
-    });
231
-  }
232
-
233
-  firebase.firestore().collection('Interprete').doc(firebase.auth().currentUser.uid).update({'push_token': token})
234
-  firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
235
 
42
 
236
-  return token;
237
-}
238
 
43
 
239
 const mapStateToProps = (store) => ({
44
 const mapStateToProps = (store) => ({
240
   currentUser: store.userState.currentUser
45
   currentUser: store.userState.currentUser

+ 76
- 50
screens/main/Confirm.js View File

65
       }
65
       }
66
     });
66
     });
67
 
67
 
68
-    const cita = firebase.firestore().collection('APPOINTMENTS').where('Day', '==', 8).onSnapshot(snapShot => {
68
+    const cita = firebase.firestore().collection('APPOINTMENTS').where("new", "==", 'true').onSnapshot(snapShot => {
69
       const appointments = snapShot.docs.map(docSnap => {
69
       const appointments = snapShot.docs.map(docSnap => {
70
         return{
70
         return{
71
           _id:docSnap.id,
71
           _id:docSnap.id,
72
+          participantes: '',
73
+          new: '',
72
           Day:'',
74
           Day:'',
73
           Month:'',
75
           Month:'',
74
           Time:'',
76
           Time:'',
75
-          i_id:'',
76
-          uid1:'',
77
+          i_token:'',
78
+          u_token:'',
77
           ...docSnap.data()
79
           ...docSnap.data()
78
         };
80
         };
79
       });
81
       });
80
       setAppointments(appointments);
82
       setAppointments(appointments);
81
-      console.log(appointments);
83
+      console.log("appointment", appointments);
84
+      //console.log(appointments.Day);
82
     });
85
     });
83
       
86
       
84
     return () => {
87
     return () => {
93
     return <Loading />;
96
     return <Loading />;
94
   }
97
   }
95
 
98
 
96
-  
97
-  function crearChat() {
98
-      firebase.firestore()
99
-        .collection('THREADS')
100
-        .add({
101
-          name: 'CHAT',
102
-          members: [
103
-            firebase.auth().currentUser.uid,
104
-            '02yOZHxFcGUX4MNwjeEbAlCShdu1'
105
-          ]
106
-        })
99
+
100
+  function crearChat(cliente, citaID) {
101
+    firebase.firestore()
102
+      .collection('THREADS')
103
+      .add({
104
+        name: 'CHAT',
105
+        members: [
106
+          firebase.auth().currentUser.uid,
107
+          cliente, 
108
+        ],
109
+        cita: citaID,
110
+      })
111
+}
112
+
113
+
114
+  function citaOld(docID) {
115
+    firebase.firestore()
116
+      .collection('APPOINTMENTS')
117
+      .doc(docID)
118
+      .update({
119
+        new: 'false',
120
+      })
121
+  }
122
+
123
+  function deleteAppointment(docID) {
124
+    firebase.firestore()
125
+      .collection('APPOINTMENTS')
126
+      .doc(docID)
127
+      .delete()
107
   }
128
   }
108
 
129
 
109
   const dimensions = Dimensions.get('window');
130
   const dimensions = Dimensions.get('window');
116
              flex: 1,
137
              flex: 1,
117
              width: screenWidth,
138
              width: screenWidth,
118
          }}
139
          }}
119
-          data={threads}
120
-          keyExtractor = {item => item._id}
121
-          ItemSeparatorComponent={() => <Divider />}
122
-          renderItem = {({item}) => (
123
-          <TouchableOpacity
124
-            onPress={() => navigation.navigate('Room', {thread: item})}
125
-          >
126
-            <List.Item
127
-              title={item.name}
128
-              titleNumberOfLines={1}
129
-              titleStyle={styles.listTitle}
130
-              descriptionStyle={styles.listDescription}
131
-              descriptionNumberOfLines={1}
132
-            />
133
-          </TouchableOpacity>
134
-        )}
135
-        />
136
-        <FlatList style={{
137
-             flex: 1,
138
-             width: screenWidth,
139
-         }}
140
           data={appointments}
140
           data={appointments}
141
           keyExtractor = {item => item._id}
141
           keyExtractor = {item => item._id}
142
           ItemSeparatorComponent={() => <Divider />}
142
           ItemSeparatorComponent={() => <Divider />}
174
         title ='Ver mapa'
174
         title ='Ver mapa'
175
         onPress= {() => navigation.navigate('Map')}
175
         onPress= {() => navigation.navigate('Map')}
176
       />
176
       />
177
-      <Button
178
-        title="No disponible"
179
-        onPress={async () => {
180
-          await sendPushNotification(expoPushToken); //item.push_token
181
-          //Borrar Appointment de fb
182
-          navigation.navigate('Home');
183
-        }}
184
-      /> 
185
-      <Button
186
-        title ='Si'
187
-        onPress= {() => {
188
-            crearChat();
189
-            navigation.navigate('Home');
190
-        }}
177
+      <FlatList style={{
178
+             flex: 1,
179
+             width: screenWidth,
180
+         }}
181
+          data={appointments}
182
+          keyExtractor = {item => item._id}
183
+          renderItem={({ item }) => {
184
+            if(item.new){
185
+            return (
186
+              <Button
187
+               title="No disponible"
188
+               onPress={async () => {
189
+               await sendPushNotification(item.u_token);
190
+               deleteAppointment(item._id);
191
+               navigation.navigate('Home');
192
+               }}
193
+             /> 
194
+            )
195
+          }}}
191
       />
196
       />
197
+      <FlatList style={{
198
+             flex: 1,
199
+             width: screenWidth,
200
+         }}
201
+          data={appointments}
202
+          keyExtractor = {item => item._id}
203
+          renderItem={({ item }) => {
204
+            if(item.new){
205
+            return (
206
+              <Button
207
+              title ='Sí'
208
+              onPress={ async () => {
209
+                citaOld(item._id)
210
+                crearChat(item.participantes[0], item._id)
211
+                navigation.navigate('Home');
212
+                }
213
+              }
214
+            /> 
215
+            )
216
+          }}}
217
+            />
192
         </ImageBackground>
218
         </ImageBackground>
193
     );
219
     );
194
   }
220
   }

+ 9
- 45
screens/main/Home_page.js View File

37
   const notificationListener = useRef();
37
   const notificationListener = useRef();
38
   const responseListener = useRef();
38
   const responseListener = useRef();
39
 
39
 
40
-  //const [oneApp, setOneApp] = useState('')
41
-
42
 
40
 
43
   useEffect(() => {
41
   useEffect(() => {
44
     registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
42
     registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
48
 
46
 
49
     responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
47
     responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
50
       console.log(response);
48
       console.log(response);
51
-      navigation.navigate('Confirm');
49
+      if (response.notification.request.content.body == 'Le solicitan una cita'){
50
+        navigation.navigate('Confirm');
51
+      } 
52
     });
52
     });
53
 
53
 
54
     const fire = firebase.firestore()
54
     const fire = firebase.firestore()
64
       });
64
       });
65
 
65
 
66
       setThreads(threads);
66
       setThreads(threads);
67
-      //console.log(threads);
68
 
67
 
69
       if(loading){
68
       if(loading){
70
         setLoading(false);
69
         setLoading(false);
71
       }
70
       }
72
     });
71
     });
73
 
72
 
74
-    const cita = firebase.firestore().collection('APPOINTMENTS').where("participantes", "array-contains", 'qj5xBCSRNoaRMik4UULmslSktLp1').onSnapshot(snapShot => {
73
+    const cita = firebase.firestore().collection('APPOINTMENTS').where("participantes", "array-contains", firebase.auth().currentUser.uid).onSnapshot(snapShot => {
75
       const appointments = snapShot.docs.map(docSnap => {
74
       const appointments = snapShot.docs.map(docSnap => {
76
         return{
75
         return{
77
           _id:docSnap.id,
76
           _id:docSnap.id,
77
+          new:'',
78
           Day:'',
78
           Day:'',
79
           Month:'',
79
           Month:'',
80
           Time:'',
80
           Time:'',
85
       });
85
       });
86
       setAppointments(appointments);
86
       setAppointments(appointments);
87
       console.log("appointment", appointments);
87
       console.log("appointment", appointments);
88
-      //console.log(appointments.Day);
89
     });
88
     });
90
 
89
 
91
-
92
-    const day = firebase.firestore().collection('APPOINTMENTS').where('Day', '==', 8).get().then((res) => {
93
-      console.log(`Day is ${res.docs[0].get('Day')}.`);
94
-      //const dia = return{`${res.doc[0].get('Day')}`};
95
-    });
96
-    //console.log("Day", dia);
97
       
90
       
98
     return () => {
91
     return () => {
99
       Notifications.removeNotificationSubscription(notificationListener.current);
92
       Notifications.removeNotificationSubscription(notificationListener.current);
108
   }
101
   }
109
    
102
    
110
   
103
   
111
-
112
-  
113
-  function handleButtonPress() {
114
-      firebase.firestore()
115
-        .collection('THREADS')
116
-        .add({
117
-          name: 'PedroFecha',
118
-          members: [
119
-            firebase.auth().currentUser.uid,
120
-            '02yOZHxFcGUX4MNwjeEbAlCShdu1'
121
-          ]
122
-        })
123
-  }
124
-
125
   const dimensions = Dimensions.get('window');
104
   const dimensions = Dimensions.get('window');
126
   const screenWidth = dimensions.width;
105
   const screenWidth = dimensions.width;
127
 
106
 
164
         renderItem = {({item}) => (
143
         renderItem = {({item}) => (
165
         <TouchableOpacity
144
         <TouchableOpacity
166
         onPress={async () => {
145
         onPress={async () => {
167
-          navigation.navigate('Cita')
146
+          navigation.navigate('Cita', {appointment_id: item._id})
168
         }}
147
         }}
169
         >
148
         >
170
           <List.Item
149
           <List.Item
192
       )}
171
       )}
193
           />
172
           />
194
         <Button
173
         <Button
195
-            title ='Send notification'
196
-            onPress={async () => {
197
-            await sendPushNotification(expoPushToken);
198
-            }}
199
-          /> 
200
-        <Button
201
           title ='Hacer Busqueda'
174
           title ='Hacer Busqueda'
202
           onPress= {() => navigation.navigate('Search')}
175
           onPress= {() => navigation.navigate('Search')}
203
         />
176
         />
258
           keyExtractor = {item => item._id}
231
           keyExtractor = {item => item._id}
259
           ItemSeparatorComponent={() => <Divider />}
232
           ItemSeparatorComponent={() => <Divider />}
260
           renderItem={({ item }) => {
233
           renderItem={({ item }) => {
234
+            if(item.new){
261
             return (
235
             return (
262
               <Button
236
               <Button
263
-              title ='Send notification'
237
+              title ='Pedir Cita'
264
               onPress={ async () => {
238
               onPress={ async () => {
265
                 await sendPushNotification(item.i_token);
239
                 await sendPushNotification(item.i_token);
266
                 }
240
                 }
267
               }
241
               }
268
             /> 
242
             /> 
269
             )
243
             )
270
-          }}
244
+          }}}
271
             />
245
             />
272
 
246
 
273
 
247
 
274
           <Button
248
           <Button
275
-            title ='Send notification'
276
-            onPress={async () => {
277
-            await sendPushNotification(expoPushToken);
278
-            }}
279
-          /> 
280
-          <Button
281
           title ='Availability'
249
           title ='Availability'
282
           onPress= {() => navigation.navigate('Availability')}
250
           onPress= {() => navigation.navigate('Availability')}
283
         />
251
         />
284
-        <Button
285
-          title ='Mapa'
286
-          onPress= {() => navigation.navigate('Map')}
287
-        />
288
           <Button
252
           <Button
289
             title ='Logout'
253
             title ='Logout'
290
             onPress= {() => firebase.auth().signOut()}
254
             onPress= {() => firebase.auth().signOut()}

+ 2
- 0
screens/main/StateTime.js View File

147
       i_id,
147
       i_id,
148
       uid, 
148
       uid, 
149
       ],
149
       ],
150
+      new: true,
150
       Month : month,
151
       Month : month,
151
       Day: day,
152
       Day: day,
152
       Time: _time_,
153
       Time: _time_,
178
       i_id,
179
       i_id,
179
       uid, 
180
       uid, 
180
       ],
181
       ],
182
+      new: true,
181
       Month : month,
183
       Month : month,
182
       Day: day,
184
       Day: day,
183
       Time: _time_,
185
       Time: _time_,