Brak opisu

Home_page.js 12KB

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