Compare commits
4 Commits
1.2.2
...
47c00a06a8
| Author | SHA1 | Date | |
|---|---|---|---|
| 47c00a06a8 | |||
| a107029b90 | |||
| baa9b296cb | |||
| f08bc72037 |
@@ -10,32 +10,15 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useResource, useAppContext, formatCurrency } from "../../react-openapi";
|
import { useResource, useAppContext, formatCurrency } from "../react-openapi";
|
||||||
import { PageHeader } from "../ui/PageHeader";
|
import { PageHeader } from "./ui/PageHeader";
|
||||||
import { EmptyState } from "../ui/EmptyState";
|
import { EmptyState } from "./ui/EmptyState";
|
||||||
import { ExpenseList } from "./ExpenseList";
|
import { StatCard } from "./common/components/StatCard";
|
||||||
import { ExpenseItem, ExpenseFieldConfigs, isExpense, currentMonthKey, monthKey, monthLabel, parseOccurredAt } from "./types";
|
import { TransactionList } from "./common/components/TransactionList";
|
||||||
|
import { buildTxnFieldConfigs } from "./common/utils/fieldConfigs";
|
||||||
function StatCard({ label, value, hint }: { label: string; value: string; hint?: string }) {
|
import { isExpense } from "./common/utils/transactions";
|
||||||
return (
|
import { currentMonthKey, monthKey, monthLabel, parseOccurredAt } from "./common/utils/dates";
|
||||||
<Paper
|
import type { ExpenseItem } from "./common/types";
|
||||||
variant="outlined"
|
|
||||||
sx={{ p: 2.5, borderRadius: 3, flex: 1, minWidth: 180 }}
|
|
||||||
>
|
|
||||||
<Typography variant="caption" color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
|
|
||||||
{label}
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="h5" fontWeight={700} sx={{ mt: 0.5, letterSpacing: "-0.02em" }}>
|
|
||||||
{value}
|
|
||||||
</Typography>
|
|
||||||
{hint && (
|
|
||||||
<Typography variant="caption" color="text.secondary">
|
|
||||||
{hint}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Expense() {
|
export default function Expense() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -43,33 +26,7 @@ export default function Expense() {
|
|||||||
const { resources } = useAppContext();
|
const { resources } = useAppContext();
|
||||||
const [items, setItems] = useState<ExpenseItem[] | null>(null);
|
const [items, setItems] = useState<ExpenseItem[] | null>(null);
|
||||||
|
|
||||||
const fieldConfigs = useMemo<ExpenseFieldConfigs | null>(() => {
|
const fieldConfigs = useMemo(() => buildTxnFieldConfigs(resources), [resources]);
|
||||||
if (!resource) return null;
|
|
||||||
const find = (name: string) => resource.fields.find((f) => f.name === name);
|
|
||||||
const entity = find("entity");
|
|
||||||
const amount = find("amount");
|
|
||||||
const account = find("account");
|
|
||||||
const tags = find("tags");
|
|
||||||
const occurredAt = find("occurred_at");
|
|
||||||
const entitiesRes = resources.find((r) => r.name === "entities");
|
|
||||||
const accountsRes = resources.find((r) => r.name === "accounts");
|
|
||||||
const tagsRes = resources.find((r) => r.name === "tags");
|
|
||||||
const logo = entitiesRes?.fields.find((f) => f.name === "logo");
|
|
||||||
if (!entity || !amount || !account || !tags || !occurredAt || !logo) return null;
|
|
||||||
return {
|
|
||||||
entity,
|
|
||||||
amount,
|
|
||||||
account,
|
|
||||||
tags,
|
|
||||||
occurredAt,
|
|
||||||
logo,
|
|
||||||
formats: {
|
|
||||||
entity: entitiesRes?.displayFormat ?? "{name}",
|
|
||||||
account: accountsRes?.displayFormat ?? "{name}",
|
|
||||||
tags: tagsRes?.displayFormat ?? "{name}",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}, [resource, resources]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
@@ -80,7 +37,7 @@ export default function Expense() {
|
|||||||
return () => {
|
return () => {
|
||||||
mounted = false;
|
mounted = false;
|
||||||
};
|
};
|
||||||
}, []);
|
}, [list]);
|
||||||
|
|
||||||
const sorted = useMemo(
|
const sorted = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -161,7 +118,7 @@ export default function Expense() {
|
|||||||
<StatCard label="Income" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
<StatCard label="Income" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{fieldConfigs && <ExpenseList items={sorted} fields={fieldConfigs} />}
|
{fieldConfigs && <TransactionList items={sorted} fields={fieldConfigs} />}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Container>
|
</Container>
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
import type { FieldConfig } from "../../react-openapi";
|
|
||||||
|
|
||||||
export interface ExpenseItem {
|
|
||||||
id: string;
|
|
||||||
entity?: { name?: string; type?: string; logo?: string } | null;
|
|
||||||
amount: number;
|
|
||||||
account?: { name?: string; number?: string; type?: string; currency?: string } | null;
|
|
||||||
tags?: { icon?: string; name?: string }[];
|
|
||||||
occurred_at?: string;
|
|
||||||
created_at?: string;
|
|
||||||
updated_at?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ExpenseFieldConfigs {
|
|
||||||
entity: FieldConfig;
|
|
||||||
amount: FieldConfig;
|
|
||||||
account: FieldConfig;
|
|
||||||
tags: FieldConfig;
|
|
||||||
occurredAt: FieldConfig;
|
|
||||||
logo: FieldConfig;
|
|
||||||
formats: {
|
|
||||||
entity: string;
|
|
||||||
account: string;
|
|
||||||
tags: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isExpense(item: ExpenseItem): boolean {
|
|
||||||
return (item.amount ?? 0) < 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseOccurredAt(value?: string): Date {
|
|
||||||
const m = value?.match(/^(\d{2})-(\d{2})-(\d{4})$/);
|
|
||||||
if (!m) {
|
|
||||||
throw new Error(`Expense occurred_at is not DD-MM-YYYY: ${value}`);
|
|
||||||
}
|
|
||||||
const [, dd, mm, yyyy] = m;
|
|
||||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
|
||||||
if (
|
|
||||||
Number.isNaN(d.getTime()) ||
|
|
||||||
d.getDate() !== Number(dd) ||
|
|
||||||
d.getMonth() !== Number(mm) - 1 ||
|
|
||||||
d.getFullYear() !== Number(yyyy)
|
|
||||||
) {
|
|
||||||
throw new Error(`Invalid expense occurred_at date: ${value}`);
|
|
||||||
}
|
|
||||||
return d;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function monthKey(value?: string): string {
|
|
||||||
const d = parseOccurredAt(value);
|
|
||||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function currentMonthKey(): string {
|
|
||||||
const now = new Date();
|
|
||||||
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function monthLabel(key: string): string {
|
|
||||||
const [y, m] = key.split("-").map(Number);
|
|
||||||
if (!y || !m) return key;
|
|
||||||
const d = new Date(y, m - 1, 1);
|
|
||||||
return d.toLocaleDateString("en-IN", { month: "long", year: "numeric" });
|
|
||||||
}
|
|
||||||
@@ -34,6 +34,7 @@ interface HeaderProps {
|
|||||||
const NAV_LINKS = [
|
const NAV_LINKS = [
|
||||||
{ label: "Home", path: "/" },
|
{ label: "Home", path: "/" },
|
||||||
{ label: "Expenses", path: "/expenses" },
|
{ label: "Expenses", path: "/expenses" },
|
||||||
|
{ label: "Reports", path: "/reports" },
|
||||||
{ label: "Fetch Requests", path: "/fetch-requests" },
|
{ label: "Fetch Requests", path: "/fetch-requests" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
211
src/Reports/GenerateReportPanel.tsx
Normal file
211
src/Reports/GenerateReportPanel.tsx
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Paper,
|
||||||
|
Typography,
|
||||||
|
TextField,
|
||||||
|
Button,
|
||||||
|
IconButton,
|
||||||
|
MenuItem,
|
||||||
|
Select,
|
||||||
|
FormControl,
|
||||||
|
InputLabel,
|
||||||
|
Autocomplete,
|
||||||
|
Alert,
|
||||||
|
} from "@mui/material";
|
||||||
|
import AddIcon from "@mui/icons-material/Add";
|
||||||
|
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
|
||||||
|
import { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
|
||||||
|
import { useToast } from "../ui/Toast";
|
||||||
|
import { isDdmmyyyy } from "../common/utils/dates";
|
||||||
|
import { apiErrorMessage, groupTypeEnum, periodHints } from "./types";
|
||||||
|
|
||||||
|
interface GroupRow {
|
||||||
|
id: number;
|
||||||
|
group_type: string;
|
||||||
|
group_value: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GenerateReportPanelProps {
|
||||||
|
onGenerated: (reports: any[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
||||||
|
const { schemas, resources } = useAppContext();
|
||||||
|
const { create } = useResource("reports");
|
||||||
|
const { list: listEntities } = useResource("entities");
|
||||||
|
const { showToast } = useToast();
|
||||||
|
|
||||||
|
const [rows, setRows] = useState<GroupRow[]>([{ id: 1, group_type: "monthly", group_value: "*" }]);
|
||||||
|
const [startDate, setStartDate] = useState("");
|
||||||
|
const [endDate, setEndDate] = useState("");
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [entityNames, setEntityNames] = useState<string[]>([]);
|
||||||
|
const [dateErrors, setDateErrors] = useState<{ start?: string; end?: string }>({});
|
||||||
|
|
||||||
|
const types = useMemo(() => groupTypeEnum(schemas), [schemas]);
|
||||||
|
const entitiesRes = resources.find((r) => r.name === "entities");
|
||||||
|
const entitiesFormat = entitiesRes?.displayFormat ?? "{name}";
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
listEntities({ limit: 0 }).then((res) => {
|
||||||
|
if (!mounted) return;
|
||||||
|
const names = (res.items ?? [])
|
||||||
|
.map((it: any) => applyDisplayFormat(it, entitiesFormat))
|
||||||
|
.filter((n: string) => n);
|
||||||
|
setEntityNames([...new Set(names)].sort((a, b) => a.localeCompare(b)));
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
mounted = false;
|
||||||
|
};
|
||||||
|
}, [listEntities, entitiesFormat]);
|
||||||
|
|
||||||
|
const isPayee = (type: string) => type === "payee";
|
||||||
|
|
||||||
|
const valueOptions = (row: GroupRow): string[] => ["*", ...(isPayee(row.group_type) ? entityNames : [])];
|
||||||
|
|
||||||
|
const valueHint = (row: GroupRow): string =>
|
||||||
|
isPayee(row.group_type) ? "Entity name, or * for all payees" : `e.g. ${periodHints(row.group_type).join(", ")}, or *`;
|
||||||
|
|
||||||
|
const nextRowId = () => Math.max(0, ...rows.map((r) => r.id)) + 1;
|
||||||
|
|
||||||
|
const addRow = () => setRows((rs) => [...rs, { id: nextRowId(), group_type: "monthly", group_value: "*" }]);
|
||||||
|
|
||||||
|
const removeRow = (id: number) => setRows((rs) => rs.filter((r) => r.id !== id));
|
||||||
|
|
||||||
|
const updateRow = (id: number, patch: Partial<GroupRow>) =>
|
||||||
|
setRows((rs) => rs.map((r) => (r.id === id ? { ...r, ...patch } : r)));
|
||||||
|
|
||||||
|
const validateDates = (): boolean => {
|
||||||
|
const errs: { start?: string; end?: string } = {};
|
||||||
|
if (startDate && !isDdmmyyyy(startDate)) errs.start = "Use DD-MM-YYYY";
|
||||||
|
if (endDate && !isDdmmyyyy(endDate)) errs.end = "Use DD-MM-YYYY";
|
||||||
|
setDateErrors(errs);
|
||||||
|
return Object.keys(errs).length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!validateDates()) return;
|
||||||
|
setError(null);
|
||||||
|
const groups = rows
|
||||||
|
.filter((r) => r.group_type && r.group_value.trim())
|
||||||
|
.map(({ group_type, group_value }) => ({ group_type, group_value: group_value.trim() }));
|
||||||
|
if (groups.length === 0) {
|
||||||
|
setError("At least one group is required");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSubmitting(true);
|
||||||
|
const payload: Record<string, any> = { groups };
|
||||||
|
if (startDate.trim()) payload.start_date = startDate.trim();
|
||||||
|
if (endDate.trim()) payload.end_date = endDate.trim();
|
||||||
|
try {
|
||||||
|
const created = await create(payload);
|
||||||
|
const list = Array.isArray(created) ? created : created ? [created] : [];
|
||||||
|
showToast(`Generated ${list.length} report${list.length === 1 ? "" : "s"}`);
|
||||||
|
onGenerated(list);
|
||||||
|
} catch (e: any) {
|
||||||
|
setError(apiErrorMessage(e));
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3, mb: 4 }}>
|
||||||
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
|
Generate report
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5, mb: 2 }}>
|
||||||
|
Choose the dimensions to snapshot. At least one group is required — with no period dimension the server
|
||||||
|
snapshots weekly, monthly and quarterly.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2, borderRadius: 2 }}>
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||||
|
{rows.map((row) => (
|
||||||
|
<Box key={row.id} sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}>
|
||||||
|
<FormControl size="small" sx={{ width: 180, flexShrink: 0 }}>
|
||||||
|
<InputLabel id={`group-type-${row.id}`}>Type</InputLabel>
|
||||||
|
<Select
|
||||||
|
labelId={`group-type-${row.id}`}
|
||||||
|
label="Type"
|
||||||
|
value={row.group_type}
|
||||||
|
onChange={(e) => updateRow(row.id, { group_type: e.target.value, group_value: "*" })}
|
||||||
|
>
|
||||||
|
{types.map((t) => (
|
||||||
|
<MenuItem key={t} value={t}>
|
||||||
|
{t}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
<Autocomplete
|
||||||
|
freeSolo
|
||||||
|
size="small"
|
||||||
|
sx={{ flex: 1, minWidth: 240 }}
|
||||||
|
options={valueOptions(row)}
|
||||||
|
value={row.group_value}
|
||||||
|
onInputChange={(_, newVal) => updateRow(row.id, { group_value: newVal ?? "" })}
|
||||||
|
renderInput={(params) => (
|
||||||
|
<TextField {...params} label="Value" helperText={valueHint(row)} />
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<IconButton
|
||||||
|
aria-label="Remove group"
|
||||||
|
disabled={rows.length === 1}
|
||||||
|
onClick={() => removeRow(row.id)}
|
||||||
|
sx={{ mt: 0.25 }}
|
||||||
|
>
|
||||||
|
<RemoveCircleOutlineIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Button startIcon={<AddIcon />} size="small" sx={{ mt: 1 }} onClick={addRow}>
|
||||||
|
Add dimension
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, mt: 2, flexWrap: "wrap" }}>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label="Start date"
|
||||||
|
placeholder="DD-MM-YYYY"
|
||||||
|
value={startDate}
|
||||||
|
onChange={(e) => setStartDate(e.target.value)}
|
||||||
|
error={Boolean(dateErrors.start)}
|
||||||
|
helperText={dateErrors.start ?? "Inclusive start (empty = unbounded)"}
|
||||||
|
sx={{ width: 200 }}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label="End date"
|
||||||
|
placeholder="DD-MM-YYYY"
|
||||||
|
value={endDate}
|
||||||
|
onChange={(e) => setEndDate(e.target.value)}
|
||||||
|
error={Boolean(dateErrors.end)}
|
||||||
|
helperText={dateErrors.end ?? "Inclusive end (empty = unbounded)"}
|
||||||
|
sx={{ width: 200 }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
startIcon={<AddIcon />}
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={submitting}
|
||||||
|
>
|
||||||
|
{submitting ? "Generating…" : "Generate"}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
144
src/Reports/Report.tsx
Normal file
144
src/Reports/Report.tsx
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import { Container, Box, Paper, Typography, Alert } from "@mui/material";
|
||||||
|
import AssessmentIcon from "@mui/icons-material/Assessment";
|
||||||
|
import { useResource, useAppContext, formatCurrency } from "../../react-openapi";
|
||||||
|
import { useToast } from "../ui/Toast";
|
||||||
|
import { PageHeader } from "../ui/PageHeader";
|
||||||
|
import { EmptyState } from "../ui/EmptyState";
|
||||||
|
import { StatCard } from "../common/components/StatCard";
|
||||||
|
import { buildTxnFieldConfigs } from "../common/utils/fieldConfigs";
|
||||||
|
import { GenerateReportPanel } from "./GenerateReportPanel";
|
||||||
|
import { ReportList } from "./ReportList";
|
||||||
|
import { ReportViewer } from "./ReportViewer";
|
||||||
|
import { apiErrorMessage, buildReportFieldConfigs } from "./types";
|
||||||
|
|
||||||
|
export default function Report() {
|
||||||
|
const { resources } = useAppContext();
|
||||||
|
const { showToast } = useToast();
|
||||||
|
const { list, loading, error } = useResource("reports");
|
||||||
|
const { create, remove } = useResource("reports");
|
||||||
|
|
||||||
|
const [reports, setReports] = useState<any[] | null>(null);
|
||||||
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
|
const [viewerVersion, setViewerVersion] = useState(0);
|
||||||
|
|
||||||
|
const reportFields = useMemo(() => buildReportFieldConfigs(resources), [resources]);
|
||||||
|
const txnFields = useMemo(() => buildTxnFieldConfigs(resources), [resources]);
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
const res = await list({ limit: 200 });
|
||||||
|
setReports(res.items ?? []);
|
||||||
|
}, [list]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const handleGenerated = useCallback(
|
||||||
|
(created: any[]) => {
|
||||||
|
load();
|
||||||
|
if (created?.[0]?.id) setSelectedId(created[0].id);
|
||||||
|
},
|
||||||
|
[load],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleRegenerate = useCallback(
|
||||||
|
async (report: any) => {
|
||||||
|
const payload: Record<string, any> = { groups: report.groups ?? [] };
|
||||||
|
if (report.start_date) payload.start_date = report.start_date;
|
||||||
|
if (report.end_date) payload.end_date = report.end_date;
|
||||||
|
try {
|
||||||
|
await create(payload);
|
||||||
|
showToast("Report regenerated");
|
||||||
|
setSelectedId(report.id);
|
||||||
|
setViewerVersion((v) => v + 1);
|
||||||
|
load();
|
||||||
|
} catch (e: any) {
|
||||||
|
showToast(apiErrorMessage(e), "error");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[create, load, showToast],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleDelete = useCallback(
|
||||||
|
async (id: string) => {
|
||||||
|
try {
|
||||||
|
await remove(id);
|
||||||
|
showToast("Report deleted");
|
||||||
|
if (selectedId === id) setSelectedId(null);
|
||||||
|
load();
|
||||||
|
} catch (e: any) {
|
||||||
|
showToast(apiErrorMessage(e), "error");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[remove, load, selectedId, showToast],
|
||||||
|
);
|
||||||
|
|
||||||
|
const summary = useMemo(() => {
|
||||||
|
const rows = reports ?? [];
|
||||||
|
const txnCount = rows.reduce((s, r) => s + (r.txn_count ?? 0), 0);
|
||||||
|
const total = rows.reduce((s, r) => s + (typeof r.metrics?.sum === "number" ? r.metrics.sum : 0), 0);
|
||||||
|
return { count: rows.length, txnCount, total };
|
||||||
|
}, [reports]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container maxWidth="lg" sx={{ py: 4 }}>
|
||||||
|
<PageHeader
|
||||||
|
crumbs={[{ label: "Home", path: "/" }, { label: "Reports" }]}
|
||||||
|
title="Reports"
|
||||||
|
subtitle="Generate period/payee snapshots from the reporting API and slice the cached data."
|
||||||
|
/>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||||
|
Failed to load reports: {error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
||||||
|
<StatCard label="Reports" value={summary.count.toLocaleString("en-IN")} />
|
||||||
|
<StatCard label="Transactions covered" value={summary.txnCount.toLocaleString("en-IN")} />
|
||||||
|
<StatCard label="Total" value={formatCurrency(summary.total, "INR")} />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<GenerateReportPanel onGenerated={handleGenerated} />
|
||||||
|
|
||||||
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em", mb: 1.5 }}>
|
||||||
|
Saved reports
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{reports !== null && reports.length === 0 ? (
|
||||||
|
<Paper variant="outlined" sx={{ borderRadius: 3 }}>
|
||||||
|
<EmptyState
|
||||||
|
icon={<AssessmentIcon />}
|
||||||
|
title="No reports yet"
|
||||||
|
description="Generate your first report above — pick a granularity and payee (a payee-only or wildcard config snapshots weekly, monthly and quarterly)."
|
||||||
|
/>
|
||||||
|
</Paper>
|
||||||
|
) : (
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2.5, mb: 4 }}>
|
||||||
|
<ReportList
|
||||||
|
reports={reports ?? []}
|
||||||
|
loading={loading}
|
||||||
|
fields={reportFields}
|
||||||
|
selectedId={selectedId}
|
||||||
|
onView={(id) => setSelectedId(id)}
|
||||||
|
onRegenerate={handleRegenerate}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedId && (
|
||||||
|
<ReportViewer
|
||||||
|
key={selectedId}
|
||||||
|
id={selectedId}
|
||||||
|
version={viewerVersion}
|
||||||
|
fields={txnFields}
|
||||||
|
onClose={() => setSelectedId(null)}
|
||||||
|
onRegenerated={handleRegenerate}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
122
src/Reports/ReportList.tsx
Normal file
122
src/Reports/ReportList.tsx
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Box, Paper, Typography, Button, IconButton, Skeleton, Tooltip } from "@mui/material";
|
||||||
|
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
||||||
|
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||||
|
import CachedIcon from "@mui/icons-material/Cached";
|
||||||
|
import { ListCellRenderer, formatCurrency } from "../../react-openapi";
|
||||||
|
import type { ReportFieldConfigs } from "./types";
|
||||||
|
|
||||||
|
interface ReportListProps {
|
||||||
|
reports: any[];
|
||||||
|
loading: boolean;
|
||||||
|
fields: ReportFieldConfigs | null;
|
||||||
|
selectedId: string | null;
|
||||||
|
onView: (id: string) => void;
|
||||||
|
onRegenerate: (report: any) => void;
|
||||||
|
onDelete: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReportList({ reports, loading, fields, selectedId, onView, onRegenerate, onDelete }: ReportListProps) {
|
||||||
|
if (loading && reports.length === 0) {
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||||
|
{[0, 1, 2].map((i) => (
|
||||||
|
<Skeleton key={i} variant="rounded" height={88} sx={{ borderRadius: 2 }} />
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||||
|
{reports.map((report) => {
|
||||||
|
const sum = typeof report.metrics?.sum === "number" ? report.metrics.sum : null;
|
||||||
|
const range =
|
||||||
|
report.start_date || report.end_date
|
||||||
|
? `range ${report.start_date || "…"} → ${report.end_date || "…"}`
|
||||||
|
: null;
|
||||||
|
return (
|
||||||
|
<Paper
|
||||||
|
key={report.id}
|
||||||
|
variant="outlined"
|
||||||
|
sx={{
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 2,
|
||||||
|
borderColor: selectedId === report.id ? "primary.main" : "divider",
|
||||||
|
transition: "border-color 160ms ease",
|
||||||
|
"&:hover": { borderColor: "primary.light" },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
||||||
|
<Box sx={{ flex: "1 1 260px", minWidth: 0 }}>
|
||||||
|
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}>
|
||||||
|
{report.group_label}
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.25 }}>
|
||||||
|
{fields && (
|
||||||
|
<ListCellRenderer field={fields.granularity} value={report.granularity} />
|
||||||
|
)}
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{report.period_label}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
/
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{report.payee}
|
||||||
|
</Typography>
|
||||||
|
{range && (
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{range}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, mt: 0.5 }}>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{report.entity_count ?? 0} entities
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{report.txn_count ?? 0} txns
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{report.expense_count ?? 0} expenses
|
||||||
|
</Typography>
|
||||||
|
{fields && (
|
||||||
|
<Box sx={{ color: "text.secondary" }}>
|
||||||
|
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ flexShrink: 0, textAlign: "right" }}>
|
||||||
|
<Typography variant="body1" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
|
{sum != null ? formatCurrency(sum, "INR") : "—"}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
|
||||||
|
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
||||||
|
View
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
startIcon={<CachedIcon />}
|
||||||
|
onClick={() => onRegenerate(report)}
|
||||||
|
>
|
||||||
|
Regenerate
|
||||||
|
</Button>
|
||||||
|
<Tooltip title="Delete">
|
||||||
|
<IconButton aria-label="Delete report" onClick={() => onDelete(report.id)}>
|
||||||
|
<DeleteOutlineIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
291
src/Reports/ReportViewer.tsx
Normal file
291
src/Reports/ReportViewer.tsx
Normal file
@@ -0,0 +1,291 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Paper,
|
||||||
|
Typography,
|
||||||
|
Button,
|
||||||
|
IconButton,
|
||||||
|
Alert,
|
||||||
|
Skeleton,
|
||||||
|
TextField,
|
||||||
|
Autocomplete,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableContainer,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
} from "@mui/material";
|
||||||
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
|
import CachedIcon from "@mui/icons-material/Cached";
|
||||||
|
import { useAppContext, useResource, formatCurrency } from "../../react-openapi";
|
||||||
|
import { StatCard } from "../common/components/StatCard";
|
||||||
|
import { TransactionList } from "../common/components/TransactionList";
|
||||||
|
import type { TxnFieldConfigs } from "../common/types";
|
||||||
|
import { toPeriodGranularity } from "../common/utils/transactions";
|
||||||
|
import { aggregateSlice, buildPivot, metricLabels } from "./types";
|
||||||
|
|
||||||
|
interface ReportViewerProps {
|
||||||
|
id: string;
|
||||||
|
version: number;
|
||||||
|
fields: TxnFieldConfigs | null;
|
||||||
|
onClose: () => void;
|
||||||
|
onRegenerated: (report: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReportViewer({ id, version, fields, onClose, onRegenerated }: ReportViewerProps) {
|
||||||
|
const { schemas } = useAppContext();
|
||||||
|
const { get } = useResource("reports");
|
||||||
|
|
||||||
|
const [report, setReport] = useState<any | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [reload, setReload] = useState(0);
|
||||||
|
const [selectedPeriod, setSelectedPeriod] = useState("*");
|
||||||
|
const [selectedPayee, setSelectedPayee] = useState("*");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let mounted = true;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
get(id)
|
||||||
|
.then((res) => {
|
||||||
|
if (!mounted) return;
|
||||||
|
setReport(res);
|
||||||
|
setSelectedPeriod("*");
|
||||||
|
setSelectedPayee("*");
|
||||||
|
})
|
||||||
|
.catch((e: any) => {
|
||||||
|
if (!mounted) return;
|
||||||
|
setError(e?.response?.data?.detail ?? e?.message ?? "Failed to load report");
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (mounted) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
mounted = false;
|
||||||
|
};
|
||||||
|
}, [id, version, reload, get]);
|
||||||
|
|
||||||
|
const data = useMemo(() => (Array.isArray(report?.data) ? report.data : null), [report]);
|
||||||
|
|
||||||
|
const groupOptions = useMemo(() => {
|
||||||
|
const options = report?.metadata?.group_options;
|
||||||
|
if (!options || typeof options !== "object") return { period: [], payee: [] };
|
||||||
|
return {
|
||||||
|
period: Array.isArray(options.period) ? options.period.map(String) : [],
|
||||||
|
payee: Array.isArray(options.payee) ? options.payee.map(String) : [],
|
||||||
|
};
|
||||||
|
}, [report]);
|
||||||
|
|
||||||
|
const slice = useMemo(
|
||||||
|
() => aggregateSlice(data ?? [], { period: selectedPeriod, payee: selectedPayee }),
|
||||||
|
[data, selectedPeriod, selectedPayee],
|
||||||
|
);
|
||||||
|
|
||||||
|
const pivot = useMemo(
|
||||||
|
() => buildPivot(data ?? [], groupOptions.period, groupOptions.payee),
|
||||||
|
[data, groupOptions],
|
||||||
|
);
|
||||||
|
|
||||||
|
const metrics = useMemo(() => {
|
||||||
|
const labels = metricLabels(schemas);
|
||||||
|
const displayKeys = ["sum", "count", "avg", "min", "max", "first_date", "last_date"];
|
||||||
|
return labels.filter((l) => displayKeys.includes(l.key));
|
||||||
|
}, [schemas]);
|
||||||
|
|
||||||
|
const metricValue = (key: string): string | null => {
|
||||||
|
if (key === "sum") return formatCurrency(slice.sum, slice.currency);
|
||||||
|
if (key === "count") return slice.count.toLocaleString("en-IN");
|
||||||
|
if (key === "avg") return slice.avg == null ? null : formatCurrency(slice.avg, slice.currency);
|
||||||
|
if (key === "min") return slice.min == null ? null : formatCurrency(slice.min, slice.currency);
|
||||||
|
if (key === "max") return slice.max == null ? null : formatCurrency(slice.max, slice.currency);
|
||||||
|
if (key === "first_date") return slice.firstDate;
|
||||||
|
if (key === "last_date") return slice.lastDate;
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
||||||
|
<Skeleton variant="text" width={220} height={28} />
|
||||||
|
<Skeleton variant="rounded" height={120} sx={{ my: 2, borderRadius: 2 }} />
|
||||||
|
<Skeleton variant="rounded" height={240} sx={{ borderRadius: 2 }} />
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Paper variant="outlined" sx={{ p: 3, borderRadius: 3 }}>
|
||||||
|
<Alert severity="error" sx={{ borderRadius: 2 }}>
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
<Button size="small" sx={{ mt: 2 }} onClick={() => setReload((r) => r + 1)}>
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!report) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper variant="outlined" sx={{ borderRadius: 3, overflow: "hidden" }}>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 2,
|
||||||
|
px: 2.5,
|
||||||
|
py: 2,
|
||||||
|
borderBottom: "1px solid",
|
||||||
|
borderColor: "divider",
|
||||||
|
flexWrap: "wrap",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||||
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
|
{report.group_label}
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{report.granularity} · {report.period_label} · {report.payee}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{report.entity_count ?? 0} entities · {report.txn_count ?? 0} txns · {report.expense_count ?? 0} expenses
|
||||||
|
</Typography>
|
||||||
|
{report.start_date || report.end_date ? (
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
range {report.start_date || "…"} → {report.end_date || "…"}
|
||||||
|
</Typography>
|
||||||
|
) : null}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
<IconButton aria-label="Close report" onClick={onClose}>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{data === null ? (
|
||||||
|
<Box sx={{ p: 3 }}>
|
||||||
|
<Alert severity="info" sx={{ borderRadius: 2, mb: 2 }}>
|
||||||
|
The cached data for this report has expired. Regenerate it to rebuild the snapshot.
|
||||||
|
</Alert>
|
||||||
|
<Button variant="contained" startIcon={<CachedIcon />} onClick={() => onRegenerated(report)}>
|
||||||
|
Regenerate
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Box sx={{ p: 2.5 }}>
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
|
||||||
|
<Autocomplete
|
||||||
|
size="small"
|
||||||
|
sx={{ width: 220 }}
|
||||||
|
options={["*", ...groupOptions.period]}
|
||||||
|
value={selectedPeriod}
|
||||||
|
onChange={(_, v) => setSelectedPeriod(v ?? "*")}
|
||||||
|
disabled={groupOptions.period.length === 0}
|
||||||
|
renderInput={(params) => <TextField {...params} label="Period" />}
|
||||||
|
/>
|
||||||
|
<Autocomplete
|
||||||
|
size="small"
|
||||||
|
sx={{ width: 220 }}
|
||||||
|
options={["*", ...groupOptions.payee]}
|
||||||
|
value={selectedPayee}
|
||||||
|
onChange={(_, v) => setSelectedPayee(v ?? "*")}
|
||||||
|
disabled={groupOptions.payee.length === 0}
|
||||||
|
renderInput={(params) => <TextField {...params} label="Payee" />}
|
||||||
|
/>
|
||||||
|
<Typography variant="body2" color="text.secondary" sx={{ alignSelf: "center" }}>
|
||||||
|
Showing {slice.count} transactions across {slice.txns.length} rows
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}>
|
||||||
|
<StatCard label="Spent" value={formatCurrency(slice.spent, slice.currency)} color="error.main" />
|
||||||
|
<StatCard label="Income" value={formatCurrency(slice.income, slice.currency)} color="success.main" />
|
||||||
|
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 3 }}>
|
||||||
|
{metrics.map((m) => {
|
||||||
|
const value = metricValue(m.key);
|
||||||
|
if (value == null) return null;
|
||||||
|
return (
|
||||||
|
<Paper key={m.key} variant="outlined" sx={{ px: 1.5, py: 1, borderRadius: 2 }}>
|
||||||
|
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
|
||||||
|
{m.label}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" fontWeight={600}>
|
||||||
|
{value}
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{selectedPeriod === "*" && selectedPayee === "*" && pivot.rows.length > 0 && (
|
||||||
|
<TableContainer
|
||||||
|
component={Paper}
|
||||||
|
variant="outlined"
|
||||||
|
sx={{ borderRadius: 2, mb: 3, overflowX: "auto" }}
|
||||||
|
>
|
||||||
|
<Table size="small">
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell sx={{ fontWeight: 700 }}>Period</TableCell>
|
||||||
|
{pivot.payees.map((payee) => (
|
||||||
|
<TableCell key={payee} align="right" sx={{ fontWeight: 700 }}>
|
||||||
|
{payee}
|
||||||
|
</TableCell>
|
||||||
|
))}
|
||||||
|
<TableCell align="right" sx={{ fontWeight: 700 }}>
|
||||||
|
Total
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{pivot.rows.map((row) => (
|
||||||
|
<TableRow key={row.period} sx={{ "&:last-child td": { borderBottom: 0 } }}>
|
||||||
|
<TableCell sx={{ fontWeight: 600 }}>{row.period}</TableCell>
|
||||||
|
{row.cells.map((cell) => (
|
||||||
|
<TableCell key={cell.payee} align="right">
|
||||||
|
{cell.sum === 0 ? "—" : formatCurrency(cell.sum, slice.currency)}
|
||||||
|
</TableCell>
|
||||||
|
))}
|
||||||
|
<TableCell align="right" sx={{ fontWeight: 700 }}>
|
||||||
|
{formatCurrency(row.periodSum, slice.currency)}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
<TableRow>
|
||||||
|
<TableCell sx={{ fontWeight: 700 }}>Total</TableCell>
|
||||||
|
{pivot.totals.map((t) => (
|
||||||
|
<TableCell key={t.payee} align="right" sx={{ fontWeight: 700 }}>
|
||||||
|
{formatCurrency(t.sum, slice.currency)}
|
||||||
|
</TableCell>
|
||||||
|
))}
|
||||||
|
<TableCell align="right" sx={{ fontWeight: 700 }}>
|
||||||
|
{formatCurrency(pivot.rows.reduce((s, r) => s + r.periodSum, 0), slice.currency)}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{slice.txns.length === 0 ? (
|
||||||
|
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3 }}>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
No transactions in this slice.
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
) : fields ? (
|
||||||
|
<TransactionList items={slice.txns} fields={fields} granularity={toPeriodGranularity(report.granularity)} />
|
||||||
|
) : null}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
238
src/Reports/types.ts
Normal file
238
src/Reports/types.ts
Normal file
@@ -0,0 +1,238 @@
|
|||||||
|
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
||||||
|
import { parseDdmmyyyy } from "../common/utils/dates";
|
||||||
|
|
||||||
|
export interface ParsedGroupKey {
|
||||||
|
period?: { granularity: string; label: string };
|
||||||
|
payee?: { label: string };
|
||||||
|
range?: { start?: string; end?: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReportGroupLike {
|
||||||
|
key: string;
|
||||||
|
group_label?: string;
|
||||||
|
metrics?: Record<string, any>;
|
||||||
|
txns?: any[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SliceFilter {
|
||||||
|
period?: string;
|
||||||
|
payee?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SliceSummary {
|
||||||
|
sum: number;
|
||||||
|
count: number;
|
||||||
|
avg: number | null;
|
||||||
|
min: number | null;
|
||||||
|
max: number | null;
|
||||||
|
firstDate: string | null;
|
||||||
|
lastDate: string | null;
|
||||||
|
txns: any[];
|
||||||
|
spent: number;
|
||||||
|
income: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PivotCell {
|
||||||
|
payee: string;
|
||||||
|
sum: number;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PivotRow {
|
||||||
|
period: string;
|
||||||
|
cells: PivotCell[];
|
||||||
|
periodSum: number;
|
||||||
|
periodCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PivotTable {
|
||||||
|
rows: PivotRow[];
|
||||||
|
payees: string[];
|
||||||
|
totals: PivotCell[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReportFieldConfigs {
|
||||||
|
groupLabel: FieldConfig;
|
||||||
|
granularity: FieldConfig;
|
||||||
|
periodLabel: FieldConfig;
|
||||||
|
payee: FieldConfig;
|
||||||
|
entityCount: FieldConfig;
|
||||||
|
generatedAt: FieldConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MetricLabel {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
order: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Split a concrete cache key into its dimension parts, e.g. `period:monthly:2026-Jan|payee:Zepto`. */
|
||||||
|
export function parseCacheKey(key: string): ParsedGroupKey {
|
||||||
|
const out: ParsedGroupKey = {};
|
||||||
|
for (const dim of key.split("|")) {
|
||||||
|
if (!dim) continue;
|
||||||
|
const [name, ...rest] = dim.split(":");
|
||||||
|
if (name === "period" && rest.length >= 2) {
|
||||||
|
out.period = { granularity: rest[0], label: rest.slice(1).join(":") };
|
||||||
|
} else if (name === "payee" && rest.length >= 1) {
|
||||||
|
out.payee = { label: rest.join(":") };
|
||||||
|
} else if (name === "range" && rest.length >= 1) {
|
||||||
|
out.range = { start: rest[0] || undefined, end: rest[1] || undefined };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function apiErrorMessage(e: any): string {
|
||||||
|
if (e?.response?.data) {
|
||||||
|
const d = e.response.data;
|
||||||
|
if (Array.isArray(d)) return d.map((x: any) => x?.msg ?? String(x)).join("; ");
|
||||||
|
if (typeof d.detail === "string") return d.detail;
|
||||||
|
if (typeof d.detail?.msg === "string") return d.detail.msg;
|
||||||
|
if (typeof d === "string") return d;
|
||||||
|
}
|
||||||
|
return e?.message ?? "Request failed";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupTypeEnum(schemas: Record<string, any>): string[] {
|
||||||
|
return schemas?.GroupSpec?.properties?.group_type?.enum ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupValueFk(schemas: Record<string, any>): { resource?: string; prefetch?: boolean } | null {
|
||||||
|
const fk = schemas?.GroupSpec?.properties?.group_value?.["x-fk"];
|
||||||
|
return fk && typeof fk === "object" ? fk : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
||||||
|
const props: Record<string, any> = schemas?.ReportMetrics?.properties ?? {};
|
||||||
|
return Object.entries(props)
|
||||||
|
.filter(([, p]) => p && typeof p === "object")
|
||||||
|
.map(([key, p]) => ({
|
||||||
|
key,
|
||||||
|
label: (p as any)["x-label"] ?? key,
|
||||||
|
order: (p as any)["x-order"] ?? Infinity,
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.order - b.order);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function periodHints(granularity: string): string[] {
|
||||||
|
const y = new Date().getFullYear();
|
||||||
|
switch (granularity) {
|
||||||
|
case "weekly":
|
||||||
|
return [`${y}-W01`, `${y}-W26`];
|
||||||
|
case "monthly":
|
||||||
|
return [`${y}-Jan`, `${y}-Feb`];
|
||||||
|
case "quarterly":
|
||||||
|
return [`${y}-Jan-Mar`, `${y}-Apr-Jun`];
|
||||||
|
case "yearly":
|
||||||
|
return [`${y - 1}`, `${y}`];
|
||||||
|
default:
|
||||||
|
return [`${y}-Jan`, `${y}-W01`, `${y}-Jan-Mar`, `${y}`];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dateVal(value: string): number {
|
||||||
|
try {
|
||||||
|
return parseDdmmyyyy(value).getTime();
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupMatches(group: ReportGroupLike, filter: SliceFilter): boolean {
|
||||||
|
const key = parseCacheKey(group.key);
|
||||||
|
if (filter.period && filter.period !== "*") {
|
||||||
|
if (!key.period || key.period.label !== filter.period) return false;
|
||||||
|
}
|
||||||
|
if (filter.payee && filter.payee !== "*") {
|
||||||
|
if (!key.payee || key.payee.label !== filter.payee) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function aggregateSlice(groups: ReportGroupLike[], filter: SliceFilter): SliceSummary {
|
||||||
|
let sum = 0;
|
||||||
|
let count = 0;
|
||||||
|
let spent = 0;
|
||||||
|
let income = 0;
|
||||||
|
let min: number | null = null;
|
||||||
|
let max: number | null = null;
|
||||||
|
let firstDate: string | null = null;
|
||||||
|
let lastDate: string | null = null;
|
||||||
|
let currency = "INR";
|
||||||
|
const txns: any[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
for (const group of groups) {
|
||||||
|
if (!groupMatches(group, filter)) continue;
|
||||||
|
const m = group.metrics ?? {};
|
||||||
|
if (typeof m.sum === "number") sum += m.sum;
|
||||||
|
if (typeof m.count === "number") count += m.count;
|
||||||
|
if (typeof m.min === "number") min = min === null ? m.min : Math.min(min, m.min);
|
||||||
|
if (typeof m.max === "number") max = max === null ? m.max : Math.max(max, m.max);
|
||||||
|
if (m.first_date && (!firstDate || dateVal(String(m.first_date)) < dateVal(firstDate))) {
|
||||||
|
firstDate = String(m.first_date);
|
||||||
|
}
|
||||||
|
if (m.last_date && (!lastDate || dateVal(String(m.last_date)) > dateVal(lastDate))) {
|
||||||
|
lastDate = String(m.last_date);
|
||||||
|
}
|
||||||
|
for (const txn of group.txns ?? []) {
|
||||||
|
if (txn?.id != null) {
|
||||||
|
if (seen.has(txn.id)) continue;
|
||||||
|
seen.add(txn.id);
|
||||||
|
}
|
||||||
|
txns.push(txn);
|
||||||
|
const amt = Number(txn?.amount ?? 0);
|
||||||
|
if (amt < 0) spent += Math.abs(amt);
|
||||||
|
else income += amt;
|
||||||
|
const c = txn?.account?.currency;
|
||||||
|
if (c) currency = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, spent, income, currency };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPivot(groups: ReportGroupLike[], periodOrder: string[], payeeOrder: string[]): PivotTable {
|
||||||
|
const payees = payeeOrder.filter((payee) =>
|
||||||
|
groups.some((g) => parseCacheKey(g.key).payee?.label === payee),
|
||||||
|
);
|
||||||
|
const totals = payees.map((payee) => ({ payee, sum: 0, count: 0 }));
|
||||||
|
const rows: PivotRow[] = [];
|
||||||
|
|
||||||
|
for (const period of periodOrder) {
|
||||||
|
const periodGroups = groups.filter((g) => parseCacheKey(g.key).period?.label === period);
|
||||||
|
if (periodGroups.length === 0) continue;
|
||||||
|
const cells = payees.map((payee, i) => {
|
||||||
|
const cellGroups = periodGroups.filter((g) => parseCacheKey(g.key).payee?.label === payee);
|
||||||
|
const sum = cellGroups.reduce((s, g) => s + (g.metrics?.sum ?? 0), 0);
|
||||||
|
const count = cellGroups.reduce((s, g) => s + (g.metrics?.count ?? 0), 0);
|
||||||
|
totals[i].sum += sum;
|
||||||
|
totals[i].count += count;
|
||||||
|
return { payee, sum, count };
|
||||||
|
});
|
||||||
|
rows.push({
|
||||||
|
period,
|
||||||
|
cells,
|
||||||
|
periodSum: cells.reduce((s, c) => s + c.sum, 0),
|
||||||
|
periodCount: cells.reduce((s, c) => s + c.count, 0),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { rows, payees, totals };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
||||||
|
const reportsRes = resources.find((r) => r.name === "reports");
|
||||||
|
if (!reportsRes) return null;
|
||||||
|
const find = (name: string) => reportsRes.fields.find((f) => f.name === name);
|
||||||
|
const groupLabel = find("group_label");
|
||||||
|
const granularity = find("granularity");
|
||||||
|
const periodLabel = find("period_label");
|
||||||
|
const payee = find("payee");
|
||||||
|
const entityCount = find("entity_count");
|
||||||
|
const generatedAt = find("generated_at");
|
||||||
|
if (!groupLabel || !granularity || !periodLabel || !payee || !entityCount || !generatedAt) return null;
|
||||||
|
return { groupLabel, granularity, periodLabel, payee, entityCount, generatedAt };
|
||||||
|
}
|
||||||
26
src/common/components/StatCard.tsx
Normal file
26
src/common/components/StatCard.tsx
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Paper, Typography } from "@mui/material";
|
||||||
|
|
||||||
|
interface StatCardProps {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
color?: string;
|
||||||
|
hint?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StatCard({ label, value, color, hint }: StatCardProps) {
|
||||||
|
return (
|
||||||
|
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3, flex: 1, minWidth: 180 }}>
|
||||||
|
<Typography variant="caption" color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
|
||||||
|
{label}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="h5" fontWeight={700} sx={{ mt: 0.5, letterSpacing: "-0.02em", color }}>
|
||||||
|
{value}
|
||||||
|
</Typography>
|
||||||
|
{hint && (
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{hint}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,120 +12,23 @@ import {
|
|||||||
import { alpha } from "@mui/material/styles";
|
import { alpha } from "@mui/material/styles";
|
||||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||||
import { ListCellRenderer, CurrencyField, applyDisplayFormat, formatCurrency } from "../../react-openapi";
|
import { formatCurrency } from "../../../react-openapi";
|
||||||
import type { ExpenseItem, ExpenseFieldConfigs } from "./types";
|
import type { ExpenseItem, TxnFieldConfigs } from "../types";
|
||||||
import { isExpense, monthKey, monthLabel, parseOccurredAt } from "./types";
|
import { groupByDate, groupByPeriod } from "../utils/transactions";
|
||||||
|
import type { PeriodGranularity } from "../utils/transactions";
|
||||||
|
import { TransactionRow } from "./TransactionRow";
|
||||||
|
|
||||||
interface GroupedMonth {
|
interface TransactionListProps {
|
||||||
key: string;
|
|
||||||
items: ExpenseItem[];
|
items: ExpenseItem[];
|
||||||
spent: number;
|
fields: TxnFieldConfigs;
|
||||||
income: number;
|
granularity?: PeriodGranularity;
|
||||||
currency: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function groupByMonth(items: ExpenseItem[]): GroupedMonth[] {
|
export function TransactionList({ items, fields, granularity = "monthly" }: TransactionListProps) {
|
||||||
const map = new Map<string, ExpenseItem[]>();
|
|
||||||
for (const item of items) {
|
|
||||||
const key = monthKey(item.occurred_at);
|
|
||||||
const list = map.get(key) ?? [];
|
|
||||||
list.push(item);
|
|
||||||
map.set(key, list);
|
|
||||||
}
|
|
||||||
return [...map.entries()]
|
|
||||||
.map(([key, list]) => {
|
|
||||||
const sorted = [...list].sort(
|
|
||||||
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
|
||||||
);
|
|
||||||
const currency = sorted.find((it) => it.account?.currency)?.account?.currency ?? "INR";
|
|
||||||
const spent = sorted.filter(isExpense).reduce((sum, it) => sum + Math.abs(it.amount ?? 0), 0);
|
|
||||||
const income = sorted.filter((it) => !isExpense(it)).reduce((sum, it) => sum + (it.amount ?? 0), 0);
|
|
||||||
return { key, items: sorted, spent, income, currency };
|
|
||||||
})
|
|
||||||
.sort((a, b) => b.key.localeCompare(a.key));
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ExpenseRowProps {
|
|
||||||
item: ExpenseItem;
|
|
||||||
currency: string;
|
|
||||||
fields: ExpenseFieldConfigs;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ExpenseRow = React.memo(function ExpenseRow({ item, currency, fields }: ExpenseRowProps) {
|
|
||||||
const itemCurrency = item.account?.currency ?? currency;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: 2,
|
|
||||||
px: 2,
|
|
||||||
py: 1.25,
|
|
||||||
border: "1px solid",
|
|
||||||
borderColor: "divider",
|
|
||||||
borderRadius: 2,
|
|
||||||
backgroundColor: "background.paper",
|
|
||||||
transition: "background-color 160ms ease, border-color 160ms ease",
|
|
||||||
"&:hover": {
|
|
||||||
backgroundColor: "action.hover",
|
|
||||||
borderColor: "primary.light",
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
width: 40,
|
|
||||||
flexShrink: 0,
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{item.entity?.logo ? (
|
|
||||||
<ListCellRenderer field={fields.logo} value={item.entity.logo} />
|
|
||||||
) : (
|
|
||||||
<Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: "action.hover" }} />
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
<Box sx={{ flex: "0 1 auto", minWidth: 0 }}>
|
|
||||||
<Typography
|
|
||||||
variant="body1"
|
|
||||||
fontWeight={600}
|
|
||||||
noWrap
|
|
||||||
sx={{ fontSize: "0.9375rem", lineHeight: 1.3 }}
|
|
||||||
>
|
|
||||||
{item.entity ? applyDisplayFormat(item.entity, fields.formats.entity) : "Unknown"}
|
|
||||||
</Typography>
|
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
|
|
||||||
<Box sx={{ color: "text.secondary" }}>
|
|
||||||
<ListCellRenderer field={fields.occurredAt} value={item.occurred_at} />
|
|
||||||
</Box>
|
|
||||||
{item.account?.name && (
|
|
||||||
<ListCellRenderer
|
|
||||||
field={fields.account}
|
|
||||||
value={item.account}
|
|
||||||
displayFormat={fields.formats.account}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
<Box sx={{ flex: 1 }} />
|
|
||||||
<CurrencyField value={item.amount} currency={itemCurrency} large />
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
interface ExpenseListProps {
|
|
||||||
items: ExpenseItem[];
|
|
||||||
fields: ExpenseFieldConfigs;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ExpenseList({ items, fields }: ExpenseListProps) {
|
|
||||||
const [activeMonth, setActiveMonth] = useState<string | null>(null);
|
const [activeMonth, setActiveMonth] = useState<string | null>(null);
|
||||||
const [openMonth, setOpenMonth] = useState<string | null>(null);
|
const [openMonth, setOpenMonth] = useState<string | null>(null);
|
||||||
const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
|
const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
|
||||||
const groups = useMemo(() => groupByMonth(items), [items]);
|
const groups = useMemo(() => groupByPeriod(items, granularity), [items, granularity]);
|
||||||
const listRef = useRef<HTMLDivElement>(null);
|
const listRef = useRef<HTMLDivElement>(null);
|
||||||
const pillRef = useRef<HTMLDivElement>(null);
|
const pillRef = useRef<HTMLDivElement>(null);
|
||||||
const didInitOpenMonth = useRef(false);
|
const didInitOpenMonth = useRef(false);
|
||||||
@@ -240,7 +143,7 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
{monthLabel(group.key)}
|
{group.label}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
||||||
@@ -258,8 +161,40 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
|||||||
</AccordionSummary>
|
</AccordionSummary>
|
||||||
<AccordionDetails sx={{ p: 1.5, pt: 1 }}>
|
<AccordionDetails sx={{ p: 1.5, pt: 1 }}>
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||||
{group.items.map((item) => (
|
{groupByDate(group.items).map((dateGroup) => (
|
||||||
<ExpenseRow
|
<Box
|
||||||
|
key={dateGroup.date}
|
||||||
|
sx={{
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: "divider",
|
||||||
|
borderRadius: 2,
|
||||||
|
backgroundColor: "background.default",
|
||||||
|
p: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 1,
|
||||||
|
px: 1,
|
||||||
|
pb: 1,
|
||||||
|
borderBottom: "1px solid",
|
||||||
|
borderColor: "divider",
|
||||||
|
mb: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant="subtitle2" fontWeight={600} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
|
{dateGroup.label}
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ flex: 1 }} />
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{dateGroup.items.length} transaction{dateGroup.items.length === 1 ? "" : "s"}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||||
|
{dateGroup.items.map((item) => (
|
||||||
|
<TransactionRow
|
||||||
key={item.id}
|
key={item.id}
|
||||||
item={item}
|
item={item}
|
||||||
currency={group.currency}
|
currency={group.currency}
|
||||||
@@ -267,6 +202,9 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Box>
|
</Box>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
</AccordionDetails>
|
</AccordionDetails>
|
||||||
</Accordion>
|
</Accordion>
|
||||||
</Box>
|
</Box>
|
||||||
@@ -319,7 +257,7 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography variant="caption" fontWeight={700} color="text.secondary">
|
<Typography variant="caption" fontWeight={700} color="text.secondary">
|
||||||
{activeMonth ? monthLabel(activeMonth) : ""}
|
{activeMonth ? (groups.find((g) => g.key === activeMonth)?.label ?? activeMonth) : ""}
|
||||||
</Typography>
|
</Typography>
|
||||||
<KeyboardArrowDownIcon sx={{ fontSize: 14, color: "text.secondary" }} />
|
<KeyboardArrowDownIcon sx={{ fontSize: 14, color: "text.secondary" }} />
|
||||||
</Box>
|
</Box>
|
||||||
@@ -339,7 +277,7 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
|||||||
onClick={() => handleSelectMonth(group.key)}
|
onClick={() => handleSelectMonth(group.key)}
|
||||||
>
|
>
|
||||||
<ListItemText
|
<ListItemText
|
||||||
primary={monthLabel(group.key)}
|
primary={group.label}
|
||||||
secondary={`${group.items.length} transactions`}
|
secondary={`${group.items.length} transactions`}
|
||||||
/>
|
/>
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
@@ -348,5 +286,3 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
|||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { groupByMonth };
|
|
||||||
71
src/common/components/TransactionRow.tsx
Normal file
71
src/common/components/TransactionRow.tsx
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Box, Typography } from "@mui/material";
|
||||||
|
import { ListCellRenderer, CurrencyField, applyDisplayFormat } from "../../../react-openapi";
|
||||||
|
import type { ExpenseItem, TxnFieldConfigs } from "../types";
|
||||||
|
|
||||||
|
interface TransactionRowProps {
|
||||||
|
item: ExpenseItem;
|
||||||
|
currency: string;
|
||||||
|
fields: TxnFieldConfigs;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TransactionRow = React.memo(function TransactionRow({ item, currency, fields }: TransactionRowProps) {
|
||||||
|
const itemCurrency = item.account?.currency ?? currency;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 2,
|
||||||
|
px: 2,
|
||||||
|
py: 1.25,
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: "divider",
|
||||||
|
borderRadius: 2,
|
||||||
|
backgroundColor: "background.paper",
|
||||||
|
transition: "background-color 160ms ease, border-color 160ms ease",
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: "action.hover",
|
||||||
|
borderColor: "primary.light",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: 40,
|
||||||
|
flexShrink: 0,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{item.entity?.logo ? (
|
||||||
|
<ListCellRenderer field={fields.logo} value={item.entity.logo} />
|
||||||
|
) : (
|
||||||
|
<Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: "action.hover" }} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<Box sx={{ flex: "0 1 auto", minWidth: 0 }}>
|
||||||
|
<Typography
|
||||||
|
variant="body1"
|
||||||
|
fontWeight={600}
|
||||||
|
noWrap
|
||||||
|
sx={{ fontSize: "0.9375rem", lineHeight: 1.3 }}
|
||||||
|
>
|
||||||
|
{item.entity ? applyDisplayFormat(item.entity, fields.formats.entity) : "Unknown"}
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
|
||||||
|
<Box sx={{ color: "text.secondary" }}>
|
||||||
|
<ListCellRenderer field={fields.occurredAt} value={item.occurred_at} />
|
||||||
|
</Box>
|
||||||
|
{item.account?.name && (
|
||||||
|
<ListCellRenderer field={fields.account} value={item.account} displayFormat={fields.formats.account} />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
<Box sx={{ flex: 1 }} />
|
||||||
|
<CurrencyField value={item.amount} currency={itemCurrency} large />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
});
|
||||||
21
src/common/types.ts
Normal file
21
src/common/types.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import type { FieldConfig } from "../../react-openapi";
|
||||||
|
|
||||||
|
export interface ExpenseItem {
|
||||||
|
id: string;
|
||||||
|
entity?: { name?: string; type?: string; logo?: string } | null;
|
||||||
|
amount: number;
|
||||||
|
account?: { name?: string; number?: string; type?: string; currency?: string } | null;
|
||||||
|
tags?: { icon?: string; name?: string }[];
|
||||||
|
occurred_at?: string;
|
||||||
|
created_at?: string;
|
||||||
|
updated_at?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TxnFieldConfigs {
|
||||||
|
entity: FieldConfig;
|
||||||
|
amount: FieldConfig;
|
||||||
|
account: FieldConfig;
|
||||||
|
occurredAt: FieldConfig;
|
||||||
|
logo: FieldConfig;
|
||||||
|
formats: { entity: string; account: string };
|
||||||
|
}
|
||||||
71
src/common/utils/dates.ts
Normal file
71
src/common/utils/dates.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
const DDMMYYYY = /^(\d{2})-(\d{2})-(\d{4})$/;
|
||||||
|
|
||||||
|
export function parseOccurredAt(value?: string): Date {
|
||||||
|
const m = value?.match(DDMMYYYY);
|
||||||
|
if (!m) {
|
||||||
|
throw new Error(`Expense occurred_at is not DD-MM-YYYY: ${value}`);
|
||||||
|
}
|
||||||
|
const [, dd, mm, yyyy] = m;
|
||||||
|
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||||
|
if (
|
||||||
|
Number.isNaN(d.getTime()) ||
|
||||||
|
d.getDate() !== Number(dd) ||
|
||||||
|
d.getMonth() !== Number(mm) - 1 ||
|
||||||
|
d.getFullYear() !== Number(yyyy)
|
||||||
|
) {
|
||||||
|
throw new Error(`Invalid expense occurred_at date: ${value}`);
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDdmmyyyy(value?: string): boolean {
|
||||||
|
if (!value) return true;
|
||||||
|
const m = value.match(DDMMYYYY);
|
||||||
|
if (!m) return false;
|
||||||
|
const [, dd, mm, yyyy] = m;
|
||||||
|
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||||
|
return !(
|
||||||
|
Number.isNaN(d.getTime()) ||
|
||||||
|
d.getDate() !== Number(dd) ||
|
||||||
|
d.getMonth() !== Number(mm) - 1 ||
|
||||||
|
d.getFullYear() !== Number(yyyy)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseDdmmyyyy(value: string): Date {
|
||||||
|
const m = value.match(DDMMYYYY);
|
||||||
|
if (!m) throw new Error(`Date is not DD-MM-YYYY: ${value}`);
|
||||||
|
const [, dd, mm, yyyy] = m;
|
||||||
|
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||||
|
if (
|
||||||
|
Number.isNaN(d.getTime()) ||
|
||||||
|
d.getDate() !== Number(dd) ||
|
||||||
|
d.getMonth() !== Number(mm) - 1 ||
|
||||||
|
d.getFullYear() !== Number(yyyy)
|
||||||
|
) {
|
||||||
|
throw new Error(`Invalid date: ${value}`);
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function monthKey(value?: string): string {
|
||||||
|
const d = parseOccurredAt(value);
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function currentMonthKey(): string {
|
||||||
|
const now = new Date();
|
||||||
|
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function monthLabel(key: string): string {
|
||||||
|
const [y, m] = key.split("-").map(Number);
|
||||||
|
if (!y || !m) return key;
|
||||||
|
const d = new Date(y, m - 1, 1);
|
||||||
|
return d.toLocaleDateString("en-IN", { month: "long", year: "numeric" });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dateLabel(value: string): string {
|
||||||
|
const d = parseOccurredAt(value);
|
||||||
|
return d.toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });
|
||||||
|
}
|
||||||
26
src/common/utils/fieldConfigs.ts
Normal file
26
src/common/utils/fieldConfigs.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import type { ResourceConfig } from "../../../react-openapi";
|
||||||
|
import type { TxnFieldConfigs } from "../types";
|
||||||
|
|
||||||
|
export function buildTxnFieldConfigs(resources: ResourceConfig[]): TxnFieldConfigs | null {
|
||||||
|
const expensesRes = resources.find((r) => r.name === "expenses");
|
||||||
|
const entitiesRes = resources.find((r) => r.name === "entities");
|
||||||
|
const accountsRes = resources.find((r) => r.name === "accounts");
|
||||||
|
const find = (res: ResourceConfig | undefined, name: string) => res?.fields.find((f) => f.name === name);
|
||||||
|
const entity = find(expensesRes, "entity");
|
||||||
|
const amount = find(expensesRes, "amount");
|
||||||
|
const account = find(expensesRes, "account");
|
||||||
|
const occurredAt = find(expensesRes, "occurred_at");
|
||||||
|
const logo = find(entitiesRes, "logo");
|
||||||
|
if (!entity || !amount || !account || !occurredAt || !logo) return null;
|
||||||
|
return {
|
||||||
|
entity,
|
||||||
|
amount,
|
||||||
|
account,
|
||||||
|
occurredAt,
|
||||||
|
logo,
|
||||||
|
formats: {
|
||||||
|
entity: entitiesRes?.displayFormat ?? "{name}",
|
||||||
|
account: accountsRes?.displayFormat ?? "{name}",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
109
src/common/utils/transactions.ts
Normal file
109
src/common/utils/transactions.ts
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
import type { ExpenseItem } from "../types";
|
||||||
|
import { dateLabel, monthKey, monthLabel, parseOccurredAt } from "./dates";
|
||||||
|
|
||||||
|
export function isExpense(item: ExpenseItem): boolean {
|
||||||
|
return (item.amount ?? 0) < 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DateGroup {
|
||||||
|
date: string;
|
||||||
|
label: string;
|
||||||
|
items: ExpenseItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupByDate(items: ExpenseItem[]): DateGroup[] {
|
||||||
|
const sorted = [...items].sort(
|
||||||
|
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
||||||
|
);
|
||||||
|
const map = new Map<string, ExpenseItem[]>();
|
||||||
|
for (const item of sorted) {
|
||||||
|
const key = item.occurred_at ?? "";
|
||||||
|
const list = map.get(key) ?? [];
|
||||||
|
list.push(item);
|
||||||
|
map.set(key, list);
|
||||||
|
}
|
||||||
|
return [...map.entries()].map(([date, list]) => ({
|
||||||
|
date,
|
||||||
|
label: dateLabel(date),
|
||||||
|
items: list,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PeriodGranularity = "weekly" | "monthly" | "quarterly" | "yearly";
|
||||||
|
|
||||||
|
export interface PeriodGroup {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
items: ExpenseItem[];
|
||||||
|
spent: number;
|
||||||
|
income: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toPeriodGranularity(value?: string): PeriodGranularity {
|
||||||
|
return value === "weekly" || value === "monthly" || value === "quarterly" || value === "yearly"
|
||||||
|
? value
|
||||||
|
: "monthly";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isoWeekKey(d: Date): string {
|
||||||
|
const date = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
|
||||||
|
const day = date.getUTCDay() || 7;
|
||||||
|
date.setUTCDate(date.getUTCDate() + 4 - day);
|
||||||
|
const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
|
||||||
|
const week = Math.ceil(((date.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
|
||||||
|
return `${date.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quarterKey(d: Date): string {
|
||||||
|
return `${d.getFullYear()}-Q${Math.floor(d.getMonth() / 3) + 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function periodKey(value: string | undefined, granularity: PeriodGranularity): string {
|
||||||
|
const d = parseOccurredAt(value);
|
||||||
|
switch (granularity) {
|
||||||
|
case "weekly":
|
||||||
|
return isoWeekKey(d);
|
||||||
|
case "quarterly":
|
||||||
|
return quarterKey(d);
|
||||||
|
case "yearly":
|
||||||
|
return String(d.getFullYear());
|
||||||
|
default:
|
||||||
|
return monthKey(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function periodLabel(key: string, granularity: PeriodGranularity): string {
|
||||||
|
switch (granularity) {
|
||||||
|
case "weekly":
|
||||||
|
case "yearly":
|
||||||
|
return key;
|
||||||
|
case "quarterly": {
|
||||||
|
const [y, q] = key.split("-Q");
|
||||||
|
return `Q${q} ${y}`;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return monthLabel(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupByPeriod(items: ExpenseItem[], granularity: PeriodGranularity = "monthly"): PeriodGroup[] {
|
||||||
|
const map = new Map<string, ExpenseItem[]>();
|
||||||
|
for (const item of items) {
|
||||||
|
const key = periodKey(item.occurred_at, granularity);
|
||||||
|
const list = map.get(key) ?? [];
|
||||||
|
list.push(item);
|
||||||
|
map.set(key, list);
|
||||||
|
}
|
||||||
|
return [...map.entries()]
|
||||||
|
.map(([key, list]) => {
|
||||||
|
const sorted = [...list].sort(
|
||||||
|
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
||||||
|
);
|
||||||
|
const currency = sorted.find((it) => it.account?.currency)?.account?.currency ?? "INR";
|
||||||
|
const spent = sorted.filter(isExpense).reduce((sum, it) => sum + Math.abs(it.amount ?? 0), 0);
|
||||||
|
const income = sorted.filter((it) => !isExpense(it)).reduce((sum, it) => sum + (it.amount ?? 0), 0);
|
||||||
|
return { key, label: periodLabel(key, granularity), items: sorted, spent, income, currency };
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.key.localeCompare(a.key));
|
||||||
|
}
|
||||||
@@ -17,7 +17,8 @@ import {
|
|||||||
import Home from './Home';
|
import Home from './Home';
|
||||||
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
||||||
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
|
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
|
||||||
import Expense from './Expense/Expense';
|
import Expense from './Expense';
|
||||||
|
import Reports from './Reports/Report';
|
||||||
import { AppProvider, useAppContext, Admin, ProfileRoutes } from '../react-openapi';
|
import { AppProvider, useAppContext, Admin, ProfileRoutes } from '../react-openapi';
|
||||||
import { AuthProvider, AuthPage, useAuth, ProfileCreate, ProfileEdit, ProfileView } from "../react-auth";
|
import { AuthProvider, AuthPage, useAuth, ProfileCreate, ProfileEdit, ProfileView } from "../react-auth";
|
||||||
import Header from './Header';
|
import Header from './Header';
|
||||||
@@ -80,6 +81,7 @@ const routerMapping = [
|
|||||||
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
||||||
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
||||||
{ path: "/expenses", component: Expense, headerTitle: "Expenses" },
|
{ path: "/expenses", component: Expense, headerTitle: "Expenses" },
|
||||||
|
{ path: "/reports", component: Reports, headerTitle: "Reports" },
|
||||||
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
||||||
{ path: "/profile/*", component: ProfileRoutes, headerTitle: "Profile" },
|
{ path: "/profile/*", component: ProfileRoutes, headerTitle: "Profile" },
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in New Issue
Block a user