Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {RW3AlternativePriceReason} from './../services/models/RW3AlternativePriceReason';
- import {API_URL_PROMOCONDITION} from './../services/url-constant';
- import {color} from './../themes/color';
- import React, {useContext, useEffect, useState} from 'react';
- import {
- FlatList,
- SafeAreaView,
- StyleSheet,
- Text,
- TouchableOpacity,
- View,
- Modal,
- Alert,
- } from 'react-native';
- import Storelistcell from '@src/components/storeList/Storelistcell';
- import StorelistcellDS from '../components/storeList/StorecellDS';
- import {useTheme} from '../themes';
- import {useNavigation} from '@react-navigation/native';
- import {API_URL_STORE} from '@src/services/url-constant';
- import getDefaultParams from '@src/services/api-params';
- import {Service} from '@src/services';
- import {RW3Store} from '@src/services/models/RW3Store';
- import {RW3PriceCheck} from '@src/services/models/RW3PriceCheck';
- import {RW3PriceCheckType} from '@src/services/models/RW3PriceCheckType';
- import {fontSizes} from '@src/themes/fontsizes';
- import {getUserSyncGUID, getUserPeopleID} from '@src/constants/AuthConstatnts';
- import StoreInstructionsAndAttachmants from './StoreInstructionsAndAttachmants';
- import {getInvalidAlertData} from '@src/constants/Constants';
- import InvalidVersionAlert from '@src/components/atoms/InvalidVersionAlert';
- import {t} from 'i18next';
- import * as geolib from 'geolib';
- import {getItemFromStorage} from '@src/utils/Storage';
- import PermissionHandler from '@src/utils/PermissionHandler';
- import {convertDate} from '@src/constants/ISPCHelper';
- import {DatabaseContext} from '@src/databaseContext';
- const StoreList = () => {
- const {theme, dark} = useTheme();
- const navigation = useNavigation();
- const [arrStoreList, setArrStoreList] = useState<RW3Store[]>([]);
- const [pageNumber, setPageNumber] = useState(1);
- const [refreshing, setRefreshing] = useState(false);
- const [isModalVisible, setIsModalVisible] = useState(false);
- const [showNoRecordLabel, setShowNoRecordLabel] = useState(false);
- const [currentLat, setCurrentLat] = useState('');
- const [currentLong, setCurrentLong] = useState('');
- //Required for display Alert
- const [alertTitle, setAlertTitle] = useState<string>();
- const [alertOptions, setAlertOptions] = useState<string[]>([]);
- const [alertMessage, setAlertMessage] = useState<string[]>([]);
- const refAlert = React.useRef<any>();
- const db = useContext(DatabaseContext);
- // Fetch Storelist data when component mount
- // useEffect(() => {
- // async function fetchData() {
- // setArrStoreList([]);
- // await fetchStoreData(pageNumber, false);
- // }
- // fetchData();
- // }, []);
- useEffect(() => {
- getLocationPermission();
- }, []);
- async function getLocationPermission() {
- const hasPermission = await PermissionHandler.hasLocationPermission();
- if (hasPermission) {
- setArrStoreList([]);
- await fetchStoreData(pageNumber, false);
- } else {
- Alert.alert(
- `${t('LOCATION_PERMISSION_DENIED_TITLE')}`,
- `${t('LOCATION_PERMISSION_DENIED_MESSAGE')}`,
- [
- {
- text: `${t('TRY_AGAIN')}`,
- onPress: async () => {
- getLocationPermission();
- },
- },
- ],
- );
- }
- }
- const fetchStoreData = async (page: number, isLoadMoreData: boolean) => {
- // const hasPermission = await PermissionHandler.hasLocationPermission();
- // if (hasPermission) {
- PermissionHandler.getCurrentLatLong();
- if (!isLoadMoreData) {
- page = 1;
- }
- setShowNoRecordLabel(false);
- try {
- const lLat = await getItemFromStorage('latitude');
- const lLong = await getItemFromStorage('longitude');
- setCurrentLat(lLat || '');
- setCurrentLong(lLong || '');
- const default_params = await getDefaultParams();
- if (!default_params) {
- //use defaultParams
- return;
- }
- default_params.append('Page', page.toString());
- default_params.append('PeopleId', (await getUserPeopleID()).toString());
- default_params.append('SyncGuid', (await getUserSyncGUID()).toString());
- const requestParams = {
- method: 'GET',
- url: `${API_URL_STORE.toString()}?${default_params.toString()}`,
- isRawData: true,
- contentType: 'text/plain',
- };
- const storeResponse = await Service.send(requestParams);
- if ([200].includes(storeResponse.status)) {
- if (storeResponse.data.length !== 0) {
- processStoreData(storeResponse, isLoadMoreData);
- } else if (isLoadMoreData) {
- Alert.alert(`${t('NO_MORE_STORES_TO_LOAD')}`);
- }
- } else {
- if (storeResponse.status === 409) {
- const getData: any = getInvalidAlertData(storeResponse.data);
- setAlertTitle(getData?.[0]);
- setAlertMessage(getData?.[1]);
- setAlertOptions(getData?.[2]);
- refAlert.current?.show();
- } else if (storeResponse.status === 401) {
- Alert.alert(
- `${t('INVALID_CREDENTIAL_TITLE')}`,
- storeResponse.data.LoginErrorMessage,
- [{text: `${t('ALERT_DISMISS')}`, style: 'cancel'}],
- );
- } else {
- if ('LoginErrorMessage' in storeResponse.data) {
- Alert.alert('', storeResponse.data.LoginErrorMessage, [
- {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
- ]);
- } else {
- Alert.alert('', storeResponse.data.Message, [
- {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
- ]);
- }
- }
- }
- } catch (err) {
- console.log('err', err);
- } finally {
- console.log('Go in finally block');
- }
- // } else {
- // console.log('dont have permission for location');
- // }
- };
- const loadMoreData = () => {
- setPageNumber(pageNumber + 1);
- fetchStoreData(pageNumber + 1, true);
- };
- const processStoreData = (storeResponse: any, isLoadMoreData: boolean) => {
- if (storeResponse && Object.keys(storeResponse.data).length) {
- const newArrStoreList: Array<RW3Store> = [];
- storeResponse.data.map(storeData => {
- const store = RW3Store.fromJSON(storeData);
- newArrStoreList.push(store);
- });
- if (isLoadMoreData) {
- setArrStoreList([...arrStoreList, ...newArrStoreList]);
- if (newArrStoreList.length === 0) {
- Alert.alert(`${t('NO_MORE_STORES_TO_LOAD')}`);
- }
- } else {
- setArrStoreList(newArrStoreList);
- }
- if (newArrStoreList.length === 0 && pageNumber === 1) {
- setShowNoRecordLabel(true);
- }
- }
- };
- const renderSeparator = () => {
- return <View style={[styles.viewSeparator]} />;
- };
- const renderFooter = () => {
- return (
- <TouchableOpacity onPress={loadMoreData}>
- <View style={[styles.viewLoadMore]}>
- <Text style={[styles.textLoadMore]}> Load More Data </Text>
- </View>
- </TouchableOpacity>
- );
- };
- function getDistanceFrom(lat: number, long: number) {
- const distance = geolib.getPreciseDistance(
- {latitude: lat, longitude: long},
- {latitude: Number(currentLat), longitude: currentLong},
- );
- const distanceInMiles = geolib.convertDistance(distance, 'mi');
- const distanceInMilesFormat = distanceInMiles.toFixed(1);
- return `${distanceInMilesFormat}`;
- }
- const renderItem = ({item, index}: any) => {
- const {
- name,
- street,
- city,
- state,
- postalCode,
- priceChecks,
- currentPriceCheck,
- latitude,
- longitude,
- } = item;
- const distance = getDistanceFrom(latitude, longitude);
- const priceCheckLength = priceChecks ? priceChecks.length : 0;
- const {type} = currentPriceCheck || {};
- let formattedDate;
- // let distanceInMi = getDistanceFrom(latitude, longitude);
- const displayViewType = (() => {
- if (!currentPriceCheck) {
- return 0;
- } else if (type === RW3PriceCheckType.RW3PriceCheckTypeBoth) {
- formattedDate = convertDate(currentPriceCheck.endDate);
- return currentPriceCheck.hasScrapeData ? 4 : 3;
- } else {
- formattedDate = convertDate(currentPriceCheck.endDate);
- return currentPriceCheck.hasScrapeData ? 2 : 1;
- }
- })();
- return displayViewType ? (
- <StorelistcellDS
- displayDate={formattedDate}
- currentType={displayViewType}
- mainTitle={name}
- subTitle={`${street}, ${city}, ${state} ${postalCode}`}
- distance={distance}
- currentPricecheck={currentPriceCheck}
- onPress={function () {
- navigateToPricecheckList(item);
- }}
- />
- ) : (
- <Storelistcell
- mainTitle={name}
- subTitle={`${street}, ${city}, ${state} ${postalCode}`}
- superSubTitle={`${priceCheckLength} ${t('NUMBER_PRICE_CHECKS')}`}
- distance={distance}
- />
- );
- };
- const navigateToPricecheckList = (item: RW3Store) => {
- console.log('index is ', item);
- const updatedPriceChecks = item.priceChecks.filter(
- pc => !pc.isExpired(pc.endDate),
- );
- if (updatedPriceChecks.length !== item.priceChecks.length) {
- presentPricecheckExpiredAlert();
- return;
- }
- didSelectStore(item);
- // navigation.navigate('pricechecklist' as never);
- };
- function didSelectStore(rw3Store: RW3Store) {
- downloadAlternativePriceReasonsOfStore(rw3Store);
- //Pending for here to get API when clicked on stores
- }
- const downloadAlternativePriceReasonsOfStore = async (store: RW3Store) => {
- const default_params = await getDefaultParams();
- if (!default_params) {
- //use defaultParams
- return;
- }
- default_params.append('StoreId', store.id.toString());
- default_params.append('PeopleId', (await getUserPeopleID()).toString());
- default_params.append('SyncGuid', (await getUserSyncGUID()).toString());
- const requestParams = {
- method: 'GET',
- url: `${API_URL_PROMOCONDITION.toString()}?${default_params.toString()}`,
- isRawData: true,
- contentType: 'text/plain',
- };
- const promoconditionResponse = await Service.send(requestParams);
- console.log(
- 'promotion response is',
- JSON.stringify(promoconditionResponse),
- );
- if ([200].includes(promoconditionResponse.status)) {
- if (promoconditionResponse.data.length !== 0) {
- promoconditionResponse.data.map(priceReason => {
- const mAlternativeReason = RW3Store.fromJSON(priceReason);
- insertAlternativePriceReason(priceReason);
- });
- //Pending from here need to store it in localstorage
- }
- } else {
- if (promoconditionResponse.status === 409) {
- const getData: any = getInvalidAlertData(promoconditionResponse.data);
- setAlertTitle(getData?.[0]);
- setAlertMessage(getData?.[1]);
- setAlertOptions(getData?.[2]);
- refAlert.current?.show();
- } else if (promoconditionResponse.status === 401) {
- Alert.alert(
- `${t('INVALID_CREDENTIAL_TITLE')}`,
- promoconditionResponse.data.LoginErrorMessage,
- [{text: `${t('ALERT_DISMISS')}`, style: 'cancel'}],
- );
- } else {
- if ('LoginErrorMessage' in promoconditionResponse.data) {
- Alert.alert('', promoconditionResponse.data.LoginErrorMessage, [
- {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
- ]);
- } else {
- Alert.alert('', promoconditionResponse.data.Message, [
- {text: `${t('ALERT_DISMISS')}`, style: 'cancel'},
- ]);
- }
- }
- }
- };
- function presentPricecheckExpiredAlert() {
- Alert.alert(
- `${t('WARNING')}`,
- `${t('PRICECHECK_NEEDS_TO_BE_UPDATED')}`,
- [
- {
- text: `${t('OK')}`,
- onPress: async () => {},
- },
- ],
- );
- }
- return (
- <SafeAreaView
- style={[
- styles.safeAreaContainer,
- {backgroundColor: theme.palette.appWhiteColor},
- ]}>
- <View
- style={[
- styles.viewContainer,
- {
- backgroundColor: theme.palette.backgroundcolor,
- },
- ]}>
- <InvalidVersionAlert
- ref={refAlert}
- title={alertTitle}
- message={alertMessage}
- options={alertOptions}
- cancelButtonIndex={0}
- />
- {showNoRecordLabel ? (
- <Text style={[styles.textNoStoreAvaialable]}>
- {`${t('NO_STORES_TO_LOAD')}`}
- </Text>
- ) : (
- <FlatList
- data={arrStoreList}
- keyExtractor={(item, index) => `${index}`}
- renderItem={renderItem}
- ItemSeparatorComponent={renderSeparator}
- ListFooterComponent={renderFooter}
- refreshing={refreshing}
- onRefresh={() => {
- setRefreshing(true);
- setArrStoreList([]);
- setPageNumber(1);
- fetchStoreData(pageNumber, false);
- setRefreshing(false);
- }}
- />
- )}
- <StoreInstructionsAndAttachmants
- showModel={isModalVisible}
- closeModal={() => setIsModalVisible(!isModalVisible)}
- />
- </View>
- </SafeAreaView>
- );
- };
- export default StoreList;
- const styles = StyleSheet.create({
- safeAreaContainer: {flex: 1},
- viewContainer: {flex: 1, padding: 0},
- viewLoadMore: {
- height: 44,
- flex: 1,
- borderBottomWidth: 1,
- borderBottomStyle: 'solid',
- borderBottomColor: '#CED0CE',
- borderTopWidth: 1,
- borderTopColor: '#CED0CE',
- justifyContent: 'center',
- alignItems: 'center',
- },
- viewSeparator: {
- height: 1,
- width: '100%',
- backgroundColor: '#CED0CE',
- },
- textLoadMore: {
- fontSize: fontSizes.storelistcell.loadMoreTitle,
- color: color.lightTheme.palette.appthemecolor,
- },
- textNoStoreAvaialable: {
- flex: 1,
- justifyContent: 'center',
- alignContent: 'center',
- textAlign: 'center',
- fontSize: fontSizes.storelistcell.loadMoreTitle,
- color: color.lightTheme.palette.lightGrey,
- paddingTop: 20,
- },
- });
- // function fetchDataFromDB() {
- // const db = useContext(DatabaseContext);
- // useEffect(() => {
- // if (db) {
- // db.transaction(tx => {
- // tx.executeSql(
- // 'SELECT * FROM AlternativePriceReason WHERE name = ?',
- // ['Apple'],
- // (_, result) => {
- // console.log('Result:', result);
- // },
- // (_, error) => {
- // console.log('Error:', error);
- // },
- // );
- // });
- // }
- // }, [db]);
- // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement