Compare commits

..

31 Commits

Author SHA1 Message Date
7470da6d2d all period types 2026-05-05 13:26:35 +05:30
34594215f9 using new state management 2026-05-05 12:58:59 +05:30
0a92126b92 toggleComparison 2026-05-05 12:58:45 +05:30
30cf227050 state controlled by Dashboard.models.ts 2026-05-05 12:26:02 +05:30
a0e62b1bc4 fixes 2026-05-05 11:42:33 +05:30
ea3b451266 removed latest items for now 2026-05-05 11:42:27 +05:30
4b4875c3f5 removed latest items for now 2026-05-05 11:39:38 +05:30
25bd882b75 dashboard using report feature 2026-05-05 11:39:23 +05:30
f684083496 report models and prepareReport function 2026-05-05 11:39:07 +05:30
0e0928af95 report models and prepareReport function 2026-05-02 14:25:55 +05:30
7b0b3fb615 period selection 2026-05-01 17:40:54 +05:30
38f7416942 refactor period (rolling/calender) to periodType 2026-05-01 17:17:17 +05:30
e82cad4f21 refactor period (rolling/calender) to periodType 2026-05-01 17:15:16 +05:30
1daa90d091 refactor period (rolling/calender) to periodType 2026-05-01 17:13:13 +05:30
2d0b0bc470 fixes for correct comparison period 2026-05-01 17:07:35 +05:30
5f85abdf86 use full for fast loading than weekly for payee report 2026-05-01 16:59:56 +05:30
cc7e6509d2 theme changes 2026-04-25 13:47:42 +05:30
8a3ebdb1be better name 2026-04-25 13:22:49 +05:30
a36d9119bb configurable Dashboard.tsx 2026-04-25 13:21:34 +05:30
67d4c85146 fixes 2026-04-25 12:49:58 +05:30
89ad8e376e Progress Cards for Top Payees 2026-04-25 12:41:05 +05:30
71afc157ff proper use of react-openapi for resource api calls 2026-04-25 12:13:28 +05:30
5acbb7ccdd hiding report resource 2026-04-24 14:55:38 +05:30
3fd20f11ab hidden resource 2026-04-24 14:55:29 +05:30
922d05ae37 dashboard feature to use dashboard data 2026-04-24 14:41:19 +05:30
1fe44abfde removed client data massaging with backend report using feature/report 2026-04-24 14:27:20 +05:30
49bdb85088 refactored ProgressCard to component 2026-04-24 14:04:24 +05:30
b1509fd5ab refactored LatestItems to component 2026-04-24 14:01:49 +05:30
175ca64d1f refactored HistoryChart to component 2026-04-24 13:58:12 +05:30
c9e609fee6 header fixes 2026-04-11 11:23:06 +05:30
82264a5c34 color pallete 2026-04-07 13:47:55 +05:30
29 changed files with 654 additions and 871 deletions

View File

