This repository has been archived on 2026-04-20. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
interaktive-systeme/components/stats/BudgetRemaining.tsx
2024-01-25 19:36:39 +01:00

82 lines
2.2 KiB
TypeScript

import React, { useState, useEffect } from 'react';
import { Text, StyleSheet } from 'react-native';
import { useTheme } from '../../app/contexts/ThemeContext';
import useFetch from '../../hooks/useFetch';
import { CategoryType } from '../../services/database';
const styles = StyleSheet.create({
container: {
margin: 10,
borderRadius: 5,
alignItems: 'center',
justifyContent: 'center'
},
text: {
fontSize: 26,
},
boldText: {
fontWeight: 'bold'
},
negativeText: {
color: 'red',
},
positiveText: {
color: 'green',
},
});
interface BudgetRemainingProps {
goodColor?: string;
badColor?: string;
}
const BudgetRemaining: React.FC<BudgetRemainingProps> = ({ goodColor = 'green', badColor = 'red' }) => {
const { colors } = useTheme();
const [spent, setSpent] = useState(0);
const [budget, setBudget] = useState(0);
const spentQuery = {
sql: "SELECT SUM(amount) as total FROM expense",
args: []
};
const budgetQuery = {
sql: `SELECT SUM(allocated_amount) as total FROM category WHERE type = '${CategoryType.EXPENSE.toString()}'`,
args: []
};
const { data: spentData, isLoading: spentLoading } = useFetch(spentQuery);
const { data: budgetData, isLoading: budgetLoading } = useFetch(budgetQuery);
useEffect(() => {
if (spentData) {
setSpent(spentData[0]?.total || 0);
}
if (budgetData) {
setBudget(budgetData[0]?.total || 0);
}
}, [spentData, budgetData]);
const remaining = budget - spent;
if (spentLoading || budgetLoading) {
return <Text>Loading...</Text>;
}
return (
<Text style={[styles.text, { color: colors.primaryText }]}>
{remaining >= 0 ? (
<>
Your remaining Budget is <Text style={[styles.boldText, { color: goodColor }]}>{remaining.toFixed(2)}</Text>.
</>
) : (
<>
Your Budget is overspent by by <Text style={[styles.boldText, { color: badColor }]}>-{Math.abs(remaining).toFixed(2)}</Text>.
</>
)}
</Text>
);
};
export default BudgetRemaining;