暫無描述

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