api integration for joined user

This commit is contained in:
Jaanu423
2025-09-22 18:50:06 +05:30
parent ff8c0439f6
commit bcd41f81e6
12 changed files with 213 additions and 113 deletions
+15 -16
View File
@@ -1,18 +1,24 @@
import React from "react";
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import { useNavigation } from "@react-navigation/native";
import { Ionicons } from "@react-native-vector-icons/ionicons"
import {Ionicons} from "@react-native-vector-icons/ionicons";
type HeaderProps = {
title: string;
showBack?: boolean; // optional, default true
onBackPress?: () => void; // optional custom back action
rightAction?: React.ReactNode; // allow passing JSX for right side
titleColor?:string;
arrowColor?:string
};
const Header: React.FC<HeaderProps> = ({
title,
showBack = true,
onBackPress,
rightAction,
titleColor = 'pink',
arrowColor='pink'
}) => {
const navigation = useNavigation();
@@ -26,12 +32,15 @@ const Header: React.FC<HeaderProps> = ({
return (
<View style={styles.header}>
{showBack && (
<TouchableOpacity onPress={handleBack} style={styles.backButton}>
<Ionicons name="arrow-back" size={24} color="#000" />
{showBack ? (
<TouchableOpacity onPress={handleBack}>
<Ionicons name="arrow-back" size={24} color={arrowColor} />
</TouchableOpacity>
) : (
<View style={{ width: 24 }} /> // placeholder to keep spacing
)}
<Text style={styles.headerTitle}>{title}</Text>
<Text style={[styles.headerTitle, {color:titleColor}]}>{title}</Text>
<View>{rightAction}</View>
</View>
);
};
@@ -42,21 +51,11 @@ const styles = StyleSheet.create({
header: {
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 16,
justifyContent: "space-between",
paddingVertical: 12,
backgroundColor: "#fff",
shadowColor: "#000",
shadowOpacity: 0.05,
shadowOffset: { width: 0, height: 2 },
shadowRadius: 6,
elevation: 3,
},
backButton: {
marginRight: 12,
},
headerTitle: {
fontSize: 18,
fontWeight: "600",
color: "#000",
},
});
+30 -5
View File
@@ -21,12 +21,12 @@ import { StackNavigationProp } from "@react-navigation/stack";
import { RootStackParamList } from "../navigation/AppNavigator";
import AppView from "../components/AppView";
import { apiCall } from "../utils/ApiHelper";
import { BASE_URL, JOIN_GROUP_URL, PUT_USER_STATUS } from "../utils/ApiUrls";
import { BASE_URL, GET_JOINED_GROUP_URL, JOIN_GROUP_URL, PUBLIC_GROUPS_URL, PUT_USER_STATUS } from "../utils/ApiUrls";
import colors from "../components/colors";
import { ApiResponse } from "./home/UserProfileStatus";
import * as Keychain from "react-native-keychain";
const { width } = Dimensions.get('window');
const PUBLIC_GROUPS_URL = "https://api.godemo.in/FundCollect/api/fund/user/public";
// --- Types ---
@@ -114,7 +114,31 @@ export default function GroupScreen() {
}
};
useFocusEffect(React.useCallback(() => { fetchGroups(); }, []));
const fetchJoinedGroups = async () => {
if (loading) return;
setLoading(true);
setError(null);
try {
console.log("first-????-")
const res = await apiCall(GET_JOINED_GROUP_URL, "GET") as { data?: Group[] };
console.log("first---", res)
if (res && res.data) {
setJoinedGroups(res.data);
} else {
throw new Error("No data received");
}
} catch (e) {
setError("Failed to fetch groups. Please try again.");
} finally {
setLoading(false);
}
};
useFocusEffect(React.useCallback(() => {
fetchGroups()
fetchJoinedGroups()
}, []));
const filterData = (data: Group[]) => {
if (!searchQuery.trim()) return data;
@@ -142,6 +166,7 @@ export default function GroupScreen() {
Alert.alert("Error", "An unexpected error occurred.");
}
};
const userStatus = async () => {
try {
const credentials = await Keychain.getGenericPassword();
@@ -239,7 +264,7 @@ export default function GroupScreen() {
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}
ListFooterComponent={<ActivityIndicator size={'large'} color={colors.Group}/>}
ListFooterComponent={<ActivityIndicator size={'large'} color={colors.Group} />}
/>
);
};
@@ -265,7 +290,7 @@ export default function GroupScreen() {
keyExtractor={(item) => item.id}
renderItem={({ item }) => <FeaturedGroupCard item={item} />}
style={styles.featuredList}
ListEmptyComponent={!loading && featuredGroups.length === 0 ? <Text style={styles.emptyFeaturedText}>No featured groups.</Text> : null}
// ListEmptyComponent={!loading && featuredGroups.length === 0 ? <Text style={styles.emptyFeaturedText}>No featured groups.</Text> : null}
/>
<View style={styles.tabHeader}>
+1 -22
View File
@@ -19,7 +19,6 @@ import type { StackNavigationProp } from "@react-navigation/stack";
import { RootStackParamList } from "../navigation/AppNavigator";
import { CustomButton, CustomInput } from "../components/common/Custom";
import colors from "../components/colors";
import { useSelector } from "react-redux";
const theme = {
primary: "#111111",
@@ -42,8 +41,7 @@ export default function LoginScreen() {
const fade = useRef(new Animated.Value(0)).current;
const slide = useRef(new Animated.Value(24)).current;
const ctaScale = useRef(new Animated.Value(1)).current;
const user = useSelector((state: any) => state.user)
console.log("current user ----", user)
useEffect(() => {
Animated.parallel([
Animated.timing(fade, { toValue: 1, duration: 600, useNativeDriver: true }),
@@ -55,8 +53,6 @@ export default function LoginScreen() {
if (mobile.length === 10) {
setLoading(true);
try {
console.log("LOGIN_URL console:", LOGIN_URL, "mobile:", mobile);
const res = await axios.get(LOGIN_URL, {
params: { mobile },
});
@@ -89,23 +85,6 @@ export default function LoginScreen() {
}
};
const onPressIn = () =>
Animated.spring(ctaScale, {
toValue: 0.97,
useNativeDriver: true,
speed: 20,
bounciness: 0,
}).start();
const onPressOut = () =>
Animated.spring(ctaScale, {
toValue: 1,
useNativeDriver: true,
speed: 20,
bounciness: 6,
}).start();
return (
<KeyboardAvoidingView
style={styles.container}
+2 -5
View File
@@ -19,10 +19,7 @@ import {
import { RootStackParamList } from "../navigation/AppNavigator";
import * as Keychain from "react-native-keychain";
import { BASE_URL, LOGIN_URL, VARIFY_OTP_URL } from "../utils/ApiUrls";
import { StackNavigationProp } from "@react-navigation/stack";
import colors from "../components/colors";
import { useDispatch } from "react-redux";
import { setUserData } from "../redux/userSlice";
import { fetchUserProfile } from "../utils/HelperFunction";
const theme = {
@@ -44,7 +41,7 @@ export default function OtpVerificationScreen() {
const inputs = useRef<Array<TextInput | null>>([]);
const route = useRoute<OtpVerifyRouteProp>();
const { mobile } = route.params;
const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();
const navigation = useNavigation<any>();
// animations
const fade = useRef(new Animated.Value(0)).current;
const slide = useRef(new Animated.Value(24)).current;
@@ -92,7 +89,7 @@ export default function OtpVerificationScreen() {
if (res.data.statusCode === 200) {
saveToken(res.data.data);
fetchUserProfile()
navigation.navigate('Home')
navigation.navigate("Home", { refreshProfile: true });
ToastAndroid.show("OTP Verified Successfully!", ToastAndroid.SHORT);
}
} catch (err: any) {
+3 -1
View File
@@ -13,6 +13,8 @@ const SplashScreen = () => {
const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();
const fadeAnim = useRef(new Animated.Value(1)).current;
const dispatch = useDispatch();
const fetchUserProfile = async (dispatch: any, navigation: any) => {
try {
@@ -100,7 +102,7 @@ const SplashScreen = () => {
};
startSplash();
}, [navigation, fadeAnim, dispatch]);
}, [navigation, fadeAnim, dispatch, ]);
return (
<View style={styles.container}>
+58 -8
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useCallback, useEffect, useState } from "react";
import {
StyleSheet,
Text,
@@ -13,27 +13,77 @@ import UserProfileStatus from "./UserProfileStatus";
import colors from "../../components/colors";
import GroupsTabs from "./GroupsTabs";
import { useSelector } from "react-redux";
import { useNavigation } from "@react-navigation/native";
import { useFocusEffect, useNavigation, useRoute } from "@react-navigation/native";
import UserHome from "./user-home/UserHome";
import { PROFILE_URL } from "../../utils/ApiUrls";
import *as Keychain from "react-native-keychain"
// Enable animation for Android
if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
type UserProfile = {
id: string;
userId: number;
firstName: string | null;
lastName: string | null;
imageBlob: string | null;
role?: string;
}
const Home = () => {
const user = useSelector((state: any) => state.user);
const navigation = useNavigation();
console.log("redux user data in Home:", user);
const route = useRoute();
console.log("route asf : ", route?.params)
const [apiUser, setApiUser] = useState<UserProfile | null | any>(null)
const fetchUserProfile = async () => {
try {
const credentials = await Keychain.getGenericPassword();
if (!credentials) {
return;
}
const token = credentials.password;
const response = await fetch(
PROFILE_URL,
{
method: "GET",
headers: {
Accept: "*/*",
Authorization: `Bearer ${token}`,
},
}
);
const result = await response.json();
console.log("👤 Profile Response:", result);
if (result.status === "success") {
setApiUser(result.data);
}
} catch (error) {
console.error("❌ Error fetching profile:", error);
}
};
useEffect(() => {
if (route.params) {
fetchUserProfile();
}
}, [route.params]);
return (
<AppView barStyle="dark-content" style={styles.container}>
{/* Header */}
<View style={styles.header}>
<Text style={styles.greeting}>Hello, {user.firstName} {user.lastName}👋</Text>
<Text style={styles.greeting}>Hello, {user.firstName || apiUser?.firstName} {user.lastName || apiUser?.lastName}👋</Text>
<TouchableOpacity onPress={() => navigation.navigate("Profile" as never)}>
<Image
source={
user.imageBlob
&& { uri: user.imageBlob ? `data:image/jpeg;base64,${user.imageBlob}` : user.profilePicture }
&& { uri: user.imageBlob || apiUser?.imageBlob ? `data:image/jpeg;base64,${user.imageBlob || apiUser?.imageBlob}` : user.profilePicture || apiUser?.imageBlob }
}
style={{ width: 40, height: 40, borderRadius: 20, borderColor: colors.primary, borderWidth: 2 }}
/>
@@ -41,8 +91,8 @@ const Home = () => {
</View>
{/* Status */}
<UserProfileStatus />
{user?.role === "USER" ? <UserHome /> :
<GroupsTabs />}
{user?.role === "USER" || apiUser?.role === "USER" ? <UserHome /> :
<GroupsTabs />}
</AppView>
);
};
+14 -6
View File
@@ -13,6 +13,7 @@ import {
import { Ionicons } from '@react-native-vector-icons/ionicons';
import colors from '../../components/colors';
import DeclineModal from './DeclineModal';
import * as keychain from 'react-native-keychain'
// Define TypeScript interfaces
interface GroupRequest {
@@ -40,11 +41,18 @@ const RequestList: React.FC = () => {
const [error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState<string>('');
const [processingRequest, setProcessingRequest] = useState<string | null>(null);
const [showDeclineModal, setShowDeclineModal] = useState<{modal: boolean, requestId: string | null}>({modal: false, requestId: null});
const [showDeclineModal, setShowDeclineModal] = useState<{ modal: boolean, requestId: string | null }>({ modal: false, requestId: null });
const [selectedRequestId, setSelectedRequestId] = useState<string | null>(null);
// Fetch data from API
const fetchRequests = async (): Promise<void> => {
const credentials = await keychain.getGenericPassword();
if (!credentials) {
Alert.alert("Error", "You are not logged in");
return;
}
const token = credentials.password;
try {
setRefreshing(true);
setError(null);
@@ -55,7 +63,7 @@ const RequestList: React.FC = () => {
method: "GET",
headers: {
accept: "*/*",
Authorization: "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2MjY1MjI5MzcxIiwidXNlcklkIjoiMTAwMDAxIiwiaWF0IjoxNzU4MDkxMjEzLCJleHAiOjE3NTgxNzc2MTN9.T3BvU7nl8fnjwwVobIWRmSFFxQzOjtyIct1Ba0i9lIU"
Authorization: `Bearer ${token}`
}
}
);
@@ -156,7 +164,7 @@ const RequestList: React.FC = () => {
};
const handleDeclineConfirm = async (requestedId: string | null, reason: string) => {
setShowDeclineModal({modal: false, requestId: null});
setShowDeclineModal({ modal: false, requestId: null });
try {
setProcessingRequest(requestedId);
@@ -197,7 +205,7 @@ const RequestList: React.FC = () => {
}// call your API
};
const onRefresh = (): void => {
fetchRequests();
@@ -332,7 +340,7 @@ const RequestList: React.FC = () => {
<View style={styles.actions}>
<TouchableOpacity
style={[styles.button, styles.declineButton]}
onPress={() => setShowDeclineModal({modal:true, requestId: request.requestId})}
onPress={() => setShowDeclineModal({ modal: true, requestId: request.requestId })}
disabled={processingRequest === request.requestId}
>
{processingRequest === request.requestId ? (
@@ -361,7 +369,7 @@ const RequestList: React.FC = () => {
{showDeclineModal.modal && (
<DeclineModal
visible={showDeclineModal.modal}
onClose={() => setShowDeclineModal({modal: false, requestId: null})}
onClose={() => setShowDeclineModal({ modal: false, requestId: null })}
onSubmit={(reason) => handleDeclineConfirm(showDeclineModal.requestId, reason)}
/>
)}
+1 -1
View File
@@ -10,7 +10,7 @@ import {
} from "react-native";
import * as Keychain from "react-native-keychain";
import { useFocusEffect, useNavigation } from "@react-navigation/native";
import { BASE_URL, PUT_USER_STATUS } from "../../utils/ApiUrls";
import { PUT_USER_STATUS } from "../../utils/ApiUrls";
import colors from "../../components/colors";
export type ApiResponse = {
+3 -1
View File
@@ -11,6 +11,7 @@ import { useRoute } from "@react-navigation/native";
import AppView from "../../../components/AppView";
import colors from "../../../components/colors";
import Ionicons from "@react-native-vector-icons/ionicons";
import Header from "../../../components/common/Header";
const GroupDetails = () => {
const route = useRoute();
@@ -88,7 +89,8 @@ const GroupDetails = () => {
return (
<AppView>
{/* Group Title */}
<Text style={styles.groupName}>{group.name}</Text>
<Header title={group.name}/>
{/* <Text style={styles.groupName}>{group.name}</Text> */}
<Text style={styles.description}>{group.description}</Text>
{/* Progress Bar */}
+85 -44
View File
@@ -1,65 +1,108 @@
import React from "react";
import React, { useEffect, useState } from "react";
import {
StyleSheet,
Text,
View,
FlatList,
TouchableOpacity,
Alert,
} from "react-native";
import { useNavigation } from "@react-navigation/native";
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
import type { RootStackParamList } from "../../../navigation/AppNavigator"; // adjust path
import type { RootStackParamList } from "../../../navigation/AppNavigator";
import colors from "../../../components/colors";
import Ionicons from "@react-native-vector-icons/ionicons";
import { Ionicons } from "@react-native-vector-icons/ionicons";
import { GET_JOINED_GROUP_URL } from "../../../utils/ApiUrls";
import * as Keychain from "react-native-keychain";
type NavigationProp = NativeStackNavigationProp<RootStackParamList, "GroupDetails">;
type NavigationProp = NativeStackNavigationProp<
RootStackParamList,
"GroupDetails"
>;
type Group = {
id: string;
name: string;
members: number;
collected: number;
goal: number;
groupName: string;
description: string;
currentParticipants: number;
maxParticipants: number;
contributionAmount: number;
status: string;
};
const groups: Group[] = [
{ id: "1", name: "Wedding Fund", members: 25, collected: 12000, goal: 20000 },
{ id: "2", name: "Birthday Gift", members: 10, collected: 4500, goal: 6000 },
{ id: "3", name: "Community Event", members: 50, collected: 22000, goal: 30000 },
];
const UserHome = () => {
const navigation = useNavigation<NavigationProp>();
const [groups, setGroups] = useState<Group[]>([]);
const [loading, setLoading] = useState<boolean>(false)
const totalGroups = groups.length;
const totalCollected = groups.reduce((sum, g) => sum + g.collected, 0);
const totalContribution = groups.reduce(
(sum, g) => sum + g.contributionAmount,
0
);
const handleGroup = async () => {
try {
setLoading(true)
const credentials = await Keychain.getGenericPassword();
if (!credentials) {
Alert.alert("Error", "You are not logged in");
return;
}
const token = credentials.password;
const response = await fetch(GET_JOINED_GROUP_URL, {
method: "GET",
headers: {
Accept: "*/*",
Authorization: `Bearer ${token}`,
},
});
const result = await response.json();
if (result.status === "success") {
console.log("GET_JOINED_GROUP_URL res : ", result);
setGroups(result.data); // save API data
setLoading(false)
} else {
Alert.alert("Error", "Failed to fetch groups");
}
} catch (error) {
console.error("❌ Error fetching groups:", error);
Alert.alert("Error", "Could not connect to server");
}finally{
setLoading(false)
}
};
useEffect(() => {
handleGroup();
}, []);
const renderItem = ({ item }: { item: Group }) => {
const progress = Math.min(item.collected / item.goal, 1) * 100;
return (
<TouchableOpacity
style={styles.card}
onPress={() => navigation.navigate("GroupDetails", { groupId: item.id })}
>
<Text style={styles.groupName}>{item.name}</Text>
<Text style={styles.groupName}>{item.groupName}</Text>
<Text style={styles.description}>{item.description}</Text>
<View style={styles.statsRow}>
<Ionicons
name="person-circle-outline"
size={20}
color={colors.primary}
/>
<Text style={styles.detail}> {item.members} members</Text>
</View>
{/* Progress Bar */}
<View style={styles.progressBar}>
<View style={[styles.progressFill, { width: `${progress}%` }]} />
<Text style={styles.detail}>
{item.currentParticipants}/{item.maxParticipants} members
</Text>
</View>
<Text style={styles.amount}>
₹{item.collected} / ₹{item.goal}
Contribution: ₹{item.contributionAmount}
</Text>
<Text style={styles.status}>Status: {item.status}</Text>
</TouchableOpacity>
);
};
@@ -67,14 +110,14 @@ const UserHome = () => {
return (
<View>
{/* Stats */}
<View style={[styles.statsRow, { marginVertical: 24, }]}>
<View style={[styles.statsRow, { marginVertical: 24 }]}>
<View style={styles.statBox}>
<Text style={styles.statValue}>{totalGroups}</Text>
<Text style={styles.statLabel}>Groups Joined</Text>
</View>
<View style={styles.statBox}>
<Text style={styles.statValue}>₹{totalCollected}</Text>
<Text style={styles.statLabel}>Total Contributed</Text>
<Text style={styles.statValue}>₹{totalContribution}</Text>
<Text style={styles.statLabel}>Total Contribution</Text>
</View>
</View>
@@ -93,16 +136,13 @@ const UserHome = () => {
export default UserHome;
const styles = StyleSheet.create({
statsRow: {
flexDirection: "row",
gap: 10
gap: 10,
},
statBox: {
flex: 1,
backgroundColor: "#fff",
// marginHorizontal: 6,
padding: 16,
borderRadius: 12,
alignItems: "center",
@@ -143,26 +183,27 @@ const styles = StyleSheet.create({
fontSize: 16,
fontWeight: "600",
color: colors.Home,
marginBottom: 6,
marginBottom: 4,
},
description: {
fontSize: 13,
color: "#475569",
marginBottom: 8,
},
detail: {
fontSize: 13,
color: "#475569",
marginBottom: 8,
},
progressBar: {
height: 6,
borderRadius: 3,
backgroundColor: "#e2e8f0",
marginBottom: 6,
overflow: "hidden",
},
progressFill: {
backgroundColor: colors.primary,
height: "100%",
},
amount: {
fontSize: 13,
color: "#64748b",
marginTop: 4,
},
status: {
fontSize: 12,
fontWeight: "500",
color: colors.primary,
marginTop: 2,
},
});
-3
View File
@@ -299,9 +299,6 @@ const Profile = () => {
);
};
console.log("statusData?.role :", statusData?.role);
console.log("statusData?.organizerStatus :", statusData?.organizerStatus);
useFocusEffect(
useCallback(() => {
userStatus();
+1 -1
View File
@@ -14,4 +14,4 @@ export const DECLINE_REQUEST_URL = `${BASE_URL}fund/user/my/groups`
export const GET_JOINED_GROUP_URL = `${BASE_URL}fund/my/join/groups`
export const PUT_USER_PROFILE_IMG = `${BASE_URL}user/update/userImg`
export const PUT_USER_PROFILE = `${BASE_URL}user/profile/update`
export const PUT_USER_STATUS = `${BASE_URL}user/profile/status`
export const PUT_USER_STATUS = `${BASE_URL}user/profile/status`