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 2 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,96 +15,12 @@ import { fetchUser } from '../../redux/actions/index'
15 15
 import Constants from 'expo-constants';
16 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 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 25
   const dimensions = Dimensions.get('window');
110 26
   const screenWidth = dimensions.width;
@@ -112,64 +28,6 @@ export function Cita({navigation}) {
112 28
   
113 29
   return (
114 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 31
       <Button
174 32
         title ='Ver mapa'
175 33
         onPress= {() => navigation.navigate('Map')}
@@ -181,60 +39,7 @@ export function Cita({navigation}) {
181 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 44
 const mapStateToProps = (store) => ({
240 45
   currentUser: store.userState.currentUser

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

@@ -65,20 +65,23 @@ export function Confirm({navigation}) {
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 69
       const appointments = snapShot.docs.map(docSnap => {
70 70
         return{
71 71
           _id:docSnap.id,
72
+          participantes: '',
73
+          new: '',
72 74
           Day:'',
73 75
           Month:'',
74 76
           Time:'',
75
-          i_id:'',
76
-          uid1:'',
77
+          i_token:'',
78
+          u_token:'',
77 79
           ...docSnap.data()
78 80
         };
79 81
       });
80 82
       setAppointments(appointments);
81
-      console.log(appointments);
83
+      console.log("appointment", appointments);
84
+      //console.log(appointments.Day);
82 85
     });
83 86
       
84 87
     return () => {
@@ -93,17 +96,35 @@ export function Confirm({navigation}) {
93 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 130
   const dimensions = Dimensions.get('window');
@@ -116,27 +137,6 @@ export function Confirm({navigation}) {
116 137
              flex: 1,
117 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 140
           data={appointments}
141 141
           keyExtractor = {item => item._id}
142 142
           ItemSeparatorComponent={() => <Divider />}
@@ -174,21 +174,47 @@ export function Confirm({navigation}) {
174 174
         title ='Ver mapa'
175 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 218
         </ImageBackground>
193 219
     );
194 220
   }

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

@@ -37,8 +37,6 @@ export function Home_page({navigation}) {
37 37
   const notificationListener = useRef();
38 38
   const responseListener = useRef();
39 39
 
40
-  //const [oneApp, setOneApp] = useState('')
41
-
42 40
 
43 41
   useEffect(() => {
44 42
     registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
@@ -48,7 +46,9 @@ export function Home_page({navigation}) {
48 46
 
49 47
     responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
50 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 54
     const fire = firebase.firestore()
@@ -64,17 +64,17 @@ export function Home_page({navigation}) {
64 64
       });
65 65
 
66 66
       setThreads(threads);
67
-      //console.log(threads);
68 67
 
69 68
       if(loading){
70 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 74
       const appointments = snapShot.docs.map(docSnap => {
76 75
         return{
77 76
           _id:docSnap.id,
77
+          new:'',
78 78
           Day:'',
79 79
           Month:'',
80 80
           Time:'',
@@ -85,15 +85,8 @@ export function Home_page({navigation}) {
85 85
       });
86 86
       setAppointments(appointments);
87 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 91
     return () => {
99 92
       Notifications.removeNotificationSubscription(notificationListener.current);
@@ -108,20 +101,6 @@ export function Home_page({navigation}) {
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 104
   const dimensions = Dimensions.get('window');
126 105
   const screenWidth = dimensions.width;
127 106
 
@@ -164,7 +143,7 @@ export function Home_page({navigation}) {
164 143
         renderItem = {({item}) => (
165 144
         <TouchableOpacity
166 145
         onPress={async () => {
167
-          navigation.navigate('Cita')
146
+          navigation.navigate('Cita', {appointment_id: item._id})
168 147
         }}
169 148
         >
170 149
           <List.Item
@@ -192,12 +171,6 @@ export function Home_page({navigation}) {
192 171
       )}
193 172
           />
194 173
         <Button
195
-            title ='Send notification'
196
-            onPress={async () => {
197
-            await sendPushNotification(expoPushToken);
198
-            }}
199
-          /> 
200
-        <Button
201 174
           title ='Hacer Busqueda'
202 175
           onPress= {() => navigation.navigate('Search')}
203 176
         />
@@ -258,33 +231,24 @@ export function Home_page({navigation}) {
258 231
           keyExtractor = {item => item._id}
259 232
           ItemSeparatorComponent={() => <Divider />}
260 233
           renderItem={({ item }) => {
234
+            if(item.new){
261 235
             return (
262 236
               <Button
263
-              title ='Send notification'
237
+              title ='Pedir Cita'
264 238
               onPress={ async () => {
265 239
                 await sendPushNotification(item.i_token);
266 240
                 }
267 241
               }
268 242
             /> 
269 243
             )
270
-          }}
244
+          }}}
271 245
             />
272 246
 
273 247
 
274 248
           <Button
275
-            title ='Send notification'
276
-            onPress={async () => {
277
-            await sendPushNotification(expoPushToken);
278
-            }}
279
-          /> 
280
-          <Button
281 249
           title ='Availability'
282 250
           onPress= {() => navigation.navigate('Availability')}
283 251
         />
284
-        <Button
285
-          title ='Mapa'
286
-          onPress= {() => navigation.navigate('Map')}
287
-        />
288 252
           <Button
289 253
             title ='Logout'
290 254
             onPress= {() => firebase.auth().signOut()}

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

@@ -147,6 +147,7 @@ export default class Time extends Component{
147 147
       i_id,
148 148
       uid, 
149 149
       ],
150
+      new: true,
150 151
       Month : month,
151 152
       Day: day,
152 153
       Time: _time_,
@@ -178,6 +179,7 @@ export default class Time extends Component{
178 179
       i_id,
179 180
       uid, 
180 181
       ],
182
+      new: true,
181 183
       Month : month,
182 184
       Day: day,
183 185
       Time: _time_,