No Description

Home_page.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 [Iuser, setIUser] = useState({})
  28. const [Uuser, setUser] = useState({})
  29. const [expoPushToken, setExpoPushToken] = useState('');
  30. const [notification, setNotification] = useState(false);
  31. const notificationListener = useRef();
  32. const responseListener = useRef();
  33. useEffect(() => {
  34. registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
  35. notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
  36. setNotification(notification);
  37. });
  38. responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
  39. console.log("response", response);
  40. console.log("response date", response.notification.date);
  41. console.log("response date", appointments[0]._id);
  42. const idDate = response.notification.date;
  43. if (response.notification.request.content.body == 'Le solicitan una cita'){
  44. navigation.navigate('Confirm');
  45. }
  46. });
  47. const user_email = firebase.auth().currentUser.email;
  48. const Iuser_data = firebase.firestore()
  49. .collection('Interprete')
  50. .where("email", "==", user_email)
  51. .onSnapshot(snapShot => {
  52. const user = snapShot.docs.map(docSnap => {
  53. return{
  54. _id:docSnap.id,
  55. email:'',
  56. username:'',
  57. ...docSnap.data()
  58. };
  59. });
  60. setIUser(user)
  61. if(loading){
  62. setLoading(false);
  63. }
  64. });
  65. const user_data = firebase.firestore()
  66. .collection('Users')
  67. .where("email", "==", user_email)
  68. .onSnapshot(snapShot => {
  69. const user = snapShot.docs.map(docSnap => {
  70. return{
  71. _id:docSnap.id,
  72. email:'',
  73. username:'',
  74. ...docSnap.data()
  75. };
  76. });
  77. setUser(user)
  78. if(loading){
  79. setLoading(false);
  80. }
  81. });
  82. const fire = firebase.firestore()
  83. .collection('THREADS')
  84. .where("members", "array-contains", firebase.auth().currentUser.uid)
  85. .onSnapshot(querySnapshot => {
  86. const threads = querySnapshot.docs.map(documentSnapshot => {
  87. return{
  88. _id:documentSnapshot.id,
  89. name:'',
  90. ...documentSnapshot.data()
  91. };
  92. });
  93. setThreads(threads);
  94. if(loading){
  95. setLoading(false);
  96. }
  97. });
  98. const cita = firebase.firestore().collection('APPOINTMENTS').where("participantes", "array-contains", firebase.auth().currentUser.uid).onSnapshot(snapShot => {
  99. const appointments = snapShot.docs.map(docSnap => {
  100. return{
  101. _id:docSnap.id,
  102. User:'',
  103. Interpreter:'',
  104. new:'',
  105. Day:'',
  106. Month:'',
  107. Time:'',
  108. i_token:'',
  109. u_token:'',
  110. Pin: {},
  111. ...docSnap.data()
  112. };
  113. });
  114. setAppointments(appointments);
  115. console.log("appointment", appointments);
  116. });
  117. return () => {
  118. Notifications.removeNotificationSubscription(notificationListener.current);
  119. Notifications.removeNotificationSubscription(responseListener.current);
  120. fire();
  121. cita();
  122. Iuser_data();
  123. user_data();
  124. }
  125. }, []);
  126. if (loading) {
  127. return <Loading />;
  128. }
  129. const dimensions = Dimensions.get('window');
  130. const screenWidth = dimensions.width;
  131. function check_user_type_INT(){
  132. firebase.firestore()
  133. .collection("Interprete")
  134. .doc(firebase.auth().currentUser.uid)
  135. .get()
  136. .then((snapshot) => {
  137. if(snapshot.exists){
  138. setState(true);
  139. }
  140. else{
  141. setState(false);
  142. }
  143. })
  144. if(loading){
  145. setLoading(false);
  146. }
  147. }
  148. function citaId(citaID) {
  149. firebase.firestore()
  150. .collection('APPOINTMENTS')
  151. .doc(citaID)
  152. .update({
  153. citaID: citaID,
  154. })
  155. }
  156. check_user_type_INT();
  157. console.log("interpreter", interpreter);
  158. if(interpreter == false){
  159. const user_name = Uuser[0].username;
  160. return (
  161. <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
  162. <FlatList style={{
  163. flex: 1,
  164. width: screenWidth,
  165. }}
  166. data={appointments}
  167. keyExtractor = {item => item._id}
  168. ItemSeparatorComponent={() => <Divider />}
  169. renderItem = {({item}) => (
  170. <TouchableOpacity
  171. onPress={async () => {
  172. console.log("item._id, home, client", item.Pin)
  173. navigation.navigate('Cita',{tag: item, Pin: item})
  174. }}
  175. >
  176. <List.Item
  177. title='Interprete: '
  178. description={item.Interpreter}
  179. titleNumberOfLines={1}
  180. titleStyle={styles.listTitle}
  181. descriptionStyle={styles.listDescription}
  182. descriptionNumberOfLines={1}
  183. />
  184. <List.Item
  185. title='Mes:'
  186. description={item.Month}
  187. titleNumberOfLines={1}
  188. titleStyle={styles.listTitle}
  189. descriptionStyle={styles.listDescription}
  190. descriptionNumberOfLines={1}
  191. />
  192. <List.Item
  193. title='Día:'
  194. description={item.Day}
  195. titleNumberOfLines={1}
  196. titleStyle={styles.listTitle}
  197. descriptionStyle={styles.listDescription}
  198. descriptionNumberOfLines={1}
  199. />
  200. <List.Item
  201. title='Hora:'
  202. description={item.Time}
  203. titleNumberOfLines={1}
  204. titleStyle={styles.listTitle}
  205. descriptionStyle={styles.listDescription}
  206. descriptionNumberOfLines={1}
  207. />
  208. </TouchableOpacity>
  209. )}
  210. />
  211. <FlatList style={{
  212. flex: 1,
  213. width: screenWidth,
  214. }}
  215. data={appointments}
  216. keyExtractor = {item => item._id}
  217. ItemSeparatorComponent={() => <Divider />}
  218. renderItem={({ item }) => {
  219. if(item.new == 'true'){
  220. return (
  221. <Button
  222. title ='Pedir Cita'
  223. onPress={ async () => {
  224. await sendPushNotification(item.i_token);
  225. citaId(item._id);
  226. }
  227. }
  228. />
  229. )
  230. }}}
  231. />
  232. <Button
  233. title ='Hacer Busqueda'
  234. onPress= {() => navigation.navigate('Search', {U_Token: expoPushToken, Username: user_name})}
  235. />
  236. <Button
  237. title ='Logout'
  238. onPress= {() => firebase.auth().signOut()}
  239. />
  240. </ImageBackground>
  241. );
  242. }
  243. else{
  244. //En caso de que se necesite el username del interprete que esta logged in.
  245. //const user_name = Iuser[0].username;
  246. return (
  247. <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
  248. <FlatList style={{
  249. flex: 1,
  250. width: screenWidth,
  251. }}
  252. data={appointments}
  253. keyExtractor = {item => item._id}
  254. ItemSeparatorComponent={() => <Divider />}
  255. renderItem = {({item}) => (
  256. <TouchableOpacity
  257. onPress={async () => {
  258. console.log("item._id, home, interpreter", item)
  259. navigation.navigate('Cita',{tag: item, Pin: item})
  260. }}
  261. >
  262. <List.Item
  263. title='Usuario:'
  264. description={item.User}
  265. titleNumberOfLines={1}
  266. titleStyle={styles.listTitle}
  267. descriptionStyle={styles.listDescription}
  268. descriptionNumberOfLines={1}
  269. />
  270. <List.Item
  271. title='Mes:'
  272. description={item.Month}
  273. titleNumberOfLines={1}
  274. titleStyle={styles.listTitle}
  275. descriptionStyle={styles.listDescription}
  276. descriptionNumberOfLines={1}
  277. />
  278. <List.Item
  279. title='Día:'
  280. description={item.Day}
  281. titleNumberOfLines={1}
  282. titleStyle={styles.listTitle}
  283. descriptionStyle={styles.listDescription}
  284. descriptionNumberOfLines={1}
  285. />
  286. <List.Item
  287. title='Hora:'
  288. description={item.Time}
  289. titleNumberOfLines={1}
  290. titleStyle={styles.listTitle}
  291. descriptionStyle={styles.listDescription}
  292. descriptionNumberOfLines={1}
  293. />
  294. </TouchableOpacity>
  295. )}
  296. />
  297. <FlatList style={{
  298. flex: 1,
  299. width: screenWidth,
  300. }}
  301. data={appointments}
  302. keyExtractor = {item => item._id}
  303. renderItem={({ item }) => {
  304. if(item.new == 'true'){
  305. return (
  306. <Button
  307. title ='Pedir Cita'
  308. onPress={ async () => {
  309. await sendPushNotification(item.i_token);
  310. citaId(item._id);
  311. }
  312. }
  313. />
  314. )
  315. }}}
  316. />
  317. <Button
  318. title ='Availability'
  319. onPress= {() => navigation.navigate('Availability')}
  320. />
  321. <Button
  322. title ='Logout'
  323. onPress= {() => firebase.auth().signOut()}
  324. />
  325. </ImageBackground>
  326. );
  327. }
  328. }
  329. // Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
  330. async function sendPushNotification(expoPushToken) {
  331. const message = {
  332. to: expoPushToken,
  333. sound: 'default',
  334. title: 'Freehand',
  335. body: 'Le solicitan una cita',
  336. data: { someData: 'goes here' },
  337. };
  338. await fetch('https://exp.host/--/api/v2/push/send', {
  339. method: 'POST',
  340. headers: {
  341. Accept: 'application/json',
  342. 'Accept-encoding': 'gzip, deflate',
  343. 'Content-Type': 'application/json',
  344. },
  345. body: JSON.stringify(message),
  346. });
  347. }
  348. async function registerForPushNotificationsAsync() {
  349. let token;
  350. if (Constants.isDevice) {
  351. const { status: existingStatus } = await Notifications.getPermissionsAsync();
  352. let finalStatus = existingStatus;
  353. if (existingStatus !== 'granted') {
  354. const { status } = await Notifications.requestPermissionsAsync();
  355. finalStatus = status;
  356. }
  357. if (finalStatus !== 'granted') {
  358. alert('Failed to get push token for push notification!');
  359. return;
  360. }
  361. token = (await Notifications.getExpoPushTokenAsync()).data;
  362. console.log('Token:', token)
  363. } else {
  364. alert('Must use physical device for Push Notifications');
  365. }
  366. if (Platform.OS === 'android') {
  367. Notifications.setNotificationChannelAsync('default', {
  368. name: 'default',
  369. importance: Notifications.AndroidImportance.MAX,
  370. vibrationPattern: [0, 250, 250, 250],
  371. lightColor: '#FF231F7C',
  372. });
  373. }
  374. firebase.firestore().collection('Interprete').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  375. firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  376. return token;
  377. }
  378. const mapStateToProps = (store) => ({
  379. currentUser: store.userState.currentUser
  380. })
  381. const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
  382. export default connect(mapStateToProps, mapDispatchProps)(Home_page);