Keine Beschreibung

Home_page.js 12KB

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