Compare commits
9 Commits
1.2.2
...
6b340d89f6
| Author | SHA1 | Date | |
|---|---|---|---|
| 6b340d89f6 | |||
| 79808d6d3e | |||
| f865f7dec2 | |||
| fc3a48a367 | |||
| f9759e3968 | |||
| 47c00a06a8 | |||
| a107029b90 | |||
| baa9b296cb | |||
| f08bc72037 |
@@ -6,6 +6,7 @@ export { useResource } from "./src/context/useResource";
|
||||
export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields";
|
||||
export { FormFieldRenderer } from "./src/components/fields/FormFieldRenderer";
|
||||
export { CurrencyField, formatCurrency } from "./src/components/fields/renderers/CurrencyField";
|
||||
export { FkMultiSelectField } from "./src/components/fields/renderers/FkMultiSelectField";
|
||||
export { SseStreamView } from "./src/components/SseStreamView";
|
||||
export { SseConnectionStatus } from "./src/components/SseConnectionStatus";
|
||||
export { getApi } from "./src/hooks/useApi";
|
||||
|
||||
@@ -3,6 +3,24 @@ import axios, { AxiosInstance } from "axios";
|
||||
let apiClient: AxiosInstance | null = null;
|
||||
let _onUnauthorized: (() => void) | undefined;
|
||||
|
||||
function serializeParams(params: Record<string, any>): string {
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params ?? {})) {
|
||||
if (value === undefined || value === null) continue;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) searchParams.append(key, String(item));
|
||||
} else if (typeof value === "object") {
|
||||
for (const [nestedKey, nestedValue] of Object.entries(value)) {
|
||||
if (nestedValue === undefined || nestedValue === null) continue;
|
||||
searchParams.append(`${key}[${nestedKey}]`, String(nestedValue));
|
||||
}
|
||||
} else {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
}
|
||||
return searchParams.toString();
|
||||
}
|
||||
|
||||
export function initApi(baseUrl: string, getToken?: () => string | null, onUnauthorized?: () => void): AxiosInstance {
|
||||
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
||||
_onUnauthorized = onUnauthorized;
|
||||
@@ -14,6 +32,7 @@ export function initApi(baseUrl: string, getToken?: () => string | null, onUnaut
|
||||
apiClient = axios.create({
|
||||
baseURL: baseUrl,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
paramsSerializer: serializeParams,
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
|
||||
@@ -10,32 +10,15 @@ import {
|
||||
} from "@mui/material";
|
||||
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useResource, useAppContext, formatCurrency } from "../../react-openapi";
|
||||
import { PageHeader } from "../ui/PageHeader";
|
||||
import { EmptyState } from "../ui/EmptyState";
|
||||
import { ExpenseList } from "./ExpenseList";
|
||||
import { ExpenseItem, ExpenseFieldConfigs, isExpense, currentMonthKey, monthKey, monthLabel, parseOccurredAt } from "./types";
|
||||
|
||||
function StatCard({ label, value, hint }: { label: string; value: string; hint?: string }) {
|
||||
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" }}>
|
||||
{value}
|
||||
</Typography>
|
||||
{hint && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{hint}
|
||||
</Typography>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
import { useResource, useAppContext, formatCurrency } from "../react-openapi";
|
||||
import { PageHeader } from "./ui/PageHeader";
|
||||
import { EmptyState } from "./ui/EmptyState";
|
||||
import { StatCard } from "./common/components/StatCard";
|
||||
import { TransactionList } from "./common/components/TransactionList";
|
||||
import { buildTxnFieldConfigs } from "./common/utils/fieldConfigs";
|
||||
import { isExpense } from "./common/utils/transactions";
|
||||
import { currentMonthKey, monthKey, monthLabel, parseOccurredAt } from "./common/utils/dates";
|
||||
import type { ExpenseItem } from "./common/types";
|
||||
|
||||
export default function Expense() {
|
||||
const navigate = useNavigate();
|
||||
@@ -43,33 +26,7 @@ export default function Expense() {
|
||||
const { resources } = useAppContext();
|
||||
const [items, setItems] = useState<ExpenseItem[] | null>(null);
|
||||
|
||||
const fieldConfigs = useMemo<ExpenseFieldConfigs | null>(() => {
|
||||
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]);
|
||||
const fieldConfigs = useMemo(() => buildTxnFieldConfigs(resources), [resources]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
@@ -80,7 +37,7 @@ export default function Expense() {
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, []);
|
||||
}, [list]);
|
||||
|
||||
const sorted = useMemo(
|
||||
() =>
|
||||
@@ -153,15 +110,15 @@ export default function Expense() {
|
||||
<>
|
||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
||||
<StatCard
|
||||
label="Total spent"
|
||||
label="Outflows"
|
||||
value={formatCurrency(summary.totalSpent, summary.currency)}
|
||||
hint={`${summary.monthItems.length} transaction${summary.monthItems.length === 1 ? "" : "s"} this month`}
|
||||
/>
|
||||
<StatCard label="This month" value={formatCurrency(summary.monthTotal, summary.currency)} hint={summary.thisMonth} />
|
||||
<StatCard label="Income" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
||||
<StatCard label="Inflows" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
||||
</Box>
|
||||
|
||||
{fieldConfigs && <ExpenseList items={sorted} fields={fieldConfigs} />}
|
||||
{fieldConfigs && <TransactionList items={sorted} fields={fieldConfigs} />}
|
||||
</>
|
||||
)}
|
||||
</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 = [
|
||||
{ label: "Home", path: "/" },
|
||||
{ label: "Expenses", path: "/expenses" },
|
||||
{ label: "Reports", path: "/reports" },
|
||||
{ label: "Fetch Requests", path: "/fetch-requests" },
|
||||
];
|
||||
|
||||
|
||||
275
src/Reports/GenerateReportPanel.tsx
Normal file
275
src/Reports/GenerateReportPanel.tsx
Normal file
@@ -0,0 +1,275 @@
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Box,
|
||||
Paper,
|
||||
Typography,
|
||||
TextField,
|
||||
Button,
|
||||
MenuItem,
|
||||
Select,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Autocomplete,
|
||||
FormControlLabel,
|
||||
Checkbox,
|
||||
Chip,
|
||||
Alert,
|
||||
} from "@mui/material";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
|
||||
import { useToast } from "../ui/Toast";
|
||||
import { isDdmmyyyy } from "../common/utils/dates";
|
||||
import { apiErrorMessage, granularityOptions, groupDimOptions, FLOW_OPTIONS } from "./types";
|
||||
|
||||
interface GenerateReportPanelProps {
|
||||
onGenerated: (report: any) => void;
|
||||
}
|
||||
|
||||
const ALL_GRANULARITIES = ["weekly", "monthly", "quarterly"];
|
||||
|
||||
export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
||||
const { schemas, resources } = useAppContext();
|
||||
const { create } = useResource("reports");
|
||||
const { list: listAccounts } = useResource("accounts");
|
||||
const { showToast } = useToast();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [granularities, setGranularities] = useState<string[]>(ALL_GRANULARITIES);
|
||||
const [groupDims, setGroupDims] = useState<string[]>(["payee", "tag"]);
|
||||
const [flow, setFlow] = useState("both");
|
||||
const [accounts, setAccounts] = useState<string[]>([]);
|
||||
const [ignoreSelf, setIgnoreSelf] = useState(true);
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [minAmount, setMinAmount] = useState("");
|
||||
const [maxAmount, setMaxAmount] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [accountOptions, setAccountOptions] = useState<string[]>([]);
|
||||
const [dateErrors, setDateErrors] = useState<{ start?: string; end?: string }>({});
|
||||
|
||||
const granularityChoices = useMemo(() => {
|
||||
const enums = granularityOptions(schemas);
|
||||
return enums.length ? enums : ALL_GRANULARITIES;
|
||||
}, [schemas]);
|
||||
const dimChoices = useMemo(() => groupDimOptions(schemas), [schemas]);
|
||||
const accountsRes = resources.find((r) => r.name === "accounts");
|
||||
const accountsFormat = accountsRes?.displayFormat ?? "{name}";
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
listAccounts({ limit: 0 }).then((res) => {
|
||||
if (!mounted) return;
|
||||
const names = (res.items ?? [])
|
||||
.map((it: any) => applyDisplayFormat(it, accountsFormat))
|
||||
.filter((n: string) => n);
|
||||
setAccountOptions([...new Set(names)].sort((a, b) => a.localeCompare(b)));
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [listAccounts, accountsFormat]);
|
||||
|
||||
const toggle = (list: string[], value: string, setter: (v: string[]) => void) =>
|
||||
setter(list.includes(value) ? list.filter((v) => v !== value) : [...list, value]);
|
||||
|
||||
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 parseAmount = (value: string): number | null => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
const n = Number(trimmed);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!validateDates()) return;
|
||||
setError(null);
|
||||
const min = parseAmount(minAmount);
|
||||
const max = parseAmount(maxAmount);
|
||||
if (minAmount.trim() && min === null) {
|
||||
setError("Min amount must be a number");
|
||||
return;
|
||||
}
|
||||
if (maxAmount.trim() && max === null) {
|
||||
setError("Max amount must be a number");
|
||||
return;
|
||||
}
|
||||
if (min !== null && max !== null && min > max) {
|
||||
setError("Min amount cannot exceed max amount");
|
||||
return;
|
||||
}
|
||||
const payload: Record<string, any> = {
|
||||
name: name.trim(),
|
||||
granularities,
|
||||
group_dims: groupDims,
|
||||
flow,
|
||||
ignore_self: ignoreSelf,
|
||||
};
|
||||
if (accounts.length) payload.accounts = accounts;
|
||||
if (startDate.trim()) payload.start_date = startDate.trim();
|
||||
if (endDate.trim()) payload.end_date = endDate.trim();
|
||||
if (min !== null) payload.min_amount = min;
|
||||
if (max !== null) payload.max_amount = max;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const created = await create(payload);
|
||||
showToast(`Generated snapshot ${created?.name ? `“${created.name}”` : ""}`.trim() || "Generated snapshot");
|
||||
onGenerated(created);
|
||||
} 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 }}>
|
||||
Define the snapshot's scope. Granularity, payee and tag are sliced at view time — the cube is built once and
|
||||
every combination stays cheap to read.
|
||||
</Typography>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Name"
|
||||
placeholder="e.g. Monthly spending"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
sx={{ maxWidth: 420 }}
|
||||
/>
|
||||
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
|
||||
Granularities
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||
{granularityChoices.map((g) => (
|
||||
<Chip
|
||||
key={g}
|
||||
label={g}
|
||||
clickable
|
||||
color={granularities.includes(g) ? "primary" : "default"}
|
||||
variant={granularities.includes(g) ? "filled" : "outlined"}
|
||||
onClick={() => toggle(granularities, g, setGranularities)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
|
||||
Group dimensions
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||
{dimChoices.map((d) => (
|
||||
<Chip
|
||||
key={d}
|
||||
label={d}
|
||||
clickable
|
||||
color={groupDims.includes(d) ? "primary" : "default"}
|
||||
variant={groupDims.includes(d) ? "filled" : "outlined"}
|
||||
onClick={() => toggle(groupDims, d, setGroupDims)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "flex-start" }}>
|
||||
<FormControl size="small" sx={{ width: 200 }}>
|
||||
<InputLabel id="flow-label">Flow</InputLabel>
|
||||
<Select labelId="flow-label" label="Flow" value={flow} onChange={(e) => setFlow(e.target.value)}>
|
||||
{FLOW_OPTIONS.map((f) => (
|
||||
<MenuItem key={f} value={f}>
|
||||
{f}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControlLabel
|
||||
control={<Checkbox checked={ignoreSelf} onChange={(e) => setIgnoreSelf(e.target.checked)} />}
|
||||
label="Ignore self-transfers"
|
||||
sx={{ mt: 0.25 }}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Autocomplete
|
||||
multiple
|
||||
freeSolo
|
||||
size="small"
|
||||
options={accountOptions}
|
||||
value={accounts}
|
||||
onChange={(_, newVal) => setAccounts(newVal)}
|
||||
renderInput={(params) => (
|
||||
<TextField {...params} label="Accounts" placeholder="Restrict to accounts (empty = all)" />
|
||||
)}
|
||||
sx={{ maxWidth: 420 }}
|
||||
/>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 1.5, 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={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Min amount"
|
||||
placeholder="e.g. 500"
|
||||
value={minAmount}
|
||||
onChange={(e) => setMinAmount(e.target.value)}
|
||||
sx={{ width: 200 }}
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Max amount"
|
||||
placeholder="e.g. 5000"
|
||||
value={maxAmount}
|
||||
onChange={(e) => setMaxAmount(e.target.value)}
|
||||
sx={{ width: 200 }}
|
||||
/>
|
||||
</Box>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
184
src/Reports/Report.tsx
Normal file
184
src/Reports/Report.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Container,
|
||||
Box,
|
||||
Paper,
|
||||
Typography,
|
||||
Alert,
|
||||
Accordion,
|
||||
AccordionSummary,
|
||||
AccordionDetails,
|
||||
} from "@mui/material";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import AssessmentIcon from "@mui/icons-material/Assessment";
|
||||
import { useResource, useAppContext } 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?.id) setSelectedId(created.id);
|
||||
},
|
||||
[load],
|
||||
);
|
||||
|
||||
const handleRegenerate = useCallback(
|
||||
async (report: any) => {
|
||||
try {
|
||||
const created = await create(report.query ?? {});
|
||||
showToast("Report regenerated");
|
||||
setSelectedId(created?.id ?? 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 granularities = new Set<string>();
|
||||
for (const r of rows) for (const g of r.query?.granularities ?? []) granularities.add(g);
|
||||
return { count: rows.length, granularities: [...granularities].join(", ") };
|
||||
}, [reports]);
|
||||
|
||||
return (
|
||||
<Container maxWidth="lg" sx={{ py: 4 }}>
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Home", path: "/" }, { label: "Reports" }]}
|
||||
title="Reports"
|
||||
subtitle="Build an immutable snapshot cube once, then slice by granularity, period, payee and tag at view time."
|
||||
/>
|
||||
|
||||
{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="Granularities covered" value={summary.granularities || "—"} />
|
||||
</Box>
|
||||
|
||||
<GenerateReportPanel onGenerated={handleGenerated} />
|
||||
|
||||
<Accordion
|
||||
disableGutters
|
||||
defaultExpanded
|
||||
sx={{
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 2,
|
||||
overflow: "hidden",
|
||||
boxShadow: "none",
|
||||
backgroundColor: "background.paper",
|
||||
"&:before": { display: "none" },
|
||||
mb: 4,
|
||||
}}
|
||||
>
|
||||
<AccordionSummary
|
||||
expandIcon={<ExpandMoreIcon />}
|
||||
sx={{
|
||||
px: 2.5,
|
||||
py: 1,
|
||||
"& .MuiAccordionSummary-content": {
|
||||
alignItems: "center",
|
||||
gap: 1.5,
|
||||
minWidth: 0,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
Saved reports
|
||||
</Typography>
|
||||
{reports !== null && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{reports.length} report{reports.length === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
)}
|
||||
</AccordionSummary>
|
||||
<AccordionDetails sx={{ px: 2.5, pb: 2.5, pt: 0 }}>
|
||||
{reports !== null && reports.length === 0 ? (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 3 }}>
|
||||
<EmptyState
|
||||
icon={<AssessmentIcon />}
|
||||
title="No reports yet"
|
||||
description="Generate your first snapshot above — choose granularities and grouping dimensions, then slice the cached cube by period, payee and tag."
|
||||
/>
|
||||
</Paper>
|
||||
) : (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}>
|
||||
<ReportList
|
||||
reports={reports ?? []}
|
||||
loading={loading}
|
||||
fields={reportFields}
|
||||
selectedId={selectedId}
|
||||
onView={(id) => setSelectedId(id)}
|
||||
onRegenerate={handleRegenerate}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
|
||||
{selectedId && (
|
||||
<ReportViewer
|
||||
key={selectedId}
|
||||
id={selectedId}
|
||||
version={viewerVersion}
|
||||
fields={txnFields}
|
||||
onClose={() => setSelectedId(null)}
|
||||
onRegenerated={handleRegenerate}
|
||||
/>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
116
src/Reports/ReportList.tsx
Normal file
116
src/Reports/ReportList.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
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 } 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 q = report.query ?? {};
|
||||
const range = q.start_date || q.end_date ? `range ${q.start_date || "…"} → ${q.end_date || "…"}` : null;
|
||||
const dims = Array.isArray(q.group_dims) ? q.group_dims.join(", ") : "";
|
||||
const granularities = Array.isArray(q.granularities) ? q.granularities.join(", ") : "";
|
||||
const accounts = Array.isArray(q.accounts) ? `${q.accounts.length} account${q.accounts.length === 1 ? "" : "s"}` : "all accounts";
|
||||
const amounts =
|
||||
q.min_amount != null || q.max_amount != null
|
||||
? `amount ${q.min_amount ?? "0"} → ${q.max_amount ?? "∞"}`
|
||||
: 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.name || report.id}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.25 }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{granularities}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
/
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{dims}
|
||||
</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">
|
||||
{accounts}
|
||||
</Typography>
|
||||
{amounts && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{amounts}
|
||||
</Typography>
|
||||
)}
|
||||
{fields && (
|
||||
<Box sx={{ color: "text.secondary" }}>
|
||||
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
330
src/Reports/ReportViewer.tsx
Normal file
330
src/Reports/ReportViewer.tsx
Normal file
@@ -0,0 +1,330 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import CachedIcon from "@mui/icons-material/Cached";
|
||||
import { FkMultiSelectField, useResource, formatCurrency } from "../../react-openapi";
|
||||
import type { FieldConfig } 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, periodSlices, FLOW_OPTIONS, apiErrorMessage } from "./types";
|
||||
|
||||
const periodField: FieldConfig = {
|
||||
name: "period",
|
||||
label: "Period",
|
||||
description: "",
|
||||
type: "string",
|
||||
order: 0,
|
||||
hidden: {},
|
||||
filterable: true,
|
||||
sortable: false,
|
||||
readOnly: false,
|
||||
required: false,
|
||||
isArray: true,
|
||||
};
|
||||
|
||||
const payeeField: FieldConfig = {
|
||||
name: "payee",
|
||||
label: "Payee",
|
||||
description: "",
|
||||
type: "string",
|
||||
order: 0,
|
||||
hidden: {},
|
||||
filterable: true,
|
||||
sortable: false,
|
||||
readOnly: false,
|
||||
required: false,
|
||||
isArray: true,
|
||||
};
|
||||
|
||||
const tagField: FieldConfig = {
|
||||
name: "tag",
|
||||
label: "Tag",
|
||||
description: "",
|
||||
type: "string",
|
||||
order: 0,
|
||||
hidden: {},
|
||||
filterable: true,
|
||||
sortable: false,
|
||||
readOnly: false,
|
||||
required: false,
|
||||
isArray: true,
|
||||
};
|
||||
|
||||
interface ReportViewerProps {
|
||||
id: string;
|
||||
version: number;
|
||||
fields: TxnFieldConfigs | null;
|
||||
onClose: () => void;
|
||||
onRegenerated: (report: any) => void;
|
||||
}
|
||||
|
||||
function snapshotGranularities(report: any): string[] {
|
||||
const fromQuery = report?.query?.granularities;
|
||||
if (Array.isArray(fromQuery) && fromQuery.length) return fromQuery;
|
||||
const fromResponse = report?.granularities;
|
||||
if (Array.isArray(fromResponse) && fromResponse.length) return fromResponse;
|
||||
const series = report?.buckets?.[0]?.series;
|
||||
return series ? Object.keys(series) : [];
|
||||
}
|
||||
|
||||
export function ReportViewer({ id, version, fields, onClose, onRegenerated }: ReportViewerProps) {
|
||||
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 [granularity, setGranularity] = useState<string | null>(null);
|
||||
const [flow, setFlow] = useState("outflows");
|
||||
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
|
||||
const [selectedPayees, setSelectedPayees] = useState<string[]>([]);
|
||||
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||
const prevGranularity = useRef<string | null>(null);
|
||||
|
||||
const params = useMemo(() => {
|
||||
const p: Record<string, any> = { flow };
|
||||
if (granularity) p.granularity = [granularity];
|
||||
if (selectedPeriods.length) p.period_ids = selectedPeriods;
|
||||
if (selectedPayees.length) p.payee = selectedPayees;
|
||||
if (selectedTags.length) p.tags = selectedTags;
|
||||
return p;
|
||||
}, [granularity, flow, selectedPeriods, selectedPayees, selectedTags]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const previous = prevGranularity.current;
|
||||
get(id, params)
|
||||
.then((res) => {
|
||||
if (!mounted) return;
|
||||
setReport(res);
|
||||
const options = snapshotGranularities(res);
|
||||
if (granularity === null && options.length) setGranularity(options[0]);
|
||||
if (previous !== null && previous !== granularity) setSelectedPeriods([]);
|
||||
prevGranularity.current = granularity;
|
||||
})
|
||||
.catch((e: any) => {
|
||||
if (!mounted) return;
|
||||
setError(apiErrorMessage(e));
|
||||
})
|
||||
.finally(() => {
|
||||
if (mounted) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [id, version, reload, params, get, granularity]);
|
||||
|
||||
const granularityOptions = useMemo(() => snapshotGranularities(report), [report]);
|
||||
|
||||
const periodOptions = useMemo(
|
||||
() => (Array.isArray(report?.period_ids) ? report.period_ids.map((label: string) => ({ value: label, label })) : []),
|
||||
[report],
|
||||
);
|
||||
const payeeOptions = useMemo(
|
||||
() => (Array.isArray(report?.payees) ? report.payees.map((label: string) => ({ value: label, label })) : []),
|
||||
[report],
|
||||
);
|
||||
const tagOptions = useMemo(
|
||||
() => (Array.isArray(report?.tags) ? report.tags.map((label: string) => ({ value: label, label })) : []),
|
||||
[report],
|
||||
);
|
||||
|
||||
const filter = useMemo(
|
||||
() => ({
|
||||
granularity: granularity ?? granularityOptions[0] ?? "",
|
||||
periods: selectedPeriods,
|
||||
payees: selectedPayees,
|
||||
tags: selectedTags,
|
||||
}),
|
||||
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
|
||||
);
|
||||
|
||||
const slice = useMemo(() => aggregateSlice(report?.buckets ?? [], filter), [report, filter]);
|
||||
const bars = useMemo(() => periodSlices(report?.buckets ?? [], filter), [report, filter]);
|
||||
|
||||
if (loading && !report) {
|
||||
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;
|
||||
|
||||
const activeGranularity = granularity ?? report.granularities?.[0] ?? "";
|
||||
const maxBar = bars.reduce((m, b) => Math.max(m, b.sum), 0);
|
||||
const range =
|
||||
report.query?.start_date || report.query?.end_date
|
||||
? `range ${report.query.start_date || "…"} → ${report.query.end_date || "…"}`
|
||||
: 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.name}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
flow {report.flow} · generated {report.generated_at ?? report.created_at}
|
||||
</Typography>
|
||||
{range && (
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{range}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{report.payees?.length ?? 0} payees · {report.tags?.length ?? 0} tags
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<IconButton aria-label="Regenerate report" onClick={() => onRegenerated(report)}>
|
||||
<CachedIcon />
|
||||
</IconButton>
|
||||
<IconButton aria-label="Close report" onClick={onClose}>
|
||||
<CloseIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ p: 2.5 }}>
|
||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "center", mb: 2 }}>
|
||||
<Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap" }}>
|
||||
{granularityOptions.map((g: string) => (
|
||||
<Chip
|
||||
key={g}
|
||||
label={g}
|
||||
clickable
|
||||
size="small"
|
||||
color={activeGranularity === g ? "primary" : "default"}
|
||||
variant={activeGranularity === g ? "filled" : "outlined"}
|
||||
onClick={() => setGranularity(g)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
<FormControl size="small" sx={{ width: 140 }}>
|
||||
<InputLabel id="viewer-flow-label">Flow</InputLabel>
|
||||
<Select labelId="viewer-flow-label" label="Flow" value={flow} onChange={(e) => setFlow(e.target.value)}>
|
||||
{FLOW_OPTIONS.map((f) => (
|
||||
<MenuItem key={f} value={f}>
|
||||
{f}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
|
||||
<Box sx={{ width: 260 }}>
|
||||
<FkMultiSelectField
|
||||
field={{ ...periodField, readOnly: periodOptions.length === 0 }}
|
||||
fkOptions={periodOptions}
|
||||
value={selectedPeriods}
|
||||
onChange={setSelectedPeriods}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ width: 260 }}>
|
||||
<FkMultiSelectField
|
||||
field={{ ...payeeField, readOnly: payeeOptions.length === 0 }}
|
||||
fkOptions={payeeOptions}
|
||||
value={selectedPayees}
|
||||
onChange={setSelectedPayees}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ width: 260 }}>
|
||||
<FkMultiSelectField
|
||||
field={{ ...tagField, readOnly: tagOptions.length === 0 }}
|
||||
fkOptions={tagOptions}
|
||||
value={selectedTags}
|
||||
onChange={setSelectedTags}
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ alignSelf: "center" }}>
|
||||
{slice.txns.length} transactions · {slice.count} rows
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}>
|
||||
<StatCard label="Outflows" value={formatCurrency(slice.spent, slice.currency)} color="error.main" />
|
||||
<StatCard label="Inflows" value={formatCurrency(slice.income, slice.currency)} color="success.main" />
|
||||
<StatCard label="Net" value={formatCurrency(slice.income - slice.spent, slice.currency)} color="info.main" />
|
||||
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
||||
</Box>
|
||||
|
||||
{bars.length === 0 ? (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mb: 2.5 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No data for this slice. Try another granularity, period or payer.
|
||||
</Typography>
|
||||
</Paper>
|
||||
) : (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 2, mb: 2.5 }}>
|
||||
{bars.map((b) => (
|
||||
<Box key={b.periodId} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
||||
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
||||
{b.periodId}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
height: 20,
|
||||
borderRadius: 1,
|
||||
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
||||
opacity: 0.85,
|
||||
minWidth: 4,
|
||||
}}
|
||||
style={{ width: `${maxBar ? Math.max((b.sum / maxBar) * 100, 2) : 2}%` }}
|
||||
/>
|
||||
<Typography variant="body2" fontWeight={600}>
|
||||
{formatCurrency(b.sum, slice.currency)}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{b.count} txn{b.count === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{slice.txns.length === 0 ? null : fields ? (
|
||||
<TransactionList
|
||||
items={slice.txns}
|
||||
fields={fields}
|
||||
granularity={toPeriodGranularity(activeGranularity)}
|
||||
showMetrics
|
||||
/>
|
||||
) : null}
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
170
src/Reports/types.ts
Normal file
170
src/Reports/types.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
||||
|
||||
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 SliceFilter {
|
||||
granularity: string;
|
||||
periods?: string[];
|
||||
payees?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export interface PeriodSlice {
|
||||
periodId: string;
|
||||
sum: number;
|
||||
count: number;
|
||||
firstDate: string | null;
|
||||
lastDate: string | null;
|
||||
}
|
||||
|
||||
export interface ReportFieldConfigs {
|
||||
name: FieldConfig;
|
||||
generatedAt: FieldConfig;
|
||||
}
|
||||
|
||||
export interface MetricLabel {
|
||||
key: string;
|
||||
label: string;
|
||||
order: number;
|
||||
}
|
||||
|
||||
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 granularityOptions(schemas: Record<string, any>): string[] {
|
||||
return schemas?.ReportQuery?.properties?.granularities?.items?.enum ?? [];
|
||||
}
|
||||
|
||||
export function groupDimOptions(schemas: Record<string, any>): string[] {
|
||||
return schemas?.ReportQuery?.properties?.group_dims?.items?.enum ?? ["payee", "tag"];
|
||||
}
|
||||
|
||||
export const FLOW_OPTIONS = ["both", "inflows", "outflows"];
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function dateVal(value: string): number {
|
||||
const t = new Date(value).getTime();
|
||||
return Number.isNaN(t) ? 0 : t;
|
||||
}
|
||||
|
||||
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
||||
const gk = bucket?.group_key ?? {};
|
||||
if (filter.payees?.length && !(gk.payee ?? []).some((p: string) => filter.payees?.includes(p))) return false;
|
||||
if (filter.tags?.length && !(gk.tag ?? []).some((t: string) => filter.tags?.includes(t))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function periodSlices(buckets: any[], filter: SliceFilter): PeriodSlice[] {
|
||||
const byPeriod = new Map<string, PeriodSlice>();
|
||||
for (const bucket of buckets ?? []) {
|
||||
if (!bucketMatches(bucket, filter)) continue;
|
||||
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
||||
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
||||
const m = period.metrics ?? {};
|
||||
const cur = byPeriod.get(period.period_id) ?? {
|
||||
periodId: period.period_id,
|
||||
sum: 0,
|
||||
count: 0,
|
||||
firstDate: null,
|
||||
lastDate: null,
|
||||
};
|
||||
cur.sum += typeof m.sum === "number" ? m.sum : 0;
|
||||
cur.count += typeof m.count === "number" ? m.count : 0;
|
||||
if (m.first_date && (!cur.firstDate || dateVal(String(m.first_date)) < dateVal(cur.firstDate))) {
|
||||
cur.firstDate = String(m.first_date);
|
||||
}
|
||||
if (m.last_date && (!cur.lastDate || dateVal(String(m.last_date)) > dateVal(cur.lastDate))) {
|
||||
cur.lastDate = String(m.last_date);
|
||||
}
|
||||
byPeriod.set(period.period_id, cur);
|
||||
}
|
||||
}
|
||||
return [...byPeriod.values()];
|
||||
}
|
||||
|
||||
export function aggregateSlice(buckets: any[], 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 bucket of buckets ?? []) {
|
||||
if (!bucketMatches(bucket, filter)) continue;
|
||||
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
||||
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
||||
const m = period.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 period.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 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 name = find("name");
|
||||
const generatedAt = find("generated_at");
|
||||
if (!name || !generatedAt) return null;
|
||||
return { name, 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,49 @@ import {
|
||||
import { alpha } from "@mui/material/styles";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||
import { ListCellRenderer, CurrencyField, applyDisplayFormat, formatCurrency } from "../../react-openapi";
|
||||
import type { ExpenseItem, ExpenseFieldConfigs } from "./types";
|
||||
import { isExpense, monthKey, monthLabel, parseOccurredAt } from "./types";
|
||||
import { formatCurrency } from "../../../react-openapi";
|
||||
import type { ExpenseItem, TxnFieldConfigs } from "../types";
|
||||
import { computeTxnMetrics, groupByDate, groupByPeriod } from "../utils/transactions";
|
||||
import type { PeriodGranularity } from "../utils/transactions";
|
||||
import { TransactionRow } from "./TransactionRow";
|
||||
import { StatCard } from "./StatCard";
|
||||
|
||||
interface GroupedMonth {
|
||||
key: string;
|
||||
interface TransactionListProps {
|
||||
items: ExpenseItem[];
|
||||
spent: number;
|
||||
income: number;
|
||||
currency: string;
|
||||
fields: TxnFieldConfigs;
|
||||
granularity?: PeriodGranularity;
|
||||
showMetrics?: boolean;
|
||||
}
|
||||
|
||||
function groupByMonth(items: ExpenseItem[]): GroupedMonth[] {
|
||||
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;
|
||||
|
||||
function GroupMetrics({ items, currency }: { items: ExpenseItem[]; currency: string }) {
|
||||
const m = computeTxnMetrics(items);
|
||||
const rows: { label: string; value: string }[] = [
|
||||
{ label: "Sum", value: formatCurrency(m.sum, currency) },
|
||||
{ label: "Avg", value: m.avg == null ? "—" : formatCurrency(m.avg, currency) },
|
||||
{ label: "Min", value: m.min == null ? "—" : formatCurrency(m.min, currency) },
|
||||
{ label: "Max", value: m.max == null ? "—" : formatCurrency(m.max, currency) },
|
||||
{
|
||||
label: "Cadence",
|
||||
value:
|
||||
m.cadenceDays == null
|
||||
? "—"
|
||||
: `${Number.isInteger(m.cadenceDays) ? m.cadenceDays : m.cadenceDays.toFixed(2)} days`,
|
||||
},
|
||||
];
|
||||
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 sx={{ display: "flex", gap: 2, flexWrap: "wrap", width: "100%" }}>
|
||||
{rows.map((row) => (
|
||||
<StatCard key={row.label} label={row.label} value={row.value} />
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
});
|
||||
|
||||
interface ExpenseListProps {
|
||||
items: ExpenseItem[];
|
||||
fields: ExpenseFieldConfigs;
|
||||
}
|
||||
|
||||
export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
export function TransactionList({ items, fields, granularity = "monthly", showMetrics = false }: TransactionListProps) {
|
||||
const [activeMonth, setActiveMonth] = useState<string | null>(null);
|
||||
const [openMonth, setOpenMonth] = useState<string | 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 pillRef = useRef<HTMLDivElement>(null);
|
||||
const didInitOpenMonth = useRef(false);
|
||||
@@ -233,38 +162,77 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
px: 2,
|
||||
py: 1,
|
||||
"& .MuiAccordionSummary-content": {
|
||||
alignItems: "center",
|
||||
gap: 1.5,
|
||||
flexDirection: "column",
|
||||
alignItems: "stretch",
|
||||
gap: 0.75,
|
||||
minWidth: 0,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
{monthLabel(group.key)}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Typography variant="body2" fontWeight={700} color="error.main">
|
||||
{formatCurrency(group.spent, group.currency)}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.disabled">
|
||||
/
|
||||
</Typography>
|
||||
<Typography variant="body2" fontWeight={700} color="success.main">
|
||||
{formatCurrency(group.income, group.currency)}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, minWidth: 0 }}>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
{group.label}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Typography variant="body2" fontWeight={700} color="error.main">
|
||||
{formatCurrency(group.spent, group.currency)}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.disabled">
|
||||
/
|
||||
</Typography>
|
||||
<Typography variant="body2" fontWeight={700} color="success.main">
|
||||
{formatCurrency(group.income, group.currency)}
|
||||
</Typography>
|
||||
</Box>
|
||||
{showMetrics && <GroupMetrics items={group.items} currency={group.currency} />}
|
||||
</AccordionSummary>
|
||||
<AccordionDetails sx={{ p: 1.5, pt: 1 }}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
{group.items.map((item) => (
|
||||
<ExpenseRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
currency={group.currency}
|
||||
fields={fields}
|
||||
/>
|
||||
{groupByDate(group.items).map((dateGroup) => (
|
||||
<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}
|
||||
item={item}
|
||||
currency={group.currency}
|
||||
fields={fields}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</AccordionDetails>
|
||||
@@ -319,7 +287,7 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" fontWeight={700} color="text.secondary">
|
||||
{activeMonth ? monthLabel(activeMonth) : ""}
|
||||
{activeMonth ? (groups.find((g) => g.key === activeMonth)?.label ?? activeMonth) : ""}
|
||||
</Typography>
|
||||
<KeyboardArrowDownIcon sx={{ fontSize: 14, color: "text.secondary" }} />
|
||||
</Box>
|
||||
@@ -339,7 +307,7 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
onClick={() => handleSelectMonth(group.key)}
|
||||
>
|
||||
<ListItemText
|
||||
primary={monthLabel(group.key)}
|
||||
primary={group.label}
|
||||
secondary={`${group.items.length} transactions`}
|
||||
/>
|
||||
</MenuItem>
|
||||
@@ -347,6 +315,4 @@ export function ExpenseList({ items, fields }: ExpenseListProps) {
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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}",
|
||||
},
|
||||
};
|
||||
}
|
||||
149
src/common/utils/transactions.ts
Normal file
149
src/common/utils/transactions.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
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));
|
||||
}
|
||||
|
||||
export interface TxnMetrics {
|
||||
sum: number;
|
||||
count: number;
|
||||
avg: number | null;
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
cadenceDays: number | null;
|
||||
}
|
||||
|
||||
/** Mirrors backend ReportMetrics.compute_metrics over a list of transactions. */
|
||||
export function computeTxnMetrics(items: ExpenseItem[]): TxnMetrics {
|
||||
const amounts = items.filter((it) => typeof it.amount === "number").map((it) => it.amount as number);
|
||||
const empty = { sum: 0, count: 0, avg: null, min: null, max: null, cadenceDays: null };
|
||||
if (amounts.length === 0) {
|
||||
return empty;
|
||||
}
|
||||
const dates = items
|
||||
.map((it) => it.occurred_at)
|
||||
.filter((d): d is string => !!d)
|
||||
.map((d) => parseOccurredAt(d).getTime())
|
||||
.sort((a, b) => a - b);
|
||||
const sum = amounts.reduce((s, a) => s + a, 0);
|
||||
let cadenceDays: number | null = null;
|
||||
if (dates.length >= 2) {
|
||||
const gaps: number[] = [];
|
||||
for (let i = 0; i < dates.length - 1; i += 1) {
|
||||
gaps.push((dates[i + 1] - dates[i]) / 86400000);
|
||||
}
|
||||
cadenceDays = Math.round((gaps.reduce((s, g) => s + g, 0) / gaps.length) * 100) / 100;
|
||||
}
|
||||
return {
|
||||
sum,
|
||||
count: amounts.length,
|
||||
avg: sum / amounts.length,
|
||||
min: Math.min(...amounts),
|
||||
max: Math.max(...amounts),
|
||||
cadenceDays,
|
||||
};
|
||||
}
|
||||
@@ -17,7 +17,8 @@ import {
|
||||
import Home from './Home';
|
||||
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
||||
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 { AuthProvider, AuthPage, useAuth, ProfileCreate, ProfileEdit, ProfileView } from "../react-auth";
|
||||
import Header from './Header';
|
||||
@@ -80,6 +81,7 @@ const routerMapping = [
|
||||
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
||||
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
||||
{ path: "/expenses", component: Expense, headerTitle: "Expenses" },
|
||||
{ path: "/reports", component: Reports, headerTitle: "Reports" },
|
||||
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
||||
{ path: "/profile/*", component: ProfileRoutes, headerTitle: "Profile" },
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user