@@ -7,28 +7,6 @@ import { createApiClient } from "../../react-auth";
let _api: AxiosInstance | null = null; let _api: AxiosInstance | null = null;
let _auth: AxiosInstance | null = null; let _auth: AxiosInstance | null = null;
function withParamsSerializer(instance: AxiosInstance): AxiosInstance {
instance.defaults.paramsSerializer = {
serialize: (params) => {
const searchParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((v) => {
searchParams.append(key, String(v)); // NO []
});
} else if (value !== undefined && value !== null) {
searchParams.append(key, String(value));
}
});
return searchParams.toString();
},
};
return instance;
}
export const api = { export const api = {
get: (...args: Parameters<AxiosInstance["get"]>) => { get: (...args: Parameters<AxiosInstance["get"]>) => {
if (!_api) throw new Error("API client not initialized"); if (!_api) throw new Error("API client not initialized");
@@ -60,6 +38,6 @@ export const auth = {
}; };
export function initializeApiClients(baseUrl: string, authBaseUrl: string) { export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
_api = withParamsSerializer(createApiClient(baseUrl)); _api = createApiClient(baseUrl);
_auth = withParamsSerializer(createApiClient(authBaseUrl)); _auth = createApiClient(authBaseUrl);
} }

View File

@@ -8,22 +8,10 @@ import {
import ConfigurableDashboard from "./components/Dashboard"; import ConfigurableDashboard from "./components/Dashboard";
import { configuration } from "./dashboard-config"; import { configuration } from "./dashboard-config";
import { import { useDashboardData } from "./features/dashboard";
useReport,
prepareReport,
} from "./features/report";
export default function Dashboard() { export default function Dashboard() {
const report = useReport({ const { data, isLoading, error } = useDashboardData();
periods: ["weekly", "monthly", "full"],
rolling: true,
include_transactions: true,
group_by: ["tags"],
})
const isLoading = report.isLoading;
const error = report.error;
if (isLoading) { if (isLoading) {
return ( return (
@@ -41,11 +29,10 @@ export default function Dashboard() {
); );
} }
if (!report) { if (!data) {
return null; return null;
} }
const data = prepareReport(report.data?.data);
return ( return (
<ConfigurableDashboard <ConfigurableDashboard
config={configuration} config={configuration}

View File

@@ -1,8 +1,4 @@
import * as React from "react"; import * as React from "react";
import {
ReportData,
GroupKey,
} from "../../features/report";
export type DashboardMode = "expense" | "income"; export type DashboardMode = "expense" | "income";
export type DashboardPeriodType = "rolling" | "calendar"; export type DashboardPeriodType = "rolling" | "calendar";
@@ -12,7 +8,6 @@ export interface DashboardState {
mode: DashboardMode; mode: DashboardMode;
periodType: DashboardPeriodType; periodType: DashboardPeriodType;
selectedPeriodId: DashboardSelectedPeriodId; selectedPeriodId: DashboardSelectedPeriodId;
selectedGroupKey: GroupKey | null;
comparison: boolean; comparison: boolean;
} }
@@ -21,6 +16,7 @@ export interface DashboardSection {
title?: string; title?: string;
summary?: string; summary?: string;
component: React.ComponentType<any>; component: React.ComponentType<any>;
dataKey: string;
settings?: Record<string, any>; settings?: Record<string, any>;
isList?: boolean; isList?: boolean;
style?: { style?: {
@@ -49,5 +45,9 @@ export interface DashboardConfig {
export interface DashboardProps { export interface DashboardProps {
config: DashboardConfig; config: DashboardConfig;
data: ReportData; data: any;
toggleMode: () => void;
togglePeriodType: () => void;
setSelectedPeriodId: (id: string | null) => void;
toggleComparison: () => void;
} }

View File

@@ -7,7 +7,6 @@ export default function Dashboard(props: DashboardProps) {
mode: "expense", mode: "expense",
periodType: "rolling", periodType: "rolling",
selectedPeriodId: null, selectedPeriodId: null,
selectedGroupKey: null,
comparison: false, comparison: false,
}); });
@@ -36,10 +35,6 @@ export default function Dashboard(props: DashboardProps) {
setState(prev => ({ ...prev, selectedPeriodId })); setState(prev => ({ ...prev, selectedPeriodId }));
}; };
const setSelectedGroupKey = (groupKey: typeof state.selectedGroupKey) => {
setState(prev => ({ ...prev, selectedGroupKey: groupKey }));
};
return ( return (
<DashboardView <DashboardView
{...props} {...props}
@@ -49,7 +44,6 @@ export default function Dashboard(props: DashboardProps) {
togglePeriodType={togglePeriodType} togglePeriodType={togglePeriodType}
toggleComparison={toggleComparison} toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId} setSelectedPeriodId={setSelectedPeriodId}
setSelectedGroupKey={setSelectedGroupKey}
/> />
); );
} }

View File

@@ -8,17 +8,11 @@ import {
ToggleButtonGroup ToggleButtonGroup
} from "@mui/material"; } from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles"; import { useTheme, alpha } from "@mui/material/styles";
import { GroupKey } from "../../features/report";
import { DashboardProps, DashboardState } from "./Dashboard.models"; import { DashboardProps, DashboardState } from "./Dashboard.models";
interface ViewProps extends DashboardProps { interface ViewProps extends DashboardProps {
state: DashboardState; state: DashboardState;
setState: React.Dispatch<React.SetStateAction<DashboardState>>; setState: React.Dispatch<React.SetStateAction<DashboardState>>;
toggleMode: () => void;
togglePeriodType: () => void;
setSelectedPeriodId: (id: string | null) => void;
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
toggleComparison: () => void;
} }
export default function DashboardView({ export default function DashboardView({
@@ -30,11 +24,10 @@ export default function DashboardView({
togglePeriodType, togglePeriodType,
toggleComparison, toggleComparison,
setSelectedPeriodId, setSelectedPeriodId,
setSelectedGroupKey,
}: ViewProps) { }: ViewProps) {
const theme = useTheme(); const theme = useTheme();
const themeMode = theme.palette.mode; const themeMode = theme.palette.mode;
const { mode, periodType, comparison, selectedPeriodId, selectedGroupKey } = state; const { mode, periodType, comparison, selectedPeriodId } = state;
// Resolve colors with fallbacks // Resolve colors with fallbacks
const colors = React.useMemo(() => { const colors = React.useMemo(() => {
@@ -108,11 +101,47 @@ export default function DashboardView({
</Box> </Box>
)} )}
{section.isList ? (
<Box>
{section.title && (
<Box sx={{ mb: 2 }}>
<Typography variant="h6" fontWeight={700}>
{section.title}
</Typography>
</Box>
)}
<Grid container spacing={2}>
{(data[section.dataKey || ""] || []).map((item: any, idx: number) => (
<Grid key={idx} size={{ xs: 12, sm: 6, md: 2.4 }}>
<Component
{...section.settings}
header={item.payeeName || item.name}
progressAmount={item.amount}
totalAmount={data.totalAmount}
accentColor={colors.primary}
colorScheme={colors}
// State management
mode={mode}
periodType={periodType}
comparison={comparison}
selectedPeriodId={selectedPeriodId}
togglePeriodType={togglePeriodType}
toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId}
/>
</Grid>
))}
</Grid>
</Box>
) : (
<Component <Component
{...section.settings} {...section.settings}
header={section.title} header={section.title}
summary={section.summary} summary={section.summary}
reportData={data} data={data[mode][section.dataKey]}
title={section.title} title={section.title}
accentColor={colors.primary} accentColor={colors.primary}
colorScheme={colors} colorScheme={colors}
@@ -123,13 +152,12 @@ export default function DashboardView({
periodType={periodType} periodType={periodType}
comparison={comparison} comparison={comparison}
selectedPeriodId={selectedPeriodId} selectedPeriodId={selectedPeriodId}
selectedGroupKey={selectedGroupKey}
togglePeriodType={togglePeriodType} togglePeriodType={togglePeriodType}
toggleComparison={toggleComparison} toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId} setSelectedPeriodId={setSelectedPeriodId}
setSelectedGroupKey={setSelectedGroupKey}
/> />
)}
</Grid> </Grid>
); );
})} })}

View File

@@ -1,75 +0,0 @@
import { ReportData } from "../../features/report";
import {
mergeBucketPeriods,
getAmount,
PeriodKey,
} from "../report.helpers";
import { ChartDataPoint } from "./HistoryChart.models";
// ─── Tab → PeriodKey ─────────────────────────────────────────
const TAB_TO_KEY: Record<string, PeriodKey> = {
Weekly: "weekly",
Monthly: "monthly",
Yearly: "yearly",
"Financial Year": "fyly",
"All Time": "full",
};
export function tabToKey(tab: string): PeriodKey {
return TAB_TO_KEY[tab] ?? "full";
}
// ─── Comparison ──────────────────────────────────────────────
function attachComparison(
points: ChartDataPoint[],
key: PeriodKey
): ChartDataPoint[] {
const getCompareIndex = (i: number) => {
if (key === "weekly") return i - 4;
if (key === "monthly") return i - 12;
if (key === "yearly") return i - 1;
if (key === "fyly") return i - 1;
return -1;
};
return points.map((p, i) => {
const ci = getCompareIndex(i);
return {
...p,
compare:
ci >= 0 && points[ci]
? {
id: points[ci].id,
label: points[ci].label,
amount: points[ci].amount,
}
: undefined,
};
});
}
// ─── Main adapter ────────────────────────────────────────────
export function buildChartData(
reportData: ReportData,
key: PeriodKey,
mode: "expense" | "income",
comparison: boolean
): ChartDataPoint[] {
const merged = mergeBucketPeriods(reportData.buckets, key);
let points: ChartDataPoint[] = merged.map((p) => ({
id: p.id,
label: p.label,
amount: getAmount(p, mode),
}));
if (comparison) {
points = attachComparison(points, key);
}
return points;
}

View File

@@ -3,11 +3,9 @@ import {
DashboardPeriodType, DashboardPeriodType,
DashboardSelectedPeriodId DashboardSelectedPeriodId
} from "../Dashboard"; } from "../Dashboard";
import { ReportData } from "../../features/report";
export interface _ChartDataPoint { export interface _ChartDataPoint {
id: string; id: string;
label: string;
amount: number; amount: number;
highlighted?: boolean; highlighted?: boolean;
} }
@@ -16,19 +14,26 @@ export interface ChartDataPoint extends _ChartDataPoint {
compare?: _ChartDataPoint; compare?: _ChartDataPoint;
} }
export interface ChartData {
weekly?: Record<string, ChartDataPoint[]>;
monthly?: Record<string, ChartDataPoint[]>;
// yearly?: Record<string, ChartDataPoint[]>;
// fyly?: Record<string, ChartDataPoint[]>;
// full?: Record<string, ChartDataPoint[]>;
}
export interface HistoryChartProps { export interface HistoryChartProps {
header: string; header: string;
summary?: string; summary?: string;
tabs: string[]; tabs: string[];
data: ChartData;
reportData: ReportData;
colorScheme: { colorScheme: {
primary: string; primary: string;
light: string; light: string;
text: string; text: string;
}; };
// State management
mode: DashboardMode; mode: DashboardMode;
periodType: DashboardPeriodType; periodType: DashboardPeriodType;
selectedPeriodId: DashboardSelectedPeriodId; selectedPeriodId: DashboardSelectedPeriodId;

View File

@@ -1,80 +1,45 @@
import * as React from "react"; import * as React from "react";
import { HistoryChartProps } from "./HistoryChart.models"; import { ChartDataPoint, HistoryChartProps, ChartData } from "./HistoryChart.models";
import HistoryChartView from "./HistoryChart.view"; import HistoryChartView from "./HistoryChart.view";
import { buildChartData, tabToKey } from "./HistoryChart.adapter";
export default function HistoryChart(props: HistoryChartProps) { export default function HistoryChart(props: HistoryChartProps) {
const { const { tabs, data, mode, periodType, comparison } = props;
tabs,
reportData,
mode,
comparison,
selectedPeriodId,
setSelectedPeriodId
} = props;
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);
const activeDataKey = tabToKey(activeTab); const activeDataKey = activeTab.toLowerCase() as keyof ChartData;
const currentData = React.useMemo(() => { let rawData: ChartDataPoint[] = [];
return buildChartData(reportData, activeDataKey, mode, comparison);
}, [reportData, activeDataKey, mode, comparison]); const section = data[activeDataKey];
rawData = section?.[periodType] || [];
const currentData = rawData;
const maxAmount = const maxAmount =
currentData.length > 0 currentData.length > 0
? Math.max( ? Math.max(
...currentData.flatMap((d) => ...currentData.flatMap((d) =>
comparison comparison ? [d.amount, d.compare?.amount ?? 0] : [d.amount]
? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
: [d.amount]
), ),
1 1
) )
: 1; : 1;
const visibleCountMap = { const visibleCountMap = { daily: 7, weekly: 6, monthly: 4 };
weekly: 6, // const visibleCountMap = { daily: 7, weekly: 6, monthly: 4, yearly: 4, fyly: 4, full: 4 };
monthly: 4, const visibleCount = visibleCountMap[activeDataKey];
yearly: 4,
fyly: 4,
full: 4,
};
const visibleCount = visibleCountMap[activeDataKey] ?? 4;
const total = currentData.length; const total = currentData.length;
const clampedStartIndex = Math.min( const clampedStartIndex = Math.min(startIndex, Math.max(total - visibleCount, 0));
startIndex,
Math.max(total - visibleCount, 0)
);
React.useEffect(() => {
if (startIndex !== clampedStartIndex) {
setStartIndex(clampedStartIndex);
}
}, [startIndex, clampedStartIndex]);
const visibleData = currentData.slice( const visibleData = currentData.slice(
clampedStartIndex, clampedStartIndex,
clampedStartIndex + visibleCount clampedStartIndex + visibleCount
); );
React.useEffect(() => {
setSelectedPeriodId(null);
}, [activeTab]);
React.useEffect(() => {
if (
selectedPeriodId &&
!visibleData.some((p) => p.id === selectedPeriodId)
) {
setSelectedPeriodId(null);
}
}, [visibleData, selectedPeriodId]);
return ( return (
<HistoryChartView <HistoryChartView
{...props} {...props}
@@ -84,7 +49,7 @@ export default function HistoryChart(props: HistoryChartProps) {
visibleData={visibleData} visibleData={visibleData}
maxAmount={maxAmount} maxAmount={maxAmount}
visibleCount={visibleCount} visibleCount={visibleCount}
startIndex={clampedStartIndex} startIndex={startIndex}
setStartIndex={setStartIndex} setStartIndex={setStartIndex}
activeDataKey={activeDataKey} activeDataKey={activeDataKey}
/> />

View File

@@ -25,3 +25,19 @@ export const formatDisplay = (
return `${formatShort(base)} (${sign}${formatShort(Math.abs(diff))})`; return `${formatShort(base)} (${sign}${formatShort(Math.abs(diff))})`;
}; };
export const formatLabel = (label: string, type: string) => {
if (type === "monthly") return label;
if (type === "weekly") {
const parts = label.split(" - ");
if (parts.length === 2) {
const [start, end] = parts;
const startDay = start.split(" ")[0];
const [endDay, month] = end.split(" ");
return `${startDay}${endDay} ${month}`;
}
}
return label;
};

View File

@@ -14,7 +14,7 @@ import {
ChartDataPoint, ChartDataPoint,
HistoryChartProps, HistoryChartProps,
} from "./HistoryChart.models"; } from "./HistoryChart.models";
import { formatDisplay } from "./HistoryChart.utils"; import { formatDisplay, formatLabel } from "./HistoryChart.utils";
interface ViewProps extends HistoryChartProps { interface ViewProps extends HistoryChartProps {
activeTab: string; activeTab: string;
@@ -35,6 +35,7 @@ export default function HistoryChartView(props: ViewProps) {
tabs, tabs,
colorScheme, colorScheme,
// State management
mode, mode,
periodType, periodType,
selectedPeriodId, selectedPeriodId,
@@ -44,6 +45,7 @@ export default function HistoryChartView(props: ViewProps) {
setSelectedPeriodId, setSelectedPeriodId,
toggleComparison, toggleComparison,
// HistoryChart state management
activeTab, activeTab,
setActiveTab, setActiveTab,
currentData, currentData,
@@ -58,28 +60,19 @@ export default function HistoryChartView(props: ViewProps) {
const theme = useTheme(); const theme = useTheme();
const isDark = theme.palette.mode === "dark"; const isDark = theme.palette.mode === "dark";
const total = currentData.length;
const maxStartIndex = Math.max(total - visibleCount, 0);
const clampedStartIndex = Math.min(startIndex, maxStartIndex);
const handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => { const handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => {
if (newTab !== null) setActiveTab(newTab); if (newTab !== null) setActiveTab(newTab);
}; };
const canGoLeft = clampedStartIndex > 0; const canGoLeft = startIndex > 0;
const canGoRight = clampedStartIndex < maxStartIndex; const canGoRight = startIndex + visibleCount < currentData.length;
const handlePrev = () => { const handlePrev = () => {
if (!canGoLeft) return; if (canGoLeft) setStartIndex((prev) => prev - visibleCount);
setStartIndex((prev) => Math.max(prev - visibleCount, 0));
}; };
const handleNext = () => { const handleNext = () => {
if (!canGoRight) return; if (canGoRight) setStartIndex((prev) => prev + visibleCount);
setStartIndex((prev) => {
const next = prev + visibleCount;
return Math.min(next, maxStartIndex);
});
}; };
return ( return (
@@ -92,9 +85,10 @@ export default function HistoryChartView(props: ViewProps) {
border: "1px solid", border: "1px solid",
borderColor: "divider", borderColor: "divider",
bgcolor: isDark ? "background.paper" : colorScheme.light, bgcolor: isDark ? "background.paper" : colorScheme.light,
transition: 'background-color 0.3s ease, border-color 0.3s ease'
}} }}
> >
<Typography variant="h6" fontWeight={700} gutterBottom> <Typography variant="h6" fontWeight={700} gutterBottom sx={{ color: isDark ? 'text.primary' : colorScheme.text }}>
{header} {header}
</Typography> </Typography>
@@ -112,10 +106,12 @@ export default function HistoryChartView(props: ViewProps) {
))} ))}
</ToggleButtonGroup> </ToggleButtonGroup>
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}> <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", mb: 3 }}>
<ToggleButtonGroup value={periodType} exclusive onChange={togglePeriodType} size="small"> <ToggleButtonGroup value={periodType} exclusive onChange={togglePeriodType} size="small">
<ToggleButton value="rolling">Rolling</ToggleButton> <ToggleButton value="rolling">Rolling</ToggleButton>
<ToggleButton value="calendar">Calendar</ToggleButton> <ToggleButton value="calendar" disabled={activeDataKey === "daily"}>
Calendar
</ToggleButton>
</ToggleButtonGroup> </ToggleButtonGroup>
<ToggleButton <ToggleButton
@@ -123,6 +119,22 @@ export default function HistoryChartView(props: ViewProps) {
selected={comparison} selected={comparison}
onChange={toggleComparison} onChange={toggleComparison}
size="small" size="small"
sx={{
textTransform: "none",
borderRadius: 2,
px: 2,
color: "text.secondary",
border: "1px solid",
borderColor: "divider",
"&.Mui-selected": {
color: "white",
bgcolor: "success.main",
borderColor: "success.main"
},
"&.Mui-selected:hover": {
bgcolor: "success.dark"
}
}}
> >
Compare Compare
</ToggleButton> </ToggleButton>
@@ -131,7 +143,19 @@ export default function HistoryChartView(props: ViewProps) {
{currentData.length > 0 ? ( {currentData.length > 0 ? (
<Box sx={{ position: "relative", mt: 4 }}> <Box sx={{ position: "relative", mt: 4 }}>
{canGoLeft && ( {canGoLeft && (
<IconButton onClick={handlePrev} size="small" sx={{ position: "absolute", left: 0, top: "50%" }}> <IconButton
onClick={handlePrev}
size="small"
sx={{
position: "absolute",
left: 0,
top: "50%",
transform: "translateY(-50%)",
zIndex: 2,
bgcolor: "background.paper",
boxShadow: 1
}}
>
<ChevronLeftIcon fontSize="small" /> <ChevronLeftIcon fontSize="small" />
</IconButton> </IconButton>
)} )}
@@ -142,67 +166,92 @@ export default function HistoryChartView(props: ViewProps) {
const compareHeight = comparison const compareHeight = comparison
? ((point.compare?.amount ?? 0) / maxAmount) * 100 ? ((point.compare?.amount ?? 0) / maxAmount) * 100
: 0; : 0;
const labelHeight = Math.max(currentHeight, compareHeight);
const isSelected = selectedPeriodId === point.id; const isSelected = selectedPeriodId === point.id;
const display = formatDisplay(point, activeDataKey, comparison); const display = formatDisplay(point, activeTab.toLowerCase(), comparison);
return ( return (
<Box <Box
key={point.id} key={point.id}
onClick={() => onClick={() => setSelectedPeriodId(isSelected ? null : point.id)}
setSelectedPeriodId(isSelected ? null : point.id)
}
sx={{ sx={{
flex: 1, flex: 1,
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
alignItems: "center", alignItems: "center",
cursor: "pointer", justifyContent: "flex-end",
height: "100%" height: "100%",
cursor: "pointer"
}} }}
> >
<Box sx={{ display: "flex", alignItems: "flex-end", gap: 1, height: "100%" }}> <Box sx={{ display: "flex", alignItems: "flex-end", gap: comparison ? 1 : 0.5, height: "100%", position: "relative" }}>
{comparison && ( <Typography
<Box variant="caption"
sx={{ sx={{
width: 8, position: "absolute",
height: `${compareHeight}%`, bottom: `${labelHeight}%`,
bgcolor: alpha(colorScheme.primary, 0.4), left: "50%",
borderRadius: "4px 4px 0 0" transform: "translate(-50%, -6px)",
fontSize: "0.65rem",
whiteSpace: "nowrap",
pointerEvents: "none",
color: 'text.secondary',
fontWeight: 600
}} }}
/> >
{isSelected ? `SELECTED: ${display}` : display}
</Typography>
{comparison && (
<Box sx={{ width: 8, height: `${compareHeight}%`, bgcolor: isDark ? alpha(colorScheme.primary, 0.3) : alpha(colorScheme.primary, 0.4), borderRadius: '4px 4px 0 0' }} />
)} )}
<Box <Box
sx={{ sx={{
width: 12, width: comparison ? 10 : 16,
height: `${currentHeight}%`, height: `${currentHeight}%`,
bgcolor: isSelected ? "warning.main" : colorScheme.primary, bgcolor: point.highlighted ? colorScheme.primary : isDark ? alpha(colorScheme.primary, 0.8) : alpha(colorScheme.primary, 0.9),
borderRadius: "4px 4px 0 0" borderRadius: '4px 4px 0 0',
boxShadow: point.highlighted ? `0 0 10px ${alpha(colorScheme.primary, 0.5)}` : 'none'
}} }}
/> />
</Box> </Box>
<Typography variant="caption"> <Box sx={{ mt: 1.5, textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", lineHeight: 1.1 }}>
{point.label} <Typography variant="caption" sx={{ fontSize: "0.7rem", opacity: 0.8, color: 'text.primary', fontWeight: 500 }}>
{formatLabel(point.id, activeDataKey)}
</Typography> </Typography>
{comparison && point.compare && ( <Typography
<Typography variant="caption" color="text.secondary"> variant="caption"
{point.compare.label} sx={{
</Typography> fontSize: "0.65rem",
)} color: "text.disabled",
visibility: comparison && point.compare && activeDataKey !== "daily" ? "visible" : "hidden"
<Typography variant="caption"> }}
{display} >
{point.compare ? formatLabel(point.compare.id, activeDataKey) : "placeholder"}
</Typography> </Typography>
</Box> </Box>
</Box>
); );
})} })}
</Box> </Box>
{canGoRight && ( {canGoRight && (
<IconButton onClick={handleNext} size="small" sx={{ position: "absolute", right: 0, top: "50%" }}> <IconButton
onClick={handleNext}
size="small"
sx={{
position: "absolute",
right: 0,
top: "50%",
transform: "translateY(-50%)",
zIndex: 2,
bgcolor: "background.paper",
boxShadow: 1
}}
>
<ChevronRightIcon fontSize="small" /> <ChevronRightIcon fontSize="small" />
</IconButton> </IconButton>
)} )}

View File

@@ -1,66 +0,0 @@
import { ReportData, Transaction, GroupKey } from "../../features/report";
import {
mergeBucketPeriods,
periodIdToKey,
formatCurrency,
filterBuckets,
} from "../report.helpers";
import { LatestItem } from "./LatestItems.models";
// ─── Transaction extraction ─────────────────────────────────
function extractTransactions(
reportData: ReportData,
selectedPeriodId: string | null,
selectedGroupKey: GroupKey | null,
mode: "expense" | "income"
): Transaction[] {
const buckets = filterBuckets(reportData.buckets, selectedGroupKey);
if (selectedPeriodId) {
const key = periodIdToKey(selectedPeriodId);
const periods = mergeBucketPeriods(buckets, key);
const selected = periods.find((p) => p.id === selectedPeriodId);
if (!selected) return [];
return mode === "expense"
? (selected.expenses.transactions || [])
: (selected.incomes.transactions || []);
}
const periods = mergeBucketPeriods(buckets, "full");
if (!periods.length) return [];
const full = periods[0];
return mode === "expense"
? (full.expenses.transactions || [])
: (full.incomes.transactions || []);
}
// ─── Main adapter ────────────────────────────────────────────
export function buildLatestItems(
reportData: ReportData,
selectedPeriodId: string | null,
selectedGroupKey: GroupKey | null,
mode: "expense" | "income"
): LatestItem[] {
const txns = extractTransactions(reportData, selectedPeriodId, selectedGroupKey, mode);
return txns
.filter((t) => (mode === "expense" ? t.amount < 0 : t.amount >= 0))
.sort(
(a, b) =>
new Date(b.occurred_at).getTime() -
new Date(a.occurred_at).getTime()
)
.map((t, index) => ({
id: index + 1,
title: t.payee.name,
subtitle: t.tags.map((tag) => tag.name).join(", "),
amount: formatCurrency(t.amount),
timeAgo: new Date(t.occurred_at).toLocaleDateString("en-IN"),
}));
}

View File

@@ -1,14 +1,18 @@
import * as React from "react";
export interface LatestItem { export interface LatestItem {
id: string | number; id: string | number;
icon: React.ReactNode;
iconBgColor?: string;
title: string; title: string;
subtitle: string; subtitle: string;
amount: string; amount: string;
timeAgo: string; timeAgo: string;
} }
export interface LatestItemsViewProps { export interface LatestItemsListProps {
title?: string;
items: LatestItem[]; items: LatestItem[];
onViewAll?: () => void;
accentColor: string; accentColor: string;
canExpand: boolean;
onExpand: () => void;
} }

View File

@@ -1,44 +1,112 @@
import * as React from "react"; import * as React from "react";
import { ReportData, GroupKey } from "../../features/report"; import {
import { buildLatestItems } from "./LatestItems.adapter"; List,
import LatestItemsView from "./LatestItems.view"; ListItem,
ListItemAvatar,
ListItemText,
Avatar,
Typography,
Box,
Button,
} from "@mui/material";
type Props = { export interface LatestItem {
reportData: ReportData; id: string | number;
mode: "expense" | "income"; icon: React.ReactNode;
selectedPeriodId: string | null; iconBgColor?: string;
selectedGroupKey?: GroupKey | null; title: string;
accentColor: string; subtitle: string;
}; amount: string;
timeAgo: string;
}
export interface LatestItemsListProps {
title?: string;
items: LatestItem[];
onViewAll?: () => void;
accentColor: any;
}
export default function LatestItems({ export default function LatestItems({
reportData, title = "Recent Transactions",
mode, items,
selectedPeriodId, onViewAll,
selectedGroupKey = null,
accentColor, accentColor,
}: Props) { }: LatestItemsListProps) {
const [visibleCount, setVisibleCount] = React.useState(5);
const allItems = React.useMemo(() => {
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, mode);
}, [reportData, selectedPeriodId, selectedGroupKey, mode]);
const hasSelection = Boolean(selectedPeriodId) || Boolean(selectedGroupKey);
const visibleItems = React.useMemo(() => {
if (!hasSelection) return allItems.slice(0, 5);
return allItems.slice(0, visibleCount);
}, [allItems, hasSelection, visibleCount]);
const canExpand = hasSelection && visibleCount < allItems.length;
return ( return (
<LatestItemsView <Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
items={visibleItems} {/* Header */}
accentColor={accentColor} <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2, px: 2 }}>
canExpand={canExpand} <Typography variant="h6" fontWeight="bold">
onExpand={() => setVisibleCount((prev) => prev + 5)} {title}
</Typography>
{onViewAll && (
<Button
variant="text"
color="inherit"
size="small"
sx={{ textTransform: "none", color: "text.secondary", fontWeight: "medium" }}
onClick={onViewAll}
>
view all
</Button>
)}
</Box>
{/* List */}
<List disablePadding>
{items.map((item, index) => (
<ListItem
key={item.id}
sx={{
px: { xs: 1, sm: 2 },
py: 2,
mb: index !== items.length - 1 ? 1 : 0,
borderRadius: 3,
"&:hover": { bgcolor: "action.hover" },
transition: "background-color 0.2s ease",
}}
>
<ListItemAvatar>
<Avatar
variant="rounded"
sx={{
bgcolor: `${accentColor}22`,
color: "inherit",
width: 48,
height: 48,
borderRadius: 3,
mr: 2,
}}
>
{item.icon}
</Avatar>
</ListItemAvatar>
<ListItemText
primary={
<Typography variant="subtitle1" fontWeight={600} color="text.primary">
{item.title}
</Typography>
}
secondary={
<Typography variant="body2" color="text.secondary">
{item.subtitle}
</Typography>
}
/> />
<Box sx={{ textAlign: "right" }}>
<Typography variant="subtitle1" fontWeight={700} color="text.primary">
{item.amount}
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
{item.timeAgo}
</Typography>
</Box>
</ListItem>
))}
</List>
</Box>
); );
} }

View File

@@ -1,88 +1,6 @@
import * as React from "react"; import LatestItemsListView from "./LatestItems.view";
import { import { LatestItemsListProps } from "./LatestItems.models";
List,
ListItem,
ListItemAvatar,
ListItemText,
Avatar,
Typography,
Box,
IconButton,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { LatestItemsViewProps } from "./LatestItems.models";
export default function LatestItemsView({ export default function LatestItemsList(props: LatestItemsListProps) {
items, return <LatestItemsListView {...props} />;
accentColor,
canExpand,
onExpand,
}: LatestItemsViewProps) {
return (
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
<Box sx={{ mb: 2, px: 2 }}>
<Typography variant="h6" fontWeight="bold">
Recent Transactions
</Typography>
</Box>
<List disablePadding>
{items.map((item, index) => (
<ListItem
key={item.id}
sx={{
px: { xs: 1, sm: 2 },
py: 2,
mb: index !== items.length - 1 ? 1 : 0,
borderRadius: 3,
"&:hover": { bgcolor: "action.hover" },
}}
>
<ListItemAvatar>
<Avatar
variant="rounded"
sx={{
bgcolor: `${accentColor}22`,
width: 48,
height: 48,
borderRadius: 3,
mr: 2,
}}
/>
</ListItemAvatar>
<ListItemText
primary={
<Typography variant="subtitle1" fontWeight={600}>
{item.title}
</Typography>
}
secondary={
<Typography variant="body2" color="text.secondary">
{item.subtitle}
</Typography>
}
/>
<Box sx={{ textAlign: "right" }}>
<Typography variant="subtitle1" fontWeight={700}>
{item.amount}
</Typography>
<Typography variant="caption" color="text.secondary">
{item.timeAgo}
</Typography>
</Box>
</ListItem>
))}
{canExpand && (
<Box sx={{ display: "flex", justifyContent: "center", mt: 2 }}>
<IconButton size="small" onClick={onExpand}>
<ExpandMoreIcon />
</IconButton>
</Box>
)}
</List>
</Box>
);
} }

View File

@@ -5,6 +5,4 @@ export interface ProgressCardProps {
totalAmount: number; totalAmount: number;
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning"; colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
compact?: boolean; compact?: boolean;
selected?: boolean;
onClick?: () => void;
} }

View File

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

View File

@@ -0,0 +1,15 @@
export const getPercentage = (progressAmount: number, totalAmount: number) => {
if (!totalAmount) return 0;
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
};
export const formatCurrency = (val: number) => {
const absVal = Math.abs(val);
if (absVal >= 100000) {
return `${(val / 100000).toFixed(2)}L`;
}
if (absVal >= 1000) {
return `${(val / 1000).toFixed(2)}k`;
}
return `${val.toFixed(2)}`;
};

View File

@@ -14,8 +14,6 @@ interface ViewProps extends ProgressCardProps {
percentage: number; percentage: number;
formattedProgress: string; formattedProgress: string;
formattedTotal: string; formattedTotal: string;
selected?: boolean;
onClick?: () => void;
} }
export default function ProgressCardView({ export default function ProgressCardView({
@@ -25,8 +23,6 @@ export default function ProgressCardView({
formattedProgress, formattedProgress,
formattedTotal, formattedTotal,
compact = false, compact = false,
selected,
onClick,
}: ViewProps) { }: ViewProps) {
const theme = useTheme(); const theme = useTheme();
const isDark = theme.palette.mode === "dark"; const isDark = theme.palette.mode === "dark";
@@ -34,14 +30,10 @@ export default function ProgressCardView({
return ( return (
<Paper <Paper
elevation={compact ? 2 : 4} elevation={compact ? 2 : 4}
onClick={onClick}
sx={{ sx={{
width: "100%", width: "100%",
p: compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 }, p: compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
borderRadius: compact ? 3 : 4, borderRadius: compact ? 3 : 4,
cursor: onClick ? "pointer" : "default",
transform: selected ? "scale(1.02)" : "scale(1)",
transition: "transform 0.2s ease, box-shadow 0.2s ease",
background: (theme) => { background: (theme) => {
const baseColor = theme.palette[colorTheme]?.main || theme.palette.primary.main; const baseColor = theme.palette[colorTheme]?.main || theme.palette.primary.main;
const lightColor = theme.palette[colorTheme]?.light || theme.palette.primary.light; const lightColor = theme.palette[colorTheme]?.light || theme.palette.primary.light;
@@ -56,19 +48,13 @@ export default function ProgressCardView({
justifyContent: "center", justifyContent: "center",
position: "relative", position: "relative",
overflow: "hidden", overflow: "hidden",
border: selected border: isDark ? "1px solid rgba(255,255,255,0.1)" : "none",
? `2px solid #fff` boxShadow: (theme) =>
: isDark ? "1px solid rgba(255,255,255,0.1)" : "none", `0 ${compact ? 6 : 12}px ${compact ? 12 : 24}px -10px ${
boxShadow: (theme) => {
const baseShadow = `0 ${compact ? 6 : 12}px ${compact ? 12 : 24}px -10px ${
isDark isDark
? "rgba(0,0,0,0.5)" ? "rgba(0,0,0,0.5)"
: theme.palette[colorTheme]?.main || theme.palette.primary.main : 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;
},
}} }}
> >
<Typography <Typography

View File

@@ -1,74 +0,0 @@
import { ReportData } from "../../features/report";
import {
getAmount,
DecoratedPeriod,
} from "../report.helpers";
// ─── Helpers ─────────────────────────────────────────────────
function findPeriod(
periods: DecoratedPeriod[],
selectedPeriodId?: string | null
) {
if (!periods.length) return null;
if (selectedPeriodId) {
const match = periods.find((p) => p.id === selectedPeriodId);
if (match) return match;
}
// fallback → latest
return periods.reduce((latest, p) =>
new Date(p.start).getTime() > new Date(latest.start).getTime()
? p
: latest
);
}
// ─── Main adapter ────────────────────────────────────────────
export interface TagItem {
tag: string;
amount: number;
}
export function extractTopTags(
reportData: ReportData,
mode: "expense" | "income",
selectedPeriodId?: string | null
): { items: TagItem[]; total: number } {
const tagMap = new Map<string, number>();
for (const bucket of reportData.buckets) {
const tags = bucket.group_key.tags;
if (!tags || tags.length === 0) continue;
// Prefer FULL if available
const fullPeriods = (bucket.periods.full || []) as DecoratedPeriod[];
const periodsToUse = selectedPeriodId
? (Object.values(bucket.periods).flat() as DecoratedPeriod[])
: fullPeriods;
const period = findPeriod(periodsToUse, selectedPeriodId);
if (!period) continue;
const amount = getAmount(period, mode);
for (const tag of tags) {
tagMap.set(tag, (tagMap.get(tag) || 0) + amount);
}
}
const arr = Array.from(tagMap.entries()).map(([tag, amount]) => ({
tag,
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,61 +0,0 @@
import * as React from "react";
import { Box } from "@mui/material";
import { ReportData, GroupKey } from "../../features/report";
import ProgressCard from "./ProgressCard";
import { extractTopTags } from "./TopTags.adapter";
type Props = {
reportData: ReportData;
mode: "expense" | "income";
selectedPeriodId?: string | null;
selectedGroupKey?: GroupKey | null;
setSelectedGroupKey?: (key: GroupKey | null) => void;
compact?: boolean;
};
export default function TopTags({
reportData,
mode,
selectedPeriodId,
selectedGroupKey,
setSelectedGroupKey,
compact = true,
}: Props) {
const { items, total } = React.useMemo(() => {
return extractTopTags(reportData, mode, selectedPeriodId);
}, [reportData, mode, selectedPeriodId]);
return (
<Box
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "repeat(2, 1fr)",
md: "repeat(4, 1fr)",
},
gap: 2,
}}
>
{items.map((item) => {
const isSelected = selectedGroupKey?.tags?.includes(item.tag);
return (
<ProgressCard
key={item.tag}
header={item.tag}
progressAmount={item.amount}
totalAmount={total}
compact={compact}
colorTheme={mode === "expense" ? "error" : "success"}
selected={isSelected}
onClick={() => {
if (setSelectedGroupKey) {
setSelectedGroupKey(isSelected ? null : { tags: [item.tag] });
}
}}
/>
);
})}
</Box>
);
}

View File

@@ -1,147 +0,0 @@
import {
ReportPeriod,
ReportBucket,
GroupKey,
} from "../features/report";
// ─── Types ────────────────────────────────────────────────────
export type PeriodKey = "weekly" | "monthly" | "yearly" | "fyly" | "full";
export type DecoratedPeriod = ReportPeriod & {
id: string;
label: string;
};
// ─── Period helpers ───────────────────────────────────────────
const PREFIX_TO_KEY: Record<string, PeriodKey> = {
W: "weekly",
M: "monthly",
Y: "yearly",
FY: "fyly",
FULL: "full",
};
/**
* Derive the period key from a decorated-period id.
* E.g. `"W:2026-04-28_2026-05-04"` → `"weekly"`
*/
export function periodIdToKey(periodId: string): PeriodKey {
const prefix = periodId.split(":")[0];
return PREFIX_TO_KEY[prefix] ?? "full";
}
// ─── Metric helpers ───────────────────────────────────────────
export function getAmount(
period: ReportPeriod,
mode: "expense" | "income"
): number {
return mode === "expense" ? period.expenses.sum : period.incomes.sum;
}
function mergeMetric(a: ReportPeriod["expenses"], b: ReportPeriod["expenses"]) {
const sum = a.sum + b.sum;
const count = a.count + b.count;
return {
...a,
sum,
count,
average: count > 0 ? sum / count : 0,
transactions:
a.transactions || b.transactions
? [...(a.transactions || []), ...(b.transactions || [])]
: undefined,
};
}
/**
* Merge periods with the same id across all buckets, summing
* their metrics and concatenating transactions.
*
* Returns sorted by start date ascending.
*/
export function mergeBucketPeriods(
buckets: ReportBucket[],
key: PeriodKey
): DecoratedPeriod[] {
const map = new Map<string, DecoratedPeriod>();
for (const bucket of buckets) {
const periods = (bucket.periods[key] || []) as DecoratedPeriod[];
for (const p of periods) {
const existing = map.get(p.id);
if (!existing) {
map.set(p.id, {
...p,
expenses: { ...p.expenses },
incomes: { ...p.incomes },
});
} else {
map.set(p.id, {
...existing,
expenses: mergeMetric(existing.expenses, p.expenses),
incomes: mergeMetric(existing.incomes, p.incomes),
});
}
}
}
return Array.from(map.values()).sort(
(a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()
);
}
// ─── Formatting ───────────────────────────────────────────────
export const formatCurrency = (val: number) => {
const absVal = Math.abs(val);
if (absVal >= 100000) {
return `${(val / 100000).toFixed(2)}L`;
}
if (absVal >= 1000) {
return `${(val / 1000).toFixed(2)}k`;
}
return `${val.toFixed(2)}`;
};
export const getPercentage = (progressAmount: number, totalAmount: number) => {
if (!totalAmount) return 0;
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
};
// ─── Group filtering ──────────────────────────────────────────
/**
* Check if a bucket's group_key matches the selected GroupKey.
* Every dimension present in `selected` must exist in the bucket
* and contain all the selected values.
*/
export function matchesGroupKey(
bucket: ReportBucket,
selected: GroupKey
): boolean {
for (const [dim, values] of Object.entries(selected)) {
const bucketValues = bucket.group_key[dim as keyof GroupKey];
if (!bucketValues) return false;
if (!(values as string[]).every((v) => bucketValues.includes(v)))
return false;
}
return true;
}
/**
* Return only buckets matching the selected group key,
* or all buckets if no selection.
*/
export function filterBuckets(
buckets: ReportBucket[],
selectedGroupKey: GroupKey | null
): ReportBucket[] {
if (!selectedGroupKey) return buckets;
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
}

View File

@@ -1,7 +1,7 @@
import HistoryChart from "./components/HistoryChart"; import HistoryChart from "./components/HistoryChart";
import ProgressCard from "./components/ProgressCard";
import LatestItems from "./components/LatestItems"; import LatestItems from "./components/LatestItems";
import { DashboardConfig } from "./components/Dashboard"; import { DashboardConfig } from "./components/Dashboard";
import TopTags from "./components/ProgressCard/TopTags";
export const configuration: DashboardConfig = { export const configuration: DashboardConfig = {
sections: [ sections: [
@@ -10,6 +10,7 @@ export const configuration: DashboardConfig = {
title: "Breakdown", title: "Breakdown",
summary: "Interactive chronological tracking", summary: "Interactive chronological tracking",
component: HistoryChart, component: HistoryChart,
dataKey: "chartData",
settings: { settings: {
tabs: ["Weekly", "Monthly"], tabs: ["Weekly", "Monthly"],
// tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"], // tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"],
@@ -19,9 +20,11 @@ export const configuration: DashboardConfig = {
}, },
}, },
{ {
id: "top-categories", id: "top-payees",
title: 'Top Categories', title: 'Top Payees',
component: TopTags, component: ProgressCard,
dataKey: "topPayees",
isList: true,
settings: { settings: {
compact: true, compact: true,
}, },
@@ -29,13 +32,15 @@ export const configuration: DashboardConfig = {
size: 12, size: 12,
}, },
}, },
{ // {
id: "items", // id: "latest",
component: LatestItems, // title: 'Recent Transactions',
style: { // component: LatestItems,
size: 12, // dataKey: "latest",
}, // style: {
}, // size: 12,
// },
// },
], ],
style: { style: {
palette: { palette: {

View File

@@ -0,0 +1,191 @@
import * as React from "react";
import MonetizationOnIcon from "@mui/icons-material/MonetizationOn";
import { LatestItem } from "../../components/LatestItems";
import {
ChartData,
ChartDataPoint,
} from "../../components/HistoryChart";
const DEFAULT_ICON = React.createElement(MonetizationOnIcon, {
sx: { color: "#388e3c" }
});
type ReportBucket = any;
export function mapToLatestItems(
items: any[],
type: "expense" | "income"
): LatestItem[] {
const isValid = (amt: number) =>
type === "expense" ? amt < 0 : amt > 0;
return items
.filter((item: any) => isValid(Number(item.amount) || 0))
.slice(0, 5)
.map((exp: any, index: number) => {
const time = new Date(exp.occurred_at).getTime();
const diffDays = Math.floor(
Math.abs(Date.now() - time) / (1000 * 60 * 60 * 24)
);
return {
id: exp.id || index,
icon: DEFAULT_ICON,
iconBgColor:
type === "expense" ? "#ffebee" : "#e8f5e9",
title: exp.payee.name,
subtitle: exp.account.name,
amount: `Rs ${Math.abs(exp.amount || 0)}`,
timeAgo: diffDays === 0 ? "Today" : `${diffDays} days ago`
};
});
}
const sumBucket = (bucket: ReportBucket, flow: "expenses" | "incomes") =>
bucket.groups.reduce(
(acc: number, g: any) => acc + (g?.[flow]?.sum || 0),
0
);
const toLabel = (start: string, end: string, type: "weekly" | "monthly" | "yearly" | "fyly" | "full") => {
const s = new Date(start);
const e = new Date(end);
if (type === "monthly") {
return s.toLocaleString("default", { month: "short" });
}
return `${s.getDate()}${e.getDate()} ${e.toLocaleString("default", {
month: "short",
})}`;
};
const getWeekOfMonth = (date: Date) => {
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
return Math.ceil((date.getDate() + firstDay.getDay()) / 7);
};
const findCompareBucket = (
current: ReportBucket,
buckets: ReportBucket[],
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
): ReportBucket | undefined => {
const start = new Date(current.start);
if (type === "monthly") {
const targetYear = start.getFullYear() - 1;
const targetMonth = start.getMonth();
return buckets.find(b => {
const d = new Date(b.start);
return (
d.getFullYear() === targetYear &&
d.getMonth() === targetMonth
);
});
}
if (type === "weekly") {
const weekIndex = getWeekOfMonth(start); // you must define this
const target = new Date(start);
target.setMonth(target.getMonth() - 1);
return buckets.find(b => {
const d = new Date(b.start);
return (
d.getFullYear() === target.getFullYear() &&
d.getMonth() === target.getMonth() &&
getWeekOfMonth(d) === weekIndex
);
});
}
return undefined;
};
const toPoints = (
buckets: ReportBucket[],
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
flow: "expenses" | "incomes"
): ChartDataPoint[] => {
return buckets.map((b) => {
const amount = sumBucket(b, flow);
const prev = findCompareBucket(b, buckets, type);
return {
id: toLabel(b.start, b.end, type),
amount,
compare: prev
? {
id: toLabel(prev.start, prev.end, type),
amount: sumBucket(prev, flow),
}
: undefined,
};
});
};
export function mapReportToDashboard(
weekly: ReportBucket[],
monthly: ReportBucket[],
payeeBuckets: ReportBucket[],
type: "expense" | "income"
) {
const flow = type === "expense" ? "expenses" : "incomes";
const chartData: ChartData = {
weekly: {
rolling: toPoints(weekly, "weekly", flow),
calendar: toPoints(weekly, "weekly", flow),
},
monthly: {
rolling: toPoints(monthly, "monthly", flow),
calendar: toPoints(monthly, "monthly", flow),
},
// yearly: {
// rolling: toPoints(yearly, "yearly", flow),
// calendar: toPoints(yearly, "yearly", flow),
// },
//
// fyly: {
// rolling: toPoints(fyly, "fyly", flow),
// calendar: toPoints(fyly, "fyly", flow),
// },
//
// full: {
// rolling: toPoints(full, "full", flow),
// calendar: toPoints(full, "full", flow),
// },
};
const totalAmount = weekly.reduce(
(acc, b) => acc + sumBucket(b, flow),
0
);
const payeeMap: Record<string, number> = {};
const sourceForPayees = (payeeBuckets && payeeBuckets.length > 0) ? payeeBuckets : weekly;
for (const b of sourceForPayees) {
for (const g of b.groups) {
const key = g.group_key || "Unknown";
const amt = g?.[flow]?.sum || 0;
payeeMap[key] = (payeeMap[key] || 0) + amt;
}
}
const topPayees = Object.entries(payeeMap)
// .filter(([name]) => name !== "Unknown")
.map(([payeeName, amount]) => ({ payeeName, amount }))
.sort((a, b) => b.amount - a.amount)
.slice(0, 5);
return {
chartData,
totalAmount,
topPayees,
};
}

View File

@@ -0,0 +1,3 @@
export {
useDashboardData
} from './useDashboardData'

View File

@@ -0,0 +1,44 @@
import { useReport } from "../report";
import { mapReportToDashboard } from "./dashboard.mapper";
export function useDashboardData() {
// Fetch reports for aggregation
const weeklyReport = useReport({ period: "weekly", rolling: true });
const monthlyReport = useReport({ period: "monthly", rolling: true });
const payeeReport = useReport({ period: "full", rolling: true, group_by: ["payee"] });
const isLoading =
weeklyReport.isLoading ||
monthlyReport.isLoading ||
payeeReport.isLoading;
const error =
weeklyReport.error ||
monthlyReport.error ||
payeeReport.error;
const aggregatedData = {
expense: weeklyReport.data?.data && monthlyReport.data?.data && payeeReport.data?.data
? mapReportToDashboard(
(weeklyReport.data.data as any).buckets,
(monthlyReport.data.data as any).buckets,
(payeeReport.data.data as any).buckets,
"expense"
)
: null,
income: weeklyReport.data?.data && monthlyReport.data?.data && payeeReport.data?.data
? mapReportToDashboard(
(weeklyReport.data.data as any).buckets,
(monthlyReport.data.data as any).buckets,
(payeeReport.data.data as any).buckets,
"income"
)
: null,
}
return {
data: aggregatedData,
isLoading,
error,
};
}

View File

@@ -3,10 +3,10 @@ export {
} from './useReport' } from './useReport'
export type { export type {
Transaction, Transaction,
PeriodData,
PeriodGroup,
Period,
ReportData, ReportData,
ReportBucket,
ReportPeriod,
GroupKey,
} from './report.models' } from './report.models'
export { export {
prepareReport prepareReport

View File

@@ -22,69 +22,40 @@ export interface Transaction {
payee: Payee; payee: Payee;
amount: number; amount: number;
account: Account; account: Account;
tags: Tag[]; tags: Tag[]
occurred_at: Date; occurred_at: Date
} }
// ----------------------------- export interface _PeriodData {
// Metrics
// -----------------------------
export interface ReportMetric {
sum: number; sum: number;
count: number; count: number;
average: number; average: number;
transactions?: Transaction[]; txns: Transaction[];
} }
// ----------------------------- export interface PeriodData extends _PeriodData {
// Period compare?: _PeriodData;
// ----------------------------- }
export interface ReportPeriod { export interface PeriodGroup {
group_key: string[];
expenses: PeriodData[];
incomes: PeriodData[];
}
export interface Period {
id: string;
label: string;
start: Date; start: Date;
end: Date; end: Date;
groups: PeriodGroup[];
expenses: ReportMetric;
incomes: ReportMetric;
} }
// -----------------------------
// Group (bucket)
// -----------------------------
export type GroupKey = {
payee?: string[];
tags?: string[];
flow?: string[];
};
export interface ReportBucket {
group_key: GroupKey;
periods: {
weekly?: ReportPeriod[];
monthly?: ReportPeriod[];
yearly?: ReportPeriod[];
fyly?: ReportPeriod[];
full?: ReportPeriod[];
};
}
// -----------------------------
// Final Report
// -----------------------------
export interface ReportData { export interface ReportData {
periods: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[]; period: "weekly" | "monthly" | "yearly" | "fyly" | "full";
rolling?: boolean;
rolling: boolean;
report_date?: string; report_date?: string;
group_by?: ("payee" | "tags")[];
group_by: ("payee" | "tags")[]; ignore_self?: boolean;
buckets: Period[];
ignore_self: boolean;
include_transactions: boolean;
buckets: ReportBucket[];
} }

View File

@@ -1,7 +1,4 @@
import { import { ReportData } from "./report.models";
ReportData,
ReportPeriod
} from "./report.models";
/* ---------- ID BUILDING ---------- */ /* ---------- ID BUILDING ---------- */
@@ -13,7 +10,7 @@ function formatDate(d: Date): string {
} }
function buildPeriodId( function buildPeriodId(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full", type: ReportData["period"],
start: Date, start: Date,
end: Date end: Date
): string { ): string {
@@ -68,19 +65,25 @@ function sameMonth(a: Date, b: Date) {
} }
function buildLabel( function buildLabel(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full", type: ReportData["period"],
start: Date, start: Date,
end: Date end: Date
): string { ): string {
switch (type) { switch (type) {
case "weekly": { case "weekly":
if (sameMonth(start, end)) {
const sDay = start.getUTCDate(); const sDay = start.getUTCDate();
const eDay = end.getUTCDate();
const m = monthFmt.format(start); const m = monthFmt.format(start);
return `${sDay} ${m}`; return `${sDay} ${m} - ${eDay} ${m}`;
} }
return `${dayFmt.format(start)} - ${dayFmt.format(end)}`;
case "monthly": case "monthly":
if (sameMonth(start, end)) {
return `${monthFmt.format(start)} ${yearFmt.format(start)}`; return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
}
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
case "yearly": case "yearly":
return yearFmt.format(start); return yearFmt.format(start);
@@ -91,6 +94,9 @@ function buildLabel(
return `FY ${startY}${String(endY).slice(-2)}`; return `FY ${startY}${String(endY).slice(-2)}`;
} }
case "full":
return `${monthFmt.format(start)} ${yearFmt.format(start)} - ${monthFmt.format(end)} ${yearFmt.format(end)}`;
default: default:
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`; return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
} }
@@ -98,34 +104,13 @@ function buildLabel(
/* ---------- MAIN ---------- */ /* ---------- MAIN ---------- */
function decoratePeriods(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
periods: ReportPeriod[]
): (ReportPeriod & { id: string; label: string })[] {
return periods.map((p) => ({
...p,
id: buildPeriodId(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
label: buildLabel(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
}));
}
export function prepareReport(reportData: ReportData): ReportData { export function prepareReport(reportData: ReportData): ReportData {
return { return {
...reportData, ...reportData,
buckets: reportData.buckets.map((bucket) => { buckets: reportData.buckets.map((p) => ({
const newPeriods: typeof bucket.periods = {}; ...p,
id: buildPeriodId(reportData.period, p.start, p.end),
for (const type of reportData.periods) { label: buildLabel(reportData.period, p.start, p.end),
const arr = bucket.periods[type]; })),
if (arr) {
newPeriods[type] = decoratePeriods(type, arr);
}
}
return {
...bucket,
periods: newPeriods,
};
}),
}; };
} }

View File

@@ -1,20 +1,18 @@
import { useResourceByName } from "../../../react-openapi"; import { useResourceByName } from "../../../react-openapi";
export interface ReportParams { export interface ReportParams {
periods?: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[]; period: "weekly" | "monthly" | "yearly" | "fyly" | "full";
rolling?: boolean; rolling?: boolean;
report_date?: string; report_date?: string;
group_by?: ("payee" | "tags")[]; group_by?: ("payee" | "tags")[];
ignore_self?: boolean; ignore_self?: boolean;
include_transactions?: boolean;
} }
export function useReport(params: ReportParams) { export function useReport(params: ReportParams) {
const { useList } = useResourceByName("reports"); const { useList } = useResourceByName("reports");
if (params.group_by) {
return useList({ // @ts-ignore
...params, params.group_by = params.group_by[0]
periods: params.periods, }
group_by: params.group_by, return useList(params);
});
} }