Group strip is now Sum/Avg/Min/Max/Cadence-Frequency; count already shown in the accordion header, per-month rate derivable from monthly buckets.
346 lines
12 KiB
TypeScript
346 lines
12 KiB
TypeScript
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 type { ListPeriodGroup } from "../common/utils/transactions";
|
|
import { buildPeriodGroups, sliceSummary, 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 periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]);
|
|
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]);
|
|
const listGroups = useMemo<ListPeriodGroup[]>(
|
|
() =>
|
|
periodGroups.map((g) => ({
|
|
key: g.key,
|
|
label: g.key,
|
|
items: g.txns,
|
|
spent: g.metrics.outflows,
|
|
income: g.metrics.inflows,
|
|
currency: g.currency,
|
|
metrics: {
|
|
sum: g.metrics.sum,
|
|
count: g.metrics.count,
|
|
avg: g.metrics.avg,
|
|
min: g.metrics.min,
|
|
max: g.metrics.max,
|
|
cadence: g.metrics.cadence,
|
|
frequency: g.metrics.frequency,
|
|
},
|
|
})),
|
|
[periodGroups],
|
|
);
|
|
|
|
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 = periodGroups.reduce((m, g) => Math.max(m, g.metrics.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.outflows, slice.currency)} color="error.main" />
|
|
<StatCard label="Inflows" value={formatCurrency(slice.inflows, slice.currency)} color="success.main" />
|
|
<StatCard label="Net" value={formatCurrency(slice.inflows - slice.outflows, slice.currency)} color="info.main" />
|
|
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
|
</Box>
|
|
|
|
{periodGroups.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 }}>
|
|
{periodGroups.map((g) => (
|
|
<Box key={g.key} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
|
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
|
{g.key}
|
|
</Typography>
|
|
<Box
|
|
sx={{
|
|
height: 20,
|
|
borderRadius: 1,
|
|
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
|
opacity: 0.85,
|
|
minWidth: 4,
|
|
}}
|
|
style={{ width: `${maxBar ? Math.max((g.metrics.sum / maxBar) * 100, 2) : 2}%` }}
|
|
/>
|
|
<Typography variant="body2" fontWeight={600}>
|
|
{formatCurrency(g.metrics.sum, slice.currency)}
|
|
</Typography>
|
|
<Typography variant="caption" color="text.disabled">
|
|
{g.metrics.count} txn{g.metrics.count === 1 ? "" : "s"}
|
|
</Typography>
|
|
</Box>
|
|
))}
|
|
</Paper>
|
|
)}
|
|
|
|
{slice.txns.length === 0 ? null : fields ? (
|
|
<TransactionList fields={fields} groups={listGroups} showMetrics />
|
|
) : null}
|
|
</Box>
|
|
</Paper>
|
|
);
|
|
} |