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

fix(web): correct balance graph handling #154

Merged
merged 1 commit into from
Jan 12, 2023
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
101 changes: 60 additions & 41 deletions frontend/apps/web/src/components/accounts/BalanceHistoryGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
selectTransactionByIdMap,
} from "@abrechnung/redux";
import { fromISOString, toISODateString } from "@abrechnung/utils";
import { Box, Divider, Theme, Typography, useTheme } from "@mui/material";
import { Card, Box, Divider, Theme, Typography, useTheme } from "@mui/material";
import { PointMouseHandler, PointTooltipProps, ResponsiveLine, Serie } from "@nivo/line";
import { DateTime } from "luxon";
import React from "react";
Expand All @@ -22,7 +22,6 @@ interface Props {

export const BalanceHistoryGraph: React.FC<Props> = ({ groupId, accountId }) => {
const theme: Theme = useTheme();
const balanceHistory = useAppSelector((state) => selectAccountBalanceHistory({ state, groupId, accountId }));
const navigate = useNavigate();

const currencySymbol = useAppSelector((state) =>
Expand All @@ -34,36 +33,64 @@ export const BalanceHistoryGraph: React.FC<Props> = ({ groupId, accountId }) =>
const accountNameMap = useAppSelector((state) =>
selectAccountIdToNameMap({ state: selectAccountSlice(state), groupId })
);

const graphData: Serie[] = [
{
id: "positive",
data: balanceHistory.map((entry, index, arr) => {
const prevEntry = index > 0 ? arr[index - 1] : null;
const nextEntry = index < arr.length - 1 ? arr[index + 1] : null;
const { graphData, seriesColors, areaBaselineValue } = useAppSelector((state) => {
const balanceHistory = selectAccountBalanceHistory({ state, groupId, accountId });
const { hasNegativeEntries, hasPositiveEntries, max, min } = balanceHistory.reduce(
(acc, curr) => {
const neg = curr.balance < 0;
const pos = curr.balance >= 0;
return {
x: fromISOString(entry.date),
y:
entry.balance >= 0 ||
(prevEntry && prevEntry.balance >= 0) ||
(nextEntry && nextEntry.balance >= 0)
? entry.balance
: null,
changeOrigin: entry.changeOrigin,
hasNegativeEntries: acc.hasNegativeEntries || neg,
hasPositiveEntries: acc.hasPositiveEntries || pos,
max: Math.max(curr.balance, acc.max),
min: Math.min(curr.balance, acc.min),
};
}),
},
{
id: "negative",
data: balanceHistory.map((entry) => {
return {
},
{ hasNegativeEntries: false, hasPositiveEntries: false, max: -Infinity, min: Infinity }
);

const areaBaselineValue =
balanceHistory.length === 0 ? undefined : !hasNegativeEntries ? min : !hasPositiveEntries ? max : undefined;

const graphData: Serie[] = [];
let lastPoint = balanceHistory[0];
const makeSerie = (): Serie => {
return {
id: `serie-${graphData.length}`,
data: [],
};
};
let currentSeries = makeSerie();
for (const entry of balanceHistory) {
if (lastPoint === undefined) {
break;
}
const hasDifferentSign = Math.sign(lastPoint.balance) !== Math.sign(entry.balance);
currentSeries.data.push({
x: fromISOString(entry.date),
y: entry.balance,
changeOrigin: entry.changeOrigin,
});
if (hasDifferentSign) {
graphData.push(currentSeries);
currentSeries = makeSerie();
currentSeries.data.push({
x: fromISOString(entry.date),
y: entry.balance < 0 ? entry.balance : null,
y: entry.balance,
changeOrigin: entry.changeOrigin,
};
}),
},
];
});
}
lastPoint = entry;
}
graphData.push(currentSeries);
const seriesColors: string[] = graphData.map((serie) =>
serie.data[0].y >= 0 ? theme.palette.success.main : theme.palette.error.main
);

console.log(graphData);

return { graphData, seriesColors, areaBaselineValue };
});

const onClick: PointMouseHandler = (point, event) => {
const changeOrigin: BalanceChangeOrigin = (point.data as any).changeOrigin;
Expand All @@ -87,16 +114,7 @@ export const BalanceHistoryGraph: React.FC<Props> = ({ groupId, accountId }) =>
);

return (
<Box
sx={{
backgroundColor: theme.palette.background.paper,
borderColor: theme.palette.divider,
borderRadius: theme.shape.borderRadius,
borderWidth: "1px",
borderStyle: "solid",
padding: 2,
}}
>
<Card sx={{ padding: 2 }}>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<Typography variant="body1" component="span">
{DateTime.fromJSDate(point.data.x as Date).toISODate()}
Expand All @@ -121,23 +139,24 @@ export const BalanceHistoryGraph: React.FC<Props> = ({ groupId, accountId }) =>
{icon} {transactionMap[changeOrigin.id].name}
</Typography>
)}
</Box>
</Card>
);
};

