Compare commits
31 Commits
main
...
7470da6d2d
| Author | SHA1 | Date | |
|---|---|---|---|
| 7470da6d2d | |||
| 34594215f9 | |||
| 0a92126b92 | |||
| 30cf227050 | |||
| a0e62b1bc4 | |||
| ea3b451266 | |||
| 4b4875c3f5 | |||
| 25bd882b75 | |||
| f684083496 | |||
| 0e0928af95 | |||
| 7b0b3fb615 | |||
| 38f7416942 | |||
| e82cad4f21 | |||
| 1daa90d091 | |||
| 2d0b0bc470 | |||
| 5f85abdf86 | |||
| cc7e6509d2 | |||
| 8a3ebdb1be | |||
| a36d9119bb | |||
| 67d4c85146 | |||
| 89ad8e376e | |||
| 71afc157ff | |||
| 5acbb7ccdd | |||
| 3fd20f11ab | |||
| 922d05ae37 | |||
| 1fe44abfde | |||
| 49bdb85088 | |||
| b1509fd5ab | |||
| 175ca64d1f | |||
| c9e609fee6 | |||
| 82264a5c34 |
@@ -7,28 +7,6 @@ import { createApiClient } from "../../react-auth";
|
||||
let _api: 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 = {
|
||||
get: (...args: Parameters<AxiosInstance["get"]>) => {
|
||||
if (!_api) throw new Error("API client not initialized");
|
||||
@@ -60,6 +38,6 @@ export const auth = {
|
||||
};
|
||||
|
||||
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
||||
_api = withParamsSerializer(createApiClient(baseUrl));
|
||||
_auth = withParamsSerializer(createApiClient(authBaseUrl));
|
||||
_api = createApiClient(baseUrl);
|
||||
_auth = createApiClient(authBaseUrl);
|
||||
}
|
||||
|
||||
@@ -8,22 +8,10 @@ import {
|
||||
|
||||
import ConfigurableDashboard from "./components/Dashboard";
|
||||
import { configuration } from "./dashboard-config";
|
||||
import {
|
||||
useReport,
|
||||
prepareReport,
|
||||
} from "./features/report";
|
||||
import { useDashboardData } from "./features/dashboard";
|
||||
|
||||
export default function Dashboard() {
|
||||
const report = useReport({
|
||||
periods: ["weekly", "monthly", "full"],
|
||||
rolling: true,
|
||||
include_transactions: true,
|
||||
group_by: ["tags"],
|
||||
})
|
||||
|
||||
const isLoading = report.isLoading;
|
||||
const error = report.error;
|
||||
|
||||
const { data, isLoading, error } = useDashboardData();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -41,11 +29,10 @@ export default function Dashboard() {
|
||||
);
|
||||
}
|
||||
|
||||
if (!report) {
|
||||
if (!data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = prepareReport(report.data?.data);
|
||||
return (
|
||||
<ConfigurableDashboard
|
||||
config={configuration}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
ReportData
|
||||
} from "../../features/report";
|
||||
|
||||
export type DashboardMode = "expense" | "income";
|
||||
export type DashboardPeriodType = "rolling" | "calendar";
|
||||
@@ -19,6 +16,7 @@ export interface DashboardSection {
|
||||
title?: string;
|
||||
summary?: string;
|
||||
component: React.ComponentType<any>;
|
||||
dataKey: string;
|
||||
settings?: Record<string, any>;
|
||||
isList?: boolean;
|
||||
style?: {
|
||||
@@ -47,5 +45,9 @@ export interface DashboardConfig {
|
||||
|
||||
export interface DashboardProps {
|
||||
config: DashboardConfig;
|
||||
data: ReportData;
|
||||
data: any;
|
||||
toggleMode: () => void;
|
||||
togglePeriodType: () => void;
|
||||
setSelectedPeriodId: (id: string | null) => void;
|
||||
toggleComparison: () => void;
|
||||
}
|
||||
|
||||
@@ -13,10 +13,6 @@ 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;
|
||||
toggleComparison: () => void;
|
||||
}
|
||||
|
||||
export default function DashboardView({
|
||||
@@ -105,26 +101,63 @@ export default function DashboardView({
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Component
|
||||
{...section.settings}
|
||||
header={section.title}
|
||||
summary={section.summary}
|
||||
reportData={data}
|
||||
title={section.title}
|
||||
accentColor={colors.primary}
|
||||
colorScheme={colors}
|
||||
{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}
|
||||
// State management
|
||||
mode={mode}
|
||||
|
||||
periodType={periodType}
|
||||
comparison={comparison}
|
||||
selectedPeriodId={selectedPeriodId}
|
||||
periodType={periodType}
|
||||
comparison={comparison}
|
||||
selectedPeriodId={selectedPeriodId}
|
||||
|
||||
togglePeriodType={togglePeriodType}
|
||||
toggleComparison={toggleComparison}
|
||||
setSelectedPeriodId={setSelectedPeriodId}
|
||||
/>
|
||||
togglePeriodType={togglePeriodType}
|
||||
toggleComparison={toggleComparison}
|
||||
setSelectedPeriodId={setSelectedPeriodId}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
</Box>
|
||||
) : (
|
||||
<Component
|
||||
{...section.settings}
|
||||
header={section.title}
|
||||
summary={section.summary}
|
||||
data={data[mode][section.dataKey]}
|
||||
title={section.title}
|
||||
accentColor={colors.primary}
|
||||
colorScheme={colors}
|
||||
|
||||
// State management
|
||||
mode={mode}
|
||||
|
||||
periodType={periodType}
|
||||
comparison={comparison}
|
||||
selectedPeriodId={selectedPeriodId}
|
||||
|
||||
togglePeriodType={togglePeriodType}
|
||||
toggleComparison={toggleComparison}
|
||||
setSelectedPeriodId={setSelectedPeriodId}
|
||||
/>
|
||||
)}
|
||||
</Grid>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -3,11 +3,9 @@ import {
|
||||
DashboardPeriodType,
|
||||
DashboardSelectedPeriodId
|
||||
} from "../Dashboard";
|
||||
import { ReportData } from "../../features/report";
|
||||
|
||||
export interface _ChartDataPoint {
|
||||
id: string;
|
||||
label: string;
|
||||
amount: number;
|
||||
highlighted?: boolean;
|
||||
}
|
||||
@@ -16,19 +14,26 @@ export interface ChartDataPoint extends _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 {
|
||||
header: string;
|
||||
summary?: string;
|
||||
tabs: string[];
|
||||
|
||||
reportData: ReportData;
|
||||
|
||||
data: ChartData;
|
||||
colorScheme: {
|
||||
primary: string;
|
||||
light: string;
|
||||
text: string;
|
||||
};
|
||||
|
||||
// State management
|
||||
mode: DashboardMode;
|
||||
periodType: DashboardPeriodType;
|
||||
selectedPeriodId: DashboardSelectedPeriodId;
|
||||
|
||||
@@ -1,200 +1,45 @@
|
||||
import * as React from "react";
|
||||
import { HistoryChartProps, ChartDataPoint } from "./HistoryChart.models";
|
||||
import { ChartDataPoint, HistoryChartProps, ChartData } from "./HistoryChart.models";
|
||||
import HistoryChartView from "./HistoryChart.view";
|
||||
import { ReportPeriod } from "../../features/report";
|
||||
|
||||
type DecoratedPeriod = ReportPeriod & {
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
const TAB_TO_KEY: Record<string, "weekly" | "monthly" | "yearly" | "fyly" | "full"> = {
|
||||
Weekly: "weekly",
|
||||
Monthly: "monthly",
|
||||
Yearly: "yearly",
|
||||
'Financial Year': "fyly",
|
||||
'All Time': "full"
|
||||
};
|
||||
|
||||
function getAmount(p: ReportPeriod, mode: "expense" | "income") {
|
||||
return mode === "expense" ? p.expenses.sum : p.incomes.sum;
|
||||
}
|
||||
|
||||
function mergeMetric(a: any, b: any) {
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
function mergeBuckets(
|
||||
buckets: any[],
|
||||
key: "weekly" | "monthly" | "yearly" | "fyly" | "full"
|
||||
): 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()
|
||||
);
|
||||
}
|
||||
|
||||
function attachComparison(
|
||||
points: ChartDataPoint[],
|
||||
key: "weekly" | "monthly" | "yearly" | "fyly" | "full"
|
||||
): 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
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildChartData(
|
||||
reportData: HistoryChartProps["reportData"],
|
||||
key: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||
mode: "expense" | "income",
|
||||
comparison: boolean
|
||||
): ChartDataPoint[] {
|
||||
const merged = mergeBuckets(reportData.buckets, key);
|
||||
console.log("Merged periods:", merged);
|
||||
|
||||
let points: ChartDataPoint[] = merged.map((p) => ({
|
||||
id: p.id,
|
||||
label: p.label,
|
||||
amount: getAmount(p, mode)
|
||||
}));
|
||||
|
||||
if (comparison) {
|
||||
points = attachComparison(points, key);
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
export default function HistoryChart(props: HistoryChartProps) {
|
||||
const {
|
||||
tabs,
|
||||
reportData,
|
||||
mode,
|
||||
periodType,
|
||||
comparison,
|
||||
selectedPeriodId,
|
||||
setSelectedPeriodId
|
||||
} = props;
|
||||
const { tabs, data, mode, periodType, comparison } = props;
|
||||
|
||||
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
|
||||
const [startIndex, setStartIndex] = React.useState(0);
|
||||
|
||||
const activeDataKey = TAB_TO_KEY[activeTab];
|
||||
const activeDataKey = activeTab.toLowerCase() as keyof ChartData;
|
||||
|
||||
const currentData = React.useMemo(() => {
|
||||
return buildChartData(reportData, activeDataKey, mode, comparison);
|
||||
}, [reportData, activeDataKey, mode, comparison]);
|
||||
let rawData: ChartDataPoint[] = [];
|
||||
|
||||
const section = data[activeDataKey];
|
||||
rawData = section?.[periodType] || [];
|
||||
|
||||
const currentData = rawData;
|
||||
|
||||
const maxAmount =
|
||||
currentData.length > 0
|
||||
? Math.max(
|
||||
...currentData.flatMap((d) =>
|
||||
comparison
|
||||
? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
|
||||
: [d.amount]
|
||||
comparison ? [d.amount, d.compare?.amount ?? 0] : [d.amount]
|
||||
),
|
||||
1
|
||||
)
|
||||
: 1;
|
||||
|
||||
const visibleCountMap = {
|
||||
weekly: 6,
|
||||
monthly: 4,
|
||||
yearly: 4,
|
||||
fyly: 4,
|
||||
full: 4,
|
||||
};
|
||||
|
||||
const visibleCount = visibleCountMap[activeDataKey] ?? 4;
|
||||
const visibleCountMap = { daily: 7, weekly: 6, monthly: 4 };
|
||||
// const visibleCountMap = { daily: 7, weekly: 6, monthly: 4, yearly: 4, fyly: 4, full: 4 };
|
||||
const visibleCount = visibleCountMap[activeDataKey];
|
||||
|
||||
const total = currentData.length;
|
||||
|
||||
const clampedStartIndex = Math.min(
|
||||
startIndex,
|
||||
Math.max(total - visibleCount, 0)
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (startIndex !== clampedStartIndex) {
|
||||
setStartIndex(clampedStartIndex);
|
||||
}
|
||||
}, [startIndex, clampedStartIndex]);
|
||||
const clampedStartIndex = Math.min(startIndex, Math.max(total - visibleCount, 0));
|
||||
|
||||
const visibleData = currentData.slice(
|
||||
clampedStartIndex,
|
||||
clampedStartIndex + visibleCount
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setSelectedPeriodId(null);
|
||||
}, [activeTab, periodType]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
selectedPeriodId &&
|
||||
!visibleData.some((p) => p.id === selectedPeriodId)
|
||||
) {
|
||||
setSelectedPeriodId(null);
|
||||
}
|
||||
}, [visibleData, selectedPeriodId]);
|
||||
|
||||
return (
|
||||
<HistoryChartView
|
||||
{...props}
|
||||
@@ -204,7 +49,7 @@ export default function HistoryChart(props: HistoryChartProps) {
|
||||
visibleData={visibleData}
|
||||
maxAmount={maxAmount}
|
||||
visibleCount={visibleCount}
|
||||
startIndex={clampedStartIndex}
|
||||
startIndex={startIndex}
|
||||
setStartIndex={setStartIndex}
|
||||
activeDataKey={activeDataKey}
|
||||
/>
|
||||
|
||||
@@ -25,3 +25,19 @@ export const formatDisplay = (
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
ChartDataPoint,
|
||||
HistoryChartProps,
|
||||
} from "./HistoryChart.models";
|
||||
import { formatDisplay } from "./HistoryChart.utils";
|
||||
import { formatDisplay, formatLabel } from "./HistoryChart.utils";
|
||||
|
||||
interface ViewProps extends HistoryChartProps {
|
||||
activeTab: string;
|
||||
@@ -35,6 +35,7 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
tabs,
|
||||
colorScheme,
|
||||
|
||||
// State management
|
||||
mode,
|
||||
periodType,
|
||||
selectedPeriodId,
|
||||
@@ -44,6 +45,7 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
setSelectedPeriodId,
|
||||
toggleComparison,
|
||||
|
||||
// HistoryChart state management
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
currentData,
|
||||
@@ -58,28 +60,19 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
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) => {
|
||||
if (newTab !== null) setActiveTab(newTab);
|
||||
};
|
||||
|
||||
const canGoLeft = clampedStartIndex > 0;
|
||||
const canGoRight = clampedStartIndex < maxStartIndex;
|
||||
const canGoLeft = startIndex > 0;
|
||||
const canGoRight = startIndex + visibleCount < currentData.length;
|
||||
|
||||
const handlePrev = () => {
|
||||
if (!canGoLeft) return;
|
||||
setStartIndex((prev) => Math.max(prev - visibleCount, 0));
|
||||
if (canGoLeft) setStartIndex((prev) => prev - visibleCount);
|
||||
};
|
||||
|
||||
const handleNext = () => {
|
||||
if (!canGoRight) return;
|
||||
setStartIndex((prev) => {
|
||||
const next = prev + visibleCount;
|
||||
return Math.min(next, maxStartIndex);
|
||||
});
|
||||
if (canGoRight) setStartIndex((prev) => prev + visibleCount);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -92,9 +85,10 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
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}
|
||||
</Typography>
|
||||
|
||||
@@ -112,10 +106,12 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
))}
|
||||
</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">
|
||||
<ToggleButton value="rolling">Rolling</ToggleButton>
|
||||
<ToggleButton value="calendar">Calendar</ToggleButton>
|
||||
<ToggleButton value="calendar" disabled={activeDataKey === "daily"}>
|
||||
Calendar
|
||||
</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<ToggleButton
|
||||
@@ -123,6 +119,22 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
selected={comparison}
|
||||
onChange={toggleComparison}
|
||||
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
|
||||
</ToggleButton>
|
||||
@@ -131,7 +143,19 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
{currentData.length > 0 ? (
|
||||
<Box sx={{ position: "relative", mt: 4 }}>
|
||||
{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" />
|
||||
</IconButton>
|
||||
)}
|
||||
@@ -142,67 +166,92 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
const compareHeight = comparison
|
||||
? ((point.compare?.amount ?? 0) / maxAmount) * 100
|
||||
: 0;
|
||||
|
||||
const labelHeight = Math.max(currentHeight, compareHeight);
|
||||
const isSelected = selectedPeriodId === point.id;
|
||||
const display = formatDisplay(point, activeDataKey, comparison);
|
||||
const display = formatDisplay(point, activeTab.toLowerCase(), comparison);
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={point.id}
|
||||
onClick={() =>
|
||||
setSelectedPeriodId(isSelected ? null : point.id)
|
||||
}
|
||||
onClick={() => setSelectedPeriodId(isSelected ? null : point.id)}
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
cursor: "pointer",
|
||||
height: "100%"
|
||||
justifyContent: "flex-end",
|
||||
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" }}>
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
position: "absolute",
|
||||
bottom: `${labelHeight}%`,
|
||||
left: "50%",
|
||||
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: alpha(colorScheme.primary, 0.4),
|
||||
borderRadius: "4px 4px 0 0"
|
||||
}}
|
||||
/>
|
||||
<Box sx={{ width: 8, height: `${compareHeight}%`, bgcolor: isDark ? alpha(colorScheme.primary, 0.3) : alpha(colorScheme.primary, 0.4), borderRadius: '4px 4px 0 0' }} />
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
width: 12,
|
||||
width: comparison ? 10 : 16,
|
||||
height: `${currentHeight}%`,
|
||||
bgcolor: isSelected ? "warning.main" : colorScheme.primary,
|
||||
borderRadius: "4px 4px 0 0"
|
||||
bgcolor: point.highlighted ? colorScheme.primary : isDark ? alpha(colorScheme.primary, 0.8) : alpha(colorScheme.primary, 0.9),
|
||||
borderRadius: '4px 4px 0 0',
|
||||
boxShadow: point.highlighted ? `0 0 10px ${alpha(colorScheme.primary, 0.5)}` : 'none'
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Typography variant="caption">
|
||||
{point.label}
|
||||
</Typography>
|
||||
|
||||
{comparison && point.compare && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{point.compare.label}
|
||||
<Box sx={{ mt: 1.5, textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", lineHeight: 1.1 }}>
|
||||
<Typography variant="caption" sx={{ fontSize: "0.7rem", opacity: 0.8, color: 'text.primary', fontWeight: 500 }}>
|
||||
{formatLabel(point.id, activeDataKey)}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Typography variant="caption">
|
||||
{display}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
fontSize: "0.65rem",
|
||||
color: "text.disabled",
|
||||
visibility: comparison && point.compare && activeDataKey !== "daily" ? "visible" : "hidden"
|
||||
}}
|
||||
>
|
||||
{point.compare ? formatLabel(point.compare.id, activeDataKey) : "placeholder"}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
||||
{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" />
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import * as React from "react";
|
||||
import { Box } from "@mui/material";
|
||||
import { ReportData, ReportPeriod } from "../../features/report";
|
||||
import ProgressCard from "./ProgressCard";
|
||||
|
||||
type Props = {
|
||||
reportData: ReportData;
|
||||
mode: "expense" | "income";
|
||||
selectedPeriodId?: string | null;
|
||||
compact?: boolean;
|
||||
};
|
||||
|
||||
type DecoratedPeriod = ReportPeriod & {
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
function getAmount(p: ReportPeriod, mode: "expense" | "income") {
|
||||
return mode === "expense" ? p.expenses.sum : p.incomes.sum;
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
export default function TopTags({
|
||||
reportData,
|
||||
mode,
|
||||
selectedPeriodId,
|
||||
compact = true
|
||||
}: Props) {
|
||||
const { items, total } = React.useMemo(() => {
|
||||
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 };
|
||||
}, [reportData, mode, selectedPeriodId]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: {
|
||||
xs: "1fr",
|
||||
sm: "repeat(2, 1fr)",
|
||||
md: "repeat(4, 1fr)"
|
||||
},
|
||||
gap: 2
|
||||
}}
|
||||
>
|
||||
{items.map((item) => (
|
||||
<ProgressCard
|
||||
key={item.tag}
|
||||
header={item.tag}
|
||||
progressAmount={item.amount}
|
||||
totalAmount={total}
|
||||
compact={compact}
|
||||
colorTheme={mode === "expense" ? "error" : "success"}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import HistoryChart from "./components/HistoryChart";
|
||||
import ProgressCard from "./components/ProgressCard";
|
||||
import LatestItems from "./components/LatestItems";
|
||||
import { DashboardConfig } from "./components/Dashboard";
|
||||
import TopTags from "./components/ProgressCard/TopTags";
|
||||
|
||||
export const configuration: DashboardConfig = {
|
||||
sections: [
|
||||
@@ -10,6 +10,7 @@ export const configuration: DashboardConfig = {
|
||||
title: "Breakdown",
|
||||
summary: "Interactive chronological tracking",
|
||||
component: HistoryChart,
|
||||
dataKey: "chartData",
|
||||
settings: {
|
||||
tabs: ["Weekly", "Monthly"],
|
||||
// tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"],
|
||||
@@ -21,7 +22,9 @@ export const configuration: DashboardConfig = {
|
||||
{
|
||||
id: "top-payees",
|
||||
title: 'Top Payees',
|
||||
component: TopTags,
|
||||
component: ProgressCard,
|
||||
dataKey: "topPayees",
|
||||
isList: true,
|
||||
settings: {
|
||||
compact: true,
|
||||
},
|
||||
|
||||
191
src/features/dashboard/dashboard.mapper.ts
Normal file
191
src/features/dashboard/dashboard.mapper.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
3
src/features/dashboard/index.ts
Normal file
3
src/features/dashboard/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export {
|
||||
useDashboardData
|
||||
} from './useDashboardData'
|
||||
44
src/features/dashboard/useDashboardData.ts
Normal file
44
src/features/dashboard/useDashboardData.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
@@ -3,8 +3,10 @@ export {
|
||||
} from './useReport'
|
||||
export type {
|
||||
Transaction,
|
||||
PeriodData,
|
||||
PeriodGroup,
|
||||
Period,
|
||||
ReportData,
|
||||
ReportPeriod,
|
||||
} from './report.models'
|
||||
export {
|
||||
prepareReport
|
||||
|
||||
@@ -18,73 +18,44 @@ export interface Tag {
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
payor: Payor;
|
||||
payee: Payee;
|
||||
amount: number;
|
||||
account: Account;
|
||||
tags: Tag[];
|
||||
occurred_at: Date;
|
||||
payor: Payor;
|
||||
payee: Payee;
|
||||
amount: number;
|
||||
account: Account;
|
||||
tags: Tag[]
|
||||
occurred_at: Date
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Metrics
|
||||
// -----------------------------
|
||||
|
||||
export interface ReportMetric {
|
||||
export interface _PeriodData {
|
||||
sum: number;
|
||||
count: number;
|
||||
average: number;
|
||||
transactions?: Transaction[];
|
||||
txns: Transaction[];
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Period
|
||||
// -----------------------------
|
||||
export interface PeriodData extends _PeriodData {
|
||||
compare?: _PeriodData;
|
||||
}
|
||||
|
||||
export interface ReportPeriod {
|
||||
export interface PeriodGroup {
|
||||
group_key: string[];
|
||||
expenses: PeriodData[];
|
||||
incomes: PeriodData[];
|
||||
}
|
||||
|
||||
export interface Period {
|
||||
id: string;
|
||||
label: string;
|
||||
start: Date;
|
||||
end: Date;
|
||||
|
||||
expenses: ReportMetric;
|
||||
incomes: ReportMetric;
|
||||
groups: PeriodGroup[];
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// 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;
|
||||
period: "weekly" | "monthly" | "yearly" | "fyly" | "full";
|
||||
rolling?: boolean;
|
||||
report_date?: string;
|
||||
|
||||
group_by: ("payee" | "tags")[];
|
||||
|
||||
ignore_self: boolean;
|
||||
include_transactions: boolean;
|
||||
|
||||
buckets: ReportBucket[];
|
||||
group_by?: ("payee" | "tags")[];
|
||||
ignore_self?: boolean;
|
||||
buckets: Period[];
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
ReportData,
|
||||
ReportPeriod
|
||||
} from "./report.models";
|
||||
import { ReportData } from "./report.models";
|
||||
|
||||
/* ---------- ID BUILDING ---------- */
|
||||
|
||||
@@ -13,7 +10,7 @@ function formatDate(d: Date): string {
|
||||
}
|
||||
|
||||
function buildPeriodId(
|
||||
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||
type: ReportData["period"],
|
||||
start: Date,
|
||||
end: Date
|
||||
): string {
|
||||
@@ -68,7 +65,7 @@ function sameMonth(a: Date, b: Date) {
|
||||
}
|
||||
|
||||
function buildLabel(
|
||||
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||
type: ReportData["period"],
|
||||
start: Date,
|
||||
end: Date
|
||||
): string {
|
||||
@@ -83,7 +80,10 @@ function buildLabel(
|
||||
return `${dayFmt.format(start)} - ${dayFmt.format(end)}`;
|
||||
|
||||
case "monthly":
|
||||
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
|
||||
if (sameMonth(start, end)) {
|
||||
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
|
||||
}
|
||||
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
|
||||
|
||||
case "yearly":
|
||||
return yearFmt.format(start);
|
||||
@@ -94,6 +94,9 @@ function buildLabel(
|
||||
return `FY ${startY}–${String(endY).slice(-2)}`;
|
||||
}
|
||||
|
||||
case "full":
|
||||
return `${monthFmt.format(start)} ${yearFmt.format(start)} - ${monthFmt.format(end)} ${yearFmt.format(end)}`;
|
||||
|
||||
default:
|
||||
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
|
||||
}
|
||||
@@ -101,34 +104,13 @@ function buildLabel(
|
||||
|
||||
/* ---------- 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,
|
||||
};
|
||||
}),
|
||||
buckets: reportData.buckets.map((p) => ({
|
||||
...p,
|
||||
id: buildPeriodId(reportData.period, p.start, p.end),
|
||||
label: buildLabel(reportData.period, p.start, p.end),
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
import { useResourceByName } from "../../../react-openapi";
|
||||
|
||||
export interface ReportParams {
|
||||
periods?: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
|
||||
period: "weekly" | "monthly" | "yearly" | "fyly" | "full";
|
||||
rolling?: boolean;
|
||||
report_date?: string;
|
||||
group_by?: ("payee" | "tags")[];
|
||||
ignore_self?: boolean;
|
||||
include_transactions?: boolean;
|
||||
}
|
||||
|
||||
export function useReport(params: ReportParams) {
|
||||
const { useList } = useResourceByName("reports");
|
||||
|
||||
return useList({
|
||||
...params,
|
||||
periods: params.periods,
|
||||
group_by: params.group_by,
|
||||
});
|
||||
}
|
||||
if (params.group_by) {
|
||||
// @ts-ignore
|
||||
params.group_by = params.group_by[0]
|
||||
}
|
||||
return useList(params);
|
||||
}
|
||||
Reference in New Issue
Block a user