No Description

Home_page.js 12KB

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