fund distribution

This commit is contained in:
Abin Toppo
2025-09-26 10:16:19 +05:30
parent a303af566e
commit 6778e79dc8
6 changed files with 630 additions and 248 deletions
+159 -196
View File
@@ -1,15 +1,15 @@
import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, ScrollView, RefreshControl, Alert, TouchableOpacity } from 'react-native';
import { useRoute, useNavigation, RouteProp } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { View, Text, StyleSheet, ActivityIndicator, ScrollView, RefreshControl, Alert, TouchableOpacity, Modal, TextInput } from 'react-native';
import { useRoute, RouteProp } from '@react-navigation/native';
import { Ionicons } from "@react-native-vector-icons/ionicons";
import colors from '../../components/colors';
import AppView from '../../components/AppView';
import { apiCall } from '../../utils/ApiHelper';
// --- TYPE DEFINITIONS ---
// --- CONSTANTS ---
const API_BASE_URL = 'https://exotic-humpback-mistakenly.ngrok-free.app/api/payments';
// Generic API Response Wrapper
// --- TYPE DEFINITIONS ---
interface ApiResponse<T> {
status: 'success' | 'error';
data: T;
@@ -17,69 +17,54 @@ interface ApiResponse<T> {
statusCode: number;
}
// Type for an individual participant in the payment details
interface Participant {
userId: string;
userName: string;
firstName: string;
lastName: string;
mobile: string;
contributionAmount: number;
paidAmount: number;
payAmount?: number;
status: 'SUCCESS' | 'PENDING';
lateFee: number;
daysLate: number;
lateFeeWaived: boolean;
}
// Fully typed payment details based on your JSON response
interface PaymentDetails {
groupId: string;
groupName: string;
currentCycle: number;
cycleType: string;
contributionAmount: number;
totalContributedAmount: number;
lateFeeMode: string;
lateFeeValue: number;
notReceivedAmount: number;
totalLateFee: number;
totalDueWithLateFee: number;
participants: Participant[];
}
// Assuming your navigation stack params look something like this
type PaymentStackParamList = {
Payments: { groupId: string };
};
type PaymentStackParamList = { Payments: { groupId: string } };
type PaymentsRouteProp = RouteProp<PaymentStackParamList, 'Payments'>;
type PaymentsNavigationProp = StackNavigationProp<PaymentStackParamList>;
const Payments: React.FC = () => {
const route = useRoute<PaymentsRouteProp>();
const navigation = useNavigation<PaymentsNavigationProp>();
const { groupId } = route.params;
const [paymentDetails, setPaymentDetails] = useState<PaymentDetails | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
// State for the waiver modal
const [isModalVisible, setModalVisible] = useState(false);
const [currentParticipant, setCurrentParticipant] = useState<Participant | null>(null);
const [waiverAmount, setWaiverAmount] = useState('');
const fetchPaymentDetails = useCallback(async () => {
if (!refreshing) setLoading(true);
try {
const response = await apiCall(
`https://exotic-humpback-mistakenly.ngrok-free.app/api/payments/current/payment/details/${groupId}`,
'GET'
) as ApiResponse<PaymentDetails>;
const response = await apiCall(`${API_BASE_URL}/current/payment/details/${groupId}`, 'GET') as ApiResponse<PaymentDetails>;
if (response && response.statusCode === 200) {
setPaymentDetails(response.data);
} else {
Alert.alert("Error", response?.message || "Failed to fetch payment details.");
Alert.alert("Error", response?.message || "Failed to fetch details.");
}
} catch (error: any) {
console.error("Fetch payment details error:", error);
Alert.alert("Error", error.message || "An unexpected error occurred.");
} finally {
setLoading(false);
@@ -91,205 +76,183 @@ const Payments: React.FC = () => {
fetchPaymentDetails();
}, [fetchPaymentDetails]);
const onRefresh = () => {
const onRefresh = useCallback(() => {
setRefreshing(true);
fetchPaymentDetails();
}, [fetchPaymentDetails]);
const openWaiverDialog = (participant: Participant) => {
setCurrentParticipant(participant);
setWaiverAmount('');
setModalVisible(true);
};
// --- UPDATED: handleWaiveFee now uses the correct API endpoint ---
const handleWaiveFee = async () => {
if (!currentParticipant || !paymentDetails) return;
const amountToWaive = parseFloat(waiverAmount);
if (isNaN(amountToWaive) || amountToWaive <= 0) {
Alert.alert("Invalid Input", "Please enter a waiver amount greater than zero.");
return;
}
if (amountToWaive > currentParticipant.lateFee) {
Alert.alert("Invalid Amount", `Waiver cannot exceed the current late fee of ₹${currentParticipant.lateFee}.`);
return;
}
try {
// Construct the exact URL as provided
const url = `${API_BASE_URL}/groups/${groupId}/cycles/${paymentDetails.currentCycle}/waive/${currentParticipant.userId}?amountToWaive=${amountToWaive}`;
const response = await apiCall(url, 'PUT', {}); // Body is empty as amount is in URL
if (response && response.statusCode === 200) {
Alert.alert("Success", `₹${amountToWaive} has been waived successfully.`);
setModalVisible(false);
onRefresh(); // Refresh data to reflect the change
} else {
throw new Error(response?.message || "Failed to apply waiver.");
}
} catch (error: any) {
Alert.alert("API Error", error.message);
}
};
// --- ENHANCED: renderParticipant now shows late fee details ---
const renderParticipant = (participant: Participant) => {
const isPending = participant.status === 'PENDING';
const canWaive = isPending && participant.lateFee > 0;
return (
<View key={participant.userId} style={styles.participantCard}>
<View style={styles.participantInfo}>
<Text style={styles.participantName}>{participant.firstName} {participant.lastName}</Text>
<Text style={styles.participantMobile}>{participant.mobile}</Text>
</View>
<View style={styles.paymentStatus}>
<Text style={[
styles.statusText,
{ color: isPending ? '#e0d626ff' : '#18b107ff' }
]}>
<Text style={[styles.statusText, { color: isPending ? colors.warning : colors.success }]}>
{participant.status}
</Text>
<Text style={styles.amountText}>
{isPending ?`₹${participant.payAmount}`:`₹${participant.paidAmount}`}
{isPending ? `₹${participant.payAmount || 0}` : `₹${participant.paidAmount}`}
</Text>
{/* --- NEW: Conditionally render late payment stats --- */}
{isPending && participant.daysLate > 0 && (
<View style={styles.lateFeeContainer}>
<Text style={styles.lateFeeText}>Late Fee: ₹{participant.lateFee}</Text>
<Text style={styles.lateFeeText}>Days Late: {participant.daysLate}</Text>
</View>
{isPending && participant.lateFee > 0 && (
<Text style={styles.lateFeeText}>Late Fee: ₹{participant.lateFee}</Text>
)}
{participant.lateFee === 0 && participant.lateFeeWaived && <Text style={styles.waivedText}>Fee Waived</Text>}
</View>
<View style={styles.menuContainer}>
{canWaive && (
<TouchableOpacity onPress={() => openWaiverDialog(participant)}>
<Ionicons name="ellipsis-vertical" size={22} color="#6c757d" />
</TouchableOpacity>
)}
</View>
</View>
);
};
if (loading && !refreshing) {
return <ActivityIndicator style={styles.centered} size="large" color={colors.primary} />;
}
if (!paymentDetails) {
return (
<View style={styles.centered}>
<Text>No payment details found.</Text>
<TouchableOpacity onPress={fetchPaymentDetails} style={styles.retryButton}>
<Text style={styles.retryButtonText}>Tap to retry</Text>
</TouchableOpacity>
</View>
);
}
return (
<AppView paddingHorizontal={0}>
<Modal
transparent={true}
visible={isModalVisible}
animationType="fade"
onRequestClose={() => setModalVisible(false)}
>
<View style={styles.modalOverlay}>
<View style={styles.modalContainer}>
<Text style={styles.modalTitle}>Waive Late Fee</Text>
<Text style={styles.modalSubtitle}>
For {currentParticipant?.firstName}. Current late fee is ₹{currentParticipant?.lateFee}.
</Text>
<TextInput
style={styles.input}
keyboardType="numeric"
value={waiverAmount}
onChangeText={setWaiverAmount}
placeholder="Enter amount to waive"
/>
<View style={styles.modalButtonContainer}>
<TouchableOpacity style={[styles.modalButton, styles.cancelButton]} onPress={() => setModalVisible(false)}>
<Text style={styles.cancelButtonText}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.modalButton, styles.saveButton]} onPress={handleWaiveFee}>
<Text style={styles.saveButtonText}>Apply Waiver</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
<ScrollView
style={styles.container}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={[colors.primary]} tintColor={colors.primary} />}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
>
<View style={styles.header}>
<Text style={styles.headerTitle}>{paymentDetails.groupName}</Text>
</View>
<View style={styles.summaryContainer}>
<View style={styles.summaryBox}>
<Text style={styles.summaryLabel}>Current Cycle</Text>
<Text style={styles.summaryValue}>{paymentDetails.currentCycle}</Text>
</View>
<View style={styles.summaryBox}>
<Text style={styles.summaryLabel}>Contribution</Text>
<Text style={styles.summaryValue}>₹{paymentDetails.contributionAmount}</Text>
</View>
<View style={styles.summaryBox}>
<Text style={styles.summaryLabel}>Total Due</Text>
<Text style={[styles.summaryValue, { color: colors.danger }]}>₹{paymentDetails.totalDueWithLateFee}</Text>
</View>
</View>
<Text style={styles.sectionTitle}>Participants</Text>
{paymentDetails.participants.map(renderParticipant)}
{loading && !refreshing ? (
<ActivityIndicator style={{marginTop: 50}} size="large" color={colors.primary} />
) : (
<>
<View style={styles.header}>
<Text style={styles.headerTitle}>{paymentDetails?.groupName}</Text>
</View>
<View style={styles.summaryContainer}>
<View style={styles.summaryBox}>
<Text style={styles.summaryLabel}>Cycle</Text>
<Text style={styles.summaryValue}>{paymentDetails?.currentCycle}</Text>
</View>
<View style={styles.summaryBox}>
<Text style={styles.summaryLabel}>Contribution</Text>
<Text style={styles.summaryValue}>₹{paymentDetails?.contributionAmount}</Text>
</View>
<View style={styles.summaryBox}>
<Text style={styles.summaryLabel}>Total Due</Text>
<Text style={[styles.summaryValue, { color: colors.danger }]}>₹{paymentDetails?.totalDueWithLateFee}</Text>
</View>
</View>
<Text style={styles.sectionTitle}>Participants</Text>
{paymentDetails?.participants.map(renderParticipant)}
</>
)}
</ScrollView>
</AppView>
);
};
const styles = StyleSheet.create({
centered: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f4f6f8',
},
container: {
flex: 1,
backgroundColor: '#f4f6f8',
},
header: {
padding: 20,
paddingBottom: 15,
},
headerTitle: {
color: '#000000',
fontSize: 24,
fontWeight: 'bold',
},
summaryContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: 20,
backgroundColor: '#fff',
marginHorizontal: 15,
borderRadius: 12,
elevation: 2,
shadowColor: '#000',
shadowOpacity: 0.05,
shadowRadius: 10,
},
summaryBox: {
alignItems: 'center',
},
summaryLabel: {
fontSize: 14,
color: '#6c757d',
marginBottom: 4,
},
summaryValue: {
fontSize: 18,
fontWeight: '700',
color: colors.primary,
},
sectionTitle: {
fontSize: 20,
fontWeight: 'bold',
marginLeft: 20,
marginTop: 20,
marginBottom: 10,
color: '#343a40',
},
participantCard: {
backgroundColor: '#fff',
marginHorizontal: 15,
marginBottom: 10,
borderRadius: 10,
padding: 15,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
elevation: 1,
},
participantInfo: {
flex: 1,
},
participantName: {
fontSize: 16,
fontWeight: '600',
color: '#212529',
},
participantMobile: {
fontSize: 14,
color: '#6c757d',
marginTop: 2,
},
paymentStatus: {
alignItems: 'flex-end',
},
statusText: {
fontSize: 14,
fontWeight: 'bold',
textTransform: 'uppercase',
},
amountText: {
fontSize: 14,
color: '#495057',
marginTop: 2,
},
// --- NEW STYLES ---
lateFeeContainer: {
marginTop: 8,
paddingTop: 5,
borderTopWidth: 1,
borderTopColor: '#e9ecef',
alignItems: 'flex-end',
},
lateFeeText: {
fontSize: 13,
color: colors.danger,
fontWeight: '600',
},
retryButton: {
marginTop: 20,
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 8,
backgroundColor: colors.primary,
},
retryButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
container: { flex: 1, backgroundColor: '#f4f6f8' },
header: { padding: 20, paddingBottom: 15 },
headerTitle: { color: '#000000', fontSize: 24, fontWeight: 'bold' },
summaryContainer: { flexDirection: 'row', justifyContent: 'space-around', padding: 20, backgroundColor: '#fff', marginHorizontal: 15, borderRadius: 12, elevation: 2 },
summaryBox: { alignItems: 'center' },
summaryLabel: { fontSize: 14, color: '#6c757d', marginBottom: 4 },
summaryValue: { fontSize: 18, fontWeight: '700', color: colors.primary },
sectionTitle: { fontSize: 20, fontWeight: 'bold', marginLeft: 20, marginTop: 20, marginBottom: 10 },
participantCard: { backgroundColor: '#fff', marginHorizontal: 15, marginBottom: 10, borderRadius: 10, padding: 15, flexDirection: 'row', alignItems: 'center', elevation: 1 },
participantInfo: { flex: 1 },
participantName: { fontSize: 16, fontWeight: '600' },
participantMobile: { fontSize: 14, color: '#6c757d', marginTop: 2 },
paymentStatus: { alignItems: 'flex-end', marginHorizontal: 10 },
statusText: { fontSize: 14, fontWeight: 'bold', textTransform: 'uppercase' },
amountText: { fontSize: 14, color: '#495057', marginTop: 2 },
lateFeeText: { fontSize: 13, color: colors.danger, fontWeight: '600', marginTop: 4 },
waivedText: { fontSize: 13, color: colors.success, fontWeight: '600', marginTop: 4 },
menuContainer: { justifyContent: 'center', alignItems: 'center', minWidth: 25 },
modalOverlay: { flex: 1, backgroundColor: 'rgba(0, 0, 0, 0.5)', justifyContent: 'center', alignItems: 'center' },
modalContainer: { width: '85%', backgroundColor: 'white', borderRadius: 15, padding: 20, elevation: 10 },
modalTitle: { fontSize: 20, fontWeight: 'bold', color: '#333', marginBottom: 5 },
modalSubtitle: { fontSize: 14, color: '#666', marginBottom: 20 },
input: { width: '100%', borderWidth: 1, borderColor: '#ddd', borderRadius: 8, paddingHorizontal: 15, paddingVertical: 12, fontSize: 16, marginBottom: 20 },
modalButtonContainer: { flexDirection: 'row', justifyContent: 'flex-end' },
modalButton: { paddingVertical: 10, paddingHorizontal: 20, borderRadius: 8, marginLeft: 10 },
cancelButton: { backgroundColor: '#f0f0f0' },
cancelButtonText: { color: '#333', fontWeight: 'bold' },
saveButton: { backgroundColor: colors.primary },
saveButtonText: { color: 'white', fontWeight: 'bold' },
});
export default Payments;