Advertisement
Badal_hs_shah

Storelist

Jan 24th, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {color} from './../themes/color';
  2. import React, {useEffect, useState} from 'react';
  3. import {
  4.   FlatList,
  5.   SafeAreaView,
  6.   StyleSheet,
  7.   Text,
  8.   TouchableOpacity,
  9.   View,
  10.   Modal,
  11.   Alert,
  12. } from 'react-native';
  13. import Storelistcell from '@src/components/storeList/Storelistcell';
  14. import StorelistcellDS from '../components/storeList/StorecellDS';
  15. import {useTheme} from '../themes';
  16. import {useNavigation} from '@react-navigation/native';
  17. import {API_URL_STORE} from '@src/services/url-constant';
  18. import getDefaultParams from '@src/services/api-params';
  19. import {Service} from '@src/services';
  20. import {RW3Store} from '@src/services/models/RW3Store';
  21. import {RW3PriceCheck} from '@src/services/models/RW3PriceCheck';
  22. import {RW3PriceCheckType} from '@src/services/models/RW3PriceCheckType';
  23. import {fontSizes} from '@src/themes/fontsizes';
  24. import {getUserSyncGUID, getUserPeopleID} from '@src/constants/AuthConstatnts';
  25. import StoreInstructionsAndAttachmants from './StoreInstructionsAndAttachmants';
  26. import {getInvalidAlertData} from '@src/constants/Constants';
  27. import InvalidVersionAlert from '@src/components/atoms/InvalidVersionAlert';
  28. import {t} from 'i18next';
  29. import * as geolib from 'geolib';
  30. import {getItemFromStorage} from '@src/utils/Storage';
  31. import PermissionHandler from '@src/utils/PermissionHandler';
  32. import {convertDate} from '@src/constants/ISPCHelper';
  33.  
  34. const StoreList = () => {
  35.   const {theme, dark} = useTheme();
  36.   const navigation = useNavigation();
  37.   const [arrStoreList, setArrStoreList] = useState<RW3Store[]>([]);
  38.   const [pageNumber, setPageNumber] = useState(1);
  39.   const [refreshing, setRefreshing] = useState(false);
  40.   const [isModalVisible, setIsModalVisible] = useState(false);
  41.   const [showNoRecordLabel, setShowNoRecordLabel] = useState(false);
  42.   const [currentLat, setCurrentLat] = useState('');
  43.   const [currentLong, setCurrentLong] = useState('');
  44.  
  45.   //Required for display Alert
  46.   const [alertTitle, setAlertTitle] = useState<string>();
  47.   const [alertOptions, setAlertOptions] = useState<string[]>([]);
  48.   const [alertMessage, setAlertMessage] = useState<string[]>([]);
  49.   const refAlert = React.useRef<any>();
  50.  
  51.   // const db = useContext(DatabaseContext);
  52.  
  53.   // Fetch Storelist data when component mount
  54.  
  55.   // useEffect(() => {
  56.   //   async function fetchData() {
  57.   //     setArrStoreList([]);
  58.   //     await fetchStoreData(pageNumber, false);
  59.   //   }
  60.   //   fetchData();
  61.   // }, []);
  62.  
  63.   useEffect(() => {
  64.     getLocationPermission();
  65.   }, []);
  66.  
  67.   async function getLocationPermission() {
  68.     const hasPermission = await PermissionHandler.hasLocationPermission();
  69.     if (hasPermission) {
  70.       setArrStoreList([]);
  71.       await fetchStoreData(pageNumber, false);
  72.     } else {
  73.     }
  74.   }
  75.  
  76.   const fetchStoreData = async (page: number, isLoadMoreData: boolean) => {
  77.     // const hasPermission = await PermissionHandler.hasLocationPermission();
  78.  
  79.     // if (hasPermission) {
  80.     PermissionHandler.getCurrentLatLong();
  81.  
  82.     if (!isLoadMoreData) {
  83.       page = 1;
  84.     }
  85.     setShowNoRecordLabel(false);
  86.     try {
  87.       const default_params = await getDefaultParams();
  88.       if (!default_params) {
  89.         //use defaultParams
  90.         return;
  91.       }
  92.       const lLat = await getItemFromStorage('latitude');
  93.       const lLong = await getItemFromStorage('longitude');
  94.       setCurrentLat(lLat || '');
  95.       setCurrentLong(lLong || '');
  96.       default_params.append('Page', page.toString());
  97.       default_params.append('PeopleId', (await getUserPeopleID()).toString());
  98.       default_params.append('SyncGuid', (await getUserSyncGUID()).toString());
  99.  
  100.       const requestParams = {
  101.         method: 'GET',
  102.         url: `${API_URL_STORE.toString()}?${default_params.toString()}`,
  103.         isRawData: true,
  104.         contentType: 'text/plain',
  105.       };
  106.       const storeResponse = await Service.send(requestParams);
  107.       if ([200].includes(storeResponse.status)) {
  108.         if (storeResponse.data.length !== 0) {
  109.           processStoreData(storeResponse, isLoadMoreData);
  110.         } else if (isLoadMoreData) {
  111.           Alert.alert(`${t('NO_MORE_STORES_TO_LOAD')}`);
  112.         }
  113.       } else {
  114.         if (storeResponse.status === 409) {
  115.           const getData: any = getInvalidAlertData(storeResponse.data);
  116.           setAlertTitle(getData?.[0]);
  117.           setAlertMessage(getData?.[1]);
  118.           setAlertOptions(getData?.[2]);
  119.           refAlert.current?.show();
  120.         } else if (storeResponse.status === 401) {
  121.           Alert.alert(
  122.             `${t('INVALID_CREDENTIAL_TITLE')}`,
  123.             storeResponse.data.LoginErrorMessage,
  124.             [{text: `${t('ALERT_DISMISS')}`, style: 'cancel'}],
  125.           );
  126.         } else {
  127.           if ('LoginErrorMessage' in storeResponse.data) {
  128.             Alert.alert('', storeResponse.data.LoginErrorMessage, [
  129.               {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
  130.             ]);
  131.           } else {
  132.             Alert.alert('', storeResponse.data.Message, [
  133.               {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
  134.             ]);
  135.           }
  136.         }
  137.       }
  138.     } catch (err) {
  139.       console.log('err', err);
  140.     } finally {
  141.       console.log('Go in finally block');
  142.     }
  143.     // } else {
  144.     //   console.log('dont have permission for location');
  145.     // }
  146.   };
  147.  
  148.   const loadMoreData = () => {
  149.     setPageNumber(pageNumber + 1);
  150.     fetchStoreData(pageNumber + 1, true);
  151.   };
  152.  
  153.   const processStoreData = (storeResponse: any, isLoadMoreData: boolean) => {
  154.     if (storeResponse && Object.keys(storeResponse.data).length) {
  155.       const newArrStoreList: Array<RW3Store> = [];
  156.       storeResponse.data.map(storeData => {
  157.         const store = RW3Store.fromJSON(storeData);
  158.         newArrStoreList.push(store);
  159.       });
  160.       if (isLoadMoreData) {
  161.         setArrStoreList([...arrStoreList, ...newArrStoreList]);
  162.         if (newArrStoreList.length === 0) {
  163.           Alert.alert(`${t('NO_MORE_STORES_TO_LOAD')}`);
  164.         }
  165.       } else {
  166.         setArrStoreList(newArrStoreList);
  167.       }
  168.       if (newArrStoreList.length === 0 && pageNumber === 1) {
  169.         setShowNoRecordLabel(true);
  170.       }
  171.     }
  172.   };
  173.  
  174.   const navigateToPricecheckList = () => {
  175.     navigation.navigate('pricechecklist' as never);
  176.   };
  177.  
  178.   const renderSeparator = () => {
  179.     return <View style={[styles.viewSeparator]} />;
  180.   };
  181.   const renderFooter = () => {
  182.     return (
  183.       <TouchableOpacity onPress={loadMoreData}>
  184.         <View style={[styles.viewLoadMore]}>
  185.           <Text style={[styles.textLoadMore]}> Load More Data </Text>
  186.         </View>
  187.       </TouchableOpacity>
  188.     );
  189.   };
  190.  
  191.   function getDistanceFrom(lat: number, long: number) {
  192.     const distance = geolib.getPreciseDistance(
  193.       {latitude: lat, longitude: long},
  194.       {latitude: Number(currentLat), longitude: currentLong},
  195.     );
  196.     const distanceInMiles = geolib.convertDistance(distance, 'mi');
  197.     const distanceInMilesFormat = distanceInMiles.toFixed(1);
  198.     return `${distanceInMilesFormat}`;
  199.   }
  200.  
  201.   const renderItem = ({item, index}: any) => {
  202.     const {
  203.       name,
  204.       street,
  205.       city,
  206.       state,
  207.       postalCode,
  208.       priceChecks,
  209.       currentPriceCheck,
  210.       latitude,
  211.       longitude,
  212.     } = item;
  213.     const distance = getDistanceFrom(latitude, longitude);
  214.  
  215.     const priceCheckLength = priceChecks ? priceChecks.length : 0;
  216.     const {type} = currentPriceCheck || {};
  217.     let formattedDate;
  218.     // let distanceInMi = getDistanceFrom(latitude, longitude);
  219.  
  220.     const displayViewType = (() => {
  221.       if (!currentPriceCheck) {
  222.         return 0;
  223.       } else if (type === RW3PriceCheckType.RW3PriceCheckTypeBoth) {
  224.         formattedDate = convertDate(currentPriceCheck.endDate);
  225.         return currentPriceCheck.hasScrapeData ? 4 : 3;
  226.       } else {
  227.         formattedDate = convertDate(currentPriceCheck.endDate);
  228.         return currentPriceCheck.hasScrapeData ? 2 : 1;
  229.       }
  230.     })();
  231.  
  232.     return displayViewType ? (
  233.       <StorelistcellDS
  234.         displayDate={formattedDate}
  235.         currentType={displayViewType}
  236.         mainTitle={name}
  237.         subTitle={`${street}, ${city}, ${state} ${postalCode}`}
  238.         distance={distance}
  239.         currentPricecheck={currentPriceCheck}
  240.         onPress={navigateToPricecheckList}
  241.       />
  242.     ) : (
  243.       <Storelistcell
  244.         mainTitle={name}
  245.         subTitle={`${street}, ${city}, ${state} ${postalCode}`}
  246.         superSubTitle={`${priceCheckLength} ${t('NUMBER_PRICE_CHECKS')}`}
  247.         distance={distance}
  248.       />
  249.     );
  250.   };
  251.  
  252.   return (
  253.     <SafeAreaView
  254.       style={[
  255.         styles.safeAreaContainer,
  256.         {backgroundColor: theme.palette.appWhiteColor},
  257.       ]}>
  258.       <View
  259.         style={[
  260.           styles.viewContainer,
  261.           {
  262.             backgroundColor: theme.palette.backgroundcolor,
  263.           },
  264.         ]}>
  265.         <InvalidVersionAlert
  266.           ref={refAlert}
  267.           title={alertTitle}
  268.           message={alertMessage}
  269.           options={alertOptions}
  270.           cancelButtonIndex={0}
  271.         />
  272.  
  273.         {showNoRecordLabel ? (
  274.           <Text style={[styles.textNoStoreAvaialable]}>
  275.             {`${t('NO_STORES_TO_LOAD')}`}
  276.           </Text>
  277.         ) : (
  278.           <FlatList
  279.             data={arrStoreList}
  280.             keyExtractor={(item, index) => `${index}`}
  281.             renderItem={renderItem}
  282.             ItemSeparatorComponent={renderSeparator}
  283.             ListFooterComponent={renderFooter}
  284.             refreshing={refreshing}
  285.             onRefresh={() => {
  286.               setRefreshing(true);
  287.               setArrStoreList([]);
  288.               setPageNumber(1);
  289.               fetchStoreData(pageNumber, false);
  290.               setRefreshing(false);
  291.             }}
  292.           />
  293.         )}
  294.         <StoreInstructionsAndAttachmants
  295.           showModel={isModalVisible}
  296.           closeModal={() => setIsModalVisible(!isModalVisible)}
  297.         />
  298.       </View>
  299.     </SafeAreaView>
  300.   );
  301. };
  302. export default StoreList;
  303.  
  304. const styles = StyleSheet.create({
  305.   safeAreaContainer: {flex: 1},
  306.   viewContainer: {flex: 1, padding: 0},
  307.   viewLoadMore: {
  308.     height: 44,
  309.     flex: 1,
  310.     borderBottomWidth: 1,
  311.     borderBottomStyle: 'solid',
  312.     borderBottomColor: '#CED0CE',
  313.     borderTopWidth: 1,
  314.     borderTopColor: '#CED0CE',
  315.     justifyContent: 'center',
  316.     alignItems: 'center',
  317.   },
  318.   viewSeparator: {
  319.     height: 1,
  320.     width: '100%',
  321.     backgroundColor: '#CED0CE',
  322.   },
  323.   textLoadMore: {
  324.     fontSize: fontSizes.storelistcell.loadMoreTitle,
  325.     color: color.lightTheme.palette.appthemecolor,
  326.   },
  327.   textNoStoreAvaialable: {
  328.     flex: 1,
  329.     justifyContent: 'center',
  330.     alignContent: 'center',
  331.     textAlign: 'center',
  332.     fontSize: fontSizes.storelistcell.loadMoreTitle,
  333.     color: color.lightTheme.palette.lightGrey,
  334.     paddingTop: 20,
  335.   },
  336. });
  337.  
  338. // function fetchDataFromDB() {
  339. //   const db = useContext(DatabaseContext);
  340.  
  341. //   useEffect(() => {
  342. //     if (db) {
  343. //       db.transaction(tx => {
  344. //         tx.executeSql(
  345. //           'SELECT * FROM AlternativePriceReason WHERE name = ?',
  346. //           ['Apple'],
  347. //           (_, result) => {
  348. //             console.log('Result:', result);
  349. //           },
  350. //           (_, error) => {
  351. //             console.log('Error:', error);
  352. //           },
  353. //         );
  354. //       });
  355. //     }
  356. //   }, [db]);
  357. // }
  358.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement