diff options
author | Ivan Chen <ivan@tagg.id> | 2021-03-18 19:48:53 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-03-18 19:48:53 -0400 |
commit | aa0ddb7c5a6612ff067f7dce1c6d5b083db44309 (patch) | |
tree | 89326275ce5ff4e48bc29952c60856258cd8b0ab /src | |
parent | 07a15098625786451270e30e61e2d6e78c02d4db (diff) | |
parent | 9a7e34bf992e0bfa3b9ce7d83643d97fad209e6e (diff) |
Merge pull request #303 from shravyaramesh/add-friends-thru-contacts
[TMA-622] Add friends from contacts
Diffstat (limited to 'src')
-rw-r--r-- | src/assets/icons/findFriends/find-friends-blue-icon.svg | 1 | ||||
-rw-r--r-- | src/components/friends/InviteFriendTile.tsx | 118 | ||||
-rw-r--r-- | src/components/friends/index.ts | 1 | ||||
-rw-r--r-- | src/components/profile/Friends.tsx | 178 | ||||
-rw-r--r-- | src/components/search/SearchBar.tsx | 2 | ||||
-rw-r--r-- | src/constants/api.ts | 4 | ||||
-rw-r--r-- | src/routes/main/MainStackNavigator.tsx | 3 | ||||
-rw-r--r-- | src/routes/main/MainStackScreen.tsx | 14 | ||||
-rw-r--r-- | src/screens/profile/FriendsListScreen.tsx | 3 | ||||
-rw-r--r-- | src/screens/profile/InviteFriendsScreen.tsx | 328 | ||||
-rw-r--r-- | src/screens/profile/index.ts | 1 | ||||
-rw-r--r-- | src/services/UserFriendsService.ts | 69 | ||||
-rw-r--r-- | src/store/actions/userFriends.ts | 21 | ||||
-rw-r--r-- | src/types/types.ts | 6 | ||||
-rw-r--r-- | src/utils/common.ts | 19 | ||||
-rw-r--r-- | src/utils/friends.ts | 2 | ||||
-rw-r--r-- | src/utils/users.ts | 2 |
17 files changed, 736 insertions, 36 deletions
diff --git a/src/assets/icons/findFriends/find-friends-blue-icon.svg b/src/assets/icons/findFriends/find-friends-blue-icon.svg new file mode 100644 index 00000000..26ca145d --- /dev/null +++ b/src/assets/icons/findFriends/find-friends-blue-icon.svg @@ -0,0 +1 @@ +<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 216 216"><defs><style>.cls-1{fill:#08e2e2;}</style></defs><path class="cls-1" d="M104.28,135.51a58.59,58.59,0,1,0-8.85,8.86l21.79,21.26,9-8.27ZM58.62,145a46.22,46.22,0,1,1,46.21-46.21A46.23,46.23,0,0,1,58.62,145Z"/><path class="cls-1" d="M216,137.23a7.87,7.87,0,0,1-7.87,7.87H185.18v23a7.81,7.81,0,0,1-15.62,0v-23H146.62a7.87,7.87,0,0,1,0-15.73h22.94v-23a7.81,7.81,0,1,1,15.62,0v23h22.95A7.88,7.88,0,0,1,216,137.23Z"/></svg>
\ No newline at end of file diff --git a/src/components/friends/InviteFriendTile.tsx b/src/components/friends/InviteFriendTile.tsx new file mode 100644 index 00000000..3fbf2e73 --- /dev/null +++ b/src/components/friends/InviteFriendTile.tsx @@ -0,0 +1,118 @@ +import React, {useEffect, useState} from 'react'; +import { + Alert, + StyleSheet, + Text, + TouchableOpacity, + TouchableWithoutFeedback, + View, +} from 'react-native'; +import {TAGG_LIGHT_BLUE} from '../../constants'; +import {ERROR_SOMETHING_WENT_WRONG} from '../../constants/strings'; +import {inviteFriendService} from '../../services'; +import {normalize} from '../../utils'; + +interface InviteFriendTileProps { + item: Object; +} + +const InviteFriendTile: React.FC<InviteFriendTileProps> = ({item}) => { + const [invited, setInvited] = useState<boolean>(false); + const [formatedPhoneNumber, setFormattedPhoneNumber] = useState<string>(''); + const handleInviteFriend = async () => { + const response = await inviteFriendService( + item.phoneNumber, + item.firstName, + item.lastName, + ); + if (response) { + setInvited(response); + } else { + Alert.alert(ERROR_SOMETHING_WENT_WRONG); + } + }; + + useEffect(() => { + const formatPhoneNumer = () => { + const unformatted_number: string = item.phoneNumber; + const part_one: string = unformatted_number.substring(2, 5); + const part_two: string = unformatted_number.substring(5, 8); + const part_three: string = unformatted_number.substring( + 8, + unformatted_number.length, + ); + const temp = '(' + part_one + ')' + part_two + '-' + part_three; + setFormattedPhoneNumber(temp); + }; + formatPhoneNumer(); + }); + + return ( + <TouchableWithoutFeedback> + <View style={styles.container}> + <View style={styles.bodyContainer}> + <Text style={styles.label}> + {item.firstName + ' ' + item.lastName} + </Text> + <Text style={styles.phoneNumber}>{formatedPhoneNumber}</Text> + </View> + <TouchableOpacity + disabled={invited} + style={styles.button} + onPress={handleInviteFriend}> + <Text style={styles.buttonTitle}> + {invited ? 'Invited' : 'Invite'} + </Text> + </TouchableOpacity> + </View> + </TouchableWithoutFeedback> + ); +}; + +const styles = StyleSheet.create({ + container: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + height: normalize(42), + marginBottom: '5%', + }, + bodyContainer: { + flexDirection: 'column', + height: normalize(42), + justifyContent: 'space-around', + }, + label: { + fontWeight: '500', + fontSize: normalize(14), + }, + phoneNumber: { + fontSize: normalize(12), + fontWeight: '400', + color: '#6C6C6C', + letterSpacing: normalize(0.1), + }, + button: { + alignSelf: 'center', + justifyContent: 'center', + alignItems: 'center', + width: 82, + height: 25, + borderColor: TAGG_LIGHT_BLUE, + borderWidth: 2, + borderRadius: 2, + padding: 0, + backgroundColor: 'transparent', + }, + buttonTitle: { + color: TAGG_LIGHT_BLUE, + padding: 0, + fontSize: normalize(11), + fontWeight: '700', + lineHeight: normalize(13.13), + letterSpacing: normalize(0.6), + paddingHorizontal: '3.8%', + }, +}); + +export default InviteFriendTile; diff --git a/src/components/friends/index.ts b/src/components/friends/index.ts new file mode 100644 index 00000000..42727784 --- /dev/null +++ b/src/components/friends/index.ts @@ -0,0 +1 @@ +export {default as InviteFriendTile} from './InviteFriendTile'; diff --git a/src/components/profile/Friends.tsx b/src/components/profile/Friends.tsx index 7c7265c5..0592def8 100644 --- a/src/components/profile/Friends.tsx +++ b/src/components/profile/Friends.tsx @@ -1,14 +1,23 @@ -import React from 'react'; -import {View, StyleSheet, ScrollView, Text} from 'react-native'; -import {ProfilePreviewType, ScreenType} from '../../types'; -import {ProfilePreview} from '../profile'; -import {normalize, SCREEN_HEIGHT, SCREEN_WIDTH} from '../../utils'; +import {useNavigation} from '@react-navigation/native'; +import React, {useEffect, useState} from 'react'; +import {Alert, Linking, ScrollView, StyleSheet, Text, View} from 'react-native'; +import {checkPermission} from 'react-native-contacts'; +import {TouchableOpacity} from 'react-native-gesture-handler'; +import {useDispatch, useSelector, useStore} from 'react-redux'; import {TAGG_LIGHT_BLUE} from '../../constants'; -import {RootState} from '../../store/rootReducer'; -import {useDispatch, useStore} from 'react-redux'; -import {handleUnfriend} from '../../utils/friends'; +import {usersFromContactsService} from '../../services'; import {NO_USER} from '../../store/initialStates'; -import {TouchableOpacity} from 'react-native-gesture-handler'; +import {RootState} from '../../store/rootReducer'; +import {ProfilePreviewType, ScreenType} from '../../types'; +import { + extractContacts, + normalize, + SCREEN_HEIGHT, + SCREEN_WIDTH, +} from '../../utils'; +import {handleAddFriend, handleUnfriend} from '../../utils/friends'; +import {ProfilePreview} from '../profile'; +import FindFriendsBlueIcon from '../../assets/icons/findFriends/find-friends-blue-icon.svg'; interface FriendsProps { result: Array<ProfilePreviewType>; @@ -17,16 +26,107 @@ interface FriendsProps { } const Friends: React.FC<FriendsProps> = ({result, screenType, userId}) => { - const state: RootState = useStore().getState(); const dispatch = useDispatch(); + const navigation = useNavigation(); + const {user: loggedInUser = NO_USER} = useSelector( + (state: RootState) => state.user, + ); + const state = useStore().getState(); + const [usersFromContacts, setUsersFromContacts] = useState< + ProfilePreviewType[] + >([]); - const {user: loggedInUser = NO_USER} = state; + useEffect(() => { + const handleFindFriends = () => { + extractContacts().then(async (contacts) => { + const permission = await checkPermission(); + if (permission === 'authorized') { + let response = await usersFromContactsService(contacts); + await setUsersFromContacts(response.existing_tagg_users); + } else { + console.log('Authorize access to contacts'); + } + }); + }; + handleFindFriends(); + }, []); + + const UsersFromContacts = () => ( + <> + {usersFromContacts?.splice(0, 2).map((profilePreview) => ( + <View key={profilePreview.id} style={styles.container}> + <View style={styles.friend}> + <ProfilePreview + {...{profilePreview}} + previewType={'Friend'} + screenType={screenType} + /> + </View> + <TouchableOpacity + style={styles.button} + onPress={() => { + console.log('screentype: ', screenType); + handleAddFriend(screenType, profilePreview, dispatch, state).then( + (success) => { + if (success) { + let users = usersFromContacts; + setUsersFromContacts( + users.filter( + (user) => user.username !== profilePreview.username, + ), + ); + } + }, + ); + }}> + <Text style={styles.buttonTitle}>Add Friend</Text> + </TouchableOpacity> + </View> + ))} + </> + ); return ( <> - <View style={styles.subheader}> - {/* <Text style={styles.subheaderText}>Friends</Text> */} - </View> + {loggedInUser.userId === userId || + (userId === undefined && ( + <View style={styles.subheader}> + <View style={styles.addFriendHeaderContainer}> + <Text style={[styles.subheaderText]}>Add Friends</Text> + <TouchableOpacity + style={styles.findFriendsButton} + onPress={async () => { + const permission = await checkPermission(); + if (permission === 'authorized') { + navigation.navigate('InviteFriendsScreen', { + screenType: ScreenType.Profile, + }); + } else { + Alert.alert( + '"Tagg" Would Like to Access Your Contacts', + 'This helps you quickly get in touch with friends on the app and more', + [ + { + text: "Don't Allow", + style: 'cancel', + }, + {text: 'Allow', onPress: () => Linking.openSettings()}, + ], + ); + } + }}> + <FindFriendsBlueIcon width={20} height={20} /> + <Text style={styles.findFriendsSubheaderText}> + Find Friends + </Text> + </TouchableOpacity> + </View> + <UsersFromContacts /> + </View> + ))} + <Text style={[styles.subheaderText, styles.friendsSubheaderText]}> + Friends + </Text> <ScrollView keyboardShouldPersistTaps={'always'} style={styles.scrollView} @@ -41,7 +141,7 @@ const Friends: React.FC<FriendsProps> = ({result, screenType, userId}) => { screenType={screenType} /> </View> - {loggedInUser.userId === userId && ( + {loggedInUser.userId !== userId && ( <TouchableOpacity style={styles.button} onPress={() => @@ -63,12 +163,19 @@ const styles = StyleSheet.create({ alignSelf: 'center', width: SCREEN_WIDTH * 0.85, }, + firstScrollView: {}, scrollViewContent: { alignSelf: 'center', paddingBottom: SCREEN_HEIGHT / 7, width: SCREEN_WIDTH * 0.85, marginTop: '1%', }, + addFriendHeaderContainer: { + flexDirection: 'row', + justifyContent: 'space-between', + marginBottom: '3%', + marginTop: '2%', + }, header: {flexDirection: 'row'}, subheader: { alignSelf: 'center', @@ -81,6 +188,20 @@ const styles = StyleSheet.create({ fontWeight: '600', lineHeight: normalize(14.32), }, + findFriendsButton: {flexDirection: 'row'}, + friendsSubheaderText: { + alignSelf: 'center', + width: SCREEN_WIDTH * 0.85, + marginVertical: '1%', + marginBottom: '2%', + }, + findFriendsSubheaderText: { + marginLeft: '5%', + color: '#08E2E2', + fontSize: normalize(12), + fontWeight: '600', + lineHeight: normalize(14.32), + }, container: { alignSelf: 'center', flexDirection: 'row', @@ -94,7 +215,7 @@ const styles = StyleSheet.create({ alignSelf: 'center', height: '100%', }, - button: { + addFriendButton: { alignSelf: 'center', justifyContent: 'center', alignItems: 'center', @@ -104,10 +225,31 @@ const styles = StyleSheet.create({ borderWidth: 2, borderRadius: 2, padding: 0, - backgroundColor: 'transparent', + backgroundColor: TAGG_LIGHT_BLUE, + }, + addFriendButtonTitle: { + color: 'white', + padding: 0, + fontSize: normalize(11), + fontWeight: '700', + lineHeight: normalize(13.13), + letterSpacing: normalize(0.6), + paddingHorizontal: '3.8%', + }, + button: { + alignSelf: 'center', + justifyContent: 'center', + alignItems: 'center', + width: 82, + height: '55%', + borderColor: TAGG_LIGHT_BLUE, + borderWidth: 2, + borderRadius: 2, + padding: 0, + backgroundColor: TAGG_LIGHT_BLUE, }, buttonTitle: { - color: TAGG_LIGHT_BLUE, + color: 'white', padding: 0, fontSize: normalize(11), fontWeight: '700', diff --git a/src/components/search/SearchBar.tsx b/src/components/search/SearchBar.tsx index 1a855f20..62bda77e 100644 --- a/src/components/search/SearchBar.tsx +++ b/src/components/search/SearchBar.tsx @@ -70,8 +70,6 @@ const SearchBar: React.FC<SearchBarProps> = ({ // TODO: FIGURE OUT WHY CHANGES IN placeholderId ARE NOT REFLECTED HERE // my thought: the value is set when the function is defined, so it keeps // its inital value of -1 forever. - console.log(`Previous ID: ${placeholderId}`); - console.log(`Next ID: ${nextId}`); setPlaceholderId(nextId); }; diff --git a/src/constants/api.ts b/src/constants/api.ts index 34ef9a1c..1e2e887a 100644 --- a/src/constants/api.ts +++ b/src/constants/api.ts @@ -33,6 +33,10 @@ export const DISCOVER_ENDPOINT: string = API_URL + 'discover/'; export const SEARCH_BUTTONS_ENDPOPINT: string = DISCOVER_ENDPOINT + 'search_buttons/'; export const WAITLIST_USER_ENDPOINT: string = API_URL + 'waitlist-user/'; export const COMMENT_THREAD_ENDPOINT: string = API_URL + 'reply/'; +export const USERS_FROM_CONTACTS_ENDPOINT: string = + API_URL + 'user_contacts/find_friends/'; +export const INVITE_FRIEND_ENDPOINT: string = +API_URL + 'user_contacts/invite_friend/'; // Suggested People export const SP_USERS_ENDPOINT: string = API_URL + 'suggested_people/'; diff --git a/src/routes/main/MainStackNavigator.tsx b/src/routes/main/MainStackNavigator.tsx index 142249ce..f848a5ab 100644 --- a/src/routes/main/MainStackNavigator.tsx +++ b/src/routes/main/MainStackNavigator.tsx @@ -84,6 +84,9 @@ export type MainStackParams = { badge_title: string; badge_img: string; }; + InviteFriendsScreen: { + screenType: ScreenType; + }; }; export const MainStack = createStackNavigator<MainStackParams>(); diff --git a/src/routes/main/MainStackScreen.tsx b/src/routes/main/MainStackScreen.tsx index 35c306e5..d2f0d460 100644 --- a/src/routes/main/MainStackScreen.tsx +++ b/src/routes/main/MainStackScreen.tsx @@ -15,6 +15,7 @@ import { EditProfile, FriendsListScreen, IndividualMoment, + InviteFriendsScreen, MomentCommentsScreen, MomentUploadPromptScreen, NotificationsScreen, @@ -221,6 +222,19 @@ const MainStackScreen: React.FC<MainStackProps> = ({route}) => { }} /> <MainStack.Screen + name="InviteFriendsScreen" + component={InviteFriendsScreen} + initialParams={{screenType}} + options={{ + ...headerBarOptions('black', 'Invites'), + }} + /> + <MainStack.Screen + name="RequestContactsAccess" + component={RequestContactsAccess} + initialParams={{screenType}} + /> + <MainStack.Screen name="EditProfile" component={EditProfile} options={{ diff --git a/src/screens/profile/FriendsListScreen.tsx b/src/screens/profile/FriendsListScreen.tsx index 1cfef058..3016c767 100644 --- a/src/screens/profile/FriendsListScreen.tsx +++ b/src/screens/profile/FriendsListScreen.tsx @@ -1,6 +1,6 @@ import {RouteProp} from '@react-navigation/native'; import React from 'react'; -import {SafeAreaView, StyleSheet, View} from 'react-native'; +import {SafeAreaView, StatusBar, StyleSheet, View} from 'react-native'; import {useSelector} from 'react-redux'; import {Friends, TabsGradient} from '../../components'; import {MainStackParams} from '../../routes'; @@ -25,6 +25,7 @@ const FriendsListScreen: React.FC<FriendsListScreenProps> = ({route}) => { return ( <> <SafeAreaView> + <StatusBar barStyle="dark-content" /> <View style={styles.body}> <Friends result={friends} screenType={screenType} userId={userXId} /> </View> diff --git a/src/screens/profile/InviteFriendsScreen.tsx b/src/screens/profile/InviteFriendsScreen.tsx new file mode 100644 index 00000000..d1142b7f --- /dev/null +++ b/src/screens/profile/InviteFriendsScreen.tsx @@ -0,0 +1,328 @@ +import React, {useEffect, useState} from 'react'; +import { + View, + Text, + TouchableOpacity, + SafeAreaView, + StyleSheet, + TextInput, + FlatList, + Keyboard, + Linking, + StatusBar, + TouchableWithoutFeedback, + ScrollView, +} from 'react-native'; +import {useDispatch, useStore} from 'react-redux'; +import {ProfilePreviewType, ScreenType} from '../../types'; +import { + extractContacts, + handleAddFriend, + HeaderHeight, + normalize, + SCREEN_HEIGHT, + SCREEN_WIDTH, + StatusBarHeight, +} from '../../utils'; +import {checkPermission} from 'react-native-contacts'; +import {usersFromContactsService} from '../../services/UserFriendsService'; +import {ProfilePreview, TabsGradient} from '../../components'; +import Animated from 'react-native-reanimated'; +import Icon from 'react-native-vector-icons/Feather'; +import {InviteFriendTile} from '../../components/friends'; +import {TAGG_LIGHT_BLUE} from '../../constants'; +const AnimatedIcon = Animated.createAnimatedComponent(Icon); + +interface InviteFriendsScreenProps { + screenType: ScreenType; +} + +const InviteFriendsScreen: React.FC<InviteFriendsScreenProps> = ({ + screenType, +}) => { + const dispatch = useDispatch(); + const state = useStore().getState(); + const [usersFromContacts, setUsersFromContacts] = useState< + ProfilePreviewType[] + >([]); + const [nonUsersFromContacts, setNonUsersFromContacts] = useState<[]>([]); + type SearchResultType = { + usersFromContacts: ProfilePreviewType[]; + nonUsersFromContacts: []; + }; + const [results, setResults] = useState<SearchResultType>({ + usersFromContacts: usersFromContacts, + nonUsersFromContacts: nonUsersFromContacts, + }); + const [query, setQuery] = useState(''); + + useEffect(() => { + const handleFindFriends = () => { + extractContacts().then(async (retrievedContacts) => { + const permission = await checkPermission(); + if (permission === 'authorized') { + let response = await usersFromContactsService(retrievedContacts); + await setUsersFromContacts(response.existing_tagg_users); + await setNonUsersFromContacts(response.invite_from_contacts); + usersFromContacts.map((user) => console.log('user: ', user.username)); + setResults({ + usersFromContacts: response.existing_tagg_users, + nonUsersFromContacts: response.invite_from_contacts, + }); + } else { + Linking.openSettings(); + } + }); + }; + handleFindFriends(); + }, []); + + /* + * Main handler for changes in query. + */ + useEffect(() => { + console.log('query is now ', query); + const search = async () => { + if (query.length > 0) { + const searchResultsUsers = usersFromContacts.filter( + (item: ProfilePreviewType) => + item.first_name.toLowerCase().includes(query) || + item.last_name.toLowerCase().includes(query) || + item.username.toLowerCase().includes(query), + ); + const searchResultsNonUsers = nonUsersFromContacts.filter( + (item) => + item.firstName.toLowerCase().includes(query) || + item.lastName.toLowerCase().includes(query), + ); + const sanitizedResult = { + usersFromContacts: searchResultsUsers, + nonUsersFromContacts: searchResultsNonUsers, + }; + setResults(sanitizedResult); + } else { + setResults({ + usersFromContacts: usersFromContacts, + nonUsersFromContacts: nonUsersFromContacts, + }); + } + }; + search(); + }, [query]); + + const UsersFromContacts = () => ( + <> + <FlatList + showsVerticalScrollIndicator={false} + scrollEnabled={false} + data={results.usersFromContacts} + keyExtractor={(item) => item.username} + renderItem={({item}) => ( + <View key={item.id} style={styles.ppContainer}> + <View style={styles.friend}> + <ProfilePreview + {...{profilePreview: item}} + previewType={'Friend'} + screenType={screenType} + /> + </View> + <TouchableOpacity + style={styles.addFriendButton} + onPress={() => { + handleAddFriend(screenType, item, dispatch, state).then( + (success) => { + if (success) { + let users = usersFromContacts; + const filteredUsers = users.filter( + (user) => user.username !== item.username, + ); + setResults({ + ...results, + usersFromContacts: filteredUsers, + }); + } + }, + ); + }}> + <Text style={styles.addFriendButtonTitle}>Add Friend</Text> + </TouchableOpacity> + </View> + )} + /> + </> + ); + + return ( + <View style={styles.mainContainer}> + <TouchableWithoutFeedback onPress={Keyboard.dismiss}> + <SafeAreaView style={{marginTop: HeaderHeight + StatusBarHeight}}> + <StatusBar barStyle="dark-content" /> + <ScrollView + style={styles.body} + contentContainerStyle={{paddingBottom: SCREEN_HEIGHT * 0.1}}> + <View style={styles.headerContainer}> + <Text style={styles.headerText}> + Sharing is caring, invite friends, and create moments together! + </Text> + </View> + <View style={styles.container}> + <Animated.View style={styles.inputContainer}> + <AnimatedIcon + name="search" + color={'#7E7E7E'} + size={16} + style={styles.searchIcon} + /> + <TextInput + style={[styles.input]} + placeholderTextColor={'#828282'} + clearButtonMode="while-editing" + autoCapitalize="none" + autoCorrect={false} + onChangeText={(text) => { + setQuery(text.toLowerCase()); + }} + onBlur={() => { + Keyboard.dismiss(); + }} + onEndEditing={() => { + Keyboard.dismiss(); + }} + value={query} + placeholder={'Search'} + /> + </Animated.View> + </View> + <View style={styles.subheader}> + <Text style={styles.subheaderText}>Add Friends</Text> + <UsersFromContacts /> + </View> + <View style={styles.subheader}> + <Text style={styles.subheaderText}>Invite your friends!</Text> + <FlatList + contentContainerStyle={styles.nonUsersFlatListContainer} + showsVerticalScrollIndicator={false} + scrollEnabled={false} + data={results.nonUsersFromContacts} + keyExtractor={(item) => item.phoneNumber} + renderItem={({item}) => <InviteFriendTile item={item} />} + /> + </View> + </ScrollView> + </SafeAreaView> + </TouchableWithoutFeedback> + <TabsGradient /> + </View> + ); +}; + +const styles = StyleSheet.create({ + mainContainer: {backgroundColor: 'white', height: SCREEN_HEIGHT}, + body: { + paddingTop: 10, + height: SCREEN_HEIGHT, + backgroundColor: '#fff', + }, + headerContainer: { + width: SCREEN_WIDTH * 0.85, + height: 50, + alignSelf: 'center', + }, + nonUsersFlatListContainer: {paddingBottom: 130}, + subheader: { + alignSelf: 'center', + width: SCREEN_WIDTH * 0.85, + marginBottom: '5%', + }, + subheaderText: { + color: '#828282', + fontSize: normalize(12), + fontWeight: '600', + lineHeight: normalize(14.32), + marginBottom: '5%', + }, + headerText: { + textAlign: 'center', + color: '#828282', + fontSize: normalize(12), + fontWeight: '600', + lineHeight: normalize(14.32), + marginBottom: '5%', + }, + container: { + alignSelf: 'center', + flexDirection: 'row', + justifyContent: 'space-between', + width: '100%', + height: normalize(42), + alignItems: 'center', + marginBottom: '3%', + marginHorizontal: 10, + }, + ppContainer: { + alignSelf: 'center', + flexDirection: 'row', + justifyContent: 'space-between', + width: '100%', + height: normalize(42), + alignItems: 'center', + marginBottom: '5%', + marginHorizontal: 10, + }, + inputContainer: { + flexGrow: 1, + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: 8, + marginHorizontal: '3%', + borderRadius: 20, + backgroundColor: '#F0F0F0', + height: 34, + }, + searchIcon: { + marginRight: '5%', + }, + input: { + flex: 1, + fontSize: normalize(16), + color: '#000', + letterSpacing: normalize(0.5), + }, + cancelButton: { + height: '100%', + position: 'absolute', + justifyContent: 'center', + paddingHorizontal: 8, + }, + cancelText: { + color: '#818181', + fontWeight: '500', + }, + friend: { + alignSelf: 'center', + height: '100%', + }, + addFriendButton: { + alignSelf: 'center', + justifyContent: 'center', + alignItems: 'center', + width: 82, + height: 25, + borderColor: TAGG_LIGHT_BLUE, + borderWidth: 2, + borderRadius: 2, + padding: 0, + backgroundColor: TAGG_LIGHT_BLUE, + }, + addFriendButtonTitle: { + color: 'white', + padding: 0, + fontSize: normalize(11), + fontWeight: '700', + lineHeight: normalize(13.13), + letterSpacing: normalize(0.6), + paddingHorizontal: '3.8%', + }, +}); + +export default InviteFriendsScreen; diff --git a/src/screens/profile/index.ts b/src/screens/profile/index.ts index 9d651729..f74946a6 100644 --- a/src/screens/profile/index.ts +++ b/src/screens/profile/index.ts @@ -6,3 +6,4 @@ export {default as MomentCommentsScreen} from './MomentCommentsScreen'; export {default as FriendsListScreen} from './FriendsListScreen'; export {default as EditProfile} from './EditProfile'; export {default as MomentUploadPromptScreen} from './MomentUploadPromptScreen'; +export {default as InviteFriendsScreen} from './InviteFriendsScreen'; diff --git a/src/services/UserFriendsService.ts b/src/services/UserFriendsService.ts index dbec1974..cea20fbe 100644 --- a/src/services/UserFriendsService.ts +++ b/src/services/UserFriendsService.ts @@ -1,9 +1,17 @@ //Abstracted common friends api calls out here +import AsyncStorage from '@react-native-community/async-storage'; import {Alert} from 'react-native'; -import {FriendshipStatusType} from '../types'; -import {FRIENDS_ENDPOINT} from '../constants'; -import {ERROR_SOMETHING_WENT_WRONG_REFRESH} from '../constants/strings'; +import {ContactType, FriendshipStatusType} from '../types'; +import { + FRIENDS_ENDPOINT, + INVITE_FRIEND_ENDPOINT, + USERS_FROM_CONTACTS_ENDPOINT, +} from '../constants'; +import { + ERROR_SOMETHING_WENT_WRONG, + ERROR_SOMETHING_WENT_WRONG_REFRESH, +} from '../constants/strings'; export const loadFriends = async (userId: string, token: string) => { try { @@ -181,3 +189,58 @@ export const deleteFriendshipService = async ( return false; } }; + +export const usersFromContactsService = async ( + contacts: Array<ContactType>, +) => { + console.log('Contacts: ', contacts); + try { + const token = await AsyncStorage.getItem('token'); + const response = await fetch(USERS_FROM_CONTACTS_ENDPOINT, { + method: 'POST', + headers: { + Authorization: 'Token ' + token, + }, + body: JSON.stringify({ + contacts: contacts, + }), + }); + const status = response.status; + if (Math.floor(status / 100) === 2) { + const users_data = await response.json(); + return users_data; + } else { + console.log( + 'Something went wrong! ðŸ˜', + 'Not able to retrieve tagg users list', + ); + } + } catch (error) { + console.log(error); + Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH); + return false; + } +}; + +export const inviteFriendService = async ( + phoneNumber: string, + inviteeFirstName: string, + inviteeLastName: string, +) => { + const token = await AsyncStorage.getItem('token'); + const response = await fetch(INVITE_FRIEND_ENDPOINT, { + method: 'POST', + headers: { + Authorization: 'Token ' + token, + }, + body: JSON.stringify({ + invitee_phone_number: phoneNumber, + invitee_first_name: inviteeFirstName, + invitee_last_name: inviteeLastName, + }), + }); + if (response.status === 201 || response.status === 200) { + return await response.json(); + } + return false; +}; diff --git a/src/store/actions/userFriends.ts b/src/store/actions/userFriends.ts index 4f55acc8..9da3cb4a 100644 --- a/src/store/actions/userFriends.ts +++ b/src/store/actions/userFriends.ts @@ -1,4 +1,4 @@ -import {getTokenOrLogout} from '../../utils'; +import {getTokenOrLogout, userXInStore} from '../../utils'; import {RootState} from '../rootReducer'; import { FriendshipStatusType, @@ -90,6 +90,7 @@ export const friendUnfriendUser = ( export const addFriend = ( friend: ProfilePreviewType, // userX's profile preview screenType: ScreenType, //screentype from content + state: RootState, ): ThunkAction< Promise<boolean | undefined>, RootState, @@ -100,14 +101,16 @@ export const addFriend = ( const token = await getTokenOrLogout(dispatch); const success = await addFriendService(friend.id, token); if (success) { - dispatch({ - type: userXFriendshipEdited.type, - payload: { - userId: friend.id, - screenType, - data: 'requested', - }, - }); + if (userXInStore(state, screenType, friend.id)) { + dispatch({ + type: userXFriendshipEdited.type, + payload: { + userId: friend.id, + screen: screenType, + data: 'requested', + }, + }); + } return true; } } catch (error) { diff --git a/src/types/types.ts b/src/types/types.ts index e068eeba..dc2817bd 100644 --- a/src/types/types.ts +++ b/src/types/types.ts @@ -256,3 +256,9 @@ export type SearchCategoryType = { name: string; category: string; }; + +export type ContactType = { + phone_number: string; + first_name: string; + last_name: string; +}; diff --git a/src/utils/common.ts b/src/utils/common.ts index c1049c42..0a76ec08 100644 --- a/src/utils/common.ts +++ b/src/utils/common.ts @@ -1,8 +1,9 @@ -import {NotificationType} from './../types/types'; +import {ContactType, NotificationType} from './../types/types'; import moment from 'moment'; import {Linking} from 'react-native'; import {BROWSABLE_SOCIAL_URLS, TOGGLE_BUTTON_TYPE} from '../constants'; import AsyncStorage from '@react-native-community/async-storage'; +import {getAll} from 'react-native-contacts'; export const getToggleButtonText: ( buttonType: string, @@ -115,3 +116,19 @@ export const shuffle = (array: any[]) => { return array; }; + +export const extractContacts = async () => { + let retrievedContacts: Array<ContactType> = []; + await getAll().then((contacts) => { + contacts.map((contact) => { + contact.phoneNumbers.map((phoneNumber) => { + retrievedContacts.push({ + first_name: contact.givenName, + last_name: contact.familyName, + phone_number: phoneNumber.number, + }); + }); + }); + }); + return retrievedContacts; +}; diff --git a/src/utils/friends.ts b/src/utils/friends.ts index 3398c123..55d65170 100644 --- a/src/utils/friends.ts +++ b/src/utils/friends.ts @@ -60,7 +60,7 @@ export const handleAddFriend = async ( dispatch: AppDispatch, state: RootState, ) => { - const success = await dispatch(addFriend(friend, screenType)); + const success = await dispatch(addFriend(friend, screenType, state)); await dispatch(updateUserXFriends(friend.id, state)); await dispatch(updateUserXProfileAllScreens(friend.id, state)); return success; diff --git a/src/utils/users.ts b/src/utils/users.ts index af4f3813..82bcb309 100644 --- a/src/utils/users.ts +++ b/src/utils/users.ts @@ -96,7 +96,7 @@ export const userXInStore = ( userId: string, ) => { const userX = state.userX[screen]; - return userId in userX && userX[userId].user.userId; + return userX && userId in userX && userX[userId].user.userId; }; /** |