refactor: revamp for older report logic with benefits of newer one
This commit is contained in:
@@ -3,6 +3,24 @@ import axios, { AxiosInstance } from "axios";
|
|||||||
let apiClient: AxiosInstance | null = null;
|
let apiClient: AxiosInstance | null = null;
|
||||||
let _onUnauthorized: (() => void) | undefined;
|
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 {
|
export function initApi(baseUrl: string, getToken?: () => string | null, onUnauthorized?: () => void): AxiosInstance {
|
||||||
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
||||||
_onUnauthorized = onUnauthorized;
|
_onUnauthorized = onUnauthorized;
|
||||||
@@ -14,6 +32,7 @@ export function initApi(baseUrl: string, getToken?: () => string | null, onUnaut
|
|||||||
apiClient = axios.create({
|
apiClient = axios.create({
|
||||||
baseURL: baseUrl,
|
baseURL: baseUrl,
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
|
paramsSerializer: serializeParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
apiClient.interceptors.request.use((config) => {
|
apiClient.interceptors.request.use((config) => {
|
||||||
|
|||||||
@@ -5,78 +5,73 @@ import {
|
|||||||
Typography,
|
Typography,
|
||||||
TextField,
|
TextField,
|
||||||
Button,
|
Button,
|
||||||
IconButton,
|
|
||||||
MenuItem,
|
MenuItem,
|
||||||
Select,
|
Select,
|
||||||
FormControl,
|
FormControl,
|
||||||
InputLabel,
|
InputLabel,
|
||||||
Autocomplete,
|
Autocomplete,
|
||||||
|
FormControlLabel,
|
||||||
|
Checkbox,
|
||||||
|
Chip,
|
||||||
Alert,
|
Alert,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import AddIcon from "@mui/icons-material/Add";
|
import AddIcon from "@mui/icons-material/Add";
|
||||||
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
|
|
||||||
import { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
|
import { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
|
||||||
import { useToast } from "../ui/Toast";
|
import { useToast } from "../ui/Toast";
|
||||||
import { isDdmmyyyy } from "../common/utils/dates";
|
import { isDdmmyyyy } from "../common/utils/dates";
|
||||||
import { apiErrorMessage, groupTypeEnum, periodHints } from "./types";
|
import { apiErrorMessage, granularityOptions, groupDimOptions, FLOW_OPTIONS } from "./types";
|
||||||
|
|
||||||
interface GroupRow {
|
|
||||||
id: number;
|
|
||||||
group_type: string;
|
|
||||||
group_value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GenerateReportPanelProps {
|
interface GenerateReportPanelProps {
|
||||||
onGenerated: (reports: any[]) => void;
|
onGenerated: (report: any) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ALL_GRANULARITIES = ["weekly", "monthly", "quarterly"];
|
||||||
|
|
||||||
export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
||||||
const { schemas, resources } = useAppContext();
|
const { schemas, resources } = useAppContext();
|
||||||
const { create } = useResource("reports");
|
const { create } = useResource("reports");
|
||||||
const { list: listEntities } = useResource("entities");
|
const { list: listAccounts } = useResource("accounts");
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
|
|
||||||
const [rows, setRows] = useState<GroupRow[]>([{ id: 1, group_type: "monthly", group_value: "*" }]);
|
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 [startDate, setStartDate] = useState("");
|
||||||
const [endDate, setEndDate] = useState("");
|
const [endDate, setEndDate] = useState("");
|
||||||
|
const [minAmount, setMinAmount] = useState("");
|
||||||
|
const [maxAmount, setMaxAmount] = useState("");
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [entityNames, setEntityNames] = useState<string[]>([]);
|
const [accountOptions, setAccountOptions] = useState<string[]>([]);
|
||||||
const [dateErrors, setDateErrors] = useState<{ start?: string; end?: string }>({});
|
const [dateErrors, setDateErrors] = useState<{ start?: string; end?: string }>({});
|
||||||
|
|
||||||
const types = useMemo(() => groupTypeEnum(schemas), [schemas]);
|
const granularityChoices = useMemo(() => {
|
||||||
const entitiesRes = resources.find((r) => r.name === "entities");
|
const enums = granularityOptions(schemas);
|
||||||
const entitiesFormat = entitiesRes?.displayFormat ?? "{name}";
|
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(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
listEntities({ limit: 0 }).then((res) => {
|
listAccounts({ limit: 0 }).then((res) => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
const names = (res.items ?? [])
|
const names = (res.items ?? [])
|
||||||
.map((it: any) => applyDisplayFormat(it, entitiesFormat))
|
.map((it: any) => applyDisplayFormat(it, accountsFormat))
|
||||||
.filter((n: string) => n);
|
.filter((n: string) => n);
|
||||||
setEntityNames([...new Set(names)].sort((a, b) => a.localeCompare(b)));
|
setAccountOptions([...new Set(names)].sort((a, b) => a.localeCompare(b)));
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
mounted = false;
|
mounted = false;
|
||||||
};
|
};
|
||||||
}, [listEntities, entitiesFormat]);
|
}, [listAccounts, accountsFormat]);
|
||||||
|
|
||||||
const isPayee = (type: string) => type === "payee";
|
const toggle = (list: string[], value: string, setter: (v: string[]) => void) =>
|
||||||
|
setter(list.includes(value) ? list.filter((v) => v !== value) : [...list, value]);
|
||||||
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 validateDates = (): boolean => {
|
||||||
const errs: { start?: string; end?: string } = {};
|
const errs: { start?: string; end?: string } = {};
|
||||||
@@ -86,25 +81,47 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
|||||||
return Object.keys(errs).length === 0;
|
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 () => {
|
const handleSubmit = async () => {
|
||||||
if (!validateDates()) return;
|
if (!validateDates()) return;
|
||||||
setError(null);
|
setError(null);
|
||||||
const groups = rows
|
const min = parseAmount(minAmount);
|
||||||
.filter((r) => r.group_type && r.group_value.trim())
|
const max = parseAmount(maxAmount);
|
||||||
.map(({ group_type, group_value }) => ({ group_type, group_value: group_value.trim() }));
|
if (minAmount.trim() && min === null) {
|
||||||
if (groups.length === 0) {
|
setError("Min amount must be a number");
|
||||||
setError("At least one group is required");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSubmitting(true);
|
if (maxAmount.trim() && max === null) {
|
||||||
const payload: Record<string, any> = { groups };
|
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 (startDate.trim()) payload.start_date = startDate.trim();
|
||||||
if (endDate.trim()) payload.end_date = endDate.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 {
|
try {
|
||||||
const created = await create(payload);
|
const created = await create(payload);
|
||||||
const list = Array.isArray(created) ? created : created ? [created] : [];
|
showToast(`Generated snapshot ${created?.name ? `“${created.name}”` : ""}`.trim() || "Generated snapshot");
|
||||||
showToast(`Generated ${list.length} report${list.length === 1 ? "" : "s"}`);
|
onGenerated(created);
|
||||||
onGenerated(list);
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(apiErrorMessage(e));
|
setError(apiErrorMessage(e));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -118,8 +135,8 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
|||||||
Generate report
|
Generate report
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5, mb: 2 }}>
|
<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
|
Define the snapshot's scope. Granularity, payee and tag are sliced at view time — the cube is built once and
|
||||||
snapshots weekly, monthly and quarterly.
|
every combination stays cheap to read.
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -128,81 +145,128 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
|||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||||
{rows.map((row) => (
|
<TextField
|
||||||
<Box key={row.id} sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}>
|
size="small"
|
||||||
<FormControl size="small" sx={{ width: 180, flexShrink: 0 }}>
|
label="Name"
|
||||||
<InputLabel id={`group-type-${row.id}`}>Type</InputLabel>
|
placeholder="e.g. Monthly spending"
|
||||||
<Select
|
value={name}
|
||||||
labelId={`group-type-${row.id}`}
|
onChange={(e) => setName(e.target.value)}
|
||||||
label="Type"
|
sx={{ maxWidth: 420 }}
|
||||||
value={row.group_type}
|
/>
|
||||||
onChange={(e) => updateRow(row.id, { group_type: e.target.value, group_value: "*" })}
|
|
||||||
>
|
<Box>
|
||||||
{types.map((t) => (
|
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
|
||||||
<MenuItem key={t} value={t}>
|
Granularities
|
||||||
{t}
|
</Typography>
|
||||||
</MenuItem>
|
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||||
))}
|
{granularityChoices.map((g) => (
|
||||||
</Select>
|
<Chip
|
||||||
</FormControl>
|
key={g}
|
||||||
<Autocomplete
|
label={g}
|
||||||
freeSolo
|
clickable
|
||||||
size="small"
|
color={granularities.includes(g) ? "primary" : "default"}
|
||||||
sx={{ flex: 1, minWidth: 240 }}
|
variant={granularities.includes(g) ? "filled" : "outlined"}
|
||||||
options={valueOptions(row)}
|
onClick={() => toggle(granularities, g, setGranularities)}
|
||||||
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>
|
||||||
))}
|
</Box>
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Button startIcon={<AddIcon />} size="small" sx={{ mt: 1 }} onClick={addRow}>
|
<Box>
|
||||||
Add dimension
|
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
|
||||||
</Button>
|
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, mt: 2, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "flex-start" }}>
|
||||||
<TextField
|
<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"
|
size="small"
|
||||||
label="Start date"
|
options={accountOptions}
|
||||||
placeholder="DD-MM-YYYY"
|
value={accounts}
|
||||||
value={startDate}
|
onChange={(_, newVal) => setAccounts(newVal)}
|
||||||
onChange={(e) => setStartDate(e.target.value)}
|
renderInput={(params) => (
|
||||||
error={Boolean(dateErrors.start)}
|
<TextField {...params} label="Accounts" placeholder="Restrict to accounts (empty = all)" />
|
||||||
helperText={dateErrors.start ?? "Inclusive start (empty = unbounded)"}
|
)}
|
||||||
sx={{ width: 200 }}
|
sx={{ maxWidth: 420 }}
|
||||||
/>
|
|
||||||
<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 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>
|
||||||
|
|
||||||
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
||||||
<Button
|
<Button variant="contained" startIcon={<AddIcon />} onClick={handleSubmit} disabled={submitting}>
|
||||||
variant="contained"
|
|
||||||
startIcon={<AddIcon />}
|
|
||||||
onClick={handleSubmit}
|
|
||||||
disabled={submitting}
|
|
||||||
>
|
|
||||||
{submitting ? "Generating…" : "Generate"}
|
{submitting ? "Generating…" : "Generate"}
|
||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||||
import AssessmentIcon from "@mui/icons-material/Assessment";
|
import AssessmentIcon from "@mui/icons-material/Assessment";
|
||||||
import { useResource, useAppContext, formatCurrency } from "../../react-openapi";
|
import { useResource, useAppContext } from "../../react-openapi";
|
||||||
import { useToast } from "../ui/Toast";
|
import { useToast } from "../ui/Toast";
|
||||||
import { PageHeader } from "../ui/PageHeader";
|
import { PageHeader } from "../ui/PageHeader";
|
||||||
import { EmptyState } from "../ui/EmptyState";
|
import { EmptyState } from "../ui/EmptyState";
|
||||||
@@ -45,22 +45,19 @@ export default function Report() {
|
|||||||
}, [load]);
|
}, [load]);
|
||||||
|
|
||||||
const handleGenerated = useCallback(
|
const handleGenerated = useCallback(
|
||||||
(created: any[]) => {
|
(created: any) => {
|
||||||
load();
|
load();
|
||||||
if (created?.[0]?.id) setSelectedId(created[0].id);
|
if (created?.id) setSelectedId(created.id);
|
||||||
},
|
},
|
||||||
[load],
|
[load],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleRegenerate = useCallback(
|
const handleRegenerate = useCallback(
|
||||||
async (report: any) => {
|
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 {
|
try {
|
||||||
await create(payload);
|
const created = await create(report.query ?? {});
|
||||||
showToast("Report regenerated");
|
showToast("Report regenerated");
|
||||||
setSelectedId(report.id);
|
setSelectedId(created?.id ?? report.id);
|
||||||
setViewerVersion((v) => v + 1);
|
setViewerVersion((v) => v + 1);
|
||||||
load();
|
load();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -86,9 +83,9 @@ export default function Report() {
|
|||||||
|
|
||||||
const summary = useMemo(() => {
|
const summary = useMemo(() => {
|
||||||
const rows = reports ?? [];
|
const rows = reports ?? [];
|
||||||
const txnCount = rows.reduce((s, r) => s + (r.txn_count ?? 0), 0);
|
const granularities = new Set<string>();
|
||||||
const total = rows.reduce((s, r) => s + (typeof r.metrics?.sum === "number" ? r.metrics.sum : 0), 0);
|
for (const r of rows) for (const g of r.query?.granularities ?? []) granularities.add(g);
|
||||||
return { count: rows.length, txnCount, total };
|
return { count: rows.length, granularities: [...granularities].join(", ") };
|
||||||
}, [reports]);
|
}, [reports]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -96,7 +93,7 @@ export default function Report() {
|
|||||||
<PageHeader
|
<PageHeader
|
||||||
crumbs={[{ label: "Home", path: "/" }, { label: "Reports" }]}
|
crumbs={[{ label: "Home", path: "/" }, { label: "Reports" }]}
|
||||||
title="Reports"
|
title="Reports"
|
||||||
subtitle="Generate period/payee snapshots from the reporting API and slice the cached data."
|
subtitle="Build an immutable snapshot cube once, then slice by granularity, period, payee and tag at view time."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -107,8 +104,7 @@ export default function Report() {
|
|||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
||||||
<StatCard label="Reports" value={summary.count.toLocaleString("en-IN")} />
|
<StatCard label="Reports" value={summary.count.toLocaleString("en-IN")} />
|
||||||
<StatCard label="Transactions covered" value={summary.txnCount.toLocaleString("en-IN")} />
|
<StatCard label="Granularities covered" value={summary.granularities || "—"} />
|
||||||
<StatCard label="Total" value={formatCurrency(summary.total, "INR")} />
|
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<GenerateReportPanel onGenerated={handleGenerated} />
|
<GenerateReportPanel onGenerated={handleGenerated} />
|
||||||
@@ -154,7 +150,7 @@ export default function Report() {
|
|||||||
<EmptyState
|
<EmptyState
|
||||||
icon={<AssessmentIcon />}
|
icon={<AssessmentIcon />}
|
||||||
title="No reports yet"
|
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)."
|
description="Generate your first snapshot above — choose granularities and grouping dimensions, then slice the cached cube by period, payee and tag."
|
||||||
/>
|
/>
|
||||||
</Paper>
|
</Paper>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Box, Paper, Typography, Button, IconButton, Skeleton, Tooltip } from "@
|
|||||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
||||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||||
import CachedIcon from "@mui/icons-material/Cached";
|
import CachedIcon from "@mui/icons-material/Cached";
|
||||||
import { ListCellRenderer, formatCurrency } from "../../react-openapi";
|
import { ListCellRenderer } from "../../react-openapi";
|
||||||
import type { ReportFieldConfigs } from "./types";
|
import type { ReportFieldConfigs } from "./types";
|
||||||
|
|
||||||
interface ReportListProps {
|
interface ReportListProps {
|
||||||
@@ -30,10 +30,14 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
return (
|
return (
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||||
{reports.map((report) => {
|
{reports.map((report) => {
|
||||||
const sum = typeof report.metrics?.sum === "number" ? report.metrics.sum : null;
|
const q = report.query ?? {};
|
||||||
const range =
|
const range = q.start_date || q.end_date ? `range ${q.start_date || "…"} → ${q.end_date || "…"}` : null;
|
||||||
report.start_date || report.end_date
|
const dims = Array.isArray(q.group_dims) ? q.group_dims.join(", ") : "";
|
||||||
? `range ${report.start_date || "…"} → ${report.end_date || "…"}`
|
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;
|
: null;
|
||||||
return (
|
return (
|
||||||
<Paper
|
<Paper
|
||||||
@@ -50,20 +54,17 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
||||||
<Box sx={{ flex: "1 1 260px", minWidth: 0 }}>
|
<Box sx={{ flex: "1 1 260px", minWidth: 0 }}>
|
||||||
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}>
|
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}>
|
||||||
{report.group_label}
|
{report.name || report.id}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.25 }}>
|
<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">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.period_label}
|
{granularities}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.disabled">
|
<Typography variant="caption" color="text.disabled">
|
||||||
/
|
/
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.payee}
|
{dims}
|
||||||
</Typography>
|
</Typography>
|
||||||
{range && (
|
{range && (
|
||||||
<Typography variant="caption" color="text.disabled">
|
<Typography variant="caption" color="text.disabled">
|
||||||
@@ -73,14 +74,13 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
</Box>
|
</Box>
|
||||||
<Box sx={{ display: "flex", gap: 1.5, mt: 0.5 }}>
|
<Box sx={{ display: "flex", gap: 1.5, mt: 0.5 }}>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.entity_count ?? 0} entities
|
{accounts}
|
||||||
</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>
|
</Typography>
|
||||||
|
{amounts && (
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{amounts}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
{fields && (
|
{fields && (
|
||||||
<Box sx={{ color: "text.secondary" }}>
|
<Box sx={{ color: "text.secondary" }}>
|
||||||
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
||||||
@@ -89,12 +89,6 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
</Box>
|
</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 }}>
|
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
|
||||||
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
||||||
View
|
View
|
||||||
|
|||||||
@@ -1,13 +1,5 @@
|
|||||||
import React, { useEffect, useMemo, useState } from "react";
|
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import {
|
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
|
||||||
Box,
|
|
||||||
Paper,
|
|
||||||
Typography,
|
|
||||||
Button,
|
|
||||||
IconButton,
|
|
||||||
Alert,
|
|
||||||
Skeleton,
|
|
||||||
} from "@mui/material";
|
|
||||||
import CloseIcon from "@mui/icons-material/Close";
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
import CachedIcon from "@mui/icons-material/Cached";
|
import CachedIcon from "@mui/icons-material/Cached";
|
||||||
import { FkMultiSelectField, useResource, formatCurrency } from "../../react-openapi";
|
import { FkMultiSelectField, useResource, formatCurrency } from "../../react-openapi";
|
||||||
@@ -16,7 +8,7 @@ import { StatCard } from "../common/components/StatCard";
|
|||||||
import { TransactionList } from "../common/components/TransactionList";
|
import { TransactionList } from "../common/components/TransactionList";
|
||||||
import type { TxnFieldConfigs } from "../common/types";
|
import type { TxnFieldConfigs } from "../common/types";
|
||||||
import { toPeriodGranularity } from "../common/utils/transactions";
|
import { toPeriodGranularity } from "../common/utils/transactions";
|
||||||
import { aggregateSlice } from "./types";
|
import { aggregateSlice, periodSlices, FLOW_OPTIONS, apiErrorMessage } from "./types";
|
||||||
|
|
||||||
const periodField: FieldConfig = {
|
const periodField: FieldConfig = {
|
||||||
name: "period",
|
name: "period",
|
||||||
@@ -46,6 +38,20 @@ const payeeField: FieldConfig = {
|
|||||||
isArray: true,
|
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 {
|
interface ReportViewerProps {
|
||||||
id: string;
|
id: string;
|
||||||
version: number;
|
version: number;
|
||||||
@@ -54,6 +60,15 @@ interface ReportViewerProps {
|
|||||||
onRegenerated: (report: any) => 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) {
|
export function ReportViewer({ id, version, fields, onClose, onRegenerated }: ReportViewerProps) {
|
||||||
const { get } = useResource("reports");
|
const { get } = useResource("reports");
|
||||||
|
|
||||||
@@ -61,23 +76,39 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [reload, setReload] = useState(0);
|
const [reload, setReload] = useState(0);
|
||||||
|
const [granularity, setGranularity] = useState<string | null>(null);
|
||||||
|
const [flow, setFlow] = useState("outflows");
|
||||||
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
|
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
|
||||||
const [selectedPayees, setSelectedPayees] = 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(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
get(id)
|
const previous = prevGranularity.current;
|
||||||
|
get(id, params)
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setReport(res);
|
setReport(res);
|
||||||
setSelectedPeriods([]);
|
const options = snapshotGranularities(res);
|
||||||
setSelectedPayees([]);
|
if (granularity === null && options.length) setGranularity(options[0]);
|
||||||
|
if (previous !== null && previous !== granularity) setSelectedPeriods([]);
|
||||||
|
prevGranularity.current = granularity;
|
||||||
})
|
})
|
||||||
.catch((e: any) => {
|
.catch((e: any) => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setError(e?.response?.data?.detail ?? e?.message ?? "Failed to load report");
|
setError(apiErrorMessage(e));
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
if (mounted) setLoading(false);
|
if (mounted) setLoading(false);
|
||||||
@@ -85,34 +116,37 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
return () => {
|
return () => {
|
||||||
mounted = false;
|
mounted = false;
|
||||||
};
|
};
|
||||||
}, [id, version, reload, get]);
|
}, [id, version, reload, params, get, granularity]);
|
||||||
|
|
||||||
const data = useMemo(() => (Array.isArray(report?.data) ? report.data : null), [report]);
|
const granularityOptions = useMemo(() => snapshotGranularities(report), [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 periodOptions = useMemo(
|
const periodOptions = useMemo(
|
||||||
() => groupOptions.period.map((label: string) => ({ value: label, label })),
|
() => (Array.isArray(report?.period_ids) ? report.period_ids.map((label: string) => ({ value: label, label })) : []),
|
||||||
[groupOptions],
|
[report],
|
||||||
);
|
);
|
||||||
const payeeOptions = useMemo(
|
const payeeOptions = useMemo(
|
||||||
() => groupOptions.payee.map((label: string) => ({ value: label, label })),
|
() => (Array.isArray(report?.payees) ? report.payees.map((label: string) => ({ value: label, label })) : []),
|
||||||
[groupOptions],
|
[report],
|
||||||
|
);
|
||||||
|
const tagOptions = useMemo(
|
||||||
|
() => (Array.isArray(report?.tags) ? report.tags.map((label: string) => ({ value: label, label })) : []),
|
||||||
|
[report],
|
||||||
);
|
);
|
||||||
|
|
||||||
const slice = useMemo(
|
const filter = useMemo(
|
||||||
() => aggregateSlice(data ?? [], { periods: selectedPeriods, payees: selectedPayees }),
|
() => ({
|
||||||
[data, selectedPeriods, selectedPayees],
|
granularity: granularity ?? granularityOptions[0] ?? "",
|
||||||
|
periods: selectedPeriods,
|
||||||
|
payees: selectedPayees,
|
||||||
|
tags: selectedTags,
|
||||||
|
}),
|
||||||
|
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
|
||||||
);
|
);
|
||||||
|
|
||||||
if (loading) {
|
const slice = useMemo(() => aggregateSlice(report?.buckets ?? [], filter), [report, filter]);
|
||||||
|
const bars = useMemo(() => periodSlices(report?.buckets ?? [], filter), [report, filter]);
|
||||||
|
|
||||||
|
if (loading && !report) {
|
||||||
return (
|
return (
|
||||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
||||||
<Skeleton variant="text" width={220} height={28} />
|
<Skeleton variant="text" width={220} height={28} />
|
||||||
@@ -137,6 +171,13 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
|
|
||||||
if (!report) return null;
|
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 (
|
return (
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 3, overflow: "hidden" }}>
|
<Paper variant="outlined" sx={{ borderRadius: 3, overflow: "hidden" }}>
|
||||||
<Box
|
<Box
|
||||||
@@ -153,77 +194,137 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
>
|
>
|
||||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
{report.group_label}
|
{report.name}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.granularity} · {report.period_label} · {report.payee}
|
flow {report.flow} · generated {report.generated_at ?? report.created_at}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.disabled">
|
{range && (
|
||||||
{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">
|
<Typography variant="caption" color="text.disabled">
|
||||||
range {report.start_date || "…"} → {report.end_date || "…"}
|
{range}
|
||||||
</Typography>
|
</Typography>
|
||||||
) : null}
|
)}
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{report.payees?.length ?? 0} payees · {report.tags?.length ?? 0} tags
|
||||||
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
<IconButton aria-label="Regenerate report" onClick={() => onRegenerated(report)}>
|
||||||
|
<CachedIcon />
|
||||||
|
</IconButton>
|
||||||
<IconButton aria-label="Close report" onClick={onClose}>
|
<IconButton aria-label="Close report" onClick={onClose}>
|
||||||
<CloseIcon />
|
<CloseIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{data === null ? (
|
<Box sx={{ p: 2.5 }}>
|
||||||
<Box sx={{ p: 3 }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "center", mb: 2 }}>
|
||||||
<Alert severity="info" sx={{ borderRadius: 2, mb: 2 }}>
|
<Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap" }}>
|
||||||
The cached data for this report has expired. Regenerate it to rebuild the snapshot.
|
{granularityOptions.map((g: string) => (
|
||||||
</Alert>
|
<Chip
|
||||||
<Button variant="contained" startIcon={<CachedIcon />} onClick={() => onRegenerated(report)}>
|
key={g}
|
||||||
Regenerate
|
label={g}
|
||||||
</Button>
|
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>
|
||||||
) : (
|
|
||||||
<Box sx={{ p: 2.5 }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
|
||||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
|
<Box sx={{ width: 260 }}>
|
||||||
<Box sx={{ width: 260 }}>
|
<FkMultiSelectField
|
||||||
<FkMultiSelectField
|
field={{ ...periodField, readOnly: periodOptions.length === 0 }}
|
||||||
field={{ ...periodField, readOnly: groupOptions.period.length === 0 }}
|
fkOptions={periodOptions}
|
||||||
fkOptions={periodOptions}
|
value={selectedPeriods}
|
||||||
value={selectedPeriods}
|
onChange={setSelectedPeriods}
|
||||||
onChange={setSelectedPeriods}
|
/>
|
||||||
/>
|
</Box>
|
||||||
</Box>
|
<Box sx={{ width: 260 }}>
|
||||||
<Box sx={{ width: 260 }}>
|
<FkMultiSelectField
|
||||||
<FkMultiSelectField
|
field={{ ...payeeField, readOnly: payeeOptions.length === 0 }}
|
||||||
field={{ ...payeeField, readOnly: groupOptions.payee.length === 0 }}
|
fkOptions={payeeOptions}
|
||||||
fkOptions={payeeOptions}
|
value={selectedPayees}
|
||||||
value={selectedPayees}
|
onChange={setSelectedPayees}
|
||||||
onChange={setSelectedPayees}
|
/>
|
||||||
/>
|
</Box>
|
||||||
</Box>
|
<Box sx={{ width: 260 }}>
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ alignSelf: "center" }}>
|
<FkMultiSelectField
|
||||||
Showing {slice.count} transactions across {slice.txns.length} rows
|
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>
|
</Typography>
|
||||||
</Box>
|
</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>
|
||||||
|
)}
|
||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}>
|
{slice.txns.length === 0 ? null : fields ? (
|
||||||
<StatCard label="Outflows" value={formatCurrency(slice.spent, slice.currency)} color="error.main" />
|
<TransactionList
|
||||||
<StatCard label="Inflows" value={formatCurrency(slice.income, slice.currency)} color="success.main" />
|
items={slice.txns}
|
||||||
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
fields={fields}
|
||||||
</Box>
|
granularity={toPeriodGranularity(activeGranularity)}
|
||||||
|
showMetrics
|
||||||
{slice.txns.length === 0 ? (
|
/>
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3 }}>
|
) : null}
|
||||||
<Typography variant="body2" color="text.secondary">
|
</Box>
|
||||||
No transactions in this slice.
|
|
||||||
</Typography>
|
|
||||||
</Paper>
|
|
||||||
) : fields ? (
|
|
||||||
<TransactionList items={slice.txns} fields={fields} granularity={toPeriodGranularity(report.granularity)} showMetrics />
|
|
||||||
) : null}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,4 @@
|
|||||||
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
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 {
|
|
||||||
periods?: string[];
|
|
||||||
payees?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SliceSummary {
|
export interface SliceSummary {
|
||||||
sum: number;
|
sum: number;
|
||||||
@@ -33,12 +14,23 @@ export interface SliceSummary {
|
|||||||
currency: string;
|
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 {
|
export interface ReportFieldConfigs {
|
||||||
groupLabel: FieldConfig;
|
name: FieldConfig;
|
||||||
granularity: FieldConfig;
|
|
||||||
periodLabel: FieldConfig;
|
|
||||||
payee: FieldConfig;
|
|
||||||
entityCount: FieldConfig;
|
|
||||||
generatedAt: FieldConfig;
|
generatedAt: FieldConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,23 +40,6 @@ export interface MetricLabel {
|
|||||||
order: number;
|
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 {
|
export function apiErrorMessage(e: any): string {
|
||||||
if (e?.response?.data) {
|
if (e?.response?.data) {
|
||||||
const d = e.response.data;
|
const d = e.response.data;
|
||||||
@@ -76,15 +51,16 @@ export function apiErrorMessage(e: any): string {
|
|||||||
return e?.message ?? "Request failed";
|
return e?.message ?? "Request failed";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function groupTypeEnum(schemas: Record<string, any>): string[] {
|
export function granularityOptions(schemas: Record<string, any>): string[] {
|
||||||
return schemas?.GroupSpec?.properties?.group_type?.enum ?? [];
|
return schemas?.ReportQuery?.properties?.granularities?.items?.enum ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function groupValueFk(schemas: Record<string, any>): { resource?: string; prefetch?: boolean } | null {
|
export function groupDimOptions(schemas: Record<string, any>): string[] {
|
||||||
const fk = schemas?.GroupSpec?.properties?.group_value?.["x-fk"];
|
return schemas?.ReportQuery?.properties?.group_dims?.items?.enum ?? ["payee", "tag"];
|
||||||
return fk && typeof fk === "object" ? fk : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const FLOW_OPTIONS = ["both", "inflows", "outflows"];
|
||||||
|
|
||||||
export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
||||||
const props: Record<string, any> = schemas?.ReportMetrics?.properties ?? {};
|
const props: Record<string, any> = schemas?.ReportMetrics?.properties ?? {};
|
||||||
return Object.entries(props)
|
return Object.entries(props)
|
||||||
@@ -97,42 +73,47 @@ export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
|||||||
.sort((a, b) => a.order - b.order);
|
.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 {
|
function dateVal(value: string): number {
|
||||||
try {
|
const t = new Date(value).getTime();
|
||||||
return parseDdmmyyyy(value).getTime();
|
return Number.isNaN(t) ? 0 : t;
|
||||||
} catch {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function groupMatches(group: ReportGroupLike, filter: SliceFilter): boolean {
|
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
||||||
const key = parseCacheKey(group.key);
|
const gk = bucket?.group_key ?? {};
|
||||||
if (filter.periods && filter.periods.length > 0) {
|
if (filter.payees?.length && !(gk.payee ?? []).some((p: string) => filter.payees?.includes(p))) return false;
|
||||||
if (!key.period || !filter.periods.includes(key.period.label)) return false;
|
if (filter.tags?.length && !(gk.tag ?? []).some((t: string) => filter.tags?.includes(t))) return false;
|
||||||
}
|
|
||||||
if (filter.payees && filter.payees.length > 0) {
|
|
||||||
if (!key.payee || !filter.payees.includes(key.payee.label)) return false;
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function aggregateSlice(groups: ReportGroupLike[], filter: SliceFilter): SliceSummary {
|
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 sum = 0;
|
||||||
let count = 0;
|
let count = 0;
|
||||||
let spent = 0;
|
let spent = 0;
|
||||||
@@ -145,30 +126,33 @@ export function aggregateSlice(groups: ReportGroupLike[], filter: SliceFilter):
|
|||||||
const txns: any[] = [];
|
const txns: any[] = [];
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
|
|
||||||
for (const group of groups) {
|
for (const bucket of buckets ?? []) {
|
||||||
if (!groupMatches(group, filter)) continue;
|
if (!bucketMatches(bucket, filter)) continue;
|
||||||
const m = group.metrics ?? {};
|
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
||||||
if (typeof m.sum === "number") sum += m.sum;
|
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
||||||
if (typeof m.count === "number") count += m.count;
|
const m = period.metrics ?? {};
|
||||||
if (typeof m.min === "number") min = min === null ? m.min : Math.min(min, m.min);
|
if (typeof m.sum === "number") sum += m.sum;
|
||||||
if (typeof m.max === "number") max = max === null ? m.max : Math.max(max, m.max);
|
if (typeof m.count === "number") count += m.count;
|
||||||
if (m.first_date && (!firstDate || dateVal(String(m.first_date)) < dateVal(firstDate))) {
|
if (typeof m.min === "number") min = min === null ? m.min : Math.min(min, m.min);
|
||||||
firstDate = String(m.first_date);
|
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))) {
|
||||||
if (m.last_date && (!lastDate || dateVal(String(m.last_date)) > dateVal(lastDate))) {
|
firstDate = String(m.first_date);
|
||||||
lastDate = String(m.last_date);
|
}
|
||||||
}
|
if (m.last_date && (!lastDate || dateVal(String(m.last_date)) > dateVal(lastDate))) {
|
||||||
for (const txn of group.txns ?? []) {
|
lastDate = String(m.last_date);
|
||||||
if (txn?.id != null) {
|
}
|
||||||
if (seen.has(txn.id)) continue;
|
for (const txn of period.txns ?? []) {
|
||||||
seen.add(txn.id);
|
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;
|
||||||
}
|
}
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,12 +163,8 @@ export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFiel
|
|||||||
const reportsRes = resources.find((r) => r.name === "reports");
|
const reportsRes = resources.find((r) => r.name === "reports");
|
||||||
if (!reportsRes) return null;
|
if (!reportsRes) return null;
|
||||||
const find = (name: string) => reportsRes.fields.find((f) => f.name === name);
|
const find = (name: string) => reportsRes.fields.find((f) => f.name === name);
|
||||||
const groupLabel = find("group_label");
|
const name = find("name");
|
||||||
const granularity = find("granularity");
|
|
||||||
const periodLabel = find("period_label");
|
|
||||||
const payee = find("payee");
|
|
||||||
const entityCount = find("entity_count");
|
|
||||||
const generatedAt = find("generated_at");
|
const generatedAt = find("generated_at");
|
||||||
if (!groupLabel || !granularity || !periodLabel || !payee || !entityCount || !generatedAt) return null;
|
if (!name || !generatedAt) return null;
|
||||||
return { groupLabel, granularity, periodLabel, payee, entityCount, generatedAt };
|
return { name, generatedAt };
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user