11 Commits

23 changed files with 621 additions and 511 deletions

View File

@@ -16,26 +16,23 @@ export interface DashboardState {
comparison: boolean; comparison: boolean;
} }
export interface DashboardStateSetters {
setSelectedPeriodId: (id: DashboardSelectedPeriodId) => void;
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
toggleFlow: () => void;
togglePeriodType: () => void;
toggleComparison: () => void;
}
export interface DashboardSection { export interface DashboardSection {
id: string; id: string;
title: string; title?: string;
component: React.ComponentType<any>;
summary?: string; summary?: string;
component: React.ComponentType<any>;
settings?: Record<string, any>; settings?: Record<string, any>;
isList?: boolean;
style?: {
size?: number;
[key: string]: any;
};
} }
export interface ColorDefinition { export interface ColorDefinition {
primary: string; primary: string;
background: string; background?: string;
text: string; text?: string;
} }
export interface ThemeAwarePalette { export interface ThemeAwarePalette {
@@ -45,29 +42,14 @@ export interface ThemeAwarePalette {
export interface DashboardConfig { export interface DashboardConfig {
sections: DashboardSection[]; sections: DashboardSection[];
style: { style?: {
palette: Record<DashboardFlow, ThemeAwarePalette>; palette?: Record<DashboardFlow, ThemeAwarePalette>;
}; };
} }
export interface DashboardProps { export interface DashboardProps {
config: DashboardConfig; config: DashboardConfig;
data: ReportData; data: ReportData;
isFetching: boolean; isFetching?: boolean;
onFlowChange?: (state: DashboardState) => void; onFlowChange?: (state: DashboardState) => void;
} }
export interface ComponentProps extends DashboardSection {
reportData: ReportData;
state: DashboardState;
stateSetters: DashboardStateSetters;
isFetching: boolean;
colorScheme: {
primary: string;
light: string;
text: string;
};
}

View File

@@ -1,24 +1,8 @@
import * as React from "react"; import * as React from "react";
import { import DashboardView from "./Dashboard.view";
Box, import { DashboardProps, DashboardState } from "./Dashboard.models";
Container,
Grid,
ToggleButton,
ToggleButtonGroup,
Button
} from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles";
import { DashboardProps, DashboardState, DashboardStateSetters, DashboardFlow } from "./Dashboard.models";
export default function Dashboard({
config,
data,
isFetching,
onFlowChange,
}: DashboardProps) {
const theme = useTheme();
const themeMode = theme.palette.mode;
export default function Dashboard(props: DashboardProps) {
const [state, setState] = React.useState<DashboardState>({ const [state, setState] = React.useState<DashboardState>({
flow: "outflows", flow: "outflows",
periodType: "rolling", periodType: "rolling",
@@ -27,36 +11,20 @@ export default function Dashboard({
comparison: false, comparison: false,
}); });
const toggleFlow = () => { const toggleFlow = (
setState(prev => { event: React.MouseEvent<HTMLElement>,
const nextFlow: DashboardFlow = prev.flow === "outflows" ? "inflows" : "outflows"; newFlow: "outflows" | "inflows" | null
const nextState: DashboardState = {
...prev,
flow: nextFlow,
selectedGroupKey: null,
selectedPeriodId: null,
};
onFlowChange?.(nextState);
return nextState;
});
};
const handleFlowChange = (
_event: React.MouseEvent<HTMLElement>,
newFlow: DashboardFlow | null
) => { ) => {
if (newFlow !== null && newFlow !== state.flow) { if (newFlow === null) return;
setState(prev => { setState(prev => {
const nextState: DashboardState = { if (prev.flow === newFlow) return prev;
...prev,
flow: newFlow, const next = { ...prev, flow: newFlow };
selectedGroupKey: null, props.onFlowChange?.(next);
selectedPeriodId: null,
}; return next;
onFlowChange?.(nextState);
return nextState;
}); });
}
}; };
const togglePeriodType = () => { const togglePeriodType = () => {
@@ -81,122 +49,16 @@ export default function Dashboard({
setState(prev => ({ ...prev, selectedGroupKey: groupKey })); setState(prev => ({ ...prev, selectedGroupKey: groupKey }));
}; };
const stateSetters: DashboardStateSetters = {
togglePeriodType,
toggleComparison,
toggleFlow,
setSelectedPeriodId,
setSelectedGroupKey,
};
const { flow, selectedGroupKey } = state;
const colors = React.useMemo(() => {
const palette = config.style.palette[flow];
const modeColors = palette[themeMode];
return {
primary: modeColors.primary,
light: modeColors.background || alpha(modeColors.primary, 0.1),
text:
modeColors.text ||
(themeMode === "light" ? theme.palette.text.primary : "#fff"),
};
// if (modeColors) {
// return {
// primary: modeColors.primary,
// light: modeColors.background || alpha(modeColors.primary, 0.1),
// text:
// modeColors.text ||
// (themeMode === "light" ? theme.palette.text.primary : "#fff"),
// };
// }
//
// const themeColor =
// flow === "outflows" ? theme.palette.error : theme.palette.success;
//
// return {
// primary: themeColor.main,
// light: alpha(themeColor.main, themeMode === "light" ? 0.08 : 0.15),
// text: themeColor.main,
// };
}, [config.style?.palette, flow, themeMode, theme.palette]);
return ( return (
<Container <DashboardView
sx={{ {...props}
mt: 4,
mb: 4,
background: `linear-gradient(180deg, ${colors.light} 0%, transparent 100%)`,
borderRadius: 4,
p: 2,
transition: "background 0.3s ease",
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
mb: 3,
}}
>
<ToggleButtonGroup
value={flow}
exclusive
onChange={handleFlowChange}
sx={{
borderRadius: 3,
overflow: "hidden",
"& .MuiToggleButton-root": {
px: 3,
textTransform: "none",
color: "text.secondary",
},
"&.Mui-selected": {
bgcolor: colors.primary,
color: "white",
borderColor: colors.primary,
},
}}
>
<ToggleButton value="outflows">Outflows</ToggleButton>
<ToggleButton value="inflows">Inflows</ToggleButton>
</ToggleButtonGroup>
{selectedGroupKey && Object.keys(selectedGroupKey).length > 0 && (
<Button
size="small"
sx={{ mt: 1, textTransform: "none" }}
onClick={() => setSelectedGroupKey(null)}
>
Clear Drill-down
</Button>
)}
</Box>
<Grid container spacing={4}>
{config.sections.map((section) => {
const Component = section.component;
return (
<Grid key={section.id} size={12}>
<Component
{...section}
reportData={data}
state={state} state={state}
stateSetters={stateSetters} setState={setState}
isFetching={isFetching} toggleFlow={toggleFlow}
togglePeriodType={togglePeriodType}
colorScheme={colors} toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId}
setSelectedGroupKey={setSelectedGroupKey}
/> />
</Grid>
);
})}
</Grid>
</Container>
); );
} }

View File

@@ -0,0 +1,143 @@
import * as React from "react";
import {
Box,
Container,
Grid,
Typography,
ToggleButton,
ToggleButtonGroup,
Button
} from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles";
import { GroupKey } from "../../features/report";
import { DashboardProps, DashboardState } from "./Dashboard.models";
interface ViewProps extends DashboardProps {
state: DashboardState;
setState: React.Dispatch<React.SetStateAction<DashboardState>>;
toggleFlow: (event: React.MouseEvent<HTMLElement>, newFlow: "outflows" | "inflows" | null) => void;
togglePeriodType: () => void;
setSelectedPeriodId: (id: string | null) => void;
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
toggleComparison: () => void;
}
export default function DashboardView({
config,
data,
state,
setState,
toggleFlow,
togglePeriodType,
toggleComparison,
setSelectedPeriodId,
setSelectedGroupKey,
}: ViewProps) {
const theme = useTheme();
const themeMode = theme.palette.mode;
const { flow, periodType, comparison, selectedPeriodId, selectedGroupKey } = state;
// Resolve colors with fallbacks
const colors = React.useMemo(() => {
const palette = config.style?.palette?.[flow];
const modeColors = palette ? palette[themeMode] : null;
if (modeColors) {
return {
primary: modeColors.primary,
light: modeColors.background || alpha(modeColors.primary, 0.1),
text: modeColors.text || (themeMode === 'light' ? theme.palette.text.primary : '#fff')
};
}
// Fallback to standard theme colors
const themeColor = flow === 'outflows' ? theme.palette.error : theme.palette.success;
return {
primary: themeColor.main,
light: alpha(themeColor.main, themeMode === 'light' ? 0.08 : 0.15),
text: themeColor.main
};
}, [config.style?.palette, flow, themeMode, theme.palette]);
return (
<Container
sx={{
mt: 4,
mb: 4,
background: `linear-gradient(180deg, ${colors.light} 0%, transparent 100%)`,
borderRadius: 4,
p: 2,
transition: 'background 0.3s ease'
}}
>
<Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", mb: 3 }}>
<ToggleButtonGroup
value={flow}
exclusive
onChange={toggleFlow}
sx={{
borderRadius: 3,
overflow: "hidden",
"& .MuiToggleButton-root": {
px: 3,
textTransform: "none",
color: "text.secondary"
},
"&.Mui-selected": {
bgcolor: colors.primary,
color: "white",
borderColor: colors.primary
},
}}
>
<ToggleButton value="outflows">Outflows</ToggleButton>
<ToggleButton value="inflows">Inflows</ToggleButton>
</ToggleButtonGroup>
{selectedGroupKey && Object.keys(selectedGroupKey).length > 0 && (
<Button
size="small"
sx={{ mt: 1, textTransform: "none" }}
onClick={() => setSelectedGroupKey(null)}
>
Clear Drill-down
</Button>
)}
</Box>
<Grid container spacing={4}>
{config.sections.map((section) => {
const Component = section.component;
return (
<Grid key={section.id} size={section.style?.size || 12 as any}>
<Component
{...section.settings}
header={section.title}
summary={section.summary}
reportData={data}
title={section.title}
accentColor={colors.primary}
colorScheme={colors}
// State management
flow={flow}
periodType={periodType}
comparison={comparison}
selectedPeriodId={selectedPeriodId}
selectedGroupKey={selectedGroupKey}
togglePeriodType={togglePeriodType}
toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId}
setSelectedGroupKey={setSelectedGroupKey}
isFetching={arguments[0].isFetching}
/>
</Grid>
);
})}
</Grid>
</Container>
);
}

View File

@@ -1,3 +1,10 @@
import {
DashboardFlow,
DashboardPeriodType,
DashboardSelectedPeriodId
} from "../Dashboard";
import { ReportData } from "../../features/report";
export interface _ChartDataPoint { export interface _ChartDataPoint {
id: string; id: string;
label: string; label: string;
@@ -8,3 +15,28 @@ export interface _ChartDataPoint {
export interface ChartDataPoint extends _ChartDataPoint { export interface ChartDataPoint extends _ChartDataPoint {
compare?: _ChartDataPoint; compare?: _ChartDataPoint;
} }
export interface HistoryChartProps {
header: string;
summary?: string;
tabs: string[];
reportData: ReportData;
colorScheme: {
primary: string;
light: string;
text: string;
};
flow: DashboardFlow;
periodType: DashboardPeriodType;
selectedPeriodId: DashboardSelectedPeriodId;
comparison: boolean;
togglePeriodType: () => void;
setSelectedPeriodId: (id: string | null) => void;
toggleComparison: () => void;
isFetching?: boolean;
}

View File

@@ -1,21 +0,0 @@
import * as React from "react";
import { ComponentProps } from "../Dashboard";
import { ChartDataPoint } from "./HistoryChart.models";
export interface HistoryChartProps extends ComponentProps {
settings: {
tabs: string[];
};
}
export interface HistoryChartViewProps extends HistoryChartProps {
activeTab: string;
setActiveTab: (v: string) => void;
currentData: ChartDataPoint[];
visibleData: ChartDataPoint[];
maxAmount: number;
visibleCount: number;
startIndex: number;
setStartIndex: React.Dispatch<React.SetStateAction<number>>;
activeDataKey: string;
}

View File

@@ -1,23 +1,18 @@
import * as React from "react"; import * as React from "react";
import { HistoryChartProps } from "./HistoryChart.models";
import HistoryChartView from "./HistoryChart.view"; import HistoryChartView from "./HistoryChart.view";
import { buildChartData, tabToKey } from "./HistoryChart.adapter"; import { buildChartData, tabToKey } from "./HistoryChart.adapter";
import { HistoryChartProps } from "./HistoryChart.props";
export default function HistoryChart(props: HistoryChartProps) { export default function HistoryChart(props: HistoryChartProps) {
const { const {
settings, tabs,
reportData, reportData,
state, flow,
stateSetters, comparison,
selectedPeriodId,
isFetching, setSelectedPeriodId
} = props; } = props;
const { flow, comparison, selectedPeriodId } = state;
const { setSelectedPeriodId } = stateSetters;
const { tabs } = settings;
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || ""); const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
const [startIndex, setStartIndex] = React.useState(0); const [startIndex, setStartIndex] = React.useState(0);

View File

@@ -11,21 +11,39 @@ import IconButton from "@mui/material/IconButton";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft"; import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight"; import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import { import {
HistoryChartViewProps, ChartDataPoint,
} from "./HistoryChart.props"; HistoryChartProps,
} from "./HistoryChart.models";
import { formatDisplay } from "./HistoryChart.utils"; import { formatDisplay } from "./HistoryChart.utils";
export default function HistoryChartView({ interface ViewProps extends HistoryChartProps {
title, activeTab: string;
setActiveTab: (v: string) => void;
currentData: ChartDataPoint[];
visibleData: ChartDataPoint[];
maxAmount: number;
visibleCount: number;
startIndex: number;
setStartIndex: React.Dispatch<React.SetStateAction<number>>;
activeDataKey: string;
}
export default function HistoryChartView(props: ViewProps) {
const {
header,
summary, summary,
settings, tabs,
state,
stateSetters,
isFetching,
colorScheme, colorScheme,
flow,
periodType,
selectedPeriodId,
comparison,
togglePeriodType,
setSelectedPeriodId,
toggleComparison,
activeTab, activeTab,
setActiveTab, setActiveTab,
currentData, currentData,
@@ -35,10 +53,7 @@ export default function HistoryChartView({
startIndex, startIndex,
setStartIndex, setStartIndex,
activeDataKey, activeDataKey,
}: HistoryChartViewProps) { } = props;
const { flow, periodType, selectedPeriodId, comparison } = state;
const { togglePeriodType, setSelectedPeriodId, toggleComparison } = stateSetters;
const theme = useTheme(); const theme = useTheme();
const isDark = theme.palette.mode === "dark"; const isDark = theme.palette.mode === "dark";
@@ -77,13 +92,13 @@ export default function HistoryChartView({
border: "1px solid", border: "1px solid",
borderColor: "divider", borderColor: "divider",
bgcolor: isDark ? "background.paper" : colorScheme.light, bgcolor: isDark ? "background.paper" : colorScheme.light,
opacity: isFetching ? 0.6 : 1, opacity: props.isFetching ? 0.6 : 1,
transition: "opacity 0.3s ease", transition: "opacity 0.3s ease",
pointerEvents: isFetching ? "none" : "auto", pointerEvents: props.isFetching ? "none" : "auto",
}} }}
> >
<Typography variant="h6" fontWeight={700} gutterBottom> <Typography variant="h6" fontWeight={700} gutterBottom>
{title} {header}
</Typography> </Typography>
{summary && ( {summary && (
@@ -93,7 +108,7 @@ export default function HistoryChartView({
)} )}
<ToggleButtonGroup value={activeTab} exclusive onChange={handleTabChange} fullWidth sx={{ mb: 4 }}> <ToggleButtonGroup value={activeTab} exclusive onChange={handleTabChange} fullWidth sx={{ mb: 4 }}>
{settings.tabs.map((tab) => ( {tabs.map((tab) => (
<ToggleButton key={tab} value={tab}> <ToggleButton key={tab} value={tab}>
{tab} {tab}
</ToggleButton> </ToggleButton>

View File

@@ -1,19 +1,67 @@
import { ReportData, GroupKey } from "../../features/report"; import { ReportData, Transaction, GroupKey } from "../../features/report";
import { import {
mergeBucketPeriods,
periodIdToKey,
formatCurrency, formatCurrency,
extractFilteredTransactions, filterBuckets,
} from "../report.helpers"; } from "../report.helpers";
import { LatestItem } from "./LatestItems.models"; import { LatestItem } from "./LatestItems.models";
// ─── Transaction extraction ─────────────────────────────────
function extractTransactions(
reportData: ReportData,
selectedPeriodId: string | null,
selectedGroupKey: GroupKey | null,
): Transaction[] {
// 1. Get raw transactions
let rawTxns: Transaction[] = [];
if (selectedPeriodId) {
const key = periodIdToKey(selectedPeriodId);
const periods = mergeBucketPeriods(reportData.buckets, key);
const selected = periods.find((p) => p.id === selectedPeriodId);
rawTxns = selected?.metric.transactions || [];
} else {
const periods = mergeBucketPeriods(reportData.buckets, "all");
if (periods.length > 0) {
rawTxns = periods[0].metric.transactions || [];
}
}
// 2. Filter by group key
if (selectedGroupKey) {
rawTxns = rawTxns.filter(txn => {
let match = true;
if (selectedGroupKey.tags && selectedGroupKey.tags.length > 0) {
if (!txn.tags) match = false;
else {
const txnTags = txn.tags.map(t => typeof t === "string" ? t : t.name);
if (!selectedGroupKey.tags.every(selectedTag => txnTags.includes(selectedTag))) match = false;
}
}
if (match && selectedGroupKey.payee && selectedGroupKey.payee.length > 0) {
if (!txn.payee || !txn.payee.name) match = false;
else {
if (!selectedGroupKey.payee.includes(txn.payee.name)) match = false;
}
}
return match;
});
}
return rawTxns;
}
// ─── Main adapter ──────────────────────────────────────────── // ─── Main adapter ────────────────────────────────────────────
export function buildLatestItems( export function buildLatestItems(
reportData: ReportData, reportData: ReportData,
selectedPeriodId: string | null | undefined, selectedPeriodId: string | null,
selectedGroupKey: GroupKey | null | undefined, selectedGroupKey: GroupKey | null,
flow: "outflows" | "inflows" flow: "outflows" | "inflows"
): LatestItem[] { ): LatestItem[] {
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey); const txns = extractTransactions(reportData, selectedPeriodId, selectedGroupKey);
return txns return txns
.sort( .sort(

View File

@@ -5,3 +5,12 @@ export interface LatestItem {
amount: string; amount: string;
timeAgo: string; timeAgo: string;
} }
export interface LatestItemsViewProps {
items: LatestItem[];
header: string;
accentColor: string;
canExpand: boolean;
onExpand: () => void;
isFetching?: boolean;
}

View File

@@ -1,10 +0,0 @@
import { ComponentProps } from "../Dashboard";
import { LatestItem } from "./LatestItems.models";
export interface LatestItemsProps extends ComponentProps {}
export interface LatestItemsViewProps extends LatestItemsProps {
items: LatestItem[];
canExpand: boolean;
onExpand: () => void;
}

View File

@@ -1,24 +1,29 @@
import * as React from "react"; import * as React from "react";
import { ReportData, GroupKey } from "../../features/report";
import { buildLatestItems } from "./LatestItems.adapter"; import { buildLatestItems } from "./LatestItems.adapter";
import LatestItemsView from "./LatestItems.view"; import LatestItemsView from "./LatestItems.view";
import { LatestItemsProps } from "./LatestItems.props";
export default function LatestItems(props: LatestItemsProps) { type Props = {
const { reportData: ReportData;
flow: "outflows" | "inflows";
header: string;
selectedPeriodId: string | null;
selectedGroupKey?: GroupKey | null;
accentColor: string;
isFetching?: boolean;
};
export default function LatestItems({
reportData, reportData,
state, flow,
stateSetters, header,
selectedPeriodId,
selectedGroupKey = null,
accentColor,
isFetching, isFetching,
} = props; }: Props) {
const { flow, selectedPeriodId, selectedGroupKey } = state;
const [visibleCount, setVisibleCount] = React.useState(5); const [visibleCount, setVisibleCount] = React.useState(5);
// Reset count when flow changes to start clean
React.useEffect(() => {
setVisibleCount(5);
}, [flow]);
const allItems = React.useMemo(() => { const allItems = React.useMemo(() => {
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, flow); return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, flow);
}, [reportData, selectedPeriodId, selectedGroupKey, flow]); }, [reportData, selectedPeriodId, selectedGroupKey, flow]);
@@ -31,9 +36,11 @@ export default function LatestItems(props: LatestItemsProps) {
return ( return (
<LatestItemsView <LatestItemsView
{...props}
items={visibleItems} items={visibleItems}
header={header}
accentColor={accentColor}
canExpand={canExpand} canExpand={canExpand}
isFetching={isFetching}
onExpand={() => setVisibleCount((prev) => prev + 5)} onExpand={() => setVisibleCount((prev) => prev + 5)}
/> />
); );

View File

@@ -10,23 +10,21 @@ import {
IconButton, IconButton,
} from "@mui/material"; } from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { LatestItemsViewProps } from "./LatestItems.props"; import { LatestItemsViewProps } from "./LatestItems.models";
export default function LatestItemsView({ export default function LatestItemsView({
items, items,
title, header,
accentColor,
canExpand, canExpand,
onExpand, onExpand,
isFetching, isFetching,
colorScheme,
}: LatestItemsViewProps) { }: LatestItemsViewProps) {
const accentColor = colorScheme?.primary || "";
return ( return (
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2, opacity: isFetching ? 0.6 : 1, transition: "opacity 0.3s ease", pointerEvents: isFetching ? "none" : "auto" }}> <Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2, opacity: isFetching ? 0.6 : 1, transition: "opacity 0.3s ease", pointerEvents: isFetching ? "none" : "auto" }}>
<Box sx={{ mb: 2, px: 2 }}> <Box sx={{ mb: 2, px: 2 }}>
<Typography variant="h6" fontWeight="bold"> <Typography variant="h6" fontWeight="bold">
{title} {header}
</Typography> </Typography>
</Box> </Box>

View File

@@ -0,0 +1,11 @@
export interface ProgressCardProps {
header: string;
summary?: string;
progressAmount: number;
totalAmount: number;
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
compact?: boolean;
selected?: boolean;
onClick?: () => void;
isFetching?: boolean;
}

View File

@@ -1,14 +0,0 @@
import { ComponentProps } from "../Dashboard";
export interface ProgressCardProps extends ComponentProps {
settings: {
compact: boolean;
};
}
export interface ProgressCardViewProps extends ProgressCardProps {
progressAmount: number;
totalAmount: number;
selected: boolean;
onClick: () => void;
}

View File

@@ -0,0 +1,25 @@
import * as React from "react";
import ProgressCardView from "./ProgressCard.view";
import { ProgressCardProps } from "./ProgressCard.models";
import { getPercentage, formatCurrency } from "../report.helpers";
export default function ProgressCard(props: ProgressCardProps) {
const { progressAmount, totalAmount, compact = false } = props;
const percentage = getPercentage(progressAmount, totalAmount);
const formattedProgress = formatCurrency(progressAmount);
const formattedTotal = formatCurrency(totalAmount);
return (
<ProgressCardView
{...props}
percentage={percentage}
formattedProgress={formattedProgress}
formattedTotal={formattedTotal}
compact={compact}
selected={props.selected}
onClick={props.onClick}
/>
);
}

View File

@@ -8,83 +8,93 @@ import {
linearProgressClasses linearProgressClasses
} from "@mui/material"; } from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles"; import { useTheme, alpha } from "@mui/material/styles";
import { getPercentage, formatCurrency } from "../report.helpers"; import { ProgressCardProps } from "./ProgressCard.models";
import { ProgressCardViewProps } from "./ProgressCard.props";
interface ViewProps extends ProgressCardProps {
percentage: number;
formattedProgress: string;
formattedTotal: string;
selected?: boolean;
onClick?: () => void;
}
export default function ProgressCardView({ export default function ProgressCardView({
title, header,
settings, colorTheme = "info",
percentage,
isFetching, formattedProgress,
formattedTotal,
colorScheme, compact = false,
progressAmount,
totalAmount,
selected, selected,
onClick, onClick,
}: ProgressCardViewProps) { }: ViewProps) {
const theme = useTheme(); const theme = useTheme();
const isDark = theme.palette.mode === "dark"; const isDark = theme.palette.mode === "dark";
const percentage = getPercentage(progressAmount, totalAmount);
const formattedProgress = formatCurrency(progressAmount);
const formattedTotal = formatCurrency(totalAmount);
return ( return (
<Paper <Paper
elevation={settings.compact ? 2 : 4} elevation={compact ? 2 : 4}
onClick={onClick} onClick={onClick}
sx={{ sx={{
width: "100%", width: "100%",
p: settings.compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 }, p: compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
borderRadius: settings.compact ? 3 : 4, borderRadius: compact ? 3 : 4,
cursor: onClick ? "pointer" : "default",
transform: selected ? "scale(1.02)" : "scale(1)", transform: selected ? "scale(1.02)" : "scale(1)",
transition: "transform 0.2s ease, box-shadow 0.2s ease", transition: "transform 0.2s ease, box-shadow 0.2s ease",
bgcolor: colorScheme.light, background: (theme) => {
color: colorScheme.text, const baseColor = theme.palette[colorTheme]?.main || theme.palette.primary.main;
const lightColor = theme.palette[colorTheme]?.light || theme.palette.primary.light;
return isDark
? `linear-gradient(135deg, ${alpha(baseColor, 0.9)} 0%, ${alpha(baseColor, 0.3)} 100%)`
: `linear-gradient(135deg, ${baseColor} 0%, ${lightColor} 100%)`;
},
color: "#fff",
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
alignItems: settings.compact ? "flex-start" : "center", alignItems: compact ? "flex-start" : "center",
justifyContent: "center", justifyContent: "center",
position: "relative", position: "relative",
overflow: "hidden", overflow: "hidden",
border: selected border: selected
? `2px solid ${colorScheme.primary}` ? `2px solid #fff`
: isDark : isDark ? "1px solid rgba(255,255,255,0.1)" : "none",
? "1px solid rgba(255,255,255,0.1)" boxShadow: (theme) => {
: "1px solid rgba(0,0,0,0.06)", const baseShadow = `0 ${compact ? 6 : 12}px ${compact ? 12 : 24}px -10px ${
boxShadow: "none", isDark
opacity: isFetching ? 0.6 : 1, ? "rgba(0,0,0,0.5)"
pointerEvents: isFetching ? "none" : "auto", : theme.palette[colorTheme]?.main || theme.palette.primary.main
}`;
return selected
? `${baseShadow}, 0 0 0 2px ${theme.palette.background.paper}, 0 0 0 4px ${theme.palette[colorTheme]?.main || theme.palette.primary.main}`
: baseShadow;
},
opacity: arguments[0].isFetching ? 0.6 : 1,
pointerEvents: arguments[0].isFetching ? "none" : "auto",
}} }}
> >
<Typography <Typography
variant={settings.compact ? "body2" : "subtitle1"} variant={compact ? "body2" : "subtitle1"}
fontWeight={700} fontWeight={700}
sx={{ sx={{
opacity: 0.95, opacity: 0.95,
mb: settings.compact ? 1.5 : 2, mb: compact ? 1.5 : 2,
width: "100%", width: '100%',
overflow: "hidden", overflow: 'hidden',
textOverflow: "ellipsis", textOverflow: 'ellipsis',
whiteSpace: "nowrap", whiteSpace: 'nowrap',
letterSpacing: 0.5, letterSpacing: 0.5,
textShadow: isDark ? "0 1px 2px rgba(0,0,0,0.3)" : "none", textShadow: isDark ? '0 1px 2px rgba(0,0,0,0.3)' : 'none'
}} }}
> >
{title} {header}
</Typography> </Typography>
<Box sx={{ mb: settings.compact ? 2 : 3, width: "100%" }}> <Box sx={{ mb: compact ? 2 : 3, width: '100%' }}>
<Typography <Typography
variant={settings.compact ? "h5" : "h3"} variant={compact ? "h5" : "h3"}
fontWeight={900} fontWeight={900}
sx={{ sx={{ mb: 0.5, lineHeight: 1.2, textShadow: isDark ? '0 2px 4px rgba(0,0,0,0.3)' : 'none' }}
mb: 0.5,
lineHeight: 1.2,
textShadow: isDark ? "0 2px 4px rgba(0,0,0,0.3)" : "none",
}}
> >
{formattedProgress} {formattedProgress}
</Typography> </Typography>
@@ -92,38 +102,38 @@ export default function ProgressCardView({
<Divider <Divider
sx={{ sx={{
my: 1, my: 1,
borderColor: isDark ? "rgba(255,255,255,0.15)" : "rgba(0,0,0,0.1)", borderColor: "rgba(255,255,255,0.25)",
width: "100%", width: "100%",
}} }}
/> />
<Typography <Typography
variant={settings.compact ? "caption" : "body2"} variant={compact ? "caption" : "body2"}
sx={{ sx={{
opacity: 0.85, opacity: 0.85,
fontWeight: 500, fontWeight: 500,
display: "block", display: "block",
color: alpha(colorScheme.text, 0.85), color: "rgba(255,255,255,0.9)"
}} }}
> >
of {formattedTotal} of {formattedTotal}
</Typography> </Typography>
</Box> </Box>
<Box sx={{ width: "100%", mt: "auto" }}> <Box sx={{ width: "100%", mt: 'auto' }}>
<LinearProgress <LinearProgress
variant="determinate" variant="determinate"
value={percentage} value={percentage}
sx={{ sx={{
height: settings.compact ? 6 : 10, height: compact ? 6 : 10,
borderRadius: 5, borderRadius: 5,
[`&.${linearProgressClasses.colorPrimary}`]: { [`&.${linearProgressClasses.colorPrimary}`]: {
backgroundColor: isDark ? "rgba(255, 255, 255, 0.12)" : "rgba(0, 0, 0, 0.08)", backgroundColor: "rgba(0, 0, 0, 0.25)",
}, },
[`& .${linearProgressClasses.bar}`]: { [`& .${linearProgressClasses.bar}`]: {
borderRadius: 5, borderRadius: 5,
backgroundColor: colorScheme.primary, backgroundColor: "#fff",
boxShadow: `0 0 8px ${alpha(colorScheme.primary, 0.4)}`, boxShadow: '0 0 8px rgba(255,255,255,0.4)'
}, },
}} }}
/> />

View File

@@ -1,8 +1,5 @@
import { mergeBucketPeriods, periodIdToKey } from "../report.helpers";
import { GroupKey, ReportData } from "../../features/report"; import { GroupKey, ReportData } from "../../features/report";
import {
extractFilteredTransactions,
aggregateTransactions,
} from "../report.helpers";
export interface PayeeItem { export interface PayeeItem {
name: string; name: string;
@@ -15,17 +12,54 @@ export function extractTopPayees(
selectedPeriodId?: string | null, selectedPeriodId?: string | null,
selectedGroupKey?: GroupKey | null selectedGroupKey?: GroupKey | null
): { items: PayeeItem[]; total: number } { ): { items: PayeeItem[]; total: number } {
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey); const payeeMap = new Map<string, number>();
const { items, total } = aggregateTransactions(txns, (txn) => { let targetPeriods = [];
if (txn.payee && txn.payee.name) {
return [txn.payee.name]; if (selectedPeriodId) {
const key = periodIdToKey(selectedPeriodId);
const periods = mergeBucketPeriods(reportData.buckets, key);
const selected = periods.find((p) => p.id === selectedPeriodId);
if (selected) {
targetPeriods.push(selected);
} }
return []; } else {
// If no specific period is selected, aggregate over the "all" period bucket
targetPeriods = mergeBucketPeriods(reportData.buckets, "all");
}
for (const p of targetPeriods) {
let txns = p.metric.transactions || [];
if (selectedGroupKey?.tags && selectedGroupKey.tags.length > 0) {
txns = txns.filter(txn => {
if (!txn.tags) return false;
const txnTags = txn.tags.map(t => typeof t === "string" ? t : t.name);
return selectedGroupKey.tags!.every(selectedTag => txnTags.includes(selectedTag));
}); });
}
for (const txn of txns) {
if (txn.payee && txn.payee.name) {
const current = payeeMap.get(txn.payee.name) || 0;
payeeMap.set(txn.payee.name, current + txn.amount);
}
}
}
let items: PayeeItem[] = [];
let total = 0;
for (const [name, amount] of payeeMap.entries()) {
items.push({ name, amount });
total += amount;
}
// Sort descending by amount
items.sort((a, b) => b.amount - a.amount);
return { return {
items, items: items.slice(0, 4), // Top 4
total, total,
}; };
} }

View File

@@ -1,22 +1,30 @@
import * as React from "react"; import * as React from "react";
import { Box, Paper, Typography } from "@mui/material"; import { Box, Paper, Typography } from "@mui/material";
import ProgressCardView from "./ProgressCard.view"; import { ReportData, GroupKey } from "../../features/report";
import ProgressCard from "./ProgressCard";
import { extractTopPayees } from "./TopPayees.adapter"; import { extractTopPayees } from "./TopPayees.adapter";
import { ProgressCardProps } from "./ProgressCard.props";
export default function TopPayees(props: ProgressCardProps) { type Props = {
const { reportData: ReportData;
title, flow: "outflows" | "inflows";
header: string;
selectedPeriodId?: string | null;
selectedGroupKey?: GroupKey | null;
setSelectedGroupKey?: (key: GroupKey | null) => void;
compact?: boolean;
isFetching?: boolean;
};
export default function TopPayees({
reportData, reportData,
state, flow,
stateSetters, header,
selectedPeriodId,
selectedGroupKey,
setSelectedGroupKey,
compact = true,
isFetching, isFetching,
} = props }: Props) {
const { flow, selectedPeriodId, selectedGroupKey } = state;
const { setSelectedGroupKey } = stateSetters;
const { items, total } = React.useMemo(() => { const { items, total } = React.useMemo(() => {
return extractTopPayees(reportData, flow, selectedPeriodId, selectedGroupKey); return extractTopPayees(reportData, flow, selectedPeriodId, selectedGroupKey);
}, [reportData, flow, selectedPeriodId, selectedGroupKey]); }, [reportData, flow, selectedPeriodId, selectedGroupKey]);
@@ -37,7 +45,7 @@ export default function TopPayees(props: ProgressCardProps) {
}} }}
> >
<Typography variant="h6" fontWeight={700} gutterBottom> <Typography variant="h6" fontWeight={700} gutterBottom>
{title} {header}
</Typography> </Typography>
<Box <Box
@@ -52,15 +60,17 @@ export default function TopPayees(props: ProgressCardProps) {
}} }}
> >
{items.map((item) => { {items.map((item) => {
const isSelected = !!selectedGroupKey?.payee?.includes(item.name); const isSelected = selectedGroupKey?.payee?.includes(item.name);
return ( return (
<ProgressCardView <ProgressCard
{...props}
key={item.name} key={item.name}
title={item.name} header={item.name}
progressAmount={item.amount} progressAmount={item.amount}
totalAmount={total} totalAmount={total}
compact={compact}
colorTheme={flow === "outflows" ? "error" : "success"}
selected={isSelected} selected={isSelected}
isFetching={isFetching}
onClick={() => { onClick={() => {
if (setSelectedGroupKey) { if (setSelectedGroupKey) {
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {}; let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};

View File

@@ -1,9 +1,11 @@
import { ReportData, GroupKey } from "../../features/report"; import { ReportData } from "../../features/report";
import { import {
extractFilteredTransactions, mergeBucketPeriods,
aggregateTransactions, periodIdToKey,
} from "../report.helpers"; } from "../report.helpers";
import { GroupKey } from "../../features/report";
export interface TagItem { export interface TagItem {
tag: string; tag: string;
amount: number; amount: number;
@@ -15,17 +17,55 @@ export function extractTopTags(
selectedPeriodId?: string | null, selectedPeriodId?: string | null,
selectedGroupKey?: GroupKey | null selectedGroupKey?: GroupKey | null
): { items: TagItem[]; total: number } { ): { items: TagItem[]; total: number } {
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey); const tagMap = new Map<string, number>();
const { items, total } = aggregateTransactions(txns, (txn) => { let periodKey: ReturnType<typeof periodIdToKey> = "all";
if (selectedPeriodId) {
periodKey = periodIdToKey(selectedPeriodId);
}
const periods = mergeBucketPeriods(reportData.buckets, periodKey);
let period = periods[0];
if (selectedPeriodId) {
period = periods.find(p => p.id === selectedPeriodId) || period;
} else if (periods.length > 0) {
period = periods.reduce((latest, p) =>
new Date(p.start).getTime() > new Date(latest.start).getTime()
? p
: latest
);
}
if (period && period.metric && period.metric.transactions) {
let txns = period.metric.transactions;
if (selectedGroupKey?.payee && selectedGroupKey.payee.length > 0) {
txns = txns.filter(txn =>
txn.payee?.name && selectedGroupKey.payee!.includes(txn.payee.name)
);
}
for (const txn of txns) {
if (txn.tags && txn.tags.length > 0) { if (txn.tags && txn.tags.length > 0) {
return txn.tags.map((t) => (typeof t === "string" ? t : t.name)); for (const tagObj of txn.tags) {
const tagName = typeof tagObj === "string" ? tagObj : tagObj.name;
tagMap.set(tagName, (tagMap.get(tagName) || 0) + txn.amount);
}
} else {
tagMap.set("Untagged", (tagMap.get("Untagged") || 0) + txn.amount);
}
}
} }
return ["Untagged"];
});
return { const arr = Array.from(tagMap.entries()).map(([tag, amount]) => ({
items: items.map((item) => ({ tag: item.name, amount: item.amount })), tag,
total, amount,
}; }));
arr.sort((a, b) => b.amount - a.amount);
const top = arr.slice(0, 4);
const total = top.reduce((sum, t) => sum + t.amount, 0);
return { items: top, total };
} }

View File

@@ -1,22 +1,30 @@
import * as React from "react"; import * as React from "react";
import { Box, Paper, Typography } from "@mui/material"; import { Box, Paper, Typography } from "@mui/material";
import ProgressCardView from "./ProgressCard.view"; import { ReportData, GroupKey } from "../../features/report";
import ProgressCard from "./ProgressCard";
import { extractTopTags } from "./TopTags.adapter"; import { extractTopTags } from "./TopTags.adapter";
import { ProgressCardProps } from "./ProgressCard.props";
export default function TopTags(props: ProgressCardProps) { type Props = {
const { reportData: ReportData;
title, flow: "outflows" | "inflows";
header: string;
selectedPeriodId?: string | null;
selectedGroupKey?: GroupKey | null;
setSelectedGroupKey?: (key: GroupKey | null) => void;
compact?: boolean;
isFetching?: boolean;
};
export default function TopTags({
reportData, reportData,
state, flow,
stateSetters, header,
selectedPeriodId,
selectedGroupKey,
setSelectedGroupKey,
compact = true,
isFetching, isFetching,
} = props }: Props) {
const { flow, selectedPeriodId, selectedGroupKey } = state;
const { setSelectedGroupKey } = stateSetters;
const { items, total } = React.useMemo(() => { const { items, total } = React.useMemo(() => {
return extractTopTags(reportData, flow, selectedPeriodId, selectedGroupKey); return extractTopTags(reportData, flow, selectedPeriodId, selectedGroupKey);
}, [reportData, flow, selectedPeriodId, selectedGroupKey]); }, [reportData, flow, selectedPeriodId, selectedGroupKey]);
@@ -37,7 +45,7 @@ export default function TopTags(props: ProgressCardProps) {
}} }}
> >
<Typography variant="h6" fontWeight={700} gutterBottom> <Typography variant="h6" fontWeight={700} gutterBottom>
{title} {header}
</Typography> </Typography>
<Box <Box
@@ -52,15 +60,17 @@ export default function TopTags(props: ProgressCardProps) {
}} }}
> >
{items.map((item) => { {items.map((item) => {
const isSelected = !!selectedGroupKey?.tags?.includes(item.tag); const isSelected = selectedGroupKey?.tags?.includes(item.tag);
return ( return (
<ProgressCardView <ProgressCard
{...props}
key={item.tag} key={item.tag}
title={item.tag} header={item.tag}
progressAmount={item.amount} progressAmount={item.amount}
totalAmount={total} totalAmount={total}
compact={compact}
colorTheme={flow === "outflows" ? "error" : "success"}
selected={isSelected} selected={isSelected}
isFetching={isFetching}
onClick={() => { onClick={() => {
if (setSelectedGroupKey) { if (setSelectedGroupKey) {
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {}; let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};

View File

@@ -1,2 +1,2 @@
export { default } from "./ProgressCard.view"; export { default } from "./ProgressCard";
export * from "./ProgressCard.props"; export * from "./ProgressCard.models";

View File

@@ -3,8 +3,6 @@ import {
ReportBucket, ReportBucket,
GroupKey, GroupKey,
PeriodType, PeriodType,
ReportData,
Transaction,
} from "../features/report"; } from "../features/report";
// ─── Types ──────────────────────────────────────────────────── // ─── Types ────────────────────────────────────────────────────
@@ -142,89 +140,3 @@ export function filterBuckets(
if (!selectedGroupKey) return buckets; if (!selectedGroupKey) return buckets;
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey)); return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
} }
export function extractFilteredTransactions(
reportData: ReportData,
selectedPeriodId: string | null | undefined,
selectedGroupKey: GroupKey | null | undefined
): Transaction[] {
let txns: Transaction[] = [];
if (selectedPeriodId) {
const key = periodIdToKey(selectedPeriodId);
const periods = mergeBucketPeriods(reportData.buckets, key);
const selected = periods.find((p) => p.id === selectedPeriodId);
txns = selected?.metric.transactions || [];
} else {
const periods = mergeBucketPeriods(reportData.buckets, "all");
if (periods.length > 0) {
const period = periods.reduce((latest, p) =>
new Date(p.start).getTime() > new Date(latest.start).getTime()
? p
: latest
, periods[0]);
txns = period?.metric.transactions || [];
}
}
if (selectedGroupKey) {
txns = txns.filter((txn) => {
let match = true;
if (selectedGroupKey.tags && selectedGroupKey.tags.length > 0) {
if (!txn.tags) {
match = false;
} else {
const txnTags = txn.tags.map((t: any) =>
typeof t === "string" ? t : t.name
);
if (
!selectedGroupKey.tags.every((selectedTag) =>
txnTags.includes(selectedTag)
)
) {
match = false;
}
}
}
if (match && selectedGroupKey.payee && selectedGroupKey.payee.length > 0) {
if (!txn.payee || !txn.payee.name) {
match = false;
} else {
if (!selectedGroupKey.payee.includes(txn.payee.name)) {
match = false;
}
}
}
return match;
});
}
return txns;
}
export function aggregateTransactions(
transactions: Transaction[],
keyExtractor: (txn: Transaction) => string[],
limit = 4
): { items: { name: string; amount: number }[]; total: number } {
const map = new Map<string, number>();
for (const txn of transactions) {
const keys = keyExtractor(txn);
for (const key of keys) {
map.set(key, (map.get(key) || 0) + txn.amount);
}
}
const items = Array.from(map.entries()).map(([name, amount]) => ({
name,
amount,
}));
items.sort((a, b) => b.amount - a.amount);
const top = items.slice(0, limit);
const total = top.reduce((sum, item) => sum + item.amount, 0);
return { items: top, total };
}

View File

@@ -14,6 +14,9 @@ export const configuration: DashboardConfig = {
settings: { settings: {
tabs: ["Weekly", "Monthly"], tabs: ["Weekly", "Monthly"],
}, },
style: {
size: 12,
},
}, },
{ {
id: "top-categories", id: "top-categories",
@@ -22,6 +25,9 @@ export const configuration: DashboardConfig = {
settings: { settings: {
compact: true, compact: true,
}, },
style: {
size: 12,
},
}, },
{ {
id: "top-payees", id: "top-payees",
@@ -30,11 +36,17 @@ export const configuration: DashboardConfig = {
settings: { settings: {
compact: true, compact: true,
}, },
style: {
size: 12,
},
}, },
{ {
id: "items", id: "items",
title: 'Recent Transactions', title: 'Recent Transactions',
component: LatestItems, component: LatestItems,
style: {
size: 12,
},
}, },
], ],
style: { style: {