Bez popisu

Home_page.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import React, {useState, useEffect, useRef} from 'react'
  2. import { Button, Text, View, StyleSheet, Dimensions} from 'react-native'
  3. import {FlatList, ListViewBase } from 'react-native'
  4. import {TouchableOpacity} from 'react-native-gesture-handler'
  5. import {List, Divider} from 'react-native-paper'
  6. import Loading from './Loading'
  7. import firebase from 'firebase';
  8. import { styles } from "../../config/styles";
  9. import { TextInput, TouchableWithoutFeedback, Keyboard, ImageBackground} from "react-native";
  10. import { connect } from 'react-redux'
  11. import { bindActionCreators } from 'redux'
  12. import { fetchUser } from '../../redux/actions/index'
  13. import Constants from 'expo-constants';
  14. import * as Notifications from 'expo-notifications';
  15. Notifications.setNotificationHandler({
  16. handleNotification: async () => ({
  17. shouldShowAlert: true,
  18. shouldPlaySound: true,
  19. shouldSetBadge: false,
  20. }),
  21. });
  22. export function Home_page({navigation}) {
  23. const [threads, setThreads] = useState([]);
  24. const [loading, setLoading] = useState(true);
  25. const [appointments, setAppointments] = useState([]);
  26. const[interpreter, setState] = useState();
  27. const [expoPushToken, setExpoPushToken] = useState('');
  28. const [notification, setNotification] = useState(false);
  29. const notificationListener = useRef();
  30. const responseListener = useRef();
  31. useEffect(() => {
  32. registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
  33. notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
  34. setNotification(notification);
  35. });
  36. responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
  37. console.log("response", response);
  38. if (response.notification.request.content.body == 'Le solicitan una cita'){
  39. navigation.navigate('Confirm');
  40. }
  41. });
  42. const fire = firebase.firestore()
  43. .collection('THREADS')
  44. .where("members", "array-contains", firebase.auth().currentUser.uid)
  45. .onSnapshot(querySnapshot => {
  46. const threads = querySnapshot.docs.map(documentSnapshot => {
  47. return{
  48. _id:documentSnapshot.id,
  49. name:'',
  50. ...documentSnapshot.data()
  51. };
  52. });
  53. setThreads(threads);
  54. if(loading){
  55. setLoading(false);
  56. }
  57. });
  58. const cita = firebase.firestore().collection('APPOINTMENTS').where("participantes", "array-contains", firebase.auth().currentUser.uid).onSnapshot(snapShot => {
  59. const appointments = snapShot.docs.map(docSnap => {
  60. return{
  61. _id:docSnap.id,
  62. new:'',
  63. Day:'',
  64. Month:'',
  65. Time:'',
  66. i_token:'',
  67. u_token:'',
  68. Pin: {},
  69. ...docSnap.data()
  70. };
  71. });
  72. setAppointments(appointments);
  73. console.log("appointment", appointments);
  74. });
  75. return () => {
  76. Notifications.removeNotificationSubscription(notificationListener.current);
  77. Notifications.removeNotificationSubscription(responseListener.current);
  78. fire();
  79. cita();
  80. }
  81. }, []);
  82. if (loading) {
  83. return <Loading />;
  84. }
  85. const dimensions = Dimensions.get('window');
  86. const screenWidth = dimensions.width;
  87. function check_user_type_INT(){
  88. firebase.firestore()
  89. .collection("Interprete")
  90. .doc(firebase.auth().currentUser.uid)
  91. .get()
  92. .then((snapshot) => {
  93. if(snapshot.exists){
  94. setState(true);
  95. }
  96. else{
  97. setState(false);
  98. }
  99. })
  100. if(loading){
  101. setLoading(false);
  102. }
  103. }
  104. function citaId(citaID) {
  105. firebase.firestore()
  106. .collection('APPOINTMENTS')
  107. .doc(citaID)
  108. .update({
  109. citaID: citaID,
  110. })
  111. }
  112. check_user_type_INT();
  113. console.log("interpreter", interpreter);
  114. if(interpreter == false){
  115. return (
  116. <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
  117. <FlatList style={{
  118. flex: 1,
  119. width: screenWidth,
  120. }}
  121. data={appointments}
  122. keyExtractor = {item => item._id}
  123. ItemSeparatorComponent={() => <Divider />}
  124. renderItem = {({item}) => (
  125. <TouchableOpacity
  126. onPress={async () => {
  127. console.log("item._id, home, client", item.Pin)
  128. navigation.navigate('Cita',{tag: item, Pin: item})
  129. }}
  130. >
  131. <List.Item
  132. title={item.Month}
  133. titleNumberOfLines={1}
  134. titleStyle={styles.listTitle}
  135. descriptionStyle={styles.listDescription}
  136. descriptionNumberOfLines={1}
  137. />
  138. <List.Item
  139. title={item.Day}
  140. titleNumberOfLines={1}
  141. titleStyle={styles.listTitle}
  142. descriptionStyle={styles.listDescription}
  143. descriptionNumberOfLines={1}
  144. />
  145. <List.Item
  146. title={item.Time}
  147. titleNumberOfLines={1}
  148. titleStyle={styles.listTitle}
  149. descriptionStyle={styles.listDescription}
  150. descriptionNumberOfLines={1}
  151. />
  152. </TouchableOpacity>
  153. )}
  154. />
  155. <FlatList style={{
  156. flex: 1,
  157. width: screenWidth,
  158. }}
  159. data={appointments}
  160. keyExtractor = {item => item._id}
  161. ItemSeparatorComponent={() => <Divider />}
  162. renderItem={({ item }) => {
  163. if(item.new == 'true'){
  164. return (
  165. <Button
  166. title ='Pedir Cita'
  167. onPress={ async () => {
  168. await sendPushNotification(item.i_token);
  169. citaId(item._id);
  170. }
  171. }
  172. />
  173. )
  174. }}}
  175. />
  176. <Button
  177. title ='Hacer Busqueda'
  178. onPress= {() => navigation.navigate('Search', {U_Token: expoPushToken})}
  179. />
  180. <Button
  181. title ='Logout'
  182. onPress= {() => firebase.auth().signOut()}
  183. />
  184. </ImageBackground>
  185. );
  186. }
  187. else{
  188. return (
  189. <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
  190. <FlatList style={{
  191. flex: 1,
  192. width: screenWidth,
  193. }}
  194. data={appointments}
  195. keyExtractor = {item => item._id}
  196. ItemSeparatorComponent={() => <Divider />}
  197. renderItem = {({item}) => (
  198. <TouchableOpacity
  199. onPress={async () => {
  200. console.log("item._id, home, interpreter", item._id)
  201. navigation.navigate('Cita',{tag: item, Pin: item})
  202. }}
  203. >
  204. <List.Item
  205. title={item.Month}
  206. titleNumberOfLines={1}
  207. titleStyle={styles.listTitle}
  208. descriptionStyle={styles.listDescription}
  209. descriptionNumberOfLines={1}
  210. />
  211. <List.Item
  212. title={item.Day}
  213. titleNumberOfLines={1}
  214. titleStyle={styles.listTitle}
  215. descriptionStyle={styles.listDescription}
  216. descriptionNumberOfLines={1}
  217. />
  218. <List.Item
  219. title={item.Time}
  220. titleNumberOfLines={1}
  221. titleStyle={styles.listTitle}
  222. descriptionStyle={styles.listDescription}
  223. descriptionNumberOfLines={1}
  224. />
  225. </TouchableOpacity>
  226. )}
  227. />
  228. <FlatList style={{
  229. flex: 1,
  230. width: screenWidth,
  231. }}
  232. data={appointments}
  233. keyExtractor = {item => item._id}
  234. renderItem={({ item }) => {
  235. if(item.new == 'true'){
  236. return (
  237. <Button
  238. title ='Pedir Cita'
  239. onPress={ async () => {
  240. await sendPushNotification(item.i_token);
  241. citaId(item._id);
  242. }
  243. }
  244. />
  245. )
  246. }}}
  247. />
  248. <Button
  249. title ='Availability'
  250. onPress= {() => navigation.navigate('Availability')}
  251. />
  252. <Button
  253. title ='Logout'
  254. onPress= {() => firebase.auth().signOut()}
  255. />
  256. </ImageBackground>
  257. );
  258. }
  259. }
  260. // Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
  261. async function sendPushNotification(expoPushToken) {
  262. const message = {
  263. to: expoPushToken,
  264. sound: 'default',
  265. title: 'Freehand',
  266. body: 'Le solicitan una cita',
  267. data: { someData: 'goes here' },
  268. };
  269. await fetch('https://exp.host/--/api/v2/push/send', {
  270. method: 'POST',
  271. headers: {
  272. Accept: 'application/json',
  273. 'Accept-encoding': 'gzip, deflate',
  274. 'Content-Type': 'application/json',
  275. },
  276. body: JSON.stringify(message),
  277. });
  278. }
  279. async function registerForPushNotificationsAsync() {
  280. let token;
  281. if (Constants.isDevice) {
  282. const { status: existingStatus } = await Notifications.getPermissionsAsync();
  283. let finalStatus = existingStatus;
  284. if (existingStatus !== 'granted') {
  285. const { status } = await Notifications.requestPermissionsAsync();
  286. finalStatus = status;
  287. }
  288. if (finalStatus !== 'granted') {
  289. alert('Failed to get push token for push notification!');
  290. return;
  291. }
  292. token = (await Notifications.getExpoPushTokenAsync()).data;
  293. console.log('Token:', token)
  294. } else {
  295. alert('Must use physical device for Push Notifications');
  296. }
  297. if (Platform.OS === 'android') {
  298. Notifications.setNotificationChannelAsync('default', {
  299. name: 'default',
  300. importance: Notifications.AndroidImportance.MAX,
  301. vibrationPattern: [0, 250, 250, 250],
  302. lightColor: '#FF231F7C',
  303. });
  304. }
  305. firebase.firestore().collection('Interprete').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  306. firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  307. return token;
  308. }
  309. const mapStateToProps = (store) => ({
  310. currentUser: store.userState.currentUser
  311. })
  312. const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
  313. export default connect(mapStateToProps, mapDispatchProps)(Home_page);