Advertisement
Badal_hs_shah

Untitled

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