made hook to streamline getting totals and expense by type of category

This commit is contained in:
Walcher 2024-01-25 18:49:05 +01:00 committed by Jakob Stornig
parent 85e92c85b4
commit 7a5ace403e
6 changed files with 233 additions and 176 deletions

View file

@ -1,63 +1,56 @@
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Text, StyleSheet } from 'react-native';
import { useTheme } from '../../app/contexts/ThemeContext';
import useFetch from '../../hooks/useFetch';
import { CategoryType } from '../../services/database';
import {useCategoryData} from '../../hooks/useCategoryData';
const BudgetOverview = () => {
const styles = StyleSheet.create({
container: {
margin: 10,
borderRadius: 5,
alignItems: 'center',
justifyContent: 'center'
},
text: {
fontSize: 26,
color: `black`
},
boldText: {
fontWeight: 'bold'
},
negativeText: {
color: 'red',
},
positiveText: {
color: 'green',
},
});
interface BudgetTotalProps {
goodColor?: string;
badColor?: string;
}
const BudgetTotal: React.FC<BudgetTotalProps> = ({ goodColor = 'green', badColor = 'red' }) => {
const { colors } = useTheme();
const [spent, setSpent] = useState(0);
const [budget, setBudget] = useState(0);
const { data, isLoading } = useCategoryData(CategoryType.EXPENSE);
const spentQuery = {
sql: `SELECT SUM(e.amount) as total FROM expense e LEFT JOIN category c ON e.category_guid = c.guid WHERE c.type = '${CategoryType.EXPENSE.toString()}'`,
args: []
};
const { total, expenseTotal } = data;
const budgetQuery = {
sql: `SELECT SUM(allocated_amount) as total FROM category WHERE type = '${CategoryType.EXPENSE.toString()}'`,
args: []
};
const remaining = total - expenseTotal;
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 styles = StyleSheet.create({
container: {
margin: 10,
borderRadius: 5,
alignItems: 'center',
justifyContent: 'center'
},
text: {
fontSize: 26,
color: colors.primaryText
},
boldText: {
fontWeight: 'bold'
}
});
if (spentLoading || budgetLoading) {
if (isLoading) {
return <Text>Loading...</Text>;
}
return (
<View style={styles.container}>
<Text style={styles.text}>
You have spent <Text style={styles.boldText}>{spent.toFixed(2)}</Text> out of your budget of <Text style={styles.boldText}>{budget.toFixed(2)}</Text>.
</Text>
</View>
<Text style={[styles.text, { color: colors.primaryText }]}>
<>
You have spent <Text style={[styles.boldText, { color: goodColor }]}>{expenseTotal.toFixed(2)}</Text> out of your Budget of <Text style={[styles.boldText]}>{total.toFixed(2)} </Text>.
</>
</Text>
);
};
export default BudgetOverview;
export default BudgetTotal;