return (
<div style={{ width: "100%", height: "300px" }}>
<ResponsiveLine
curve="stepAfter"
data={graphData}
margin={{ top: 50, right: 50, bottom: 50, left: 60 }}
xScale={{ type: "time", precision: "day", format: "native" }}
yScale={{ type: "linear", min: "auto", max: "auto" }}
colors={[theme.palette.success.main, theme.palette.error.main]}
colors={seriesColors}
areaBaselineValue={areaBaselineValue}
tooltip={renderTooltip}
onClick={onClick}
pointLabel={(p) => `${toISODateString(p.x as Date)}: ${p.y}`}
useMesh={true}
yFormat=">-.2f"
axisLeft={{
format: (value: number) => `${value.toFixed(2)} ${currencySymbol}`,
}}
Expand Down
7 changes: 4 additions & 3 deletions frontend/libs/core/src/lib/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
Account,
AccountBalanceMap,
Transaction,
ClearingAccount,
TransactionPosition,
ClearingShares,
TransactionBalanceEffect,
Expand Down Expand Up @@ -183,7 +184,7 @@ export interface BalanceHistoryEntry {

export const computeAccountBalanceHistory = (
accountId: number,
clearingAccounts: Account[],
clearingAccounts: ClearingAccount[],
balances: AccountBalanceMap,
transactions: Transaction[], // sorted after last change date
transactionBalanceEffects: { [k: number]: TransactionBalanceEffect }
Expand All @@ -198,7 +199,7 @@ export const computeAccountBalanceHistory = (
const a = balanceEffect[accountId];
if (a) {
balanceChanges.push({
date: transaction.lastChanged,
date: transaction.billedAt,
change: a.total,
changeOrigin: {
type: "transaction",
Expand All @@ -211,7 +212,7 @@ export const computeAccountBalanceHistory = (
for (const account of clearingAccounts) {
if (balances[account.id]?.clearingResolution[accountId] !== undefined) {
balanceChanges.push({
date: account.lastChanged,
date: account.dateInfo,
change: balances[account.id].clearingResolution[accountId],
changeOrigin: {
type: "clearing",
Expand Down
14 changes: 9 additions & 5 deletions frontend/libs/redux/src/lib/accounts/accountSlice.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Api } from "@abrechnung/api";
import { Account, AccountBase, AccountType } from "@abrechnung/types";
import { Account, AccountBase, AccountType, PersonalAccount, ClearingAccount } from "@abrechnung/types";
import { createAsyncThunk, createSlice, PayloadAction, Draft } from "@reduxjs/toolkit";
import { AccountSliceState, AccountState, ENABLE_OFFLINE_MODE, IRootState, StateStatus } from "../types";
import { getGroupScopedState } from "../utils";
Expand Down Expand Up @@ -108,14 +108,18 @@ export const selectAccountsFilteredCount = memoize(
}
);

export const selectGroupAccountsFilteredInternal = (args: {
type NarrowedAccount<AccountTypeT extends AccountType> = AccountTypeT extends "personal"
? PersonalAccount
: ClearingAccount;

export const selectGroupAccountsFilteredInternal = <AccountTypeT extends AccountType>(args: {
state: AccountSliceState;
groupId: number;
type: AccountType;
}): Account[] => {
type: AccountTypeT;
}): NarrowedAccount<AccountTypeT>[] => {
const { state, groupId, type } = args;
const accounts = selectGroupAccountsInternal({ state, groupId });
return accounts.filter((acc: Account) => acc.type === type);
return accounts.filter((acc: Account) => acc.type === type) as NarrowedAccount<AccountTypeT>[];
};

export const selectSortedAccounts = memoize(
Expand Down