Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/minor updates #112

Merged
merged 8 commits into from
Apr 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"format": "prettier --write ./src"
},
"dependencies": {
"@budgetbuddyde/types": "^1.0.20",
"@budgetbuddyde/types": "^1.0.21",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.14.15",
Expand Down
1 change: 0 additions & 1 deletion src/components/Base/Charts/ApexPieChart.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export const ApexPieChart: React.FC<TApexPieChartProps> = ({data, ...props}) =>
},
},
labels: data.map(({label}) => label),

dataLabels: {
// @ts-ignore
formatter(val, opts) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {BarChart, Card, StyledAutocompleteOption, type TBarChartData} from '@/co
import {ArrowRightRounded} from '@mui/icons-material';
import {Autocomplete, TextField, Button, Box, Skeleton, Paper, Typography} from '@mui/material';
import {useFetchCategories} from '..';
import {TCategory} from '@budgetbuddyde/types';
import {type TCategory} from '@budgetbuddyde/types';
import {ParentSize} from '@visx/responsive';
import {useFetchTransactions} from '@/components/Transaction';
import {format, isBefore, isSameMonth, isSameYear} from 'date-fns';
Expand Down
7 changes: 6 additions & 1 deletion src/components/Category/Chart/IncomeChart.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ export const CategoryIncomeChart: React.FC<TCategoryIncomeChartProps> = () => {
</ParentSize>
</Box>
) : (
<NoResults sx={{mt: 2}} />
<NoResults
sx={{m: 2}}
text={
chart === 'MONTH' ? 'There are no transactions for this month!' : "You haven't receive any income yet!"
}
/>
)}
</Card.Body>
</Card>
Expand Down
24 changes: 21 additions & 3 deletions src/components/Category/Chip.component.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import React from 'react';
import {Chip, type ChipProps} from '@mui/material';
import {Chip, Tooltip, type ChipProps} from '@mui/material';
import type {TCategory} from '@budgetbuddyde/types';
import {useFilterStore} from '../Filter';
import {useTransactionStore} from '../Transaction';

export type TCategoryChipProps = ChipProps & {category: TCategory};
export type TCategoryChipProps = ChipProps & {category: TCategory; showUsage?: boolean};

