Compare commits
3 Commits
67d4c85146
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 77b60ba073 | |||
| f213a9455b | |||
| 009ab50b47 |
@@ -7,6 +7,28 @@ 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");
|
||||||
@@ -38,6 +60,6 @@ export const auth = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
||||||
_api = createApiClient(baseUrl);
|
_api = withParamsSerializer(createApiClient(baseUrl));
|
||||||
_auth = createApiClient(authBaseUrl);
|
_auth = withParamsSerializer(createApiClient(authBaseUrl));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,43 +2,28 @@ import * as React from "react";
|
|||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
Container,
|
Container,
|
||||||
Grid,
|
|
||||||
CircularProgress,
|
CircularProgress,
|
||||||
Alert,
|
Alert
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
Typography
|
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
|
|
||||||
import LatestItems from "./components/LatestItems";
|
import ConfigurableDashboard from "./components/Dashboard";
|
||||||
import HistoryChart from "./components/HistoryChart";
|
import { configuration } from "./dashboard-config";
|
||||||
import ProgressCard from "./components/ProgressCard";
|
import {
|
||||||
|
useReport,
|
||||||
import { useDashboardData } from "./features/dashboard";
|
prepareReport,
|
||||||
|
} from "./features/report";
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
const [mode, setMode] = React.useState<"expense" | "income">("expense");
|
const report = useReport({
|
||||||
const [period, setPeriod] = React.useState<"rolling" | "calendar">("rolling");
|
periods: ["weekly", "monthly", "full"],
|
||||||
const [comparison, setComparison] = React.useState(false);
|
rolling: true,
|
||||||
|
include_transactions: true,
|
||||||
|
group_by: ["tags"],
|
||||||
|
})
|
||||||
|
|
||||||
const palette = {
|
const isLoading = report.isLoading;
|
||||||
expense: {
|
const error = report.error;
|
||||||
primary: "#d32f2f",
|
|
||||||
light: "#fdecea",
|
|
||||||
dark: "#9a0007",
|
|
||||||
text: "#b71c1c"
|
|
||||||
},
|
|
||||||
income: {
|
|
||||||
primary: "#2e7d32",
|
|
||||||
light: "#e8f5e9",
|
|
||||||
dark: "#1b5e20",
|
|
||||||
text: "#1b5e20"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const { data, latest, isLoading, error } = useDashboardData(mode);
|
|
||||||
|
|
||||||
const colors = palette[mode];
|
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
@@ -56,92 +41,15 @@ export default function Dashboard() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!data) {
|
if (!report) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const data = prepareReport(report.data?.data);
|
||||||
return (
|
return (
|
||||||
<Container
|
<ConfigurableDashboard
|
||||||
sx={{
|
config={configuration}
|
||||||
mt: 4,
|
data={data}
|
||||||
mb: 4,
|
/>
|
||||||
background: `linear-gradient(180deg, ${colors.light} 0%, transparent 100%)`,
|
|
||||||
borderRadius: 4,
|
|
||||||
p: 2
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", mb: 3 }}>
|
|
||||||
<ToggleButtonGroup
|
|
||||||
value={mode}
|
|
||||||
exclusive
|
|
||||||
onChange={(_, val) => val && setMode(val)}
|
|
||||||
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="expense">Expenses</ToggleButton>
|
|
||||||
<ToggleButton value="income">Income</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Grid container spacing={4} direction="row">
|
|
||||||
<Grid size={12}>
|
|
||||||
<HistoryChart
|
|
||||||
header={`${mode === "expense" ? "Expense" : "Income"} Breakdown`}
|
|
||||||
summary="Interactive chronological tracking"
|
|
||||||
tabs={["Daily", "Weekly", "Monthly"]}
|
|
||||||
data={data.chartData}
|
|
||||||
period={period}
|
|
||||||
onPeriodChange={setPeriod}
|
|
||||||
comparison={comparison}
|
|
||||||
setComparison={setComparison}
|
|
||||||
colorScheme={colors}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
{data.topPayees && data.topPayees.length > 0 && (
|
|
||||||
<Grid size={12}>
|
|
||||||
<Box sx={{ mb: 2 }}>
|
|
||||||
<Typography variant="h6" fontWeight={700}>
|
|
||||||
Top {mode === "expense" ? "Payees" : "Payors"}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
<Grid container spacing={2}>
|
|
||||||
{data.topPayees.map((payee: any) => (
|
|
||||||
<Grid key={payee.payeeName} size={{ xs: 12, sm: 6, md: 2.4 }}>
|
|
||||||
<ProgressCard
|
|
||||||
header={payee.payeeName}
|
|
||||||
progressAmount={payee.amount}
|
|
||||||
totalAmount={data.totalAmount}
|
|
||||||
colorTheme={mode === "expense" ? "error" : "success"}
|
|
||||||
compact
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</Grid>
|
|
||||||
</Grid>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Grid size={12}>
|
|
||||||
<LatestItems
|
|
||||||
title={`Recent ${mode === "expense" ? "Expenses" : "Income"}`}
|
|
||||||
items={latest || []}
|
|
||||||
onViewAll={() => {}}
|
|
||||||
accentColor={colors.primary}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
</Grid>
|
|
||||||
</Container>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
53
src/components/Dashboard/Dashboard.models.ts
Normal file
53
src/components/Dashboard/Dashboard.models.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import {
|
||||||
|
ReportData,
|
||||||
|
GroupKey,
|
||||||
|
} from "../../features/report";
|
||||||
|
|
||||||
|
export type DashboardMode = "expense" | "income";
|
||||||
|
export type DashboardPeriodType = "rolling" | "calendar";
|
||||||
|
export type DashboardSelectedPeriodId = string | null;
|
||||||
|
|
||||||
|
export interface DashboardState {
|
||||||
|
mode: DashboardMode;
|
||||||
|
periodType: DashboardPeriodType;
|
||||||
|
selectedPeriodId: DashboardSelectedPeriodId;
|
||||||
|
selectedGroupKey: GroupKey | null;
|
||||||
|
comparison: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardSection {
|
||||||
|
id: string;
|
||||||
|
title?: string;
|
||||||
|
summary?: string;
|
||||||
|
component: React.ComponentType<any>;
|
||||||
|
settings?: Record<string, any>;
|
||||||
|
isList?: boolean;
|
||||||
|
style?: {
|
||||||
|
size?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ColorDefinition {
|
||||||
|
primary: string;
|
||||||
|
background?: string;
|
||||||
|
text?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ThemeAwarePalette {
|
||||||
|
light: ColorDefinition;
|
||||||
|
dark: ColorDefinition;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardConfig {
|
||||||
|
sections: DashboardSection[];
|
||||||
|
style?: {
|
||||||
|
palette?: Record<DashboardMode, ThemeAwarePalette>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardProps {
|
||||||
|
config: DashboardConfig;
|
||||||
|
data: ReportData;
|
||||||
|
}
|
||||||
55
src/components/Dashboard/Dashboard.tsx
Normal file
55
src/components/Dashboard/Dashboard.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import DashboardView from "./Dashboard.view";
|
||||||
|
import { DashboardProps, DashboardState } from "./Dashboard.models";
|
||||||
|
|
||||||
|
export default function Dashboard(props: DashboardProps) {
|
||||||
|
const [state, setState] = React.useState<DashboardState>({
|
||||||
|
mode: "expense",
|
||||||
|
periodType: "rolling",
|
||||||
|
selectedPeriodId: null,
|
||||||
|
selectedGroupKey: null,
|
||||||
|
comparison: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const toggleMode = () => {
|
||||||
|
setState(prev => ({
|
||||||
|
...prev,
|
||||||
|
mode: prev.mode === "expense" ? "income" : "expense",
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const togglePeriodType = () => {
|
||||||
|
setState(prev => ({
|
||||||
|
...prev,
|
||||||
|
periodType: prev.periodType === "rolling" ? "calendar" : "rolling",
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleComparison = () => {
|
||||||
|
setState(prev => ({
|
||||||
|
...prev,
|
||||||
|
comparison: !prev.comparison,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const setSelectedPeriodId = (selectedPeriodId: typeof state.selectedPeriodId) => {
|
||||||
|
setState(prev => ({ ...prev, selectedPeriodId }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const setSelectedGroupKey = (groupKey: typeof state.selectedGroupKey) => {
|
||||||
|
setState(prev => ({ ...prev, selectedGroupKey: groupKey }));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardView
|
||||||
|
{...props}
|
||||||
|
state={state}
|
||||||
|
setState={setState}
|
||||||
|
toggleMode={toggleMode}
|
||||||
|
togglePeriodType={togglePeriodType}
|
||||||
|
toggleComparison={toggleComparison}
|
||||||
|
setSelectedPeriodId={setSelectedPeriodId}
|
||||||
|
setSelectedGroupKey={setSelectedGroupKey}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
139
src/components/Dashboard/Dashboard.view.tsx
Normal file
139
src/components/Dashboard/Dashboard.view.tsx
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Container,
|
||||||
|
Grid,
|
||||||
|
Typography,
|
||||||
|
ToggleButton,
|
||||||
|
ToggleButtonGroup
|
||||||
|
} 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>>;
|
||||||
|
toggleMode: () => void;
|
||||||
|
togglePeriodType: () => void;
|
||||||
|
setSelectedPeriodId: (id: string | null) => void;
|
||||||
|
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
|
||||||
|
toggleComparison: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardView({
|
||||||
|
config,
|
||||||
|
data,
|
||||||
|
state,
|
||||||
|
setState,
|
||||||
|
toggleMode,
|
||||||
|
togglePeriodType,
|
||||||
|
toggleComparison,
|
||||||
|
setSelectedPeriodId,
|
||||||
|
setSelectedGroupKey,
|
||||||
|
}: ViewProps) {
|
||||||
|
const theme = useTheme();
|
||||||
|
const themeMode = theme.palette.mode;
|
||||||
|
const { mode, periodType, comparison, selectedPeriodId, selectedGroupKey } = state;
|
||||||
|
|
||||||
|
// Resolve colors with fallbacks
|
||||||
|
const colors = React.useMemo(() => {
|
||||||
|
const palette = config.style?.palette?.[mode];
|
||||||
|
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 = mode === 'expense' ? 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, mode, 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", justifyContent: "center", mb: 3 }}>
|
||||||
|
<ToggleButtonGroup
|
||||||
|
value={mode}
|
||||||
|
exclusive
|
||||||
|
onChange={toggleMode}
|
||||||
|
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="expense">Expenses</ToggleButton>
|
||||||
|
<ToggleButton value="income">Income</ToggleButton>
|
||||||
|
</ToggleButtonGroup>
|
||||||
|
</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}>
|
||||||
|
{section.title && !section.isList && (
|
||||||
|
<Box sx={{ mb: 2 }}>
|
||||||
|
<Typography variant="h6" fontWeight={700}>
|
||||||
|
{section.title}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Component
|
||||||
|
{...section.settings}
|
||||||
|
header={section.title}
|
||||||
|
summary={section.summary}
|
||||||
|
reportData={data}
|
||||||
|
title={section.title}
|
||||||
|
accentColor={colors.primary}
|
||||||
|
colorScheme={colors}
|
||||||
|
|
||||||
|
// State management
|
||||||
|
mode={mode}
|
||||||
|
|
||||||
|
periodType={periodType}
|
||||||
|
comparison={comparison}
|
||||||
|
selectedPeriodId={selectedPeriodId}
|
||||||
|
selectedGroupKey={selectedGroupKey}
|
||||||
|
|
||||||
|
togglePeriodType={togglePeriodType}
|
||||||
|
toggleComparison={toggleComparison}
|
||||||
|
setSelectedPeriodId={setSelectedPeriodId}
|
||||||
|
setSelectedGroupKey={setSelectedGroupKey}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Grid>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
2
src/components/Dashboard/index.ts
Normal file
2
src/components/Dashboard/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default } from "./Dashboard";
|
||||||
|
export * from "./Dashboard.models";
|
||||||
75
src/components/HistoryChart/HistoryChart.adapter.ts
Normal file
75
src/components/HistoryChart/HistoryChart.adapter.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -1,5 +1,13 @@
|
|||||||
|
import {
|
||||||
|
DashboardMode,
|
||||||
|
DashboardPeriodType,
|
||||||
|
DashboardSelectedPeriodId
|
||||||
|
} 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;
|
||||||
}
|
}
|
||||||
@@ -8,30 +16,25 @@ export interface ChartDataPoint extends _ChartDataPoint {
|
|||||||
compare?: _ChartDataPoint;
|
compare?: _ChartDataPoint;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ChartData {
|
|
||||||
daily?: ChartDataPoint[];
|
|
||||||
weekly?: Record<string, ChartDataPoint[]>;
|
|
||||||
monthly?: Record<string, ChartDataPoint[]>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AggregatedDashboardData {
|
|
||||||
chartData: ChartData;
|
|
||||||
totalAmount: number;
|
|
||||||
topPayees: Array<{ payeeName: string; amount: number }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HistoryChartProps {
|
export interface HistoryChartProps {
|
||||||
header: string;
|
header: string;
|
||||||
summary?: string;
|
summary?: string;
|
||||||
tabs: string[];
|
tabs: string[];
|
||||||
data: ChartData;
|
|
||||||
period: "rolling" | "calendar";
|
reportData: ReportData;
|
||||||
onPeriodChange: (p: "rolling" | "calendar") => void;
|
|
||||||
comparison: boolean;
|
|
||||||
setComparison: (v: boolean) => void;
|
|
||||||
colorScheme: {
|
colorScheme: {
|
||||||
primary: string;
|
primary: string;
|
||||||
light: string;
|
light: string;
|
||||||
text: string;
|
text: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
mode: DashboardMode;
|
||||||
|
periodType: DashboardPeriodType;
|
||||||
|
selectedPeriodId: DashboardSelectedPeriodId;
|
||||||
|
comparison: boolean;
|
||||||
|
|
||||||
|
togglePeriodType: () => void;
|
||||||
|
setSelectedPeriodId: (id: string | null) => void;
|
||||||
|
toggleComparison: () => void;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +1,80 @@
|
|||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { ChartDataPoint, HistoryChartProps, ChartData } from "./HistoryChart.models";
|
import { HistoryChartProps } 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 { tabs, data, period, comparison } = props;
|
const {
|
||||||
|
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 = activeTab.toLowerCase() as keyof ChartData;
|
const activeDataKey = tabToKey(activeTab);
|
||||||
|
|
||||||
let rawData: ChartDataPoint[] = [];
|
const currentData = React.useMemo(() => {
|
||||||
|
return buildChartData(reportData, activeDataKey, mode, comparison);
|
||||||
if (activeDataKey === "daily") {
|
}, [reportData, activeDataKey, mode, comparison]);
|
||||||
rawData = data.daily || [];
|
|
||||||
} else {
|
|
||||||
const section = data[activeDataKey];
|
|
||||||
rawData = section?.[period] || [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentData = rawData;
|
|
||||||
|
|
||||||
const maxAmount =
|
const maxAmount =
|
||||||
currentData.length > 0
|
currentData.length > 0
|
||||||
? Math.max(
|
? Math.max(
|
||||||
...currentData.flatMap((d) =>
|
...currentData.flatMap((d) =>
|
||||||
comparison ? [d.amount, d.compare?.amount ?? 0] : [d.amount]
|
comparison
|
||||||
|
? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
|
||||||
|
: [d.amount]
|
||||||
),
|
),
|
||||||
1
|
1
|
||||||
)
|
)
|
||||||
: 1;
|
: 1;
|
||||||
|
|
||||||
const visibleCountMap = { daily: 7, weekly: 6, monthly: 4 };
|
const visibleCountMap = {
|
||||||
const visibleCount = visibleCountMap[activeDataKey];
|
weekly: 6,
|
||||||
|
monthly: 4,
|
||||||
|
yearly: 4,
|
||||||
|
fyly: 4,
|
||||||
|
full: 4,
|
||||||
|
};
|
||||||
|
|
||||||
|
const visibleCount = visibleCountMap[activeDataKey] ?? 4;
|
||||||
|
|
||||||
const total = currentData.length;
|
const total = currentData.length;
|
||||||
|
|
||||||
const clampedStartIndex = Math.min(startIndex, Math.max(total - visibleCount, 0));
|
const clampedStartIndex = Math.min(
|
||||||
|
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}
|
||||||
@@ -52,7 +84,7 @@ export default function HistoryChart(props: HistoryChartProps) {
|
|||||||
visibleData={visibleData}
|
visibleData={visibleData}
|
||||||
maxAmount={maxAmount}
|
maxAmount={maxAmount}
|
||||||
visibleCount={visibleCount}
|
visibleCount={visibleCount}
|
||||||
startIndex={startIndex}
|
startIndex={clampedStartIndex}
|
||||||
setStartIndex={setStartIndex}
|
setStartIndex={setStartIndex}
|
||||||
activeDataKey={activeDataKey}
|
activeDataKey={activeDataKey}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -25,19 +25,3 @@ 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;
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
ToggleButton,
|
ToggleButton,
|
||||||
Paper
|
Paper
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
|
import { useTheme, alpha } from "@mui/material/styles";
|
||||||
import IconButton from "@mui/material/IconButton";
|
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";
|
||||||
@@ -13,7 +14,7 @@ import {
|
|||||||
ChartDataPoint,
|
ChartDataPoint,
|
||||||
HistoryChartProps,
|
HistoryChartProps,
|
||||||
} from "./HistoryChart.models";
|
} from "./HistoryChart.models";
|
||||||
import { formatDisplay, formatLabel } from "./HistoryChart.utils";
|
import { formatDisplay } from "./HistoryChart.utils";
|
||||||
|
|
||||||
interface ViewProps extends HistoryChartProps {
|
interface ViewProps extends HistoryChartProps {
|
||||||
activeTab: string;
|
activeTab: string;
|
||||||
@@ -32,11 +33,17 @@ export default function HistoryChartView(props: ViewProps) {
|
|||||||
header,
|
header,
|
||||||
summary,
|
summary,
|
||||||
tabs,
|
tabs,
|
||||||
period,
|
|
||||||
onPeriodChange,
|
|
||||||
comparison,
|
|
||||||
setComparison,
|
|
||||||
colorScheme,
|
colorScheme,
|
||||||
|
|
||||||
|
mode,
|
||||||
|
periodType,
|
||||||
|
selectedPeriodId,
|
||||||
|
comparison,
|
||||||
|
|
||||||
|
togglePeriodType,
|
||||||
|
setSelectedPeriodId,
|
||||||
|
toggleComparison,
|
||||||
|
|
||||||
activeTab,
|
activeTab,
|
||||||
setActiveTab,
|
setActiveTab,
|
||||||
currentData,
|
currentData,
|
||||||
@@ -48,34 +55,46 @@ export default function HistoryChartView(props: ViewProps) {
|
|||||||
activeDataKey,
|
activeDataKey,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
|
const theme = useTheme();
|
||||||
|
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 = startIndex > 0;
|
const canGoLeft = clampedStartIndex > 0;
|
||||||
const canGoRight = startIndex + visibleCount < currentData.length;
|
const canGoRight = clampedStartIndex < maxStartIndex;
|
||||||
|
|
||||||
const handlePrev = () => {
|
const handlePrev = () => {
|
||||||
if (canGoLeft) setStartIndex((prev) => prev - visibleCount);
|
if (!canGoLeft) return;
|
||||||
|
setStartIndex((prev) => Math.max(prev - visibleCount, 0));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleNext = () => {
|
const handleNext = () => {
|
||||||
if (canGoRight) setStartIndex((prev) => prev + visibleCount);
|
if (!canGoRight) return;
|
||||||
|
setStartIndex((prev) => {
|
||||||
|
const next = prev + visibleCount;
|
||||||
|
return Math.min(next, maxStartIndex);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Paper
|
<Paper
|
||||||
sx={{
|
sx={{
|
||||||
p: { xs: 2, sm: 4 },
|
p: { xs: 2.5, sm: 4 },
|
||||||
borderRadius: 4,
|
borderRadius: 4,
|
||||||
width: "100%",
|
width: "100%",
|
||||||
boxShadow: "none",
|
boxShadow: "none",
|
||||||
border: "1px solid",
|
border: "1px solid",
|
||||||
borderColor: "divider",
|
borderColor: "divider",
|
||||||
bgcolor: colorScheme.light,
|
bgcolor: isDark ? "background.paper" : colorScheme.light,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography variant="h6" fontWeight={700} gutterBottom color={colorScheme.text}>
|
<Typography variant="h6" fontWeight={700} gutterBottom>
|
||||||
{header}
|
{header}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
@@ -93,35 +112,17 @@ export default function HistoryChartView(props: ViewProps) {
|
|||||||
))}
|
))}
|
||||||
</ToggleButtonGroup>
|
</ToggleButtonGroup>
|
||||||
|
|
||||||
<Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", mb: 3 }}>
|
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}>
|
||||||
<ToggleButtonGroup value={period} exclusive onChange={(_, v) => v && onPeriodChange(v)} size="small">
|
<ToggleButtonGroup value={periodType} exclusive onChange={togglePeriodType} size="small">
|
||||||
<ToggleButton value="rolling">Rolling</ToggleButton>
|
<ToggleButton value="rolling">Rolling</ToggleButton>
|
||||||
<ToggleButton value="calendar" disabled={activeDataKey === "daily"}>
|
<ToggleButton value="calendar">Calendar</ToggleButton>
|
||||||
Calendar
|
|
||||||
</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
</ToggleButtonGroup>
|
||||||
|
|
||||||
<ToggleButton
|
<ToggleButton
|
||||||
value="compare"
|
value="compare"
|
||||||
selected={comparison}
|
selected={comparison}
|
||||||
onChange={() => setComparison(!comparison)}
|
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>
|
||||||
@@ -130,19 +131,7 @@ 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
|
<IconButton onClick={handlePrev} size="small" sx={{ position: "absolute", left: 0, top: "50%" }}>
|
||||||
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>
|
||||||
)}
|
)}
|
||||||
@@ -153,77 +142,67 @@ 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 display = formatDisplay(point, activeDataKey, comparison);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box key={point.id} sx={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-end", height: "100%" }}>
|
<Box
|
||||||
<Box sx={{ display: "flex", alignItems: "flex-end", gap: comparison ? 0.5 : 0, height: "100%", position: "relative" }}>
|
key={point.id}
|
||||||
<Typography
|
onClick={() =>
|
||||||
variant="caption"
|
setSelectedPeriodId(isSelected ? null : point.id)
|
||||||
sx={{
|
}
|
||||||
position: "absolute",
|
sx={{
|
||||||
bottom: `${labelHeight}%`,
|
flex: 1,
|
||||||
left: "50%",
|
display: "flex",
|
||||||
transform: "translate(-50%, -6px)",
|
flexDirection: "column",
|
||||||
fontSize: "0.65rem",
|
alignItems: "center",
|
||||||
whiteSpace: "nowrap",
|
cursor: "pointer",
|
||||||
pointerEvents: "none"
|
height: "100%"
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{formatDisplay(point, activeTab.toLowerCase(), comparison)}
|
<Box sx={{ display: "flex", alignItems: "flex-end", gap: 1, height: "100%" }}>
|
||||||
</Typography>
|
|
||||||
|
|
||||||
{comparison && (
|
{comparison && (
|
||||||
<Box sx={{ width: 6, height: `${compareHeight}%`, bgcolor: `${colorScheme.primary}55`, borderRadius: 2 }} />
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: 8,
|
||||||
|
height: `${compareHeight}%`,
|
||||||
|
bgcolor: alpha(colorScheme.primary, 0.4),
|
||||||
|
borderRadius: "4px 4px 0 0"
|
||||||
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box sx={{ width: 4 }} />
|
|
||||||
|
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
width: 10,
|
width: 12,
|
||||||
height: `${currentHeight}%`,
|
height: `${currentHeight}%`,
|
||||||
bgcolor: point.highlighted ? colorScheme.primary : `${colorScheme.primary}99`,
|
bgcolor: isSelected ? "warning.main" : colorScheme.primary,
|
||||||
borderRadius: 2
|
borderRadius: "4px 4px 0 0"
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box sx={{ mt: 1, textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", lineHeight: 1.1 }}>
|
<Typography variant="caption">
|
||||||
<Typography variant="caption" sx={{ fontSize: "0.7rem", opacity: 0.7 }}>
|
{point.label}
|
||||||
{formatLabel(point.id, activeDataKey)}
|
</Typography>
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Typography
|
{comparison && point.compare && (
|
||||||
variant="caption"
|
<Typography variant="caption" color="text.secondary">
|
||||||
sx={{
|
{point.compare.label}
|
||||||
fontSize: "0.65rem",
|
|
||||||
color: "grey.400",
|
|
||||||
visibility: comparison && point.compare && activeDataKey !== "daily" ? "visible" : "hidden"
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{point.compare ? formatLabel(point.compare.id, activeDataKey) : "placeholder"}
|
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
)}
|
||||||
|
|
||||||
|
<Typography variant="caption">
|
||||||
|
{display}
|
||||||
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{canGoRight && (
|
{canGoRight && (
|
||||||
<IconButton
|
<IconButton onClick={handleNext} size="small" sx={{ position: "absolute", right: 0, top: "50%" }}>
|
||||||
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>
|
||||||
)}
|
)}
|
||||||
|
|||||||
66
src/components/LatestItems/LatestItems.adapter.ts
Normal file
66
src/components/LatestItems/LatestItems.adapter.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
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"),
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -1,18 +1,14 @@
|
|||||||
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 LatestItemsListProps {
|
export interface LatestItemsViewProps {
|
||||||
title?: string;
|
|
||||||
items: LatestItem[];
|
items: LatestItem[];
|
||||||
onViewAll?: () => void;
|
|
||||||
accentColor: string;
|
accentColor: string;
|
||||||
|
canExpand: boolean;
|
||||||
|
onExpand: () => void;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,112 +1,44 @@
|
|||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import {
|
import { ReportData, GroupKey } from "../../features/report";
|
||||||
List,
|
import { buildLatestItems } from "./LatestItems.adapter";
|
||||||
ListItem,
|
import LatestItemsView from "./LatestItems.view";
|
||||||
ListItemAvatar,
|
|
||||||
ListItemText,
|
|
||||||
Avatar,
|
|
||||||
Typography,
|
|
||||||
Box,
|
|
||||||
Button,
|
|
||||||
} from "@mui/material";
|
|
||||||
|
|
||||||
export interface LatestItem {
|
type Props = {
|
||||||
id: string | number;
|
reportData: ReportData;
|
||||||
icon: React.ReactNode;
|
mode: "expense" | "income";
|
||||||
iconBgColor?: string;
|
selectedPeriodId: string | null;
|
||||||
title: string;
|
selectedGroupKey?: GroupKey | null;
|
||||||
subtitle: string;
|
accentColor: string;
|
||||||
amount: string;
|
};
|
||||||
timeAgo: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LatestItemsListProps {
|
|
||||||
title?: string;
|
|
||||||
items: LatestItem[];
|
|
||||||
onViewAll?: () => void;
|
|
||||||
accentColor: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function LatestItems({
|
export default function LatestItems({
|
||||||
title = "Recent Transactions",
|
reportData,
|
||||||
items,
|
mode,
|
||||||
onViewAll,
|
selectedPeriodId,
|
||||||
|
selectedGroupKey = null,
|
||||||
accentColor,
|
accentColor,
|
||||||
}: LatestItemsListProps) {
|
}: Props) {
|
||||||
|
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 (
|
||||||
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
|
<LatestItemsView
|
||||||
{/* Header */}
|
items={visibleItems}
|
||||||
<Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2, px: 2 }}>
|
accentColor={accentColor}
|
||||||
<Typography variant="h6" fontWeight="bold">
|
canExpand={canExpand}
|
||||||
{title}
|
onExpand={() => setVisibleCount((prev) => prev + 5)}
|
||||||
</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>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,88 @@
|
|||||||
import LatestItemsListView from "./LatestItems.view";
|
import * as React from "react";
|
||||||
import { LatestItemsListProps } from "./LatestItems.models";
|
import {
|
||||||
|
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 LatestItemsList(props: LatestItemsListProps) {
|
export default function LatestItemsView({
|
||||||
return <LatestItemsListView {...props} />;
|
items,
|
||||||
|
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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,4 +5,6 @@ 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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 "./ProgressCard.utils";
|
import { getPercentage, formatCurrency } from "../report.helpers";
|
||||||
|
|
||||||
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,6 +18,8 @@ export default function ProgressCard(props: ProgressCardProps) {
|
|||||||
formattedProgress={formattedProgress}
|
formattedProgress={formattedProgress}
|
||||||
formattedTotal={formattedTotal}
|
formattedTotal={formattedTotal}
|
||||||
compact={compact}
|
compact={compact}
|
||||||
|
selected={props.selected}
|
||||||
|
onClick={props.onClick}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
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)}`;
|
|
||||||
};
|
|
||||||
@@ -7,12 +7,15 @@ import {
|
|||||||
Divider,
|
Divider,
|
||||||
linearProgressClasses
|
linearProgressClasses
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
|
import { useTheme, alpha } from "@mui/material/styles";
|
||||||
import { ProgressCardProps } from "./ProgressCard.models";
|
import { ProgressCardProps } from "./ProgressCard.models";
|
||||||
|
|
||||||
interface ViewProps extends ProgressCardProps {
|
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({
|
||||||
@@ -22,18 +25,30 @@ export default function ProgressCardView({
|
|||||||
formattedProgress,
|
formattedProgress,
|
||||||
formattedTotal,
|
formattedTotal,
|
||||||
compact = false,
|
compact = false,
|
||||||
|
selected,
|
||||||
|
onClick,
|
||||||
}: ViewProps) {
|
}: ViewProps) {
|
||||||
|
const theme = useTheme();
|
||||||
|
const isDark = theme.palette.mode === "dark";
|
||||||
|
|
||||||
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,
|
||||||
background: (theme) =>
|
cursor: onClick ? "pointer" : "default",
|
||||||
colorTheme === "info"
|
transform: selected ? "scale(1.02)" : "scale(1)",
|
||||||
? "linear-gradient(135deg, #0284c7 0%, #06b6d4 100%)"
|
transition: "transform 0.2s ease, box-shadow 0.2s ease",
|
||||||
: `linear-gradient(135deg, ${theme.palette[colorTheme].main} 0%, ${theme.palette[colorTheme].light} 100%)`,
|
background: (theme) => {
|
||||||
|
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",
|
color: "#fff",
|
||||||
display: "flex",
|
display: "flex",
|
||||||
flexDirection: "column",
|
flexDirection: "column",
|
||||||
@@ -41,25 +56,33 @@ export default function ProgressCardView({
|
|||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
position: "relative",
|
position: "relative",
|
||||||
overflow: "hidden",
|
overflow: "hidden",
|
||||||
boxShadow: (theme) =>
|
border: selected
|
||||||
`0 ${compact ? 6 : 12}px ${compact ? 12 : 24}px -10px ${
|
? `2px solid #fff`
|
||||||
theme.palette.mode === "dark"
|
: isDark ? "1px solid rgba(255,255,255,0.1)" : "none",
|
||||||
? "#000"
|
boxShadow: (theme) => {
|
||||||
: theme.palette[colorTheme].main
|
const baseShadow = `0 ${compact ? 6 : 12}px ${compact ? 12 : 24}px -10px ${
|
||||||
}`,
|
isDark
|
||||||
|
? "rgba(0,0,0,0.5)"
|
||||||
|
: 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
|
||||||
variant={compact ? "body2" : "subtitle1"}
|
variant={compact ? "body2" : "subtitle1"}
|
||||||
fontWeight={700}
|
fontWeight={700}
|
||||||
sx={{
|
sx={{
|
||||||
opacity: 0.9,
|
opacity: 0.95,
|
||||||
mb: 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'
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{header}
|
{header}
|
||||||
@@ -69,7 +92,7 @@ export default function ProgressCardView({
|
|||||||
<Typography
|
<Typography
|
||||||
variant={compact ? "h5" : "h3"}
|
variant={compact ? "h5" : "h3"}
|
||||||
fontWeight={900}
|
fontWeight={900}
|
||||||
sx={{ mb: 0.5, lineHeight: 1.2 }}
|
sx={{ mb: 0.5, lineHeight: 1.2, textShadow: isDark ? '0 2px 4px rgba(0,0,0,0.3)' : 'none' }}
|
||||||
>
|
>
|
||||||
{formattedProgress}
|
{formattedProgress}
|
||||||
</Typography>
|
</Typography>
|
||||||
@@ -77,7 +100,7 @@ export default function ProgressCardView({
|
|||||||
<Divider
|
<Divider
|
||||||
sx={{
|
sx={{
|
||||||
my: 1,
|
my: 1,
|
||||||
borderColor: "rgba(255,255,255,0.4)",
|
borderColor: "rgba(255,255,255,0.25)",
|
||||||
width: "100%",
|
width: "100%",
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -85,12 +108,13 @@ export default function ProgressCardView({
|
|||||||
<Typography
|
<Typography
|
||||||
variant={compact ? "caption" : "body2"}
|
variant={compact ? "caption" : "body2"}
|
||||||
sx={{
|
sx={{
|
||||||
opacity: 0.8,
|
opacity: 0.85,
|
||||||
fontWeight: 400,
|
fontWeight: 500,
|
||||||
display: "block"
|
display: "block",
|
||||||
|
color: "rgba(255,255,255,0.9)"
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{formattedTotal}
|
of {formattedTotal}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
@@ -102,11 +126,12 @@ export default function ProgressCardView({
|
|||||||
height: compact ? 6 : 10,
|
height: compact ? 6 : 10,
|
||||||
borderRadius: 5,
|
borderRadius: 5,
|
||||||
[`&.${linearProgressClasses.colorPrimary}`]: {
|
[`&.${linearProgressClasses.colorPrimary}`]: {
|
||||||
backgroundColor: "rgba(0, 0, 0, 0.2)",
|
backgroundColor: "rgba(0, 0, 0, 0.25)",
|
||||||
},
|
},
|
||||||
[`& .${linearProgressClasses.bar}`]: {
|
[`& .${linearProgressClasses.bar}`]: {
|
||||||
borderRadius: 5,
|
borderRadius: 5,
|
||||||
backgroundColor: "#fff",
|
backgroundColor: "#fff",
|
||||||
|
boxShadow: '0 0 8px rgba(255,255,255,0.4)'
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
74
src/components/ProgressCard/TopTags.adapter.ts
Normal file
74
src/components/ProgressCard/TopTags.adapter.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
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 };
|
||||||
|
}
|
||||||
61
src/components/ProgressCard/TopTags.tsx
Normal file
61
src/components/ProgressCard/TopTags.tsx
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
147
src/components/report.helpers.ts
Normal file
147
src/components/report.helpers.ts
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
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));
|
||||||
|
}
|
||||||
68
src/dashboard-config.ts
Normal file
68
src/dashboard-config.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import HistoryChart from "./components/HistoryChart";
|
||||||
|
import LatestItems from "./components/LatestItems";
|
||||||
|
import { DashboardConfig } from "./components/Dashboard";
|
||||||
|
import TopTags from "./components/ProgressCard/TopTags";
|
||||||
|
|
||||||
|
export const configuration: DashboardConfig = {
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
id: "breakdown",
|
||||||
|
title: "Breakdown",
|
||||||
|
summary: "Interactive chronological tracking",
|
||||||
|
component: HistoryChart,
|
||||||
|
settings: {
|
||||||
|
tabs: ["Weekly", "Monthly"],
|
||||||
|
// tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"],
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
size: 12,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "top-categories",
|
||||||
|
title: 'Top Categories',
|
||||||
|
component: TopTags,
|
||||||
|
settings: {
|
||||||
|
compact: true,
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
size: 12,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "items",
|
||||||
|
component: LatestItems,
|
||||||
|
style: {
|
||||||
|
size: 12,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
style: {
|
||||||
|
palette: {
|
||||||
|
expense: {
|
||||||
|
light: {
|
||||||
|
primary: "#d32f2f",
|
||||||
|
background: "#fdecea",
|
||||||
|
text: "#b71c1c"
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "#f44336",
|
||||||
|
background: "rgba(244, 67, 54, 0.15)",
|
||||||
|
text: "#ffcdd2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
income: {
|
||||||
|
light: {
|
||||||
|
primary: "#2e7d32",
|
||||||
|
background: "#e8f5e9",
|
||||||
|
text: "#1b5e20"
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
primary: "#4caf50",
|
||||||
|
background: "rgba(76, 175, 80, 0.15)",
|
||||||
|
text: "#c8e6c9"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import MonetizationOnIcon from "@mui/icons-material/MonetizationOn";
|
|
||||||
import { LatestItem } from "../../components/LatestItems";
|
|
||||||
|
|
||||||
const DEFAULT_ICON = React.createElement(MonetizationOnIcon, {
|
|
||||||
sx: { color: "#388e3c" }
|
|
||||||
});
|
|
||||||
|
|
||||||
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 || exp.created_at || Date.now()
|
|
||||||
).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 || exp.payee || "Unknown Payee",
|
|
||||||
subtitle:
|
|
||||||
exp.category?.name || exp.account?.name || "Transaction",
|
|
||||||
amount: `Rs ${Math.abs(exp.amount || 0)}`,
|
|
||||||
timeAgo: diffDays === 0 ? "Today" : `${diffDays} days ago`
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
export {
|
|
||||||
useDashboardData
|
|
||||||
} from './useDashboardData'
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import { useResourceByName } from "../../../react-openapi";
|
|
||||||
import { mapToLatestItems } from "./dashboard.mapper";
|
|
||||||
import { mapReportToDashboard } from "../report/report.mapper";
|
|
||||||
|
|
||||||
export function useDashboardData(type: "expense" | "income") {
|
|
||||||
const { useList: useExpenseList } = useResourceByName("expenses");
|
|
||||||
const { useList: useReportList } = useResourceByName("reports");
|
|
||||||
|
|
||||||
// Fetch latest transactions
|
|
||||||
const latestQuery = useExpenseList({
|
|
||||||
limit: 100,
|
|
||||||
sort: "-occurred_at"
|
|
||||||
});
|
|
||||||
|
|
||||||
// Fetch reports for aggregation
|
|
||||||
const weeklyReport = useReportList({ period: "weekly", rolling: true });
|
|
||||||
const monthlyReport = useReportList({ period: "monthly", rolling: true });
|
|
||||||
const payeeReport = useReportList({ period: "weekly", rolling: true, group_by: "payee" });
|
|
||||||
|
|
||||||
const isLoading =
|
|
||||||
latestQuery.isLoading ||
|
|
||||||
weeklyReport.isLoading ||
|
|
||||||
monthlyReport.isLoading ||
|
|
||||||
payeeReport.isLoading;
|
|
||||||
|
|
||||||
const error =
|
|
||||||
latestQuery.error ||
|
|
||||||
weeklyReport.error ||
|
|
||||||
monthlyReport.error ||
|
|
||||||
payeeReport.error;
|
|
||||||
|
|
||||||
const latest = latestQuery.data?.data
|
|
||||||
? mapToLatestItems(latestQuery.data.data, type)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const aggregatedData =
|
|
||||||
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,
|
|
||||||
type
|
|
||||||
)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
data: aggregatedData,
|
|
||||||
latest: latest,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
export {
|
export {
|
||||||
useReport
|
useReport
|
||||||
} from './useReport'
|
} from './useReport'
|
||||||
|
export type {
|
||||||
|
Transaction,
|
||||||
|
ReportData,
|
||||||
|
ReportBucket,
|
||||||
|
ReportPeriod,
|
||||||
|
GroupKey,
|
||||||
|
} from './report.models'
|
||||||
|
export {
|
||||||
|
prepareReport
|
||||||
|
} from './report.utils'
|
||||||
|
|||||||
@@ -1,100 +0,0 @@
|
|||||||
import {
|
|
||||||
AggregatedDashboardData,
|
|
||||||
ChartData,
|
|
||||||
ChartDataPoint,
|
|
||||||
} from "../../components/HistoryChart";
|
|
||||||
|
|
||||||
type ReportBucket = any;
|
|
||||||
|
|
||||||
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") => {
|
|
||||||
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 toPoints = (
|
|
||||||
buckets: ReportBucket[],
|
|
||||||
type: "weekly" | "monthly",
|
|
||||||
flow: "expenses" | "incomes"
|
|
||||||
): ChartDataPoint[] => {
|
|
||||||
return buckets.map((b, i) => {
|
|
||||||
const amount = sumBucket(b, flow);
|
|
||||||
const prev = buckets[i - 1];
|
|
||||||
|
|
||||||
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"
|
|
||||||
): AggregatedDashboardData {
|
|
||||||
const flow = type === "expense" ? "expenses" : "incomes";
|
|
||||||
|
|
||||||
const chartData: ChartData = {
|
|
||||||
daily: [],
|
|
||||||
|
|
||||||
weekly: {
|
|
||||||
rolling: toPoints(weekly, "weekly", flow),
|
|
||||||
calendar: toPoints(weekly, "weekly", flow),
|
|
||||||
},
|
|
||||||
|
|
||||||
monthly: {
|
|
||||||
rolling: toPoints(monthly, "monthly", flow),
|
|
||||||
calendar: toPoints(monthly, "monthly", 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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
90
src/features/report/report.models.ts
Normal file
90
src/features/report/report.models.ts
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
export interface Payor {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Payee {
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Account {
|
||||||
|
name: string;
|
||||||
|
number: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Tag {
|
||||||
|
name: string;
|
||||||
|
icon: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Transaction {
|
||||||
|
payor: Payor;
|
||||||
|
payee: Payee;
|
||||||
|
amount: number;
|
||||||
|
account: Account;
|
||||||
|
tags: Tag[];
|
||||||
|
occurred_at: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// Metrics
|
||||||
|
// -----------------------------
|
||||||
|
|
||||||
|
export interface ReportMetric {
|
||||||
|
sum: number;
|
||||||
|
count: number;
|
||||||
|
average: number;
|
||||||
|
transactions?: Transaction[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// Period
|
||||||
|
// -----------------------------
|
||||||
|
|
||||||
|
export interface ReportPeriod {
|
||||||
|
start: Date;
|
||||||
|
end: Date;
|
||||||
|
|
||||||
|
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 {
|
||||||
|
periods: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
|
||||||
|
|
||||||
|
rolling: boolean;
|
||||||
|
report_date?: string;
|
||||||
|
|
||||||
|
group_by: ("payee" | "tags")[];
|
||||||
|
|
||||||
|
ignore_self: boolean;
|
||||||
|
include_transactions: boolean;
|
||||||
|
|
||||||
|
buckets: ReportBucket[];
|
||||||
|
}
|
||||||
131
src/features/report/report.utils.ts
Normal file
131
src/features/report/report.utils.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import {
|
||||||
|
ReportData,
|
||||||
|
ReportPeriod
|
||||||
|
} from "./report.models";
|
||||||
|
|
||||||
|
/* ---------- ID BUILDING ---------- */
|
||||||
|
|
||||||
|
function formatDate(d: Date): string {
|
||||||
|
const y = d.getUTCFullYear();
|
||||||
|
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||||
|
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||||
|
return `${y}-${m}-${day}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPeriodId(
|
||||||
|
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||||
|
start: Date,
|
||||||
|
end: Date
|
||||||
|
): string {
|
||||||
|
const s = formatDate(start);
|
||||||
|
const e = formatDate(end);
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case "weekly":
|
||||||
|
return `W:${s}_${e}`;
|
||||||
|
case "monthly":
|
||||||
|
return `M:${s}_${e}`;
|
||||||
|
case "yearly":
|
||||||
|
return `Y:${s}_${e}`;
|
||||||
|
case "fyly":
|
||||||
|
return `FY:${s}_${e}`;
|
||||||
|
case "full":
|
||||||
|
return `FULL:${s}_${e}`;
|
||||||
|
default:
|
||||||
|
return `${s}_${e}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- LABEL BUILDING ---------- */
|
||||||
|
|
||||||
|
const dayFmt = new Intl.DateTimeFormat("en-GB", {
|
||||||
|
day: "numeric",
|
||||||
|
month: "short",
|
||||||
|
timeZone: "UTC",
|
||||||
|
});
|
||||||
|
|
||||||
|
const monthDayFmt = new Intl.DateTimeFormat("en-GB", {
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
timeZone: "UTC",
|
||||||
|
});
|
||||||
|
|
||||||
|
const monthFmt = new Intl.DateTimeFormat("en-GB", {
|
||||||
|
month: "short",
|
||||||
|
timeZone: "UTC",
|
||||||
|
});
|
||||||
|
|
||||||
|
const yearFmt = new Intl.DateTimeFormat("en-GB", {
|
||||||
|
year: "numeric",
|
||||||
|
timeZone: "UTC",
|
||||||
|
});
|
||||||
|
|
||||||
|
function sameMonth(a: Date, b: Date) {
|
||||||
|
return (
|
||||||
|
a.getUTCFullYear() === b.getUTCFullYear() &&
|
||||||
|
a.getUTCMonth() === b.getUTCMonth()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLabel(
|
||||||
|
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||||
|
start: Date,
|
||||||
|
end: Date
|
||||||
|
): string {
|
||||||
|
switch (type) {
|
||||||
|
case "weekly": {
|
||||||
|
const sDay = start.getUTCDate();
|
||||||
|
const m = monthFmt.format(start);
|
||||||
|
return `${sDay} ${m}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "monthly":
|
||||||
|
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
|
||||||
|
|
||||||
|
case "yearly":
|
||||||
|
return yearFmt.format(start);
|
||||||
|
|
||||||
|
case "fyly": {
|
||||||
|
const startY = start.getUTCFullYear();
|
||||||
|
const endY = end.getUTCFullYear();
|
||||||
|
return `FY ${startY}–${String(endY).slice(-2)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 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 {
|
||||||
|
return {
|
||||||
|
...reportData,
|
||||||
|
buckets: reportData.buckets.map((bucket) => {
|
||||||
|
const newPeriods: typeof bucket.periods = {};
|
||||||
|
|
||||||
|
for (const type of reportData.periods) {
|
||||||
|
const arr = bucket.periods[type];
|
||||||
|
if (arr) {
|
||||||
|
newPeriods[type] = decoratePeriods(type, arr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...bucket,
|
||||||
|
periods: newPeriods,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,14 +1,20 @@
|
|||||||
import { useResourceByName } from "../../../react-openapi";
|
import { useResourceByName } from "../../../react-openapi";
|
||||||
|
|
||||||
export interface ReportParams {
|
export interface ReportParams {
|
||||||
period: "weekly" | "monthly" | "yearly" | "fyly";
|
periods?: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
|
||||||
rolling?: boolean;
|
rolling?: boolean;
|
||||||
report_date?: string;
|
report_date?: string;
|
||||||
group_by?: ("flow" | "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");
|
||||||
return useList(params);
|
|
||||||
}
|
return useList({
|
||||||
|
...params,
|
||||||
|
periods: params.periods,
|
||||||
|
group_by: params.group_by,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user