Skip to content

Commit

Permalink
environment change toggle in settings
Browse files Browse the repository at this point in the history
  • Loading branch information
mayankkumawat committed Jan 9, 2024
1 parent 121eb32 commit cc575fb
Show file tree
Hide file tree
Showing 22 changed files with 212 additions and 140 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,5 @@ yarn-error.log
# Temporary files created by Metro to check the health of the file watcher
.metro-health-check*
# testing
/coverage
/coverage
/environment.tsx
47 changes: 25 additions & 22 deletions app/actions/species.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@ import {
import { LogTypes } from '../utils/constants';
import { SET_SPECIE, CLEAR_SPECIE } from './Types';
import { APIConfig } from './Config';
import { store } from '../redux/store';
import { ENVS } from '../../environment';

const { protocol, cdnUrl } = APIConfig;
const { protocol } = APIConfig;

/**
* This function dispatches type SET_SPECIE with payload specie to show specie detail on SpecieInfo screen
* It requires the following param
* @param {Object} specie - specie which is to be shown or updated
*/
export const setSpecie = (specie) => (dispatch) => {
export const setSpecie = specie => dispatch => {
dispatch({
type: SET_SPECIE,
payload: specie,
Expand All @@ -29,7 +31,7 @@ export const setSpecie = (specie) => (dispatch) => {
/**
* This function dispatches type CLEAR_SPECIE to clear the species after navigated back from SpecieInfo screen
*/
export const clearSpecie = () => (dispatch) => {
export const clearSpecie = () => dispatch => {
dispatch({
type: CLEAR_SPECIE,
});
Expand All @@ -42,7 +44,7 @@ export const getSpeciesList = () => {
return new Promise((resolve, reject) => {
// makes an authorized GET request on /species to get the species list.
getAuthenticatedRequest('/treemapper/species')
.then((res) => {
.then(res => {
const { data, status } = res;
// checks if the status code is 200 the resolves the promise with the fetched data
if (status === 200) {
Expand All @@ -57,7 +59,7 @@ export const getSpeciesList = () => {
resolve(false);
}
})
.catch((err) => {
.catch(err => {
// logs the error
console.error(`Error at /actions/species/getSpeciesList, ${JSON.stringify(err.response)}`);
// logs the error of the failed request in DB
Expand All @@ -78,11 +80,11 @@ export const getSpeciesList = () => {
* @param {object} specieData - contains scientificSpecies as property having scientific specie id and
* aliases as property (a name given by user to that scientific specie)
*/
export const addUserSpecie = (specieData) => {
export const addUserSpecie = specieData => {
return new Promise((resolve, reject) => {
// makes an authorized POST request on /species to add a specie of user.
postAuthenticatedRequest('/treemapper/species', specieData)
.then((res) => {
.then(res => {
const { data, status } = res;

// checks if the status code is 200 the resolves the promise with the fetched data
Expand All @@ -104,7 +106,7 @@ export const addUserSpecie = (specieData) => {
resolve(false);
}
})
.catch((err) => {
.catch(err => {
// logs the error
console.error(`Error at /actions/species/addUserSpecie, ${JSON.stringify(err?.response)}`);
// logs the error of the failed request in DB
Expand All @@ -123,11 +125,11 @@ export const addUserSpecie = (specieData) => {
* Delete the user specie from the server using the specie id
* @param {object} specieId - specie id of user saved species which is use to delete specie from server
*/
export const deleteUserSpecie = (specieId) => {
export const deleteUserSpecie = specieId => {
return new Promise((resolve, reject) => {
// makes an authorized DELETE request on /species to delete a specie of user.
deleteAuthenticatedRequest(`/treemapper/species/${specieId}`)
.then((res) => {
.then(res => {
const { status } = res;

// checks if the status code is 204 then resolves the promise
Expand All @@ -143,7 +145,7 @@ export const deleteUserSpecie = (specieId) => {
resolve(false);
}
})
.catch((err) => {
.catch(err => {
// logs the error
console.error(
`Error at /actions/species/deleteUserSpecie, ${JSON.stringify(err?.response)}, ${err}`,
Expand Down Expand Up @@ -171,7 +173,7 @@ export const updateUserSpecie = ({
const data = { aliases, description, imageFile: image };
// makes an authorized DELETE request on /species to delete a specie of user.
putAuthenticatedRequest(`/treemapper/species/${specieId}`, data)
.then((res) => {
.then(res => {
const { status } = res;
// checks if the status code is 204 then resolves the promise
if (status === 200) {
Expand All @@ -187,7 +189,7 @@ export const updateUserSpecie = ({
resolve(false);
}
})
.catch((err) => {
.catch(err => {
// logs the error of the failed request in DB
dbLog.error({
logType: LogTypes.MANAGE_SPECIES,
Expand All @@ -207,14 +209,14 @@ export const UpdateSpeciesImage = (image, speciesId, SpecieGuid) => {
};

putAuthenticatedRequest(`/treemapper/species/${speciesId}`, body)
.then((res) => {
.then(res => {
const { status } = res;
if (status === 200) {
changeIsUpdatedStatus({ scientificSpecieGuid: SpecieGuid, isUpdated: true });
resolve(true);
}
})
.catch((err) => {
.catch(err => {
// logs the error of the failed request in DB
dbLog.error({
logType: LogTypes.MANAGE_SPECIES,
Expand All @@ -227,24 +229,25 @@ export const UpdateSpeciesImage = (image, speciesId, SpecieGuid) => {
});
};

export const getBase64ImageFromURL = async (specieImage) => {
export const getBase64ImageFromURL = async specieImage => {
return new Promise((resolve, reject) => {
if (cdnUrl) {
const currentEnv = store.getState().envSlice.currentEnv;
if (ENVS[currentEnv].CDN_URL) {
RNFS.downloadFile({
fromUrl: `${protocol}://${cdnUrl}/media/cache/species/default/${specieImage}`,
fromUrl: `${protocol}://${ENVS[currentEnv].CDN_URL}/media/cache/species/default/${specieImage}`,
toFile: `${RNFS.DocumentDirectoryPath}/${specieImage}`,
}).promise.then((response) => {
}).promise.then(response => {
if (response.statusCode === 200) {
RNFS.readFile(`${RNFS.DocumentDirectoryPath}/${specieImage}`, 'base64')
.then((data) => {
.then(data => {
resolve(data);
RNFS.unlink(`${RNFS.DocumentDirectoryPath}/${specieImage}`).catch((err) => {
RNFS.unlink(`${RNFS.DocumentDirectoryPath}/${specieImage}`).catch(err => {
reject(err);
// `unlink` will throw an error, if the item to unlink does not exist
console.error(err.message);
});
})
.catch((err) => {
.catch(err => {
dbLog.error({
logType: LogTypes.MANAGE_SPECIES,
message: 'Error while reading file image',
Expand Down
7 changes: 5 additions & 2 deletions app/components/Common/InventoryCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import { APIConfig } from './../../../actions/Config';
import { cmToInch, meterToFoot, nonISUCountries } from '../../../utils/constants';
import { INCOMPLETE, INCOMPLETE_SAMPLE_TREE, SINGLE } from '../../../utils/inventoryConstants';
import { single_tree_png, placeholder_image, map_img, multiple_tree_png } from '../../../assets';
import { store } from '../../../redux/store';
import { ENVS } from '../../../../environment';

const { protocol, cdnUrl } = APIConfig;
const { protocol } = APIConfig;

interface IInventoryCardProps {
data?: any;
Expand All @@ -37,8 +39,9 @@ const InventoryCard = ({
uri: `${imageURIPrefix}${RNFS.DocumentDirectoryPath}/${data.imageURL}`,
});
} else if (data.cdnImageUrl) {
const currentEnv = store.getState().envSlice.currentEnv;
setImageSource({
uri: `${protocol}://${cdnUrl}/media/cache/coordinate/thumb/${data.cdnImageUrl}`,
uri: `${protocol}://${ENVS[currentEnv].CDN_URL}/media/cache/coordinate/thumb/${data.cdnImageUrl}`,
});
} else if (
activeBtn === true ||
Expand Down
15 changes: 10 additions & 5 deletions app/components/Common/Modal/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,20 @@ import { Typography, Colors } from '_styles';
import CountryData from '../../../utils/countryData.json';
import i18next from 'i18next';
import { APIConfig } from '../../../actions/Config';
import { ENVS } from '../../../../environment';
import { useSelector } from 'react-redux';

const { protocol, cdnUrl } = APIConfig;
const { protocol } = APIConfig;

export default function index({ visible, openModal, userCountry }) {
const [countryData, setCountryData] = useState(null);
const [search, setSearch] = useState(null);
const { currentEnv } = useSelector(state => state.envSlice);

const renderItem = ({ item }) => {
return <Item title={item} onPress={() => selectCountry(item)} />;
};
const selectCountry = (title) => {
const selectCountry = title => {
userCountry(title);
};
const Item = ({ title, onPress }) => (
Expand All @@ -34,7 +37,9 @@ export default function index({ visible, openModal, userCountry }) {
<Image
source={{
// not using currencyCountryFlag any more as we have flags for every country
uri: cdnUrl ? `${protocol}://${cdnUrl}/media/images/flags/png/256/${title.countryCode}.png` : null,
uri: ENVS[currentEnv].CDN_URL
? `${protocol}://${ENVS[currentEnv].CDN_URL}/media/images/flags/png/256/${title.countryCode}.png`
: null,
}}
style={styles.countryFlag}
resizeMode="contain"
Expand Down Expand Up @@ -74,8 +79,8 @@ export default function index({ visible, openModal, userCountry }) {
openModal(false);
};

const handleFilter = (input) => {
const filteredData = CountryData.filter((el) =>
const handleFilter = input => {
const filteredData = CountryData.filter(el =>
el.countryName.toLowerCase().includes(input.toLowerCase()),
);
setCountryData(filteredData);
Expand Down
25 changes: 19 additions & 6 deletions app/components/Environment/Environment.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
import React from 'react';
import React, { useContext } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import FontAwesome5Icon from 'react-native-vector-icons/FontAwesome5';
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Alert } from 'react-native';

import { View, Text, StyleSheet, TouchableOpacity, Dimensions } from 'react-native';

import { ENV_TYPE } from '../../environment';
import { ENV_TYPE } from '../../../environment';
import HeaderV2 from '../Common/Header/HeaderV2';
import { Colors, Typography } from '../../styles';
import { IS_ANDROID, scaleSize } from '../../styles/mixins';
import { SET_APP_ENVIRONMENT } from '../../redux/slices/envSlice';
import { InventoryContext } from '../../reducers/inventory';
import { clearAllUploadedInventory } from '../../repositories/inventory';

const { width, height } = Dimensions.get('screen');

const Environment = () => {
const { currentEnv } = useSelector(state => state.envSlice);
const { state } = useContext(InventoryContext);
const dispatch = useDispatch();
const insects = useSafeAreaInsets();

const handleChangeEnv = async type => {
if (state.isUploading) {
Alert.alert('Inventory upload is in progress');
} else {
await clearAllUploadedInventory();
dispatch(SET_APP_ENVIRONMENT(type));
}
};

return (
<View style={styles.container}>
<HeaderV2
Expand All @@ -30,7 +41,8 @@ const Environment = () => {
<View style={styles.btnCon}>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => dispatch(SET_APP_ENVIRONMENT(ENV_TYPE.STAGING))}>
disabled={state.isUploading}
onPress={() => handleChangeEnv(ENV_TYPE.STAGING)}>
<View
style={[
styles.btn,
Expand All @@ -46,7 +58,8 @@ const Environment = () => {
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => dispatch(SET_APP_ENVIRONMENT(ENV_TYPE.PROD))}>
disabled={state.isUploading}
onPress={() => handleChangeEnv(ENV_TYPE.PROD)}>
<View
style={[
styles.btn,
Expand Down
6 changes: 5 additions & 1 deletion app/components/InventoryOverview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ import { getScientificSpeciesById } from '../../repositories/species';
import { getUserInformation } from '../../repositories/user';
import { cmToInch, meterToFoot, nonISUCountries } from '../../utils/constants';
import { UserContext } from '../../reducers/user';
import { useSelector } from 'react-redux';
import { ENVS } from '../../../environment';

let scrollAdjust = 0;

Expand All @@ -79,7 +81,9 @@ type RootStackParamList = {
type InventoryOverviewScreenRouteProp = RouteProp<RootStackParamList, 'InventoryOverview'>;

const InventoryOverview = ({ navigation }: any) => {
const { protocol, cdnUrl } = APIConfig;
const { protocol } = APIConfig;
const { currentEnv } = useSelector(state => state.envSlice);
const cdnUrl = ENVS[currentEnv].CDN_URL;
const windowHeight = Dimensions.get('window').height;

// reference for camera to focus on map
Expand Down
3 changes: 1 addition & 2 deletions app/components/MainScreen/BottomBar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Text, View, StyleSheet, TouchableOpacity, Vibration } from 'react-native';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import React, { useRef, useState } from 'react';
import { SvgXml } from 'react-native-svg';
import { add_icon, ListIcon, PlotIcon, MapExplore } from '../../assets';
Expand Down Expand Up @@ -30,7 +30,6 @@ const BottomBar = ({ state, descriptors, navigation }: IBottomBarProps) => {
const _addOptionsRef = useRef();

const onAddPress = () => {
Vibration.vibrate();
setOpen(prev => !prev);
};

Expand Down
8 changes: 7 additions & 1 deletion app/components/MainScreen/NavDrawer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import i18next from 'i18next';
import { useState } from 'react';
import React, { useContext } from 'react';
import { useSelector } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
Expand Down Expand Up @@ -28,8 +29,9 @@ import { Colors, Spacing, Typography } from '../../../styles';
import { InventoryContext } from '../../../reducers/inventory';
import { auth0Login, auth0Logout } from '../../../actions/user';
import { isPlantForThePlanetEmail } from '../../../utils';
import { ENVS } from '../../../../environment';

const { protocol, cdnUrl, webAppUrl } = APIConfig;
const { protocol } = APIConfig;

const getIcon = screenName => {
switch (screenName) {
Expand Down Expand Up @@ -84,11 +86,15 @@ const state = {
const NavDrawer = props => {
const { state: userState, dispatch: userDispatch } = useContext(UserContext);
const { dispatch } = useContext(InventoryContext);
const { currentEnv } = useSelector(state => state.envSlice);
const [loading, setLoading] = useState(false);

const navigation = useNavigation();
const insects = useSafeAreaInsets();

const cdnUrl = ENVS[currentEnv].CDN_URL;
const webAppUrl = ENVS[currentEnv].WEB_APP_URL;

const handleLogout = async () => {
const isLogout = await auth0Logout(userDispatch);
};
Expand Down
Loading

0 comments on commit cc575fb

Please sign in to comment.