export const CategoryChip: React.FC<TCategoryChipProps> = ({category, ...otherProps}) => {
export const CategoryChip: React.FC<TCategoryChipProps> = ({category, showUsage = false, ...otherProps}) => {
const {filters, setFilters} = useFilterStore();
const {categoryUsage} = useTransactionStore();

const handleChipClick = () => {
if (!filters.categories) {
Expand All @@ -30,6 +32,22 @@ export const CategoryChip: React.FC<TCategoryChipProps> = ({category, ...otherPr
});
};

if (showUsage) {
return (
<Tooltip
title={`Used ${categoryUsage.has(category.id) ? categoryUsage.get(category.id) : 0} times`}
placement="top"
arrow>
<Chip
onClick={handleChipClick}
onDelete={filters.categories && filters.categories.includes(category.id) ? handleChipDelete : undefined}
label={category.name}
variant="outlined"
{...otherProps}
/>
</Tooltip>
);
}
return (
<Chip
onClick={handleChipClick}
Expand Down
48 changes: 48 additions & 0 deletions src/components/Download/DownloadButton.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React from 'react';
import {Button, Tooltip, type ButtonProps} from '@mui/material';
import {useSnackbarContext} from '@/components/Snackbar';

export type TDownloadButtonProps = ButtonProps & {
exportFormat: /*'CSV' |*/ 'JSON';
exportFileName: string;
data: object;
withTooltip?: boolean;
};

export const DownloadButton: React.FC<TDownloadButtonProps> = ({
exportFormat,
exportFileName,
data,
...buttonProps
}) => {
const {showSnackbar} = useSnackbarContext();
const downloadBtnRef = React.useRef<HTMLAnchorElement | null>(null);

const downloadContent = () => {
if (!downloadBtnRef.current)
return showSnackbar({
message: 'Download button not found',
action: <Button onClick={downloadContent}>Retry</Button>,
});
downloadBtnRef.current.setAttribute(
'href',
`data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(data, null, 2))}`,
);
downloadBtnRef.current?.setAttribute('download', `${exportFileName}.${exportFormat.toLowerCase()}`);
downloadBtnRef.current.click();
showSnackbar({message: 'Download started'});
};

return (
<React.Fragment>
{buttonProps.withTooltip ? (
<Tooltip title={`Download as ${exportFormat}`}>
<Button {...buttonProps} onClick={downloadContent} />
</Tooltip>
) : (
<Button {...buttonProps} onClick={downloadContent} />
)}
<a aria-hidden ref={downloadBtnRef} />
</React.Fragment>
);
};
1 change: 1 addition & 0 deletions src/components/Download/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './DownloadButton.component';
30 changes: 27 additions & 3 deletions src/components/PaymentMethod/Chip.component.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import React from 'react';
import {Chip, type ChipProps} from '@mui/material';
import {Chip, Tooltip, type ChipProps} from '@mui/material';
import type {TPaymentMethod} from '@budgetbuddyde/types';
import {useFilterStore} from '../Filter';
import {useTransactionStore} from '../Transaction';

export type TPaymentMethodChipProps = ChipProps & {paymentMethod: TPaymentMethod};
export type TPaymentMethodChipProps = ChipProps & {paymentMethod: TPaymentMethod; showUsage?: boolean};

export const PaymentMethodChip: React.FC<TPaymentMethodChipProps> = ({paymentMethod, ...otherProps}) => {
export const PaymentMethodChip: React.FC<TPaymentMethodChipProps> = ({
paymentMethod,
showUsage = false,
...otherProps
}) => {
const {filters, setFilters} = useFilterStore();
const {paymentMethodUsage} = useTransactionStore();

const handleChipClick = () => {
if (!filters.paymentMethods) {
Expand All @@ -30,6 +36,24 @@ export const PaymentMethodChip: React.FC<TPaymentMethodChipProps> = ({paymentMet
});
};

if (showUsage) {
return (
<Tooltip
title={`Used ${paymentMethodUsage.has(paymentMethod.id) ? paymentMethodUsage.get(paymentMethod.id) : 0} times`}
placement="top"
arrow>
<Chip
onClick={handleChipClick}
onDelete={
filters.paymentMethods && filters.paymentMethods.includes(paymentMethod.id) ? handleChipDelete : undefined
}
label={paymentMethod.name}
variant="outlined"
{...otherProps}
/>
</Tooltip>
);
}
return (
<Chip
onClick={handleChipClick}
Expand Down
41 changes: 41 additions & 0 deletions src/components/Transaction/Transaction.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {type IAuthContext} from '../Auth';
import {type TDashboardStats} from '@/components/DashboardStatsWrapper.component';
import {FileService} from '@/services/File.service';
import {isRunningInProdEnv} from '@/utils/isRunningInProdEnv.util';
import {type ITransactionStore} from './Transaction.store';

/**
* Service for managing transactions.
Expand Down Expand Up @@ -338,4 +339,44 @@ export class TransactionService {
fileUrl: FileService.getFileUrl(file, user),
};
}

/**
* Calculates the usage per category based on the provided transactions.
* @param transactions - An array of transactions.
* @returns A map containing the usage count per category ID.
*/
static calculateUsagePerCategory(transactions: TTransaction[]): ITransactionStore['categoryUsage'] {
const usage: ITransactionStore['categoryUsage'] = new Map();
for (const {
category: {id},
} of transactions) {
if (usage.has(id)) {
usage.set(id, (usage.get(id) as number) + 1);
} else {
usage.set(id, 1);
}
}
console.log('categoryUsage', usage);
return usage;
}

/**
* Calculates the usage per payment-method based on the provided transactions.
* @param transactions - An array of transactions.
* @returns A map containing the usage count per payment-method ID.
*/
static calculateUsagePerPaymentMethod(transactions: TTransaction[]): ITransactionStore['paymentMethodUsage'] {
const usage: ITransactionStore['paymentMethodUsage'] = new Map();
for (const {
paymentMethod: {id},
} of transactions) {
if (usage.has(id)) {
usage.set(id, (usage.get(id) as number) + 1);
} else {
usage.set(id, 1);
}
}
console.log('paymentMethodUsage', usage);
return usage;
}
}
22 changes: 18 additions & 4 deletions src/components/Transaction/Transaction.store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {create} from 'zustand';
import type {TTransaction, TUser} from '@budgetbuddyde/types';
import type {TCategory, TPaymentMethod, TTransaction, TUser} from '@budgetbuddyde/types';
import {TransactionService} from './Transaction.service';

export interface IBaseStore<T> {
data: T;
Expand All @@ -8,16 +9,29 @@ export interface IBaseStore<T> {
}

export interface ITransactionStore extends IBaseStore<TTransaction[]> {
categoryUsage: Map<TCategory['id'], number>;
paymentMethodUsage: Map<TPaymentMethod['id'], number>;
fetchedBy: TUser['uuid'] | null;
fetchedAt: Date | null;
setFetchedData: (data: TTransaction[], fetchedBy: TUser['uuid'] | null) => void;
}

export const useTransactionStore = create<ITransactionStore>(set => ({
data: [],
categoryUsage: new Map(),
paymentMethodUsage: new Map(),
fetchedBy: null,
fetchedAt: null,
set: data => set({data: data}),
setFetchedData: (data, fetchedBy) => set({data: data, fetchedBy: fetchedBy, fetchedAt: new Date()}),
clear: () => set({data: [], fetchedBy: null, fetchedAt: null}),
set: data => {
const categoryUsage = TransactionService.calculateUsagePerCategory(data);
const paymentMethodUsage = TransactionService.calculateUsagePerPaymentMethod(data);
set({data, categoryUsage, paymentMethodUsage});
},
setFetchedData: (data, fetchedBy) => {
const categoryUsage = TransactionService.calculateUsagePerCategory(data);
const paymentMethodUsage = TransactionService.calculateUsagePerPaymentMethod(data);
set({data, categoryUsage, paymentMethodUsage, fetchedBy: fetchedBy, fetchedAt: new Date()});
},
clear: () =>
set({data: [], categoryUsage: new Map(), paymentMethodUsage: new Map(), fetchedBy: null, fetchedAt: null}),
}));
11 changes: 10 additions & 1 deletion src/routes/Categories.route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import {useLocation, useNavigate} from 'react-router-dom';
import {SearchInput} from '@/components/Base/Search';
import {type ISelectionHandler} from '@/components/Base/Select';
import {ToggleFilterDrawerButton} from '@/components/Filter';
import {DownloadButton} from '@/components/Download';
import {format} from 'date-fns';

interface ICategoriesHandler {
onSearch: (keyword: string) => void;
Expand Down Expand Up @@ -153,7 +155,7 @@ export const Categories = () => {
/>
</TableCell>
<TableCell size={AppConfig.table.cellSize}>
<CategoryChip category={category} />
<CategoryChip category={category} showUsage />
</TableCell>
<TableCell sx={DescriptionTableCellStyle} size={AppConfig.table.cellSize}>
<Linkify>{category.description ?? 'No Description'}</Linkify>
Expand All @@ -179,6 +181,13 @@ export const Categories = () => {
<IconButton color="primary" onClick={() => handler.onCreateCategory()}>
<AddRounded fontSize="inherit" />
</IconButton>
<DownloadButton
data={categories}
exportFileName={`bb_categories_${format(new Date(), 'yyyy_mm_dd')}`}
exportFormat="JSON"
withTooltip>
Export
</DownloadButton>
</React.Fragment>
}
withSelection
Expand Down
18 changes: 1 addition & 17 deletions src/routes/Dashboard/Budget.view.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
import React from 'react';
import {BudgetList, BudgetProgressWrapper, StatsWrapper, useFetchBudgetProgress} from '@/components/Budget';
import {BudgetList, StatsWrapper} from '@/components/Budget';
import {CategorySpendingsChart, CategoryIncomeChart} from '@/components/Category';
import {Grid} from '@mui/material';
import {DailyTransactionChart} from '@/components/Transaction';
import {CircularProgress} from '@/components/Loading';
import {MonthlyBalanceChartCard, MonthlyBalanceWidget} from '@/components/Transaction/MonthlyBalance';

export const DATE_RANGE_INPUT_FORMAT = 'dd.MM';
export type TChartContentType = 'INCOME' | 'SPENDINGS';
export const ChartContentTypes = [
{type: 'INCOME' as TChartContentType, label: 'Income'},
{type: 'SPENDINGS' as TChartContentType, label: 'Spendings'},
];

export const BudgetView = () => {
const {budgetProgress, loading: loadingBudgetProgress} = useFetchBudgetProgress();

return (
<React.Fragment>
<Grid item xs={12} md={12} lg={5} xl={5}>
Expand All @@ -31,12 +21,6 @@ export const BudgetView = () => {

<Grid item xs={12} md={12} lg={12} xl={12}>
<BudgetList />

{loadingBudgetProgress ? (
<CircularProgress />
) : (
<BudgetProgressWrapper data={budgetProgress} cardProps={{sx: {mt: 2}}} />
)}
</Grid>

<Grid item xs={12} md={12} lg={6} xl={6}>
Expand Down
14 changes: 13 additions & 1 deletion src/routes/Dashboard/DashboardLayout.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import {Outlet, useLocation, useNavigate} from 'react-router-dom';
import {withAuthLayout} from '@/components/Auth/Layout';
import {useAuthContext} from '@/components/Auth';
import {ContentGrid} from '@/components/Layout';
import {type TDashboardView, DashboardViewMapping, DashboardViewDescriptionMapping} from './index';
import {
type TDashboardView,
DashboardViewMapping,
DashboardViewDescriptionMapping,
DashboardViewIconMapping,
} from './index';
import {ActionPaper} from '@/components/Base';

export type TDashboardLayoutProps = React.PropsWithChildren<{
Expand Down Expand Up @@ -34,6 +39,13 @@ const DashboardLayout: React.FC<TDashboardLayoutProps> = ({children, useOutletIn
exclusive>
{Object.entries(DashboardViewMapping).map(([path, view]: [string, TDashboardView]) => (
<ToggleButton key={path} value={path}>
{React.isValidElement(DashboardViewIconMapping[view]) &&
// @ts-expect-error
React.cloneElement(DashboardViewIconMapping[view], {
sx: {
mr: 0.5,
},
})}
{view.substring(0, 1).toUpperCase() + view.substring(1)}
</ToggleButton>
))}
Expand Down
Loading
Loading