Skip to content

Commit

Permalink
Merge pull request #17 from Moises088/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
Moises088 committed Jan 7, 2023
2 parents b02e39c + a520fea commit 19fee70
Show file tree
Hide file tree
Showing 12 changed files with 120 additions and 33 deletions.
10 changes: 8 additions & 2 deletions src/components/budget/budget-card/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { View, Text } from 'react-native';
import { View, Text, Image } from 'react-native';
import { ThemeContext } from '../../../contexts/themeContext';
import { styles } from './styles';
import { FontAwesome5 } from '@expo/vector-icons';
Expand All @@ -13,10 +13,16 @@ const BudgetCard: React.FC<{ item: BudgetsBalanceCategory }> = ({ item }) => {

const progress = parseFloat(((item.used * 100) / item.total).toFixed(2));

const Icon: React.FC = () => {
if (item.categoryId) return <FontAwesome5 name={item.category?.icon} size={18} color={theme.text.primary} />
if (item.debtId) return <Image source={item.debt?.logo} style={style.image} />
return <View />
}

return (
<View style={style.container}>
<View style={style.containerIcon}>
<FontAwesome5 name={item.category?.icon} size={18} color={theme.text.primary} />
<Icon />
</View>
<View style={style.containerInfo}>
<View style={style.containerHeader}>
Expand Down
5 changes: 5 additions & 0 deletions src/components/budget/budget-card/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ export const styles = (theme: ThemesConfig) => {
text: {
letterSpacing: 1.05,
color: theme.text.primary
},
image: {
width: 38,
height: 38,
borderRadius: 38
}
})
};
8 changes: 7 additions & 1 deletion src/components/home/home-budget-itens/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,18 @@ const HomeBudgetItens: React.FC<{ item: BudgetsBalanceCategory }> = ({ item }) =

const progress = parseFloat(((item.used * 100) / item.total).toFixed(2));

const Icon: React.FC = () => {
if (item.categoryId) return <FontAwesome5 name={item.category?.icon} size={18} color={theme.text.primary} />
if (item.debtId) return <Image source={item.debt?.logo} style={style.image} />
return <View />
}

