image handle in whole project

This commit is contained in:
Jaanu423
2025-09-26 15:30:27 +05:30
parent 8dbacb4ba5
commit 87872f1df1
5 changed files with 367 additions and 195 deletions
+252 -115
View File
@@ -10,6 +10,8 @@ import {
Alert,
ActivityIndicator,
Share,
Image,
ToastAndroid,
} from 'react-native';
import { RootStackParamList } from '../../navigation/AppNavigator'; // Adjust path
import { apiCall } from '../../utils/ApiHelper'; // Adjust path
@@ -20,6 +22,11 @@ import Clipboard from '@react-native-clipboard/clipboard';
import { CompositeScreenProps } from '@react-navigation/native';
import { BottomTabScreenProps } from '@react-navigation/bottom-tabs';
import { ManagementTabParamList } from './ManagementTabNavigation'; // Adjust path
import { UPLOAD_GROUP_IMAGE } from '../../utils/ApiUrls';
import { launchImageLibrary } from 'react-native-image-picker';
import *as Keychain from 'react-native-keychain'
import Ionicons from '@react-native-vector-icons/ionicons';
import { CustomButton } from '../../components/common/Custom';
// --- Type Definitions ---
interface Participant {
@@ -51,6 +58,7 @@ export interface GroupDetails {
organizerId: string;
totalParticipants: number;
participants: Participant[];
imageBlob:string
}
export interface EditGroupPayload {
@@ -92,12 +100,14 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
lateFeeMode: null,
lateFeeValue: null,
});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [starting, setStarting] = useState(false);
const [inviting, setInviting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedImage, setSelectedImage] = useState<string | null>()
const [imageUpdating, setImageUpdating] = useState<boolean>(false)
// ... (All your handler functions: initializeEditableData, fetchGroupDetails, handleCancel, handleSave, etc. remain the same)
const initializeEditableData = (data: GroupDetails) => {
@@ -120,7 +130,7 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
setError(null);
try {
const response = await apiCall(`https://exotic-humpback-mistakenly.ngrok-free.app/api/fund/group/details?groupId=${groupId}`, 'GET') as { status: string; data?: GroupDetails; message?: string };
console.log("groupDetails",response)
console.log("groupDetails", response)
if (response.status === 'success' && response.data) {
setGroupDetails(response.data);
initializeEditableData(response.data);
@@ -140,7 +150,7 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
const handleCancel = () => {
if (groupDetails) {
initializeEditableData(groupDetails);
initializeEditableData(groupDetails);
}
setEditingCard(null);
};
@@ -149,10 +159,10 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
if (!groupDetails) return;
if (editableData.maxParticipants < groupDetails.totalParticipants) {
Alert.alert('Invalid Input', `Max participants cannot be less than the current count (${groupDetails.totalParticipants}).`);
return;
Alert.alert('Invalid Input', `Max participants cannot be less than the current count (${groupDetails.totalParticipants}).`);
return;
}
setSaving(true);
try {
await apiCall(`https://exotic-humpback-mistakenly.ngrok-free.app/api/fund/groups/${groupDetails.id}/edit`, 'PUT', editableData);
@@ -193,30 +203,30 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
]
);
};
const handleInvite = async () => {
if (!groupDetails) return;
setInviting(true);
try {
const response = await apiCall(`https://exotic-humpback-mistakenly.ngrok-free.app/api/invite/generate?groupId=${groupDetails.id}`, 'GET') as { data?: string };
const response = await apiCall(`https://exotic-humpback-mistakenly.ngrok-free.app/api/invite/generate?groupId=${groupDetails.id}`, 'GET') as { data?: string };
const inviteLink = response.data;
if (inviteLink) {
Clipboard.setString(inviteLink);
Alert.alert('Copied!', 'Invitation link copied to clipboard.');
await Share.share({
message: `Join my group on CircleCollect! ${inviteLink}`,
url: inviteLink,
title: 'CircleCollect Group Invitation'
});
} else {
throw new Error('Could not generate invitation link.');
}
const inviteLink = response.data;
if (inviteLink) {
Clipboard.setString(inviteLink);
Alert.alert('Copied!', 'Invitation link copied to clipboard.');
await Share.share({
message: `Join my group on CircleCollect! ${inviteLink}`,
url: inviteLink,
title: 'CircleCollect Group Invitation'
});
} else {
throw new Error('Could not generate invitation link.');
}
} catch (error: any) {
Alert.alert('Error', error.message || 'Failed to generate invitation.');
Alert.alert('Error', error.message || 'Failed to generate invitation.');
} finally {
setInviting(false);
setInviting(false);
}
};
@@ -227,81 +237,81 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
// ... (renderField and renderCard functions also remain the same)
const renderField = (field: keyof EditGroupPayload, label: string, displayValue: string | number, isEditing: boolean) => {
const commonInputProps = { style: styles.input, placeholderTextColor: "#9CA3AF" };
const getInputForField = () => {
switch(field) {
case 'groupName':
return <TextInput {...commonInputProps} value={editableData.groupName} onChangeText={(text) => handleUpdateField('groupName', text)} />;
case 'description':
return <TextInput {...commonInputProps} style={[styles.input, styles.textArea]} value={editableData.description} onChangeText={(text) => handleUpdateField('description', text)} multiline />;
case 'contributionAmount':
return <TextInput {...commonInputProps} value={String(editableData.contributionAmount ?? '')} onChangeText={(text) => handleUpdateField('contributionAmount', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'maxParticipants':
return <TextInput {...commonInputProps} value={String(editableData.maxParticipants ?? '')} onChangeText={(text) => handleUpdateField('maxParticipants', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'latePaymentCharge':
return <TextInput {...commonInputProps} value={String(editableData.latePaymentCharge ?? '')} onChangeText={(text) => handleUpdateField('latePaymentCharge', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'cycleType':
return (
<Picker selectedValue={editableData.cycleType} onValueChange={(itemValue) => handleUpdateField('cycleType', itemValue)} style={styles.picker}>
{['MONTHLY', 'WEEKLY', 'QUARTERLY', 'CUSTOM'].map(c => <Picker.Item key={c} label={c} value={c} />)}
</Picker>
);
case 'customCycleDays':
if (editableData.cycleType !== 'CUSTOM') return null;
return <TextInput {...commonInputProps} value={String(editableData.customCycleDays ?? '')} onChangeText={(text) => handleUpdateField('customCycleDays', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'visibility':
return (
<Picker selectedValue={editableData.visibility} onValueChange={(itemValue) => handleUpdateField('visibility', itemValue)} style={styles.picker}>
<Picker.Item label="PUBLIC" value="PUBLIC" />
<Picker.Item label="PRIVATE" value="PRIVATE" />
</Picker>
);
default:
return null;
}
switch (field) {
case 'groupName':
return <TextInput {...commonInputProps} value={editableData.groupName} onChangeText={(text) => handleUpdateField('groupName', text)} />;
case 'description':
return <TextInput {...commonInputProps} style={[styles.input, styles.textArea]} value={editableData.description} onChangeText={(text) => handleUpdateField('description', text)} multiline />;
case 'contributionAmount':
return <TextInput {...commonInputProps} value={String(editableData.contributionAmount ?? '')} onChangeText={(text) => handleUpdateField('contributionAmount', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'maxParticipants':
return <TextInput {...commonInputProps} value={String(editableData.maxParticipants ?? '')} onChangeText={(text) => handleUpdateField('maxParticipants', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'latePaymentCharge':
return <TextInput {...commonInputProps} value={String(editableData.latePaymentCharge ?? '')} onChangeText={(text) => handleUpdateField('latePaymentCharge', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'cycleType':
return (
<Picker selectedValue={editableData.cycleType} onValueChange={(itemValue) => handleUpdateField('cycleType', itemValue)} style={styles.picker}>
{['MONTHLY', 'WEEKLY', 'QUARTERLY', 'CUSTOM'].map(c => <Picker.Item key={c} label={c} value={c} />)}
</Picker>
);
case 'customCycleDays':
if (editableData.cycleType !== 'CUSTOM') return null;
return <TextInput {...commonInputProps} value={String(editableData.customCycleDays ?? '')} onChangeText={(text) => handleUpdateField('customCycleDays', text ? Number(text.replace(/[^0-9]/g, '')) : 0)} keyboardType="numeric" />;
case 'visibility':
return (
<Picker selectedValue={editableData.visibility} onValueChange={(itemValue) => handleUpdateField('visibility', itemValue)} style={styles.picker}>
<Picker.Item label="PUBLIC" value="PUBLIC" />
<Picker.Item label="PRIVATE" value="PRIVATE" />
</Picker>
);
default:
return null;
}
};
return (
<View style={styles.fieldContainer}>
<Text style={styles.infoLabel}>{label}</Text>
{isEditing && isEditable ? (
<View style={{marginTop: 8}}>{getInputForField()}</View>
) : (
<Text style={styles.infoValue}>{displayValue}</Text>
)}
</View>
<View style={styles.fieldContainer}>
<Text style={styles.infoLabel}>{label}</Text>
{isEditing && isEditable ? (
<View style={{ marginTop: 8 }}>{getInputForField()}</View>
) : (
<Text style={styles.infoValue}>{displayValue}</Text>
)}
</View>
);
}
const renderCard = (title: string, fields: Array<{ field: keyof EditGroupPayload, label: string, displayValue: () => string | number }>, cardKey: EditingCard) => {
const isEditingThisCard = editingCard === cardKey;
return (
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>{title}</Text>
{isEditable && !editingCard && (
<TouchableOpacity onPress={() => setEditingCard(cardKey)} style={styles.editButton}>
<Text style={styles.editButtonText}>✎</Text>
</TouchableOpacity>
)}
</View>
{fields.map(({ field, label, displayValue }) =>
renderField(field, label, displayValue(), isEditingThisCard)
)}
{isEditingThisCard && (
<View style={styles.cardActions}>
<TouchableOpacity style={[styles.button, styles.cancelButton]} onPress={handleCancel} disabled={saving}>
<Text style={[styles.buttonText, { color: '#374151' }]}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.saveButton]} onPress={handleSave} disabled={saving}>
{saving ? <ActivityIndicator color="#FFFFFF" size="small" /> : <Text style={styles.buttonText}>Save</Text>}
</TouchableOpacity>
</View>
)}
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>{title}</Text>
{isEditable && !editingCard && (
<TouchableOpacity onPress={() => setEditingCard(cardKey)} style={styles.editButton}>
<Text style={styles.editButtonText}>✎</Text>
</TouchableOpacity>
)}
</View>
{fields.map(({ field, label, displayValue }) =>
renderField(field, label, displayValue(), isEditingThisCard)
)}
{isEditingThisCard && (
<View style={styles.cardActions}>
<TouchableOpacity style={[styles.button, styles.cancelButton]} onPress={handleCancel} disabled={saving}>
<Text style={[styles.buttonText, { color: '#374151' }]}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, styles.saveButton]} onPress={handleSave} disabled={saving}>
{saving ? <ActivityIndicator color="#FFFFFF" size="small" /> : <Text style={styles.buttonText}>Save</Text>}
</TouchableOpacity>
</View>
)}
</View>
);
}
@@ -313,6 +323,84 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
const isInvitable = groupDetails.status === 'APPROVED';
const canStartGroup = groupDetails.status === 'APPROVED' && groupDetails.totalParticipants >= groupDetails.minParticipants;
const pickImage = () => {
launchImageLibrary({ mediaType: "photo", quality: 0.5 }, (response) => {
if (response.didCancel) return;
if (response.errorCode) {
Alert.alert("Error", response.errorMessage || "Something went wrong");
} else if (response.assets && response.assets.length > 0) {
const selectedImage = response.assets[0];
console.log(selectedImage?.uri)
setSelectedImage(selectedImage?.uri)
}
});
};
const handleUpdateImage = async () => {
try {
const credentials = await Keychain.getGenericPassword();
if (!credentials) {
Alert.alert("Error", "You are not logged in");
return;
}
const token = credentials.password;
if (!selectedImage) {
Alert.alert("Error", "Please select an image first");
return;
}
setImageUpdating(true);
// Get file extension and mime type dynamically
const fileExtension = selectedImage.split('.').pop();
const formData = new FormData();
formData.append("file", {
uri: selectedImage,
type: "image/jpeg",
name: `group_${groupId}_profile.${fileExtension || "jpg"}`,
});
const url = `${UPLOAD_GROUP_IMAGE}${groupId}/upload-image`;
console.log("url : ", url)
console.log("formdata : ", formData)
// return
const response = await fetch(url, {
method: "PUT",
headers: {
"Content-Type": "multipart/form-data",
"Authorization": `Bearer ${token}`,
},
body: formData,
});
console.log("image response : ", response)
if(response?.status === 200){
fetchGroupDetails()
ToastAndroid.show('Group uploaded successfully', ToastAndroid.SHORT)
}
} catch (error:any) {
console.error("❌ Error updating group image:", error);
Alert.alert("Error", error.message || "Could not update group image");
} finally {
setImageUpdating(false);
}
};
const getProfileImage = () => {
return selectedImage
? selectedImage
: groupDetails?.imageBlob
? `data:image/jpeg;base64,${groupDetails.imageBlob}`
: "https://img.freepik.com/premium-vector/people-group-frame-icon_791764-2649.jpg";
};
// Helper function to get MIME type
return (
// Use AppView as the root container with flex: 1
<AppView style={{ flex: 1, paddingHorizontal: 0 }}>
@@ -330,42 +418,64 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
contentContainerStyle={styles.contentContainer}
showsVerticalScrollIndicator={false}
>
<View style={[styles.avatarContainer, { flexDirection: 'row', flex: 1, gap: 10 }]}>
<View style={{}}>
<Image
// source={{ uri: groupDetails?.imageBlob ? groupDetails?.imageBlob : selectedImage || "https://img.freepik.com/premium-vector/people-group-frame-icon_791764-2649.jpg" }}
source={{ uri: getProfileImage() }}
style={styles.avatar}
onError={() => console.log("Error loading image")}
/>
<TouchableOpacity style={styles.cameraIcon} onPress={pickImage}>
<Ionicons name="camera" size={18} color="#000" />
</TouchableOpacity>
</View>
<View style={{justifyContent:'center'}}>
<CustomButton
title={imageUpdating ? "Updating..." : "Update Image"}
onPress={handleUpdateImage}
icon={imageUpdating ? undefined : "cloud-upload"}
style={{paddingHorizontal:20}}
buttonBackground={colors.pastelBlue}
/>
</View>
</View>
{renderCard('Group Info', [
{ field: 'groupName', label: 'Group Name', displayValue: () => groupDetails.groupName },
{ field: 'description', label: 'Description', displayValue: () => groupDetails.description },
{ field: 'groupName', label: 'Group Name', displayValue: () => groupDetails.groupName },
{ field: 'description', label: 'Description', displayValue: () => groupDetails.description },
], 'groupInfo')}
{renderCard('Financial Rules', [
{ field: 'contributionAmount', label: 'Contribution', displayValue: () => `₹${groupDetails.contributionAmount.toLocaleString('en-IN')}` },
{ field: 'maxParticipants', label: 'Max Participants', displayValue: () => `${groupDetails.totalParticipants} / ${groupDetails.maxParticipants}` },
{ field: 'minParticipants', label: 'Min Participants', displayValue: () => `${groupDetails.minParticipants}` },
{ field: 'latePaymentCharge', label: 'Late Fee', displayValue: () => `₹${(groupDetails.latePaymentCharge ?? 0).toLocaleString('en-IN')}` },
{ field: 'contributionAmount', label: 'Contribution', displayValue: () => `₹${groupDetails.contributionAmount.toLocaleString('en-IN')}` },
{ field: 'maxParticipants', label: 'Max Participants', displayValue: () => `${groupDetails.totalParticipants} / ${groupDetails.maxParticipants}` },
{ field: 'minParticipants', label: 'Min Participants', displayValue: () => `${groupDetails.minParticipants}` },
{ field: 'latePaymentCharge', label: 'Late Fee', displayValue: () => `₹${(groupDetails.latePaymentCharge ?? 0).toLocaleString('en-IN')}` },
], 'financialRules')}
{renderCard('Configuration', [
{ field: 'cycleType', label: 'Payment Cycle', displayValue: () => groupDetails.cycleType },
{ field: 'customCycleDays', label: 'Custom Days', displayValue: () => `${groupDetails.customCycleDays ?? ''} days` },
{ field: 'visibility', label: 'Visibility', displayValue: () => groupDetails.visibility },
{ field: 'cycleType', label: 'Payment Cycle', displayValue: () => groupDetails.cycleType },
{ field: 'customCycleDays', label: 'Custom Days', displayValue: () => `${groupDetails.customCycleDays ?? ''} days` },
{ field: 'visibility', label: 'Visibility', displayValue: () => groupDetails.visibility },
], 'configuration')}
{/* Participants Card ... */}
<View style={styles.card}>
<Text style={styles.cardTitle}>Participants ({groupDetails.totalParticipants})</Text>
{groupDetails.participants.length > 0 ? (
groupDetails.participants.map(p => (
<View key={p.id} style={styles.participantRow}>
<View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.participantName}>{`${p.firstName} ${p.lastName || ''}`.trim()}</Text>
{p.role === 'ORGANIZER' && <View style={styles.organizerBadge}><Text style={styles.organizerBadgeText}>Organizer</Text></View>}
</View>
<Text style={styles.participantMobile}>{p.mobile}</Text>
</View>
</View>
))
) : (
<Text style={styles.noParticipantsText}>No participants yet.</Text>
)}
<Text style={styles.cardTitle}>Participants ({groupDetails.totalParticipants})</Text>
{groupDetails.participants.length > 0 ? (
groupDetails.participants.map(p => (
<View key={p.id} style={styles.participantRow}>
<View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.participantName}>{`${p.firstName} ${p.lastName || ''}`.trim()}</Text>
{p.role === 'ORGANIZER' && <View style={styles.organizerBadge}><Text style={styles.organizerBadgeText}>Organizer</Text></View>}
</View>
<Text style={styles.participantMobile}>{p.mobile}</Text>
</View>
</View>
))
) : (
<Text style={styles.noParticipantsText}>No participants yet.</Text>
)}
</View>
</ScrollView>
@@ -394,7 +504,7 @@ const EditGroupScreen: React.FC<EditGroupScreenProps> = ({ route }) => {
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#F3F4F6' },
// Added more paddingBottom to ensure content doesn't hide behind the button AND the tab bar
contentContainer: { padding: 16, paddingTop: 0, paddingBottom: 150 },
contentContainer: { padding: 16, paddingTop: 0, paddingBottom: 150 },
centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
errorText: { color: '#EF4444', fontSize: 16, textAlign: 'center' },
headerContainer: {
@@ -407,6 +517,33 @@ const styles = StyleSheet.create({
borderBottomWidth: 1,
borderBottomColor: '#E5E7EB',
},
avatarContainer: {
position: "relative",
marginVertical: 16,
},
avatar: {
width: 120,
height: 120,
borderRadius: 60,
borderWidth: 4,
borderColor: "#e2e8f0",
},
cameraIcon: {
position: "absolute",
// right: 0,
bottom: 0,
backgroundColor: colors.pastelBlue,
borderRadius: 20,
width: 40,
height: 40,
justifyContent: "center",
alignItems: "center",
borderWidth: 3,
borderColor: "#fff",
elevation: 2,
},
headerTitle: { fontSize: 28, fontWeight: 'bold', color: '#111827' },
card: { backgroundColor: '#FFFFFF', borderRadius: 16, padding: 20, marginBottom: 16, shadowColor: '#374151', shadowOpacity: 0.05, shadowRadius: 10 },
cardHeader: {