errors are there

This commit is contained in:
Abin Toppo
2025-09-19 15:59:31 +05:30
parent 34ab2f0db7
commit 82b121b993
4 changed files with 248 additions and 210 deletions
+2
View File
@@ -14,12 +14,14 @@ import colors from "../colors";
type CustomInputProps = TextInputProps & { type CustomInputProps = TextInputProps & {
label?: string; label?: string;
icon?: IoniconsIconName; icon?: IoniconsIconName;
error:string
}; };
const CustomInput: React.FC<CustomInputProps> = ({ const CustomInput: React.FC<CustomInputProps> = ({
label, label,
icon, icon,
style, style,
error,
...rest ...rest
}) => { }) => {
return ( return (
+150 -135
View File
@@ -7,97 +7,68 @@ import {
KeyboardAvoidingView, KeyboardAvoidingView,
Platform, Platform,
TouchableOpacity, TouchableOpacity,
Modal,
Alert, Alert,
} from "react-native"; } from "react-native";
import Slider from "@react-native-community/slider";
import { useNavigation } from "@react-navigation/native"; import { useNavigation } from "@react-navigation/native";
import { CustomInput } from "../components/common/Custom"; import { CustomInput } from "../components/common/Custom";
import CustomButton from "../components/CustomButton"; import CustomButton from "../components/CustomButton";
import { Calendar } from "react-native-calendars";
import { Ionicons } from "@react-native-vector-icons/ionicons";
import colors from "../components/colors"; import colors from "../components/colors";
const calendarTheme = {
backgroundColor: '#ffffff',
calendarBackground: '#ffffff',
textSectionTitleColor: '#62b59a',
selectedDayTextColor: '#333',
todayTextColor: '#62b59a',
dayTextColor: '#333',
textDisabledColor: '#d9e1e8',
arrowColor: '#62b59a',
monthTextColor: '#333',
textDayFontWeight: '500',
textMonthFontWeight: 'bold',
textDayHeaderFontWeight: '600',
textDayFontSize: 16,
textMonthFontSize: 18,
textDayHeaderFontSize: 14,
};
export default function GroupCreationForm() { export default function GroupCreationForm() {
const navigation = useNavigation<any>(); const navigation = useNavigation<any>();
const [form, setForm] = useState({ const [form, setForm] = useState({
contributionAmount: "4000",
customCycleDays: "",
cycleType: "MONTHLY",
description: "",
groupName: "", groupName: "",
maxParticipants: "", description: "",
minParticipants: "",
startDate: "",
visibility: "PRIVATE", visibility: "PRIVATE",
withdrawalMethod: "SEQUENTIAL", withdrawalMethod: "RANDOM",
minParticipants: "",
maxParticipants: "",
contributionAmount: "",
cycleType: "MONTHLY",
customCycleDays: "",
lateFeeMode: "DAILY",
lateFeeValue: "",
}); });
const [errors, setErrors] = useState<any>({}); // State for validation errors const [errors, setErrors] = useState<any>({});
const [isCalendarVisible, setCalendarVisible] = useState(false);
const handleChange = (key: string, value: string) => { const handleChange = (key: string, value: string) => {
setForm({ ...form, [key]: value }); setForm({ ...form, [key]: value });
// Clear error for the field when user starts typing
if (errors[key]) { if (errors[key]) {
setErrors({ ...errors, [key]: null }); setErrors({ ...errors, [key]: null });
} }
}; };
const handleAmountChange = (value: number) => {
setForm({ ...form, contributionAmount: Math.round(value).toString() });
};
const handleDayPress = (day: any) => {
setForm({ ...form, startDate: day.dateString });
setCalendarVisible(false);
setErrors({ ...errors, startDate: null });
};
const presetAmounts = [2000, 4000, 8000];
const cycleTypes = ["CUSTOM", "MONTHLY", "QUARTERLY", "YEARLY"]; const cycleTypes = ["CUSTOM", "MONTHLY", "QUARTERLY", "YEARLY"];
const distributionTypes = ["SEQUENTIAL", "RANDOM"]; const distributionTypes = ["SEQUENTIAL", "RANDOM"];
const lateFeeModes = ["DAILY", "FIXED"];
const handlePresetAmount = (amount: number) => {
setForm({ ...form, contributionAmount: amount.toString() });
};
const validateForm = () => { const validateForm = () => {
const newErrors: any = {}; const newErrors: any = {};
if (!form.groupName.trim()) newErrors.groupName = "Group name is required."; if (!form.groupName.trim()) newErrors.groupName = "Group name is required.";
if (!form.description.trim()) newErrors.description = "Description is required."; if (!form.description.trim()) newErrors.description = "Description is required.";
if (!form.minParticipants || Number(form.minParticipants) <= 0) newErrors.minParticipants = "Min participants must be greater than 0."; if (!form.minParticipants || Number(form.minParticipants) <= 1) newErrors.minParticipants = "Min participants must be at least 2.";
if (!form.maxParticipants || Number(form.maxParticipants) < Number(form.minParticipants)) newErrors.maxParticipants = "Max must be greater than or equal to min."; if (!form.maxParticipants || Number(form.maxParticipants) < Number(form.minParticipants)) newErrors.maxParticipants = "Max must be greater than or equal to min.";
if (!form.contributionAmount || Number(form.contributionAmount) <= 0) newErrors.contributionAmount = "Amount must be greater than 0."; if (!form.contributionAmount || Number(form.contributionAmount) <= 0) newErrors.contributionAmount = "Amount must be greater than 0.";
if (form.cycleType === "CUSTOM" && (!form.customCycleDays || Number(form.customCycleDays) <= 0)) newErrors.customCycleDays = "Custom days must be greater than 0."; if (form.cycleType === "CUSTOM" && (!form.customCycleDays || Number(form.customCycleDays) <= 0)) newErrors.customCycleDays = "Custom days must be greater than 0.";
if (!form.startDate) newErrors.startDate = "Start date is required."; if (form.lateFeeMode && (!form.lateFeeValue || Number(form.lateFeeValue) <= 0)) newErrors.lateFeeValue = "Late fee value is required.";
setErrors(newErrors); setErrors(newErrors);
return Object.keys(newErrors).length === 0; return Object.keys(newErrors).length === 0;
}; };
const handleReview = () => { const handleReview = () => {
if (validateForm()) { if (validateForm()) {
console.log("------",form) const payload = {
navigation.navigate("GroupReview", { form }); ...form,
contributionAmount: Number(form.contributionAmount),
customCycleDays: Number(form.customCycleDays) || 0,
lateFeeValue: Number(form.lateFeeValue) || 0,
maxParticipants: Number(form.maxParticipants),
minParticipants: Number(form.minParticipants),
};
console.log("Reviewing Payload:", payload);
navigation.navigate("GroupReview", { form: payload });
} else { } else {
Alert.alert("Incomplete Form", "Please fill out all required fields correctly."); Alert.alert("Incomplete Form", "Please fill out all required fields correctly.");
} }
@@ -106,101 +77,145 @@ export default function GroupCreationForm() {
return ( return (
<KeyboardAvoidingView <KeyboardAvoidingView
style={{ flex: 1, backgroundColor: "#f5f6fa", paddingTop: Platform.OS === "android" ? 40 : 0 }} style={{ flex: 1, backgroundColor: "#f5f6fa", paddingTop: Platform.OS === "android" ? 40 : 0 }}
behavior={Platform.OS === "ios" ? "padding" : undefined} behavior={Platform.OS === "ios" ? "padding" : "height"}
> >
<ScrollView contentContainerStyle={styles.container} showsVerticalScrollIndicator={false}> <ScrollView contentContainerStyle={styles.container} showsVerticalScrollIndicator={false}>
<View style={styles.titleContainer}><Text style={styles.title}>Group Creation</Text></View> <View style={styles.titleContainer}><Text style={styles.title}>Create New Group</Text></View>
<CustomInput label="Group Name" placeholder="Enter your group name" value={form.groupName} onChangeText={(val) => handleChange("groupName", val)} icon="people" /> <CustomInput label="Group Name" placeholder="e.g., 'Family Savings'" value={form.groupName} onChangeText={(val) => handleChange("groupName", val)} icon="people" error={errors.groupName} />
<CustomInput label="Description" placeholder="Enter a short description" value={form.description} onChangeText={(val) => handleChange("description", val)} multiline icon="document-text" error={errors.description} /> <CustomInput label="Description" placeholder="e.g., 'Monthly fund for family needs'" value={form.description} onChangeText={(val) => handleChange("description", val)} multiline icon="document-text" error={errors.description} />
<Text style={styles.label}>Visibility</Text> <Section title="Group Settings">
<View style={styles.toggleContainer}> <SettingRow label="Visibility">
<TouchableOpacity style={[styles.toggleButton, form.visibility === "PRIVATE" && styles.selectedButton]} onPress={() => handleChange("visibility", "PRIVATE")}><Text style={[styles.toggleButtonText, form.visibility === "PRIVATE" && styles.selectedButtonText]}>Private</Text></TouchableOpacity> <ToggleButtons
<TouchableOpacity style={[styles.toggleButton, form.visibility === "PUBLIC" && styles.selectedButton]} onPress={() => handleChange("visibility", "PUBLIC")}><Text style={[styles.toggleButtonText, form.visibility === "PUBLIC" && styles.selectedButtonText]}>Public</Text></TouchableOpacity> options={["PRIVATE", "PUBLIC"]}
</View> selectedValue={form.visibility}
onSelect={(val) => handleChange("visibility", val)}
/>
</SettingRow>
<SettingRow label="Fund Distribution">
<ToggleButtons
options={distributionTypes}
selectedValue={form.withdrawalMethod}
onSelect={(val) => handleChange("withdrawalMethod", val)}
/>
</SettingRow>
</Section>
<Text style={styles.label}>Fund Distribution</Text> <Section title="Participant Rules">
<View style={styles.toggleContainer}> <View style={styles.participantsRow}>
{distributionTypes.map((type) => (<TouchableOpacity key={type} onPress={() => handleChange("withdrawalMethod", type)} style={[styles.toggleButton, form.withdrawalMethod === type && styles.selectedButton]}><Text style={[styles.toggleButtonText, form.withdrawalMethod === type && styles.selectedButtonText]}>{type.charAt(0) + type.slice(1).toLowerCase()}</Text></TouchableOpacity>))} <View style={styles.participantInput}><CustomInput label="Min" placeholder="e.g., 5" value={form.minParticipants} onChangeText={(val) => handleChange("minParticipants", val)} keyboardType="numeric" icon="person-add" error={errors.minParticipants} /></View>
</View> <View style={styles.participantInput}><CustomInput label="Max" placeholder="e.g., 10" value={form.maxParticipants} onChangeText={(val) => handleChange("maxParticipants", val)} keyboardType="numeric" icon="people-circle" error={errors.maxParticipants} /></View>
</View>
<View style={styles.participantsRow}> </Section>
<View style={styles.participantInput}><CustomInput label="Min" placeholder="Min" value={form.minParticipants} onChangeText={(val) => handleChange("minParticipants", val)} keyboardType="numeric" icon="person-add" /></View>
<View style={styles.participantInput}><CustomInput label="Max" placeholder="Max" value={form.maxParticipants} onChangeText={(val) => handleChange("maxParticipants", val)} keyboardType="numeric" icon="people-circle" /></View>
</View>
<Text style={styles.label}>Contribution Amount (INR)</Text> <Section title="Financial Details">
<View style={styles.presetContainer}> <CustomInput label="Contribution Amount (INR)" placeholder="e.g., 5000" value={form.contributionAmount} onChangeText={(val) => handleChange("contributionAmount", val)} keyboardType="numeric" icon="cash" error={errors.contributionAmount} />
{presetAmounts.map((amount) => (<TouchableOpacity key={amount} onPress={() => handlePresetAmount(amount)} style={[styles.presetButton, form.contributionAmount === amount.toString() && styles.presetSelected]}><Text style={[styles.presetButtonText, form.contributionAmount === amount.toString() && styles.presetSelectedText]}>{amount}</Text></TouchableOpacity>))} <SettingRow label="Payment Cycle">
</View> <ToggleButtons
<View style={styles.amountContainer}> options={cycleTypes}
<Slider style={styles.slider} minimumValue={0} maximumValue={50000} step={100} value={parseInt(form.contributionAmount, 10) || 0} onValueChange={handleAmountChange} minimumTrackTintColor={colors.pastelGreen} maximumTrackTintColor="#ddd" thumbTintColor="#62b59a" /> selectedValue={form.cycleType}
<View style={styles.amountInput}><CustomInput label="" placeholder="Amount" value={form.contributionAmount} onChangeText={(val) => handleChange("contributionAmount", val)} keyboardType="numeric" icon="cash" /></View> onSelect={(val) => handleChange("cycleType", val)}
</View> isWrap={true}
/>
<Text style={styles.label}>Cycle Type</Text> </SettingRow>
<View style={styles.cycleTypeContainer}> {form.cycleType === "CUSTOM" && (<CustomInput label="Custom Cycle (Days)" placeholder="Enter number of days" value={form.customCycleDays} onChangeText={(val) => handleChange("customCycleDays", val)} keyboardType="numeric" icon="calendar" error={errors.customCycleDays} />)}
{cycleTypes.map((type) => (<TouchableOpacity key={type} onPress={() => handleChange("cycleType", type)} style={[styles.cycleTypeButton, form.cycleType === type && styles.cycleTypeSelected]}><Text style={[styles.cycleTypeButtonText, form.cycleType === type && styles.cycleTypeSelectedText]}>{type.charAt(0) + type.slice(1).toLowerCase()}</Text></TouchableOpacity>))} </Section>
</View>
{form.cycleType === "CUSTOM" && (<CustomInput label="Custom Cycle Days" placeholder="Enter number of days" value={form.customCycleDays} onChangeText={(val) => handleChange("customCycleDays", val)} keyboardType="numeric" icon="calendar" />)}
<Text style={styles.label}>Start Date</Text> <Section title="Late Fee Policy">
<TouchableOpacity style={[styles.datePickerButton, errors.startDate && styles.errorBorder]} onPress={() => setCalendarVisible(true)}> <SettingRow label="Fee Mode">
<Ionicons name="calendar-outline" size={20} color="#555" /> <ToggleButtons
<Text style={styles.datePickerText}>{form.startDate || "Select a start date"}</Text> options={lateFeeModes}
</TouchableOpacity> selectedValue={form.lateFeeMode}
{errors.startDate && <Text style={styles.errorText}>{errors.startDate}</Text>} onSelect={(val) => handleChange("lateFeeMode", val)}
/>
</SettingRow>
<CustomInput label="Late Fee Value (INR)" placeholder="e.g., 50" value={form.lateFeeValue} onChangeText={(val) => handleChange("lateFeeValue", val)} keyboardType="numeric" icon="alert-circle" error={errors.lateFeeValue} />
</Section>
<CustomButton title="Review" onPress={handleReview} /> <CustomButton title="Review Group" onPress={handleReview} style={{marginTop: 20}} />
</ScrollView> </ScrollView>
<Modal animationType="fade" transparent={true} visible={isCalendarVisible} onRequestClose={() => setCalendarVisible(false)}>
<TouchableOpacity style={styles.modalBackdrop} activeOpacity={1} onPressOut={() => setCalendarVisible(false)}>
<View style={styles.calendarWrapper}><Calendar onDayPress={handleDayPress} markedDates={{[form.startDate]: { selected: true, selectedColor: '#83f5cc' }}} theme={calendarTheme} /></View>
</TouchableOpacity>
</Modal>
</KeyboardAvoidingView> </KeyboardAvoidingView>
); );
} }
// --- Helper Components for a cleaner layout ---
const Section: React.FC<{ title: string, children: React.ReactNode }> = ({ title, children }) => (
<View style={styles.section}>
<Text style={styles.sectionTitle}>{title}</Text>
{children}
</View>
);
const SettingRow: React.FC<{ label: string, children: React.ReactNode }> = ({ label, children }) => (
<View style={styles.settingRow}>
<Text style={styles.label}>{label}</Text>
{children}
</View>
);
const ToggleButtons: React.FC<{ options: string[], selectedValue: string, onSelect: (value: string) => void, isWrap?: boolean }> = ({ options, selectedValue, onSelect, isWrap = false }) => (
<View style={[styles.toggleContainer, isWrap && { flexWrap: 'wrap' }]}>
{options.map((option) => (
<TouchableOpacity
key={option}
onPress={() => onSelect(option)}
style={[styles.toggleButton, selectedValue === option && styles.selectedButton, isWrap && {flex: 0, paddingHorizontal: 15}]}
>
<Text style={[styles.toggleButtonText, selectedValue === option && styles.selectedButtonText]}>
{option.charAt(0) + option.slice(1).toLowerCase()}
</Text>
</TouchableOpacity>
))}
</View>
);
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { flexGrow: 1, padding: 20, backgroundColor: "#f5f6fa" }, container: { flexGrow: 1, padding: 16, backgroundColor: "#f5f6fa" },
titleContainer: { paddingVertical: 2, borderRadius: 15, alignSelf: "flex-start", marginBottom: 30 }, titleContainer: { marginBottom: 20, paddingHorizontal: 4 },
title: { fontSize: 22, fontWeight: "bold", color: "#333" }, title: { fontSize: 28, fontWeight: "bold", color: "#1F2937" },
label: { fontSize: 14, fontWeight: "600", marginBottom: 10, color: "#444" },
toggleContainer: { flexDirection: "row", gap: 10, marginBottom: 15 }, section: {
toggleButton: { flex: 1, paddingVertical: 12, borderWidth: 1, borderColor: "#ddd", borderRadius: 12, alignItems: "center", backgroundColor: "#fff" }, backgroundColor: '#fff',
borderRadius: 12,
padding: 16,
marginBottom: 16,
elevation: 1,
shadowColor: '#4A5568',
shadowOpacity: 0.06,
shadowRadius: 10,
},
sectionTitle: {
fontSize: 18,
fontWeight: '600',
color: '#374151',
marginBottom: 16,
borderBottomWidth: 1,
borderBottomColor: '#F3F4F6',
paddingBottom: 10,
},
settingRow: {
marginBottom: 16,
},
label: { fontSize: 14, fontWeight: "600", marginBottom: 8, color: "#4B5563" },
toggleContainer: { flexDirection: "row", gap: 10 },
toggleButton: {
flex: 1,
paddingVertical: 12,
borderWidth: 1,
borderColor: "#D1D5DB",
borderRadius: 8,
alignItems: "center",
backgroundColor: "#F9FAFB"
},
selectedButton: { backgroundColor: colors.pastelGreen, borderColor: "#62b59a" }, selectedButton: { backgroundColor: colors.pastelGreen, borderColor: "#62b59a" },
toggleButtonText: { color: "#444", fontWeight: "600" }, toggleButtonText: { color: "#374151", fontWeight: "600", textTransform: 'capitalize' },
selectedButtonText: { color: "#333" }, selectedButtonText: { color: "#1F2937" },
participantsRow: { flexDirection: "row", justifyContent: "space-between", alignItems: 'flex-start', marginBottom: 10 },
participantInput: { flex: 0.48 }, participantsRow: { flexDirection: "row", gap: 15 },
presetContainer: { flexDirection: 'row', justifyContent: 'flex-start', gap: 10, marginBottom: 10 }, participantInput: { flex: 1 },
presetButton: { paddingVertical: 8, paddingHorizontal: 15, backgroundColor: '#ddd', borderRadius: 20 },
presetSelected: { backgroundColor: colors.pastelGreen, },
presetButtonText: { color: '#555', fontWeight: '600' },
presetSelectedText: { color: '#333' },
amountContainer: { flexDirection: 'row', alignItems: 'center', marginBottom: 15, },
slider: { flex: 1 },
amountInput: { width: 120, marginLeft: 10 },
cycleTypeContainer: { flexDirection: 'row', flexWrap: 'wrap', gap: 10, marginBottom: 20 },
cycleTypeButton: { paddingVertical: 10, paddingHorizontal: 15, backgroundColor: '#fff', borderWidth: 1, borderColor: '#ddd', borderRadius: 20, elevation: 1 },
cycleTypeSelected: { backgroundColor: colors.pastelGreen, borderColor: '#62b59a' },
cycleTypeButtonText: { color: '#444', fontWeight: '600', textTransform: 'capitalize' },
cycleTypeSelectedText: { color: '#333' },
datePickerButton: { flexDirection: 'row', alignItems: 'center', backgroundColor: '#fff', borderWidth: 1, borderColor: '#ddd', borderRadius: 12, paddingVertical: 15, paddingHorizontal: 15, marginBottom: 5, },
datePickerText: { marginLeft: 10, fontSize: 16, color: '#333' },
modalBackdrop: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0, 0, 0, 0.5)' },
calendarWrapper: { width: '90%', backgroundColor: 'white', borderRadius: 16, paddingVertical: 10, elevation: 5, shadowColor: '#000', shadowOpacity: 0.2, shadowRadius: 10, },
// --- ERROR STYLES ---
errorBorder: {
borderColor: '#ff4d4d', // Red border for fields with errors
},
errorText: {
color: '#ff4d4d',
fontSize: 12,
marginBottom: 10,
marginLeft: 5,
},
}); });
+95 -75
View File
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react"; import React, { useState } from "react";
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Modal, ActivityIndicator } from "react-native"; import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Modal, ActivityIndicator } from "react-native";
import { Ionicons } from "@react-native-vector-icons/ionicons"; import { Ionicons } from "@react-native-vector-icons/ionicons";
import AppView from "../components/AppView"; import AppView from "../components/AppView";
@@ -6,42 +6,34 @@ import { apiCall } from "../utils/ApiHelper";
import { GROUP_CREATION_URL } from "../utils/ApiUrls"; import { GROUP_CREATION_URL } from "../utils/ApiUrls";
import colors from "../components/colors"; import colors from "../components/colors";
// --- Simplified Dialog Component --- // --- Themed Dialog Component ---
const ThemedDialog = ({ visible, isSuccess, onClose }: { visible: boolean; isSuccess: boolean; onClose: () => void; }) => { const ThemedDialog = ({ visible, isSuccess, message, onClose, onNavigate }: { visible: boolean; isSuccess: boolean; message: string; onClose: () => void; onNavigate: () => void; }) => {
if (!visible) return null; if (!visible) return null;
const dialogConfig = { const config = isSuccess ? {
success: { icon: "checkmark-circle" as const,
icon: "checkmark-circle" as const, color: "#2ecc71",
color: "#2ecc71", title: "Success!",
title: "Success!", buttonText: "Go Home",
message: "Your group has been created.", action: onNavigate,
buttonText: "Awesome!", } : {
}, icon: "close-circle" as const,
failure: { color: "#e74c3c",
icon: "close-circle" as const, title: "Oops!",
color: "#e74c3c", buttonText: "Try Again",
title: "Oops!", action: onClose,
message: "Something went wrong. Please try again.",
buttonText: "Try Again",
},
}; };
const config = isSuccess ? dialogConfig.success : dialogConfig.failure;
return ( return (
<Modal animationType="fade" transparent={true} visible={visible} onRequestClose={onClose}> <Modal animationType="fade" transparent={true} visible={visible}>
<View style={styles.modalBackdrop}> <View style={styles.modalBackdrop}>
<View style={styles.dialogBox}> <View style={styles.dialogBox}>
<Ionicons name={config.icon} size={60} color={config.color} /> <Ionicons name={config.icon} size={60} color={config.color} />
<Text style={styles.dialogTitle}>{config.title}</Text> <Text style={styles.dialogTitle}>{config.title}</Text>
<Text style={styles.dialogMessage}>{config.message}</Text> <Text style={styles.dialogMessage}>{message}</Text>
{/* Only show button for failure case */} <TouchableOpacity style={styles.dialogButton} onPress={config.action}>
{!isSuccess && ( <Text style={styles.dialogButtonText}>{config.buttonText}</Text>
<TouchableOpacity style={styles.dialogButton} onPress={onClose}> </TouchableOpacity>
<Text style={styles.dialogButtonText}>{config.buttonText}</Text>
</TouchableOpacity>
)}
</View> </View>
</View> </View>
</Modal> </Modal>
@@ -51,56 +43,56 @@ const ThemedDialog = ({ visible, isSuccess, onClose }: { visible: boolean; isSuc
export default function GroupReview({ route, navigation }: any) { export default function GroupReview({ route, navigation }: any) {
const { form } = route.params; const { form } = route.params;
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
// --- Simplified State ---
const [isSuccess, setIsSuccess] = useState(false); const [isSuccess, setIsSuccess] = useState(false);
const [modalVisible, setModalVisible] = useState(false); const [modalVisible, setModalVisible] = useState(false);
const [feedbackMessage, setFeedbackMessage] = useState("");
// --- Automatic Navigation Effect --- const handleNavigateHome = () => {
useEffect(() => { setModalVisible(false);
// If the modal is visible and the operation was a success... navigation.reset({ index: 0, routes: [{ name: 'Home' }] });
if (modalVisible && isSuccess) { };
// ...wait for 2 seconds, then navigate.
const timer = setTimeout(() => {
setModalVisible(false); // Close the dialog
navigation.reset({ // Reset the navigation stack
index: 0,
routes: [{ name: 'Home',}],
});
}, 2000);
return () => clearTimeout(timer); // Cleanup timer on unmount
}
}, [modalVisible, isSuccess, navigation]);
const handleSubmit = async () => { const handleSubmit = async () => {
setIsLoading(true); setIsLoading(true);
try { try {
const payload = { const res = await apiCall(GROUP_CREATION_URL, "POST", form) as { statusCode?: number, message?: string };
...form,
contributionAmount: Number(form.contributionAmount) || 0,
customCycleDays: Number(form.customCycleDays) || 0,
maxParticipants: Number(form.maxParticipants) || 0,
minParticipants: Number(form.minParticipants) || 0,
};
console.log("payload:", payload);
const res = await apiCall(GROUP_CREATION_URL, "POST", payload) as { statusCode?: number };
if (res?.statusCode === 201) { if (res?.statusCode === 201) {
setIsSuccess(true); setIsSuccess(true);
setFeedbackMessage(res.message || "Your group has been created successfully.");
} else { } else {
throw new Error("Failed to create group."); throw new Error(res?.message || "Failed to create the group.");
} }
} catch (error) { } catch (error: any) {
setIsSuccess(false); setIsSuccess(false);
setFeedbackMessage(error.message || "An unexpected error occurred.");
} finally { } finally {
setIsLoading(false); setIsLoading(false);
setModalVisible(true); // Show the dialog for both success and failure setModalVisible(true);
} }
}; };
// --- UI COMPONENTS --- const TimelineSection: React.FC<{ icon: any; title: string; children: React.ReactNode }> = ({ icon, title, children }) => (
const TimelineSection = ({ icon, title, children }: { icon: any; title: string; children: React.ReactNode }) => ( <View style={styles.section}> <View style={styles.timeline}> <View style={styles.timelineIcon}> <Ionicons name={icon} size={22} color="#fff" /> </View> <View style={styles.timelineLine} /> </View> <View style={styles.content}> <Text style={styles.sectionTitle}>{title}</Text> <View style={styles.card}> {children} </View> </View> </View> ); <View style={styles.section}>
const renderRow = (label: string, value: string | number) => { if (!value && typeof value !== 'number') return null; return ( <View style={styles.row}> <Text style={styles.label}>{label}</Text> <Text style={styles.value}>{value}</Text> </View> ); }; <View style={styles.timeline}>
<View style={styles.timelineIcon}><Ionicons name={icon} size={22} color="#fff" /></View>
<View style={styles.timelineLine} />
</View>
<View style={styles.content}>
<Text style={styles.sectionTitle}>{title}</Text>
<View style={styles.card}>{children}</View>
</View>
</View>
);
const renderRow = (label: string, value: string | number | null) => {
if (value === null || value === undefined || value === "") return null;
return (
<View style={styles.row}>
<Text style={styles.label}>{label}</Text>
<Text style={styles.value}>{value}</Text>
</View>
);
};
return ( return (
<AppView> <AppView>
@@ -110,32 +102,60 @@ export default function GroupReview({ route, navigation }: any) {
<Text style={styles.subtitle}>Confirm the details to launch your group.</Text> <Text style={styles.subtitle}>Confirm the details to launch your group.</Text>
</View> </View>
{/* --- Timeline Sections --- */} <TimelineSection icon="information-circle-outline" title="Basic Information">
<TimelineSection icon="information-circle-outline" title="Basic Information">{renderRow("Name", form.groupName)}{form.description ? ( <View style={styles.descriptionContainer}> <Text style={styles.label}>Description</Text> <Text style={styles.descriptionText}>{form.description}</Text> </View> ) : null}</TimelineSection> {renderRow("Name", form.groupName)}
<TimelineSection icon="shield-checkmark-outline" title="Rules & Privacy">{renderRow("Visibility", form.visibility)}{renderRow("Distribution", form.withdrawalMethod)}{renderRow("Min Members", form.minParticipants)}{renderRow("Max Members", form.maxParticipants)}</TimelineSection> {form.description ? (
<TimelineSection icon="wallet-outline" title="Financial Details">{renderRow("Contribution", `${form.contributionAmount} INR`)}{renderRow("Cycle", form.cycleType)}{form.cycleType === "CUSTOM" && renderRow("Cycle Days", `${form.customCycleDays} days`)}{renderRow("Start Date", form.startDate)}</TimelineSection> <View style={styles.descriptionContainer}>
<Text style={styles.label}>Description</Text>
<Text style={styles.descriptionText}>{form.description}</Text>
</View>
) : null}
</TimelineSection>
<TimelineSection icon="shield-checkmark-outline" title="Rules & Privacy">
{renderRow("Visibility", form.visibility)}
{renderRow("Distribution", form.withdrawalMethod)}
{renderRow("Min Members", form.minParticipants)}
{renderRow("Max Members", form.maxParticipants)}
</TimelineSection>
<TimelineSection icon="wallet-outline" title="Financial Details">
{renderRow("Contribution", `₹${form.contributionAmount}`)}
{renderRow("Cycle", form.cycleType)}
{form.cycleType === "CUSTOM" && renderRow("Cycle Days", `${form.customCycleDays} days`)}
</TimelineSection>
<TimelineSection icon="alert-circle-outline" title="Late Fee Policy">
{renderRow("Fee Mode", form.lateFeeMode)}
{renderRow("Fee Value", `₹${form.lateFeeValue}`)}
</TimelineSection>
<TouchableOpacity onPress={handleSubmit} style={styles.submitBtn} disabled={isLoading}> <TouchableOpacity onPress={handleSubmit} style={styles.submitBtn} disabled={isLoading}>
{isLoading ? <ActivityIndicator color="#333" /> : ( <> <Ionicons name="rocket-outline" size={22} color="#333" /> <Text style={styles.btnText}>Create Group</Text> </> )} {isLoading ? <ActivityIndicator color="#333" /> : (
<>
<Ionicons name="rocket-outline" size={22} color="#333" />
<Text style={styles.btnText}>Create Group</Text>
</>
)}
</TouchableOpacity> </TouchableOpacity>
</ScrollView> </ScrollView>
{/* --- Simplified Dialog Call --- */}
<ThemedDialog <ThemedDialog
visible={modalVisible} visible={modalVisible}
isSuccess={isSuccess} isSuccess={isSuccess}
message={feedbackMessage}
onClose={() => setModalVisible(false)} onClose={() => setModalVisible(false)}
onNavigate={handleNavigateHome}
/> />
</AppView> </AppView>
); );
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
// ... (All previous styles remain the same)
container: { padding: 20, backgroundColor: "#f5f6fa" }, container: { padding: 20, backgroundColor: "#f5f6fa" },
header: { marginBottom: 30, alignItems: 'flex-start' }, header: { marginBottom: 30 },
title: { fontSize: 28, fontWeight: "bold", color: "#333" }, title: { fontSize: 28, fontWeight: "bold", color: "#333" },
subtitle: { fontSize: 16, color: "#666", marginTop: 2 }, subtitle: { fontSize: 16, color: "#666", marginTop: 4 },
section: { flexDirection: 'row', marginBottom: 10 }, section: { flexDirection: 'row', marginBottom: 10 },
timeline: { alignItems: 'center', width: 40 }, timeline: { alignItems: 'center', width: 40 },
timelineIcon: { width: 40, height: 40, borderRadius: 20, backgroundColor: colors.pastelGreen, justifyContent: 'center', alignItems: 'center', elevation: 3 }, timelineIcon: { width: 40, height: 40, borderRadius: 20, backgroundColor: colors.pastelGreen, justifyContent: 'center', alignItems: 'center', elevation: 3 },
@@ -143,17 +163,17 @@ const styles = StyleSheet.create({
content: { flex: 1, paddingLeft: 10, paddingBottom: 20 }, content: { flex: 1, paddingLeft: 10, paddingBottom: 20 },
sectionTitle: { fontSize: 18, fontWeight: 'bold', color: '#444', marginBottom: 10 }, sectionTitle: { fontSize: 18, fontWeight: 'bold', color: '#444', marginBottom: 10 },
card: { backgroundColor: "#fff", borderRadius: 12, padding: 15, elevation: 2 }, card: { backgroundColor: "#fff", borderRadius: 12, padding: 15, elevation: 2 },
row: { flexDirection: "row", justifyContent: "space-between", paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: '#f5f5f5' }, row: { flexDirection: "row", justifyContent: "space-between", paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: '#f5f5f5' },
label: { fontSize: 15, color: "#666", fontWeight: "500" }, label: { fontSize: 15, color: "#666", fontWeight: "500" },
value: { fontSize: 15, color: "#333", fontWeight: "600", textAlign: 'right', textTransform: 'capitalize' }, value: { fontSize: 15, color: "#333", fontWeight: "600", textTransform: 'capitalize' },
descriptionContainer: { paddingVertical: 10 }, descriptionContainer: { paddingVertical: 10 },
descriptionText: { fontSize: 15, color: '#333', marginTop: 4, lineHeight: 22 }, descriptionText: { fontSize: 15, color: '#333', marginTop: 4, lineHeight: 22 },
submitBtn: { backgroundColor: colors.pastelGreen, flexDirection: 'row', justifyContent: 'center', alignItems: "center", paddingVertical: 16, borderRadius: 12, elevation: 3, marginTop: 20, borderWidth: 1.5, borderColor: '#62b59a' }, submitBtn: { backgroundColor: colors.pastelGreen, flexDirection: 'row', justifyContent: 'center', alignItems: "center", paddingVertical: 16, borderRadius: 12, marginTop: 20 },
btnText: { color: "#333", fontWeight: "bold", fontSize: 18, marginLeft: 10 }, btnText: { color: "#333", fontWeight: "bold", fontSize: 18, marginLeft: 10 },
modalBackdrop: { flex: 1, backgroundColor: 'rgba(0, 0, 0, 0.6)', justifyContent: 'center', alignItems: 'center' }, modalBackdrop: { flex: 1, backgroundColor: 'rgba(0, 0, 0, 0.6)', justifyContent: 'center', alignItems: 'center' },
dialogBox: { width: '85%', backgroundColor: 'white', borderRadius: 16, padding: 25, alignItems: 'center', elevation: 10 }, dialogBox: { width: '85%', backgroundColor: 'white', borderRadius: 16, padding: 25, alignItems: 'center', elevation: 10 },
dialogTitle: { fontSize: 22, fontWeight: 'bold', color: '#333', marginTop: 15, marginBottom: 5 }, dialogTitle: { fontSize: 22, fontWeight: 'bold', color: '#333', marginTop: 15, marginBottom: 10 },
dialogMessage: { fontSize: 16, color: '#666', textAlign: 'center', marginBottom: 25 }, dialogMessage: { fontSize: 16, color: '#666', textAlign: 'center', marginBottom: 25 },
dialogButton: { backgroundColor: colors.pastelGreen, paddingVertical: 12, paddingHorizontal: 40, borderRadius: 10 }, dialogButton: { backgroundColor: '#f0f0f0', paddingVertical: 12, paddingHorizontal: 40, borderRadius: 10 },
dialogButtonText: { color: '#333', fontWeight: 'bold', fontSize: 16 }, dialogButtonText: { color: '#333', fontWeight: 'bold', fontSize: 16 },
}); });
+1
View File
@@ -28,6 +28,7 @@ export const fetchUserProfile = async () => {
); );
const result = await response.json(); const result = await response.json();
console.log("user api data",result)
if (result.status === "success") { if (result.status === "success") {
dispatch(setUserData({ dispatch(setUserData({
id: result?.data.id, id: result?.data.id,