return (
<View style={style.container}>
<Image source={BACKGROUN_IMAGE} style={style.backgroundImage} />
<View style={style.containerTitle}>
<View style={[style.containerIcon, { backgroundColor: item.category?.color ?? theme.background.primary }]}>
{item.category && (<FontAwesome5 name={item.category.icon} size={22} color={theme.text.primary} />)}
<Icon />
</View>
<Text style={style.text}>{item.category?.name}</Text>
</View>
Expand Down
5 changes: 5 additions & 0 deletions src/components/home/home-budget-itens/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ export const styles = (theme: ThemesConfig) => {
containerProgress: {
width: "90%",
marginLeft: "5%"
},
image: {
width: 38,
height: 38,
borderRadius: 38
}
})
};
2 changes: 1 addition & 1 deletion src/components/home/home-budget/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const HomeBudget: React.FC = () => {
<Carousel
width={250}
itens={
budgets?.categories.map((budget, i) => (
budgets?.categories.map((budget, i) => i < 5 && (
<HomeBudgetItens key={i} item={budget} />
)) as JSX.Element[] ?? []
}
Expand Down
11 changes: 9 additions & 2 deletions src/interfaces/services/budget.interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CategoryEntity } from "./category.interface";
import { DebtsInstitution } from "./debts.interface";

interface Budget {
year: string;
Expand All @@ -7,6 +8,10 @@ interface Budget {
categoryId: number;
total: number;
}[];
debts: {
debtId: number;
total: number;
}[];
}
export interface BudgetDto extends Budget {
total: string
Expand All @@ -20,9 +25,11 @@ export interface BudgetEntity extends Budget {
}

export interface BudgetsBalanceCategory {
category: CategoryEntity | undefined;
categoryId?: number;
category?: CategoryEntity;
debtId?: number;
debt?: DebtsInstitution;
used: number;
categoryId: number;
total: number;
}

Expand Down
3 changes: 2 additions & 1 deletion src/interfaces/services/finance.interface.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CategoryEntity } from "./category.interface";
import { DebtsInstitution } from "./debts.interface";
import { DebtsEntity, DebtsInstitution } from "./debts.interface";

interface Finance {
name: string;
Expand Down Expand Up @@ -36,6 +36,7 @@ export interface FinanceBalance {
}

export interface FinanceBalancePerCategory {
bill?: { institution: DebtsInstitution | undefined, id: number };
category: CategoryEntity | undefined;
total: number;
}
4 changes: 2 additions & 2 deletions src/screens/budget/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ export const styles = (theme: ThemesConfig) => {
marginRight: 4
},
containerButton: {
width: "70%",
marginLeft: "15%",
width: "80%",
marginLeft: "10%",
marginTop: 20,
marginBottom: 20
}
Expand Down
36 changes: 26 additions & 10 deletions src/screens/create-budget/createBudgetScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { DATE_MONTH, DATE_YEAR } from '../../constants/date.constants';
import { BudgetDto } from '../../interfaces/services/budget.interface';
import { getPipeMoneyNumber, getPipeMoneyString } from '../../utils/money.util';
import { AppBudgetService } from '../../services/budget';
import { COLOR_SUCCESS } from '../../constants/colors';
import { COLOR_DANGER, COLOR_SUCCESS } from '../../constants/colors';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { BudgetsContext } from '../../contexts/budgetsContext';
Expand Down Expand Up @@ -62,20 +62,35 @@ const CreateBudgetScreen: React.FC = () => {
setBudgetForm(prev => ({ ...prev, categories, debts, total: getPipeMoneyString(total) }))
}

const setTotal = (total: string, index: number) => {
const sum = budgetForm.categories
.filter((r, i) => i !== index)
.reduce((partialSum, a) => partialSum + parseFloat(a.total.replace(",", ".")), 0);
const setTotal = (total: string, index: number, type: "Categories" | "Debts") => {
let categories = budgetForm.categories.map(c => c);
let debts = budgetForm.debts.map(c => c);

setBudgetForm(prev => ({ ...prev, total: (sum + parseFloat(total.replace(",", "."))).toFixed(2).replace(".", ",") }))
if (type == "Categories") categories = categories.filter((_, i) => i !== index);
if (type == "Debts") debts = debts.filter((_, i) => i !== index);

const formatTotal = (partial: string) => parseFloat(partial.replace(",", "."))

const sumCategories = categories.reduce((partialSum, a) => partialSum + formatTotal(a.total), 0);
const sumDebts = debts.reduce((partialSum, a) => partialSum + formatTotal(a.total), 0);
const totals = formatTotal(total);

const sum = sumCategories + sumDebts + totals;

setBudgetForm(prev => ({ ...prev, total: sum.toFixed(2).replace(".", ",") }))
}

const savebudget = async () => {
const { categories, total } = budgetForm;
const { categories, total, debts } = budgetForm;

const categoriesDto = categories.map(category => (
{ categoryId: category.category.id, total: getPipeMoneyNumber(category.total) }
)).filter(c => c.total > 0);

const debtsDto = debts.map(debt => (
{ debtId: debt.debt.id, total: getPipeMoneyNumber(debt.total) }
)).filter(d => d.total > 0);

const erros = [];
if (!categoriesDto?.length) erros.push("Adicione ao menos uma categoria")
if (!getPipeMoneyNumber(total)) erros.push("O total é obrigatório e maior que zero")
Expand All @@ -89,7 +104,7 @@ const CreateBudgetScreen: React.FC = () => {
}

try {
const budgetDto: BudgetDto = { month: filteredMonth, year: filteredYear, categories: categoriesDto, total }
const budgetDto: BudgetDto = { month: filteredMonth, year: filteredYear, categories: categoriesDto, debts: debtsDto, total }
await AppBudgetService.create(budgetDto)
await getBudgetsBalance()
navigation.goBack()
Expand Down Expand Up @@ -139,6 +154,7 @@ const CreateBudgetScreen: React.FC = () => {
</View>

<Text style={[style.textButton, { fontSize: 14, marginTop: 10 }]}>Escolha as categorias</Text>
<Text style={[style.textButton, { fontSize: 11, marginTop: 10, color: COLOR_DANGER }]}>Apenas gastos</Text>

{budgetForm.categories.map((cate, i) => (
<View key={i} style={style.containerCategory}>
Expand All @@ -156,7 +172,7 @@ const CreateBudgetScreen: React.FC = () => {
options={INPUT_MASK_OPTIONS}
value={budgetForm?.categories[i]?.total}
onChangeText={(total: string) => {
setTotal(total, i)
setTotal(total, i, "Categories")
setBudgetForm(prev => ({
...prev, categories: budgetForm.categories.map((category, index) => {
if (index == i) category.total = total;
Expand Down Expand Up @@ -186,7 +202,7 @@ const CreateBudgetScreen: React.FC = () => {
options={INPUT_MASK_OPTIONS}
value={budgetForm?.debts[i]?.total}
onChangeText={(total: string) => {
setTotal(total, i)
setTotal(total, i, "Debts")
setBudgetForm(prev => ({
...prev, debts: budgetForm.debts.map((debt, index) => {
if (index == i) debt.total = total;
Expand Down
7 changes: 5 additions & 2 deletions src/screens/create-debt/createDebtScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import { StackNavigationProp } from '@react-navigation/stack';
import { useRoute, RouteProp, useNavigation } from "@react-navigation/native";
import { DebtsContext } from '../../contexts/debtsContext';
import { DebtsParamRoute } from '../../interfaces/screens/debts.interface';
import { FinancesContext } from '../../contexts/financesContext';

const CreateDebtScreen: React.FC = () => {

const { getFinancesBalance } = React.useContext(FinancesContext);
const { getDebtsBalance } = React.useContext(DebtsContext);
const { theme } = React.useContext(ThemeContext);
const style = styles(theme);
Expand All @@ -44,7 +46,7 @@ const CreateDebtScreen: React.FC = () => {
if (params?.debts) {
const debts = params.debts;
const getTotalPerMonth = () => {
if(debts.total == debts.totalPerMonth) return "0";
if (debts.total == debts.totalPerMonth) return "0";
return getPipeMoneyString(debts.totalPerMonth)
}

Expand Down Expand Up @@ -90,13 +92,14 @@ const CreateDebtScreen: React.FC = () => {
institutionName
}

if(!debtId){
if (!debtId) {
await AppDebtsService.create(debtDto);
} else {
await AppDebtsService.update(debtId, debtDto);
}

await getDebtsBalance()
await getFinancesBalance()
navigation.goBack()
} catch (error: any) {
if (error?.message) setValidation([error.message])
Expand Down
41 changes: 30 additions & 11 deletions src/services/balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,12 @@ class BalanceService {
const category = categories.find(c => c.id == finance.categoryId);
const getBill = bills.find(bill => bill.id == finance.billId);
const getInstitution = DEBTS_INSTITUTION.find(bill => bill.id == getBill?.institutionId);
if(!getInstitution) return;

const bill = decontextualize<DebtsInstitution>(getInstitution);
if (bill.name == "OUTRO") bill.name = getBill?.institutionName ?? "";
let bill;
if (getInstitution) {
bill = decontextualize<DebtsInstitution>(getInstitution);
if (bill.name == "OUTRO") bill.name = getBill?.institutionName ?? "";
}

return { ...finance, category, bill };
}
Expand All @@ -112,16 +114,33 @@ class BalanceService {
const perCategory: FinanceBalancePerCategory[] = [];

for (const balance of balances.finances) {
const category = perCategory.find(category => category?.category?.id == balance.categoryId);
if (category?.total) {
category.total += balance.value;
continue
if (balance.categoryId) {
const category = perCategory.find(category => category?.category?.id == balance.categoryId);
if (category?.total) {
category.total += balance.value;
continue
}

perCategory.push({
bill: undefined,
category: balance.category,
total: balance.value
})
}

perCategory.push({
category: balance.category,
total: balance.value
})
if (balance.billId) {
const bill = perCategory.find(bill => bill.bill?.id == balance.billId);
if (bill?.total) {
bill.total += balance.value;
continue
}

perCategory.push({
bill: { institution: balance.bill, id: balance.billId },
category: undefined,
total: balance.value
})
}
}

return { ...balances, categories: perCategory }
Expand Down
21 changes: 20 additions & 1 deletion src/services/budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ASYNC_BUDGETS } from "../constants/storage.constant";
import { AppCategoryService } from "./category";
import { AppFinanceService } from "./finance";
import { AppBalanceService } from "./balance";
import { AppDebtsService } from "./debts";

class Budget implements BudgetEntity {
id: number;
Expand All @@ -16,12 +17,14 @@ class Budget implements BudgetEntity {
month: string;
value: number;
categories: { categoryId: number; total: number; }[];
debts: { debtId: number; total: number; }[];

constructor(budgetDto: BudgetDto, id: number) {
this.id = id + 1;
this.year = budgetDto.year;
this.month = budgetDto.month;
this.categories = budgetDto.categories;
this.debts = budgetDto.debts;
this.value = getPipeMoneyNumber(budgetDto.total);
this.createdAt = getPipeDateTimeString();
}
Expand All @@ -36,12 +39,14 @@ class BudgetService implements Services<BudgetEntity, BudgetDto>{

public async getBudgetBalance(month: string, year: string): Promise<BudgetsBalanceEntity | undefined> {
const budgets = await this.find();
const debts = await AppDebtsService.findInstitutions();
const budget = budgets.find(budget => budget.month == month && budget.year == year);
const { categories, totalExpense } = await AppBalanceService.getFinancesBalancePerCategory(month, year, 1);

if (!budget?.categories) return;

const budgetCategoriesFilter: BudgetsBalanceCategory[] = []
const budgetCategoriesFilter: BudgetsBalanceCategory[] = [];

for (const budgetCategory of budget.categories) {
const findCategory = categories.find(c => c.category?.id == budgetCategory.categoryId);
if (!findCategory) {
Expand All @@ -55,6 +60,20 @@ class BudgetService implements Services<BudgetEntity, BudgetDto>{
budgetCategoriesFilter.push({ ...budgetCategory, category, used: total })
}

for (const debtCategory of budget.debts) {
const findDebt = categories.find(debt => debt.bill?.id == debtCategory.debtId)
if (!findDebt) {
const debt = await debts.find(debt => debt.id == debtCategory.debtId);
if (!debt) continue;

budgetCategoriesFilter.push({ ...debtCategory, debt, used: 0 });
continue
}

const { bill, total } = findDebt;
budgetCategoriesFilter.push({ ...debtCategory, debt: bill?.institution, used: total })
}

return { ...budget, categories: budgetCategoriesFilter, totalExpense }
}

Expand Down

0 comments on commit 19fee70

Please sign in to comment.