3 Commits

Author SHA1 Message Date
a107029b90 feat: group transactions by date inside month accordions
Add two-layer grouping to the shared transaction list: each month
accordion now renders one card per occurred_at date (most recent first)
with a date label and txn count header, nesting the usual transaction
rows inside. Add dateLabel + groupByDate helpers to src/common and use
them in TransactionList. Month accordions, scroll pill/menu, and month
totals are unchanged.
2026-08-20 14:14:44 +05:30
baa9b296cb refactor: extract shared expense/report module into src/common
Collapse the Expenses page into a single src/Expense.tsx file and rename
the Reports page to src/Reports/Report.tsx, extracting their shared
transaction-list UI, date/grouping helpers, field configs, and types
into an expense/report-agnostic src/common module. Update ReportViewer
and GenerateReportPanel to consume the shared components, rewire
main.jsx imports, and remove the old src/Expense/ folder and
src/Reports/Reports.tsx.
2026-08-20 13:29:44 +05:30
f08bc72037 reports page: spec-driven generate panel, list, and sliceable viewer
Add a /reports page built on react-openapi's runtime configs:
- inline generate panel (GroupSpec enum, prefetched payee picker,
  strict DD-MM-YYYY range, 400 surfacing)
- metadata report list with view/regenerate/delete
- viewer that slices the cached per-entity payload via
  metadata.group_options, aggregates metrics + txns, pivots
  period x payee, and renders month accordions
- route + nav entry; no hand-rolled schema duplication
2026-08-19 22:00:14 +05:30
29 changed files with 696 additions and 1546 deletions

1
.gitignore vendored
View File

@@ -14,4 +14,3 @@ dist
dist-ssr
*.local
.idea
tsconfig.tsbuildinfo

View File

@@ -5,18 +5,12 @@ export { useAppContext } from "./src/context/AppContext";
export { useResource } from "./src/context/useResource";
export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields";
export { FormFieldRenderer } from "./src/components/fields/FormFieldRenderer";
export { MultiEnumField } from "./src/components/fields/renderers/MultiEnumField";
export { extractFields } from "./src/transformers/field-config";
export { useFkFieldOptions } from "./src/hooks/useFkFieldOptions";
export type { FkOption } from "./src/hooks/useFkFieldOptions";
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";
export { useItemSse } from "./src/hooks/useItemSse";
export { sanitizePayload } from "./src/utils/sanitize-payload";
export type { FkResolver } from "./src/utils/sanitize-payload";
export { formatDate, formatDateTime } from "./src/utils/datetime";
export type { FilterComponentProps } from "./src/context/useResource";
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship, ProfileOperation, ProfileComponents, AuthConfig } from "./src/types";

View File

@@ -6,7 +6,6 @@ import { NumberField } from "./renderers/NumberField";
import { DateField } from "./renderers/DateField";
import { BooleanField } from "./renderers/BooleanField";
import { EnumField } from "./renderers/EnumField";
import { MultiEnumField } from "./renderers/MultiEnumField";
import { FkSelectField } from "./renderers/FkSelectField";
import { FkMultiSelectField } from "./renderers/FkMultiSelectField";
import { FileUploadField } from "./renderers/FileUploadField";
@@ -82,17 +81,6 @@ export function FormFieldRenderer({ field, value, onChange, error, fkOptions, fk
);
}
if (field.isArray && field.enumValues) {
return (
<MultiEnumField
field={field}
value={value}
onChange={onChange}
error={error}
/>
);
}
if (field.enumValues) {
return (
<EnumField

View File

@@ -3,7 +3,6 @@ import { useNavigate } from "react-router-dom";
import { Box, Typography, Chip, Avatar, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
import type { FieldConfig } from "../../types";
import { applyDisplayFormat, resolveMediaUrl } from "./utils";
import { formatByFieldFormat } from "../../utils/datetime";
import { InlineRefField } from "./renderers/InlineRefField";
import { CurrencyField } from "./renderers/CurrencyField";
import { extractFields } from "../../transformers/field-config";
@@ -58,7 +57,7 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
{sf.label}
</Typography>
<Typography variant="body2">
{fv == null ? "—" : typeof fv === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(fv, sf.inlineDisplayFormat) : JSON.stringify(fv)) : formatByFieldFormat(fv, sf.format)}
{fv == null ? "—" : typeof fv === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(fv, sf.inlineDisplayFormat) : JSON.stringify(fv)) : String(fv)}
</Typography>
</Box>
</Grid>
@@ -154,5 +153,5 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
return <Typography variant="body2">{applyDisplayFormat(value, displayFormat ?? "")}</Typography>;
}
return <Typography variant="body2">{formatByFieldFormat(value, field.format)}</Typography>;
return <Typography variant="body2">{String(value)}</Typography>;
}

View File

@@ -3,5 +3,4 @@ export { ListCellRenderer } from "./ListCellRenderer";
export { DetailFieldRenderer } from "./DetailFieldRenderer";
export { applyDisplayFormat } from "./utils";
export { JsonField } from "./renderers/JsonField";
export { MultiEnumField } from "./renderers/MultiEnumField";
export { CurrencyField, formatCurrency } from "./renderers/CurrencyField";

View File

@@ -10,26 +10,11 @@ interface Props {
}
export function DateField({ field, value, onChange, error }: Props) {
// `x-edit-as: date` renders a date-time field as a plain date picker;
// the picked day is submitted as midnight so the stored type is intact.
const editAsDate = field.format === "date" || field.editAs === "date";
const inputType = field.format === "date" ? "date" : "datetime-local";
const inputType = editAsDate ? "date" : "datetime-local";
const normalized = (() => {
if (field.format !== "date-time" || typeof value !== "string") return value;
if (editAsDate) return value.slice(0, 10);
return value.replace(/\.\d+Z$/, "").replace(/Z$/, "");
})();
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const v = e.target.value;
if (editAsDate && field.format === "date-time" && /^\d{4}-\d{2}-\d{2}$/.test(v)) {
onChange(`${v}T00:00:00`);
} else {
onChange(v);
}
};
const normalized = field.format === "date-time" && typeof value === "string"
? value.replace(/\.\d+Z$/, "").replace(/Z$/, "")
: value;
return (
<TextField
@@ -37,7 +22,7 @@ export function DateField({ field, value, onChange, error }: Props) {
label={field.label}
type={inputType}
value={normalized ?? ""}
onChange={handleChange}
onChange={(e) => onChange(e.target.value)}
error={!!error}
helperText={error || field.description || undefined}
placeholder={field.description || undefined}

View File

@@ -2,7 +2,6 @@ import React, { useState } from "react";
import { Box, Typography, Chip, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
import type { FieldConfig } from "../../../types";
import { applyDisplayFormat } from "../utils";
import { formatByFieldFormat } from "../../../utils/datetime";
import { extractFields } from "../../../transformers/field-config";
import { useAppContext } from "../../../context/AppContext";
@@ -69,7 +68,7 @@ export function InlineRefField({ field, value }: Props) {
<Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ mb: 0.25, display: "block" }}>
{sf.label}
</Typography>
<Typography variant="body2">{value?.[sf.name] == null ? "—" : typeof value[sf.name] === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(value[sf.name], sf.inlineDisplayFormat) : JSON.stringify(value[sf.name])) : formatByFieldFormat(value[sf.name], sf.format)}</Typography>
<Typography variant="body2">{value?.[sf.name] == null ? "—" : typeof value[sf.name] === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(value[sf.name], sf.inlineDisplayFormat) : JSON.stringify(value[sf.name])) : String(value[sf.name])}</Typography>
</Box>
</Grid>
))}

View File

@@ -1,59 +0,0 @@
import React from "react";
import { Autocomplete, TextField, Chip, Box } from "@mui/material";
import DoneIcon from "@mui/icons-material/Done";
import type { FieldConfig } from "../../../types";
interface Props {
field: FieldConfig;
value: any;
onChange: (value: any[]) => void;
error?: string;
}
export function MultiEnumField({ field, value, onChange, error }: Props) {
const selected: string[] = Array.isArray(value) ? value : [];
return (
<Autocomplete
multiple
disableCloseOnSelect
size="small"
options={field.enumValues ?? []}
value={selected}
onChange={(_, newVal) => onChange(newVal)}
renderOption={(props, option, { selected: isSelected }) => {
const { key, ...rest } = props as any;
return (
<li key={key} {...rest}>
{isSelected ? (
<DoneIcon sx={{ fontSize: 14, mr: 1, color: "primary.main" }} />
) : (
<Box sx={{ width: 22, mr: 1 }} />
)}
{option}
</li>
);
}}
renderTags={(tagValue, getTagProps) =>
tagValue.map((tag, index) => {
const { key, ...tagProps } = getTagProps({ index });
return <Chip key={key} {...tagProps} label={tag} size="small" />;
})
}
renderInput={(params) => (
<TextField
{...params}
label={field.label}
placeholder={field.description || undefined}
error={!!error}
helperText={error || field.description || undefined}
size="small"
/>
)}
sx={{
"& .MuiAutocomplete-popupIndicator, & .MuiAutocomplete-clearIndicator": { width: 20, height: 20, fontSize: 16 },
}}
disabled={field.readOnly}
/>
);
}

View File

@@ -1,5 +1,3 @@
import { formatIsoLike } from "../../utils/datetime";
function getNested(obj: any, path: string): any {
return path.split(".").reduce((o, k) => o?.[k], obj);
}
@@ -8,7 +6,7 @@ export function applyDisplayFormat(item: any, format: string): string {
if (!item || typeof item !== "object") return String(item ?? "");
return format.replace(/\{([\w.]+)\}/g, (_, key) => {
const val = getNested(item, key);
return val != null ? formatIsoLike(val) : "";
return val != null ? String(val) : "";
});
}

View File

@@ -3,24 +3,6 @@ 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;
@@ -32,7 +14,6 @@ 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) => {

View File

@@ -1,82 +0,0 @@
import { useCallback, useEffect, useState } from "react";
import type { FieldConfig, FKFieldConfig } from "../types";
import { useAppContext } from "../context/AppContext";
import { getApi } from "./useApi";
export interface FkOption {
value: any;
label: string;
}
function applyFormat(obj: any, format: string): string {
if (!obj || typeof obj !== "object") return String(obj ?? "");
return format.replace(/\{(\w+)\}/g, (_, key) => String(obj[key] ?? ""));
}
/**
* Loads select options for FK-annotated fields of a field set.
* Option values bind to `fk.value` when set (e.g. account names),
* otherwise to the target resource's primary key.
*/
export function useFkFieldOptions(fields: FieldConfig[]) {
const { resources } = useAppContext();
const [fkOptions, setFkOptions] = useState<Record<string, FkOption[]>>({});
const [fkLoading, setFkLoading] = useState<Record<string, boolean>>({});
const loadFkOptions = useCallback(
async (fieldName: string, fk: FKFieldConfig) => {
setFkLoading((prev) => ({ ...prev, [fieldName]: true }));
try {
const targetRes = resources.find((r) => r.name === fk.resource);
if (!targetRes) return;
const api = getApi();
const params: Record<string, any> = {};
if (targetRes.pagination) params.limit = 0;
const res = await api.get(targetRes.path, { params });
let items: any[];
if (targetRes.pagination) {
if (!res.data || typeof res.data !== "object" || !Array.isArray(res.data.items)) {
throw new Error(`Expected paginated response from ${targetRes.path}`);
}
items = res.data.items;
} else {
if (!Array.isArray(res.data)) {
throw new Error(`Expected array response from ${targetRes.path}`);
}
items = res.data;
}
const opts: FkOption[] = items.map((item: any) => ({
value: item[fk.value ?? targetRes.primaryKey],
label: applyFormat(item, targetRes.displayFormat),
}));
setFkOptions((prev) => ({ ...prev, [fieldName]: opts }));
} catch {
// leave options empty; the field renders without suggestions
} finally {
setFkLoading((prev) => ({ ...prev, [fieldName]: false }));
}
},
[resources]
);
useEffect(() => {
fields.forEach((f) => {
if (f.fk?.prefetch) loadFkOptions(f.name, f.fk);
});
}, [fields, loadFkOptions]);
const loadFkOnOpen = useCallback(
(fieldName: string) => {
const field = fields.find((f) => f.name === fieldName);
if (field?.fk && !field.fk.prefetch && !fkOptions[fieldName]) {
loadFkOptions(fieldName, field.fk);
}
},
[fields, fkOptions, loadFkOptions]
);
return { fkOptions, fkLoading, loadFkOnOpen };
}

View File

@@ -64,7 +64,6 @@ function extractOneOfOptions(schema: any, schemas: Record<string, any>, discrimi
description: prop["x-description"] ?? "",
type: prop.type ?? "string",
format: prop.format,
editAs: prop["x-edit-as"],
order: prop["x-order"] ?? Infinity,
hidden: prop["x-hidden"] ?? {},
filterable: prop["x-filterable"] ?? false,
@@ -131,17 +130,13 @@ export function extractFields(schemaName: string, schema: any, schemas: Record<s
description: prop["x-description"] ?? "",
type: isRef && refSchema ? "object" : isOneOf ? "object" : (prop.type ?? "string"),
format: prop.format,
editAs: prop["x-edit-as"],
order: prop["x-order"] ?? Infinity,
hidden: prop["x-hidden"] ?? {},
filterable: prop["x-filterable"] ?? false,
sortable: prop["x-sortable"] ?? false,
readOnly: prop.readOnly ?? false,
required: requiredFields.includes(name),
// Lift enum constraints from array items so arrays-of-enum can render
// as multi-selects (e.g. ReportQuery.granularities).
enumValues: prop.enum ?? (prop.type === "array" ? prop.items?.enum : undefined),
defaultValue: prop.default,
enumValues: prop.enum,
fk: prop["x-fk"],
uiType: prop["x-ui-type"],
uploadUrl: prop["x-upload-url"],

View File

@@ -85,8 +85,6 @@ export interface ResourceConfig {
export interface FKFieldConfig {
resource: string;
prefetch: boolean;
/** Target property used as the wire value (defaults to the target's primary key). */
value?: string;
}
export interface OneOfOption {
@@ -101,8 +99,6 @@ export interface FieldConfig {
description: string;
type: string;
format?: string;
/** `x-edit-as: date` — edit a `date-time` field with a plain date input; submits midnight. */
editAs?: string;
order: number;
hidden: { form?: boolean; list?: boolean; detail?: boolean };
filterable: boolean;
@@ -110,8 +106,6 @@ export interface FieldConfig {
readOnly: boolean;
required: boolean;
enumValues?: string[];
/** Schema-level `default` used to seed create-form state. */
defaultValue?: any;
fk?: FKFieldConfig;
uiType?: string;
uploadUrl?: string;

View File

@@ -1,63 +0,0 @@
/**
* Zero-dependency date/time display helpers.
*
* Only ISO-shaped strings ("2026-08-24", "2026-08-24T09:07:25[.f][Z]") are
* reformatted; anything else (DD-MM-YYYY expense strings, free text) passes
* through untouched. Naive strings without a zone are parsed as clock time
* so the displayed wall time matches what the backend stored.
*/
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
function parseIso(value: any): Date | null {
if (typeof value !== "string") return null;
if (!ISO_DATE.test(value) && !ISO_DATETIME.test(value)) return null;
const d = new Date(value);
return isNaN(d.getTime()) ? null : d;
}
const DATE_FMT = new Intl.DateTimeFormat("en-IN", { day: "numeric", month: "short", year: "numeric" });
const DATETIME_FMT = new Intl.DateTimeFormat("en-IN", {
day: "numeric",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
function fallback(value: any): string {
return typeof value === "string" ? value : value != null ? String(value) : "";
}
/** "2026-08-24" -> "24 Aug 2026"; non-ISO values pass through. */
export function formatDate(value: any): string {
const d = parseIso(value);
return d ? DATE_FMT.format(d) : fallback(value);
}
/** "2026-08-24T09:07:25" -> "24 Aug 2026, 09:07"; non-ISO values pass through. */
export function formatDateTime(value: any): string {
const d = parseIso(value);
return d ? DATETIME_FMT.format(d) : fallback(value);
}
/** Route by OpenAPI field format ("date" | "date-time"); other formats render plainly. */
export function formatByFieldFormat(value: any, format?: string): string {
if (format === "date") return formatDate(value);
if (format === "date-time") return formatDateTime(value);
return fallback(value);
}
/**
* Metadata-free variant for display-format templates ({key} interpolation):
* reformats a scalar only when it happens to be ISO-shaped.
*/
export function formatIsoLike(value: any): string {
if (typeof value === "string") {
if (ISO_DATETIME.test(value)) return formatDateTime(value);
if (ISO_DATE.test(value)) return formatDate(value);
}
return fallback(value);
}

View File

@@ -29,9 +29,7 @@ export async function sanitizePayload(
const val = result[key];
// FK fields whose wire value is a plain target property (fk.value, e.g.
// account names) are already in wire format — no id→object resolution.
if (field.fk && !field.fk.value) {
if (field.fk) {
if (val == null || val === "") {
result[key] = null;
} else if (resolveFk) {

View File

@@ -110,12 +110,12 @@ export default function Expense() {
<>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
<StatCard
label="Outflows"
label="Total spent"
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="Inflows" value={formatCurrency(summary.totalIncome, summary.currency)} />
<StatCard label="Income" value={formatCurrency(summary.totalIncome, summary.currency)} />
</Box>
{fieldConfigs && <TransactionList items={sorted} fields={fieldConfigs} />}

View File

@@ -1,60 +1,22 @@
import React, { useEffect, useMemo, useState } from "react";
import {
Box, Container, Typography, Paper, Button, Alert,
CircularProgress, IconButton, Tooltip,
CircularProgress,
} from "@mui/material";
import { useNavigate } from "react-router-dom";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { alpha } from "@mui/material/styles";
import { useAppContext, useResource, ListCellRenderer, FormFieldRenderer, getApi, applyDisplayFormat } from "../../react-openapi";
import type { FieldConfig } from "../../react-openapi";
import { PageHeader } from "../ui/PageHeader";
import { EmptyState } from "../ui/EmptyState";
import { formatApiError } from "../features/fetch-requests";
import { useToast } from "../ui/Toast";
const CREATE_FIELDS = ["account", "bank", "pipeline", "trust_fallback", "start_date", "end_date", "source"];
// Two-pane form partition — explicit names, spec order is unreliable.
// Grid stretch keeps both panes equal-height regardless of which source
// variant is active (email adds From/Subject under the type select).
const SOURCE_PANE_FIELDS = ["account", "bank"];
const POLICY_PANE_FIELDS = ["start_date", "end_date", "pipeline", "trust_fallback"];
const glassSx = (theme: any) => ({
backgroundColor: alpha(theme.palette.background.default, 0.72),
backdropFilter: "blur(8px)",
borderColor: "divider",
boxShadow: 1,
});
function GlassPanel({ title, children }: { title: string; children: React.ReactNode }) {
return (
<Paper variant="outlined" sx={(theme) => ({ p: 3, borderRadius: 3, ...glassSx(theme) })}>
<Typography
variant="overline"
sx={{ display: "block", mb: 2, color: "text.secondary", letterSpacing: 1.2, lineHeight: 1.4 }}
>
{title}
</Typography>
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>{children}</Box>
</Paper>
);
}
const CREATE_FIELDS = ["account", "bank", "pipeline", "start_date", "end_date", "source"];
function FetchRequestList() {
const navigate = useNavigate();
const { list, remove, resource } = useResource("fetch-requests");
const { list, resource } = useResource("fetch-requests");
const { resources: allResources } = useAppContext();
const [rows, setRows] = useState<any[] | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
const { showToast } = useToast();
const reload = () => {
if (!resource) return;
list({ limit: 20 }).then((res) => setRows(res.items ?? []));
};
const columns = useMemo(() => {
if (!resource) return [];
@@ -68,26 +30,6 @@ function FetchRequestList() {
list({ limit: 20 }).then((res) => setRows(res.items ?? []));
}, [resource?.name]);
const handleDelete = async (e: React.MouseEvent, id: string) => {
e.stopPropagation();
if (
!window.confirm(
"Delete this fetch request along with all its expenses and ambiguities? This cannot be undone.",
)
)
return;
setDeletingId(id);
try {
await remove(id);
showToast("Fetch request deleted");
reload();
} catch (err: any) {
showToast(formatApiError(err), "error");
} finally {
setDeletingId(null);
}
};
if (!rows) {
return (
<Box sx={{ display: "flex", justifyContent: "center", py: 6 }}>
@@ -116,63 +58,30 @@ function FetchRequestList() {
<Paper
key={row.id ?? i}
variant="outlined"
sx={(theme) => ({
sx={{
p: 2,
cursor: "pointer",
borderRadius: 3,
transition: "border-color 160ms ease, box-shadow 160ms ease, background-color 160ms ease",
"&:hover": {
borderColor: "primary.main",
boxShadow: 1,
backgroundColor: alpha(theme.palette.background.default, 0.9),
},
...glassSx(theme),
})}
borderRadius: 2,
transition: "border-color 160ms ease, box-shadow 160ms ease",
"&:hover": { borderColor: "primary.main", boxShadow: 1 },
}}
onClick={() => navigate(`/fetch-requests/${row.id}`)}
>
<Box sx={{ display: "flex", gap: 2, alignItems: "center" }}>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center", flex: 1, minWidth: 0 }}>
{columns
.filter((col) => col.name !== "created_at")
.map((col) => (
<Box key={col.name} sx={{ minWidth: 120 }}>
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
{col.label}
</Typography>
<ListCellRenderer
field={col}
value={row[col.name]}
displayFormat={col.fk
? (allResources.find((r) => r.name === col.fk!.resource)?.displayFormat ?? displayFormat)
: displayFormat}
/>
</Box>
))}
</Box>
{(() => {
const dateCol = columns.find((col) => col.name === "created_at");
if (!dateCol) return null;
return (
<Box sx={{ flexShrink: 0, textAlign: "right" }}>
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
{dateCol.label}
</Typography>
<ListCellRenderer field={dateCol} value={row.created_at} displayFormat={displayFormat} />
</Box>
);
})()}
<Box sx={{ flexShrink: 0 }}>
<Tooltip title="Delete fetch request">
<IconButton
size="small"
color="error"
disabled={deletingId === row.id || row.status === "processing"}
onClick={(e) => handleDelete(e, row.id)}
>
<DeleteOutlineIcon fontSize="small" />
</IconButton>
</Tooltip>
</Box>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center" }}>
{columns.map((col) => (
<Box key={col.name} sx={{ minWidth: 120 }}>
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
{col.label}
</Typography>
<ListCellRenderer
field={col}
value={row[col.name]}
displayFormat={col.fk
? (allResources.find((r) => r.name === col.fk!.resource)?.displayFormat ?? displayFormat)
: displayFormat}
/>
</Box>
))}
</Box>
</Paper>
);
@@ -185,7 +94,6 @@ export default function FetchRequestCreate() {
const { resources: allResources } = useAppContext();
const resource = useMemo(() => allResources.find((r) => r.name === "fetch-requests"), [allResources]);
const { create } = useResource("fetch-requests");
const navigate = useNavigate();
const [formData, setFormData] = useState<Record<string, any>>({});
const [fkOptions, setFkOptions] = useState<Record<string, { value: any; label: string }[]>>({});
const [loading, setLoading] = useState(false);
@@ -235,10 +143,6 @@ export default function FetchRequestCreate() {
const display = applyDisplayFormat(created, resource!.displayFormat);
setResult({ severity: "success", message: `Created: ${display}` });
setFormData({});
const newId = (created as any)?.id;
if (newId) {
navigate(`/fetch-requests/${newId}`);
}
} catch (e: any) {
const detail = e?.response?.data?.detail;
const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join("; ") : (detail ?? e?.message ?? "Unknown error");
@@ -256,90 +160,59 @@ export default function FetchRequestCreate() {
);
}
const renderPaneFields = (names: string[]) =>
names.map((name) => {
const field = formFields.find((f) => f.name === name);
if (!field) return null;
return (
<FormFieldRenderer
key={field.name}
field={field}
value={formData[field.name] ?? ""}
onChange={(val) => handleChange(field.name, val)}
fkOptions={fkOptions[field.name]}
/>
);
});
return (
<Box sx={{ position: "relative" }}>
{/* Decorative gradient backdrop — gives the frosted panes something to blur. */}
<Box
aria-hidden
sx={{
position: "fixed",
inset: 0,
zIndex: 0,
pointerEvents: "none",
background: (theme) =>
[
`radial-gradient(640px circle at 12% 8%, ${alpha(theme.palette.primary.main, 0.14)}, transparent 70%)`,
`radial-gradient(900px circle at 88% 92%, ${alpha(theme.palette.primary.main, 0.09)}, transparent 70%)`,
`radial-gradient(520px circle at 78% 22%, ${alpha(theme.palette.primary.light, 0.07)}, transparent 70%)`,
].join(", "),
}}
<Container maxWidth="lg" sx={{ py: 4 }}>
<PageHeader
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests" }]}
title="Fetch Requests"
subtitle="Import transactions from bank statements or email and track pipeline progress."
/>
<Container maxWidth="lg" sx={{ py: 4, position: "relative", zIndex: 1 }}>
<PageHeader
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests" }]}
title="Fetch Requests"
subtitle="Import transactions from bank statements or email and track pipeline progress."
/>
<Box id="new-fetch-request" sx={{ mb: 4 }}>
<Typography variant="subtitle1" fontWeight={700} gutterBottom>
New Fetch Request
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2.5, maxWidth: 560, lineHeight: 1.6 }}>
Choose an account, pipeline, and a file or email source to kick off an import.
</Typography>
<Paper
id="new-fetch-request"
variant="outlined"
sx={{ p: 3, mb: 4, borderRadius: 3 }}
>
<Typography variant="subtitle1" fontWeight={700} gutterBottom>
New Fetch Request
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3, maxWidth: 520, lineHeight: 1.6 }}>
Choose an account, pipeline, and a file or email source to kick off an import.
</Typography>
<Box
sx={{
display: "grid",
gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
gap: 2,
}}
>
<GlassPanel title="Source & Account">
{renderPaneFields(SOURCE_PANE_FIELDS)}
{renderPaneFields(["source"])}
</GlassPanel>
<GlassPanel title="Window & Policy">{renderPaneFields(POLICY_PANE_FIELDS)}</GlassPanel>
</Box>
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, gap: 1.5 }}>
<Button variant="outlined" onClick={() => { setFormData({}); setResult(null); }}>
Reset
</Button>
<Button variant="contained" onClick={handleSubmit} disabled={loading} sx={{ minWidth: 180 }}>
{loading ? <CircularProgress size={20} sx={{ mr: 0.5 }} /> : null}
Create Fetch Request
</Button>
</Box>
{result && (
<Alert severity={result.severity} sx={{ mt: 2 }} onClose={() => setResult(null)}>
{result.message}
</Alert>
)}
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, maxWidth: 520 }}>
{formFields.map((field) => (
<FormFieldRenderer
key={field.name}
field={field}
value={formData[field.name] ?? ""}
onChange={(val) => handleChange(field.name, val)}
fkOptions={fkOptions[field.name]}
/>
))}
</Box>
<Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}>
Recent Fetch Requests
</Typography>
<FetchRequestList />
</Container>
</Box>
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, gap: 1.5 }}>
<Button variant="outlined" onClick={() => { setFormData({}); setResult(null); }}>
Reset
</Button>
<Button variant="contained" onClick={handleSubmit} disabled={loading} sx={{ minWidth: 180 }}>
{loading ? <CircularProgress size={20} sx={{ mr: 0.5 }} /> : null}
Create Fetch Request
</Button>
</Box>
{result && (
<Alert severity={result.severity} sx={{ mt: 2 }} onClose={() => setResult(null)}>
{result.message}
</Alert>
)}
</Paper>
<Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}>
Recent Fetch Requests
</Typography>
<FetchRequestList />
</Container>
);
}

View File

@@ -10,7 +10,6 @@ import {
CircularProgress,
Alert,
Divider,
Tooltip,
} from "@mui/material";
import ReplayIcon from "@mui/icons-material/Replay";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
@@ -19,7 +18,6 @@ import WarningAmberIcon from "@mui/icons-material/WarningAmber";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { useResource, useItemSse, useAppContext, DetailFieldRenderer, applyDisplayFormat } from "../../react-openapi";
import { useQuery } from "@tanstack/react-query";
import { RETRY_MAX, formatApiError } from "../features/fetch-requests";
@@ -87,12 +85,11 @@ function Section({ title, children, action }: { title: string; children: React.R
export default function FetchRequestDetail() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { get, patch, remove, resource } = useResource("fetch-requests");
const { get, patch, resource } = useResource("fetch-requests");
const { resources: allResources } = useAppContext();
const [stepStats, setStepStats] = useState<Record<string, number>>({});
const [liveParsedCount, setLiveParsedCount] = useState<number | undefined>(undefined);
const [retrying, setRetrying] = useState(false);
const [deleting, setDeleting] = useState(false);
const { showToast } = useToast();
const feedRef = useRef<HTMLDivElement>(null);
@@ -177,26 +174,6 @@ export default function FetchRequestDetail() {
}
};
const handleDelete = async () => {
if (!id || !remove || deleting) return;
if (
!window.confirm(
"Delete this fetch request along with all its expenses and ambiguities? This cannot be undone.",
)
)
return;
setDeleting(true);
try {
await remove(id);
showToast("Fetch request deleted");
navigate("/fetch-requests");
} catch (err: any) {
showToast(formatApiError(err), "error");
} finally {
setDeleting(false);
}
};
const req = fetchRequest as any;
const retryCount = req?.retry_count ?? 0;
const isRetryExhausted = retryCount >= RETRY_MAX;
@@ -309,20 +286,6 @@ export default function FetchRequestDetail() {
Retry
</Button>
)}
<Tooltip title={status === "processing" ? "Cannot delete while processing" : "Delete fetch request"}>
<span>
<Button
variant="outlined"
size="small"
color="error"
startIcon={<DeleteOutlineIcon />}
onClick={handleDelete}
disabled={deleting || status === "processing"}
>
Delete
</Button>
</span>
</Tooltip>
</Box>
</Section>

View File

@@ -29,12 +29,7 @@ function computeProgressPercent(
let pct = 0;
if (
seenSteps.has("raw_lines") ||
seenSteps.has("txn_blocks")
) {
pct += 10;
}
if (seenSteps.has("raw_lines") || seenSteps.has("txn_blocks")) pct += 10;
if (txnBlockCount > 0) {
const current = Math.max(liveCount, stepStats.txn_dicts ?? 0);

View File

@@ -1,85 +1,114 @@
import React, { useCallback, useEffect, useMemo, useState } from "react";
import React, { useEffect, useMemo, useState } from "react";
import {
Box,
Paper,
Typography,
TextField,
Button,
Grid,
IconButton,
MenuItem,
Select,
FormControl,
InputLabel,
Autocomplete,
Alert,
} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import {
useResource,
useAppContext,
FormFieldRenderer,
extractFields,
useFkFieldOptions,
} from "../../react-openapi";
import type { FieldConfig } from "../../react-openapi";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
import { useToast } from "../ui/Toast";
import { apiErrorMessage } from "./types";
import { isDdmmyyyy } from "../common/utils/dates";
import { apiErrorMessage, groupTypeEnum, periodHints } from "./types";
interface GroupRow {
id: number;
group_type: string;
group_value: string;
}
interface GenerateReportPanelProps {
onGenerated: (report: any) => void;
onGenerated: (reports: any[]) => void;
}
export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
const { schemas } = useAppContext();
const { create, loading: submitting } = useResource("reports");
const { schemas, resources } = useAppContext();
const { create } = useResource("reports");
const { list: listEntities } = useResource("entities");
const { showToast } = useToast();
const [formData, setFormData] = useState<Record<string, any>>({});
const [rows, setRows] = useState<GroupRow[]>([{ id: 1, group_type: "monthly", group_value: "*" }]);
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [entityNames, setEntityNames] = useState<string[]>([]);
const [dateErrors, setDateErrors] = useState<{ start?: string; end?: string }>({});
const fields: FieldConfig[] = useMemo(() => {
const schema = schemas?.ReportQuery;
if (!schema) return [];
return extractFields("ReportQuery", schema, schemas).sort(
(a, b) => a.order - b.order || a.name.localeCompare(b.name)
);
}, [schemas]);
const { fkOptions, fkLoading, loadFkOnOpen } = useFkFieldOptions(fields);
const types = useMemo(() => groupTypeEnum(schemas), [schemas]);
const entitiesRes = resources.find((r) => r.name === "entities");
const entitiesFormat = entitiesRes?.displayFormat ?? "{name}";
useEffect(() => {
setFormData((prev) => {
const next = { ...prev };
let changed = false;
for (const f of fields) {
if (next[f.name] === undefined && f.defaultValue !== undefined) {
next[f.name] = Array.isArray(f.defaultValue) ? [...f.defaultValue] : f.defaultValue;
changed = true;
}
}
return changed ? next : prev;
let mounted = true;
listEntities({ limit: 0 }).then((res) => {
if (!mounted) return;
const names = (res.items ?? [])
.map((it: any) => applyDisplayFormat(it, entitiesFormat))
.filter((n: string) => n);
setEntityNames([...new Set(names)].sort((a, b) => a.localeCompare(b)));
});
}, [fields]);
return () => {
mounted = false;
};
}, [listEntities, entitiesFormat]);
const handleChange = useCallback((name: string, value: any) => {
setFormData((prev) => ({ ...prev, [name]: value }));
setError(null);
}, []);
const isPayee = (type: string) => type === "payee";
const buildPayload = (): Record<string, any> => {
const payload: Record<string, any> = {};
for (const f of fields) {
const v = formData[f.name];
if (v === undefined || v === null || v === "") continue;
if (Array.isArray(v) && v.length === 0) continue;
payload[f.name] = v;
}
return payload;
const valueOptions = (row: GroupRow): string[] => ["*", ...(isPayee(row.group_type) ? entityNames : [])];
const valueHint = (row: GroupRow): string =>
isPayee(row.group_type) ? "Entity name, or * for all payees" : `e.g. ${periodHints(row.group_type).join(", ")}, or *`;
const nextRowId = () => Math.max(0, ...rows.map((r) => r.id)) + 1;
const addRow = () => setRows((rs) => [...rs, { id: nextRowId(), group_type: "monthly", group_value: "*" }]);
const removeRow = (id: number) => setRows((rs) => rs.filter((r) => r.id !== id));
const updateRow = (id: number, patch: Partial<GroupRow>) =>
setRows((rs) => rs.map((r) => (r.id === id ? { ...r, ...patch } : r)));
const validateDates = (): boolean => {
const errs: { start?: string; end?: string } = {};
if (startDate && !isDdmmyyyy(startDate)) errs.start = "Use DD-MM-YYYY";
if (endDate && !isDdmmyyyy(endDate)) errs.end = "Use DD-MM-YYYY";
setDateErrors(errs);
return Object.keys(errs).length === 0;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const handleSubmit = async () => {
if (!validateDates()) return;
setError(null);
const groups = rows
.filter((r) => r.group_type && r.group_value.trim())
.map(({ group_type, group_value }) => ({ group_type, group_value: group_value.trim() }));
if (groups.length === 0) {
setError("At least one group is required");
return;
}
setSubmitting(true);
const payload: Record<string, any> = { groups };
if (startDate.trim()) payload.start_date = startDate.trim();
if (endDate.trim()) payload.end_date = endDate.trim();
try {
const created = await create(buildPayload());
showToast(`Generated snapshot ${created?.name ? `“${created.name}”` : ""}`.trim() || "Generated snapshot");
onGenerated(created);
const created = await create(payload);
const list = Array.isArray(created) ? created : created ? [created] : [];
showToast(`Generated ${list.length} report${list.length === 1 ? "" : "s"}`);
onGenerated(list);
} catch (e: any) {
setError(apiErrorMessage(e));
} finally {
setSubmitting(false);
}
};
@@ -89,8 +118,8 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
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.
Choose the dimensions to snapshot. At least one group is required — with no period dimension the server
snapshots weekly, monthly and quarterly.
</Typography>
{error && (
@@ -99,28 +128,84 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
</Alert>
)}
<Box component="form" onSubmit={handleSubmit}>
<Grid container spacing={2}>
{fields.map((field) => (
<Grid item xs={12} sm={6} md={4} key={field.name}>
<FormFieldRenderer
field={field}
value={formData[field.name]}
onChange={(val) => handleChange(field.name, val)}
fkOptions={fkOptions[field.name]}
fkLoading={fkLoading[field.name]}
onFkOpen={loadFkOnOpen}
/>
</Grid>
))}
</Grid>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
{rows.map((row) => (
<Box key={row.id} sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}>
<FormControl size="small" sx={{ width: 180, flexShrink: 0 }}>
<InputLabel id={`group-type-${row.id}`}>Type</InputLabel>
<Select
labelId={`group-type-${row.id}`}
label="Type"
value={row.group_type}
onChange={(e) => updateRow(row.id, { group_type: e.target.value, group_value: "*" })}
>
{types.map((t) => (
<MenuItem key={t} value={t}>
{t}
</MenuItem>
))}
</Select>
</FormControl>
<Autocomplete
freeSolo
size="small"
sx={{ flex: 1, minWidth: 240 }}
options={valueOptions(row)}
value={row.group_value}
onInputChange={(_, newVal) => updateRow(row.id, { group_value: newVal ?? "" })}
renderInput={(params) => (
<TextField {...params} label="Value" helperText={valueHint(row)} />
)}
/>
<IconButton
aria-label="Remove group"
disabled={rows.length === 1}
onClick={() => removeRow(row.id)}
sx={{ mt: 0.25 }}
>
<RemoveCircleOutlineIcon />
</IconButton>
</Box>
))}
</Box>
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
<Button type="submit" variant="contained" startIcon={<AddIcon />} disabled={submitting}>
{submitting ? "Generating…" : "Generate"}
</Button>
</Box>
<Button startIcon={<AddIcon />} size="small" sx={{ mt: 1 }} onClick={addRow}>
Add dimension
</Button>
<Box sx={{ display: "flex", gap: 1.5, mt: 2, flexWrap: "wrap" }}>
<TextField
size="small"
label="Start date"
placeholder="DD-MM-YYYY"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
error={Boolean(dateErrors.start)}
helperText={dateErrors.start ?? "Inclusive start (empty = unbounded)"}
sx={{ width: 200 }}
/>
<TextField
size="small"
label="End date"
placeholder="DD-MM-YYYY"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
error={Boolean(dateErrors.end)}
helperText={dateErrors.end ?? "Inclusive end (empty = unbounded)"}
sx={{ width: 200 }}
/>
</Box>
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
<Button
variant="contained"
startIcon={<AddIcon />}
onClick={handleSubmit}
disabled={submitting}
>
{submitting ? "Generating…" : "Generate"}
</Button>
</Box>
</Paper>
);
}
}

View File

@@ -1,17 +1,7 @@
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 { Container, Box, Paper, Typography, Alert } from "@mui/material";
import AssessmentIcon from "@mui/icons-material/Assessment";
import { useResource, useAppContext } from "../../react-openapi";
import { useResource, useAppContext, formatCurrency } from "../../react-openapi";
import { useToast } from "../ui/Toast";
import { PageHeader } from "../ui/PageHeader";
import { EmptyState } from "../ui/EmptyState";
@@ -45,19 +35,22 @@ export default function Report() {
}, [load]);
const handleGenerated = useCallback(
(created: any) => {
(created: any[]) => {
load();
if (created?.id) setSelectedId(created.id);
if (created?.[0]?.id) setSelectedId(created[0].id);
},
[load],
);
const handleRegenerate = useCallback(
async (report: any) => {
const payload: Record<string, any> = { groups: report.groups ?? [] };
if (report.start_date) payload.start_date = report.start_date;
if (report.end_date) payload.end_date = report.end_date;
try {
const created = await create(report.query ?? {});
await create(payload);
showToast("Report regenerated");
setSelectedId(created?.id ?? report.id);
setSelectedId(report.id);
setViewerVersion((v) => v + 1);
load();
} catch (e: any) {
@@ -83,9 +76,9 @@ export default function Report() {
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(", ") };
const txnCount = rows.reduce((s, r) => s + (r.txn_count ?? 0), 0);
const total = rows.reduce((s, r) => s + (typeof r.metrics?.sum === "number" ? r.metrics.sum : 0), 0);
return { count: rows.length, txnCount, total };
}, [reports]);
return (
@@ -93,7 +86,7 @@ export default function Report() {
<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."
subtitle="Generate period/payee snapshots from the reporting API and slice the cached data."
/>
{error && (
@@ -104,70 +97,37 @@ export default function Report() {
<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 || "—"} />
<StatCard label="Transactions covered" value={summary.txnCount.toLocaleString("en-IN")} />
<StatCard label="Total" value={formatCurrency(summary.total, "INR")} />
</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>
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em", mb: 1.5 }}>
Saved reports
</Typography>
{reports !== null && reports.length === 0 ? (
<Paper variant="outlined" sx={{ borderRadius: 3 }}>
<EmptyState
icon={<AssessmentIcon />}
title="No reports yet"
description="Generate your first report above — pick a granularity and payee (a payee-only or wildcard config snapshots weekly, monthly and quarterly)."
/>
</Paper>
) : (
<Box sx={{ display: "flex", flexDirection: "column", gap: 2.5, mb: 4 }}>
<ReportList
reports={reports ?? []}
loading={loading}
fields={reportFields}
selectedId={selectedId}
onView={(id) => setSelectedId(id)}
onRegenerate={handleRegenerate}
onDelete={handleDelete}
/>
</Box>
)}
{selectedId && (
<ReportViewer

View File

@@ -3,7 +3,7 @@ import { Box, Paper, Typography, Button, IconButton, Skeleton, Tooltip } from "@
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 { ListCellRenderer, formatCurrency } from "../../react-openapi";
import type { ReportFieldConfigs } from "./types";
interface ReportListProps {
@@ -30,14 +30,10 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
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 ?? "∞"}`
const sum = typeof report.metrics?.sum === "number" ? report.metrics.sum : null;
const range =
report.start_date || report.end_date
? `range ${report.start_date || "…"} → ${report.end_date || "…"}`
: null;
return (
<Paper
@@ -51,20 +47,23 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
"&:hover": { borderColor: "primary.light" },
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
<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}
{report.group_label}
</Typography>
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.25 }}>
{fields && (
<ListCellRenderer field={fields.granularity} value={report.granularity} />
)}
<Typography variant="caption" color="text.secondary">
{granularities}
{report.period_label}
</Typography>
<Typography variant="caption" color="text.disabled">
/
</Typography>
<Typography variant="caption" color="text.secondary">
{dims}
{report.payee}
</Typography>
{range && (
<Typography variant="caption" color="text.disabled">
@@ -74,21 +73,27 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
</Box>
<Box sx={{ display: "flex", gap: 1.5, mt: 0.5 }}>
<Typography variant="caption" color="text.secondary">
{accounts}
{report.entity_count ?? 0} entities
</Typography>
{amounts && (
<Typography variant="caption" color="text.secondary">
{amounts}
</Typography>
<Typography variant="caption" color="text.secondary">
{report.txn_count ?? 0} txns
</Typography>
<Typography variant="caption" color="text.secondary">
{report.expense_count ?? 0} expenses
</Typography>
{fields && (
<Box sx={{ color: "text.secondary" }}>
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
</Box>
)}
</Box>
</Box>
{fields && (
<Box sx={{ ml: "auto", flexShrink: 0, color: "text.secondary" }}>
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
</Box>
)}
<Box sx={{ flexShrink: 0, textAlign: "right" }}>
<Typography variant="body1" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
{sum != null ? formatCurrency(sum, "INR") : "—"}
</Typography>
</Box>
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>

View File

@@ -1,61 +1,28 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
import React, { useEffect, useMemo, useState } from "react";
import {
Box,
Paper,
Typography,
Button,
IconButton,
Alert,
Skeleton,
TextField,
Autocomplete,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import CachedIcon from "@mui/icons-material/Cached";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import { FkMultiSelectField, useResource, formatCurrency, formatDateTime } from "../../react-openapi";
import type { FieldConfig } from "../../react-openapi";
import { useAppContext, useResource, formatCurrency } from "../../react-openapi";
import { StatCard } from "../common/components/StatCard";
import { TransactionList } from "../common/components/TransactionList";
import type { TxnFieldConfigs } from "../common/types";
import type { ListPeriodGroup } from "../common/utils/transactions";
import { buildDimensionBars, buildPeriodGroups, sliceSummary, FLOW_OPTIONS, apiErrorMessage } from "./types";
import type { ReportDim } from "./types";
const MAX_VISIBLE_BARS = 10;
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,
};
import { aggregateSlice, buildPivot, metricLabels } from "./types";
interface ReportViewerProps {
id: string;
@@ -65,60 +32,31 @@ interface ReportViewerProps {
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 { schemas } = useAppContext();
const { get } = useResource("reports");
const [report, setReport] = useState<any | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reload, setReload] = useState(0);
const [granularity, setGranularity] = useState<string | null>(null);
const [flow, setFlow] = useState("outflows");
const [dim, setDim] = useState<ReportDim>("period");
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;
// The active breakdown dim requests every cube value ("*") when its own
// filter is unselected, so bars show the full distribution.
if (selectedPayees.length) p.payee = selectedPayees;
else if (dim === "payee") p.payee = ["*"];
if (selectedTags.length) p.tags = selectedTags;
else if (dim === "tag") p.tags = ["*"];
return p;
}, [granularity, flow, dim, selectedPeriods, selectedPayees, selectedTags]);
const [selectedPeriod, setSelectedPeriod] = useState("*");
const [selectedPayee, setSelectedPayee] = useState("*");
useEffect(() => {
let mounted = true;
setLoading(true);
setError(null);
const previous = prevGranularity.current;
get(id, params)
get(id)
.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;
setSelectedPeriod("*");
setSelectedPayee("*");
})
.catch((e: any) => {
if (!mounted) return;
setError(apiErrorMessage(e));
setError(e?.response?.data?.detail ?? e?.message ?? "Failed to load report");
})
.finally(() => {
if (mounted) setLoading(false);
@@ -126,86 +64,47 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
return () => {
mounted = false;
};
}, [id, version, reload, params, get, granularity]);
}, [id, version, reload, get]);
const granularityOptions = useMemo(() => snapshotGranularities(report), [report]);
const data = useMemo(() => (Array.isArray(report?.data) ? report.data : null), [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 groupOptions = useMemo(() => {
const options = report?.metadata?.group_options;
if (!options || typeof options !== "object") return { period: [], payee: [] };
return {
period: Array.isArray(options.period) ? options.period.map(String) : [],
payee: Array.isArray(options.payee) ? options.payee.map(String) : [],
};
}, [report]);
const slice = useMemo(
() => aggregateSlice(data ?? [], { period: selectedPeriod, payee: selectedPayee }),
[data, selectedPeriod, selectedPayee],
);
const filter = useMemo(
() => ({
granularity: granularity ?? granularityOptions[0] ?? "",
periods: selectedPeriods,
payees: selectedPayees,
tags: selectedTags,
}),
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
const pivot = useMemo(
() => buildPivot(data ?? [], groupOptions.period, groupOptions.payee),
[data, groupOptions],
);
const periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]);
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]);
const bars = useMemo(() => buildDimensionBars(report?.buckets ?? [], filter, dim), [report, filter, dim]);
const visibleBars = useMemo(() => bars.slice(0, MAX_VISIBLE_BARS), [bars]);
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],
);
const metrics = useMemo(() => {
const labels = metricLabels(schemas);
const displayKeys = ["sum", "count", "avg", "min", "max", "first_date", "last_date"];
return labels.filter((l) => displayKeys.includes(l.key));
}, [schemas]);
const barsListRef = useRef<HTMLDivElement>(null);
const [barScroll, setBarScroll] = useState({ canUp: false, canDown: false, overflow: false });
const metricValue = (key: string): string | null => {
if (key === "sum") return formatCurrency(slice.sum, slice.currency);
if (key === "count") return slice.count.toLocaleString("en-IN");
if (key === "avg") return slice.avg == null ? null : formatCurrency(slice.avg, slice.currency);
if (key === "min") return slice.min == null ? null : formatCurrency(slice.min, slice.currency);
if (key === "max") return slice.max == null ? null : formatCurrency(slice.max, slice.currency);
if (key === "first_date") return slice.firstDate;
if (key === "last_date") return slice.lastDate;
return null;
};
const updateBarScroll = useCallback(() => {
const el = barsListRef.current;
if (!el) return;
const overflow = el.scrollHeight > el.clientHeight + 2;
setBarScroll({
overflow,
canUp: overflow && el.scrollTop > 2,
canDown: overflow && el.scrollTop < el.scrollHeight - el.clientHeight - 2,
});
}, []);
useEffect(() => {
const el = barsListRef.current;
if (el) el.scrollTop = 0;
updateBarScroll();
}, [dim, visibleBars.length, updateBarScroll]);
const scrollBarsByPage = useCallback((dir: number) => {
const el = barsListRef.current;
if (!el) return;
el.scrollTo({ top: dir > 0 ? el.scrollHeight : 0, behavior: "smooth" });
}, []);
if (loading && !report) {
if (loading) {
return (
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
<Skeleton variant="text" width={220} height={28} />
@@ -230,22 +129,6 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
if (!report) return null;
const activeGranularity = granularity ?? report.granularities?.[0] ?? "";
const maxBar = bars.reduce((m, b) => Math.max(m, Math.abs(b.sum)), 0);
const dimOptions: { id: ReportDim; label: string; count: number }[] = [
{ id: "period", label: "Period", count: report.period_ids?.length ?? 0 },
{ id: "payee", label: "Payees", count: report.payees?.length ?? 0 },
{ id: "tag", label: "Tags", count: report.tags?.length ?? 0 },
];
const activeDimIndex = Math.max(
0,
dimOptions.findIndex((d) => d.id === dim),
);
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
@@ -262,241 +145,146 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
>
<Box sx={{ flex: 1, minWidth: 0 }}>
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
{report.name}
{report.group_label}
</Typography>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
<Typography variant="caption" color="text.secondary">
flow {report.flow} · generated {formatDateTime(report.generated_at ?? report.created_at)}
{report.granularity} · {report.period_label} · {report.payee}
</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
{report.entity_count ?? 0} entities · {report.txn_count ?? 0} txns · {report.expense_count ?? 0} expenses
</Typography>
{report.start_date || report.end_date ? (
<Typography variant="caption" color="text.disabled">
range {report.start_date || "…"} → {report.end_date || "…"}
</Typography>
) : null}
</Box>
</Box>
<IconButton aria-label="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>
{data === null ? (
<Box sx={{ p: 3 }}>
<Alert severity="info" sx={{ borderRadius: 2, mb: 2 }}>
The cached data for this report has expired. Regenerate it to rebuild the snapshot.
</Alert>
<Button variant="contained" startIcon={<CachedIcon />} onClick={() => onRegenerated(report)}>
Regenerate
</Button>
</Box>
<Box sx={{ 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 sx={{ p: 2.5 }}>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
<Autocomplete
size="small"
sx={{ width: 220 }}
options={["*", ...groupOptions.period]}
value={selectedPeriod}
onChange={(_, v) => setSelectedPeriod(v ?? "*")}
disabled={groupOptions.period.length === 0}
renderInput={(params) => <TextField {...params} label="Period" />}
/>
<Autocomplete
size="small"
sx={{ width: 220 }}
options={["*", ...groupOptions.payee]}
value={selectedPayee}
onChange={(_, v) => setSelectedPayee(v ?? "*")}
disabled={groupOptions.payee.length === 0}
renderInput={(params) => <TextField {...params} label="Payee" />}
/>
<Typography variant="body2" color="text.secondary" sx={{ alignSelf: "center" }}>
Showing {slice.count} transactions across {slice.txns.length} rows
</Typography>
</Box>
<Box sx={{ 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>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}>
<StatCard label="Spent" value={formatCurrency(slice.spent, slice.currency)} color="error.main" />
<StatCard label="Income" value={formatCurrency(slice.income, slice.currency)} color="success.main" />
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
</Box>
<Box sx={{ mb: 2.5 }}>
<Box
sx={{
position: "relative",
display: "flex",
alignItems: "stretch",
width: "fit-content",
maxWidth: "100%",
border: "1px solid",
borderColor: "divider",
borderRadius: "999px",
p: 0.5,
backgroundColor: "background.default",
}}
>
<Box
aria-hidden
sx={{
position: "absolute",
top: 4,
bottom: 4,
left: 4,
width: `calc((100% - 8px) / ${dimOptions.length})`,
borderRadius: "999px",
backgroundColor: "primary.main",
transform: `translateX(${activeDimIndex * 100}%)`,
transition: "transform 250ms cubic-bezier(0.4, 0, 0.2, 1)",
}}
/>
{dimOptions.map((d) => {
const active = d.id === dim;
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 3 }}>
{metrics.map((m) => {
const value = metricValue(m.key);
if (value == null) return null;
return (
<Box
key={d.id}
component="button"
type="button"
disabled={d.count <= 1}
onClick={() => setDim(d.id)}
sx={{
position: "relative",
zIndex: 1,
flex: 1,
border: "none",
background: "transparent",
px: 3,
py: 1,
borderRadius: "999px",
cursor: d.count <= 1 ? "default" : "pointer",
typography: "body2",
fontWeight: 700,
letterSpacing: "-0.01em",
color:
d.count <= 1
? "text.disabled"
: active
? "primary.contrastText"
: "text.secondary",
whiteSpace: "nowrap",
transition: "color 160ms ease",
"&:focus-visible": { outline: "2px solid", outlineColor: "primary.main" },
}}
>
{d.label}
</Box>
<Paper key={m.key} variant="outlined" sx={{ px: 1.5, py: 1, borderRadius: 2 }}>
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
{m.label}
</Typography>
<Typography variant="body2" fontWeight={600}>
{value}
</Typography>
</Paper>
);
})}
</Box>
{visibleBars.length === 0 ? (
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mt: 1.5 }}>
{selectedPeriod === "*" && selectedPayee === "*" && pivot.rows.length > 0 && (
<TableContainer
component={Paper}
variant="outlined"
sx={{ borderRadius: 2, mb: 3, overflowX: "auto" }}
>
<Table size="small">
<TableHead>
<TableRow>
<TableCell sx={{ fontWeight: 700 }}>Period</TableCell>
{pivot.payees.map((payee) => (
<TableCell key={payee} align="right" sx={{ fontWeight: 700 }}>
{payee}
</TableCell>
))}
<TableCell align="right" sx={{ fontWeight: 700 }}>
Total
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{pivot.rows.map((row) => (
<TableRow key={row.period} sx={{ "&:last-child td": { borderBottom: 0 } }}>
<TableCell sx={{ fontWeight: 600 }}>{row.period}</TableCell>
{row.cells.map((cell) => (
<TableCell key={cell.payee} align="right">
{cell.sum === 0 ? "—" : formatCurrency(cell.sum, slice.currency)}
</TableCell>
))}
<TableCell align="right" sx={{ fontWeight: 700 }}>
{formatCurrency(row.periodSum, slice.currency)}
</TableCell>
</TableRow>
))}
<TableRow>
<TableCell sx={{ fontWeight: 700 }}>Total</TableCell>
{pivot.totals.map((t) => (
<TableCell key={t.payee} align="right" sx={{ fontWeight: 700 }}>
{formatCurrency(t.sum, slice.currency)}
</TableCell>
))}
<TableCell align="right" sx={{ fontWeight: 700 }}>
{formatCurrency(pivot.rows.reduce((s, r) => s + r.periodSum, 0), slice.currency)}
</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
)}
{slice.txns.length === 0 ? (
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3 }}>
<Typography variant="body2" color="text.secondary">
No data for this slice. Try another granularity, period or payer.
No transactions in this slice.
</Typography>
</Paper>
) : (
<Paper variant="outlined" sx={{ borderRadius: 2, mt: 1.5 }}>
<Box sx={{ display: "flex", alignItems: "stretch" }}>
<Box
ref={barsListRef}
onScroll={updateBarScroll}
sx={{
flex: 1,
minWidth: 0,
maxHeight: 220,
overflowY: "auto",
py: 1,
px: 2,
scrollbarWidth: "none",
"&::-webkit-scrollbar": { display: "none" },
}}
>
{visibleBars.map((b) => (
<Box key={b.key} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
{b.key}
</Typography>
<Box
sx={{
height: 20,
borderRadius: 1,
bgcolor: flow === "outflows" ? "error.main" : "success.main",
opacity: 0.85,
minWidth: 4,
flexGrow: 0,
}}
style={{
width: `${maxBar ? Math.max((Math.abs(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>
))}
</Box>
{barScroll.overflow && (
<Box sx={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 0.5, pr: 1.5 }}>
<IconButton
size="small"
aria-label="Scroll bars up"
disabled={!barScroll.canUp}
onClick={() => scrollBarsByPage(-1)}
>
<KeyboardArrowUpIcon fontSize="small" />
</IconButton>
<IconButton
size="small"
aria-label="Scroll bars down"
disabled={!barScroll.canDown}
onClick={() => scrollBarsByPage(1)}
>
<KeyboardArrowDownIcon fontSize="small" />
</IconButton>
</Box>
)}
</Box>
</Paper>
)}
) : fields ? (
<TransactionList items={slice.txns} fields={fields} />
) : null}
</Box>
{slice.txns.length === 0 ? null : fields ? (
<TransactionList fields={fields} groups={listGroups} showMetrics />
) : null}
</Box>
)}
</Paper>
);
}

View File

@@ -1,50 +1,63 @@
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
import { parseOccurredAt } from "../common/utils/dates";
import { parseDdmmyyyy } from "../common/utils/dates";
export interface PeriodMetricsVM {
outflows: number;
inflows: number;
sum: number;
count: number;
avg: number | null;
min: number | null;
max: number | null;
firstDate: string | null;
lastDate: string | null;
cadence: number | null;
frequency: number | null;
export interface ParsedGroupKey {
period?: { granularity: string; label: string };
payee?: { label: string };
range?: { start?: string; end?: string };
}
export interface ReportPeriodGroup {
export interface ReportGroupLike {
key: string;
metrics: PeriodMetricsVM;
txns: any[];
currency: string;
}
export interface SliceSummary {
outflows: number;
inflows: number;
sum: number;
count: number;
avg: number | null;
min: number | null;
max: number | null;
firstDate: string | null;
lastDate: string | null;
txns: any[];
currency: string;
group_label?: string;
metrics?: Record<string, any>;
txns?: any[];
}
export interface SliceFilter {
granularity: string;
periods?: string[];
payees?: string[];
tags?: string[];
period?: string;
payee?: string;
}
export interface SliceSummary {
sum: number;
count: number;
avg: number | null;
min: number | null;
max: number | null;
firstDate: string | null;
lastDate: string | null;
txns: any[];
spent: number;
income: number;
currency: string;
}
export interface PivotCell {
payee: string;
sum: number;
count: number;
}
export interface PivotRow {
period: string;
cells: PivotCell[];
periodSum: number;
periodCount: number;
}
export interface PivotTable {
rows: PivotRow[];
payees: string[];
totals: PivotCell[];
}
export interface ReportFieldConfigs {
name: FieldConfig;
groupLabel: FieldConfig;
granularity: FieldConfig;
periodLabel: FieldConfig;
payee: FieldConfig;
entityCount: FieldConfig;
generatedAt: FieldConfig;
}
@@ -54,6 +67,23 @@ export interface MetricLabel {
order: number;
}
/** Split a concrete cache key into its dimension parts, e.g. `period:monthly:2026-Jan|payee:Zepto`. */
export function parseCacheKey(key: string): ParsedGroupKey {
const out: ParsedGroupKey = {};
for (const dim of key.split("|")) {
if (!dim) continue;
const [name, ...rest] = dim.split(":");
if (name === "period" && rest.length >= 2) {
out.period = { granularity: rest[0], label: rest.slice(1).join(":") };
} else if (name === "payee" && rest.length >= 1) {
out.payee = { label: rest.join(":") };
} else if (name === "range" && rest.length >= 1) {
out.range = { start: rest[0] || undefined, end: rest[1] || undefined };
}
}
return out;
}
export function apiErrorMessage(e: any): string {
if (e?.response?.data) {
const d = e.response.data;
@@ -65,7 +95,14 @@ export function apiErrorMessage(e: any): string {
return e?.message ?? "Request failed";
}
export const FLOW_OPTIONS = ["both", "inflows", "outflows"];
export function groupTypeEnum(schemas: Record<string, any>): string[] {
return schemas?.GroupSpec?.properties?.group_type?.enum ?? [];
}
export function groupValueFk(schemas: Record<string, any>): { resource?: string; prefetch?: boolean } | null {
const fk = schemas?.GroupSpec?.properties?.group_value?.["x-fk"];
return fk && typeof fk === "object" ? fk : null;
}
export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
const props: Record<string, any> = schemas?.ReportMetrics?.properties ?? {};
@@ -79,210 +116,123 @@ export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
.sort((a, b) => a.order - b.order);
}
export function periodHints(granularity: string): string[] {
const y = new Date().getFullYear();
switch (granularity) {
case "weekly":
return [`${y}-W01`, `${y}-W26`];
case "monthly":
return [`${y}-Jan`, `${y}-Feb`];
case "quarterly":
return [`${y}-Jan-Mar`, `${y}-Apr-Jun`];
case "yearly":
return [`${y - 1}`, `${y}`];
default:
return [`${y}-Jan`, `${y}-W01`, `${y}-Jan-Mar`, `${y}`];
}
}
function dateVal(value: string): number {
try {
return parseOccurredAt(value).getTime();
return parseDdmmyyyy(value).getTime();
} catch {
return 0;
}
}
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;
export function groupMatches(group: ReportGroupLike, filter: SliceFilter): boolean {
const key = parseCacheKey(group.key);
if (filter.period && filter.period !== "*") {
if (!key.period || key.period.label !== filter.period) return false;
}
if (filter.payee && filter.payee !== "*") {
if (!key.payee || key.payee.label !== filter.payee) return false;
}
return true;
}
function num(v: any): number | null {
return typeof v === "number" && Number.isFinite(v) ? v : null;
}
/**
* Groups cube periods by their canonical period_id, merging buckets per
* period. The server returns disjoint slices, so additive metric merge is
* safe; txn ids are deduped defensively. Metrics come verbatim from the API
* except when multiple buckets contribute to one period — then cadence and
* frequency are re-derived from the merged txn dates.
*/
export function buildPeriodGroups(buckets: any[], filter: SliceFilter): ReportPeriodGroup[] {
interface Acc {
metrics: PeriodMetricsVM;
txns: any[];
sources: number;
apiCadence: number | null;
apiFrequency: number | null;
}
const byPeriod = new Map<string, Acc>();
const seenTxnIds = new Set<string>();
let currency = "INR";
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 ?? {};
let acc = byPeriod.get(period.period_id);
if (!acc) {
acc = {
metrics: {
outflows: 0,
inflows: 0,
sum: 0,
count: 0,
avg: null,
min: null,
max: null,
firstDate: null,
lastDate: null,
cadence: null,
frequency: null,
},
txns: [],
sources: 0,
apiCadence: num(m.cadence),
apiFrequency: num(m.frequency),
};
byPeriod.set(period.period_id, acc);
}
acc.sources += 1;
const vm = acc.metrics;
vm.outflows += m.outflows ?? 0;
vm.inflows += m.inflows ?? 0;
vm.sum += m.sum ?? 0;
vm.count += m.count ?? 0;
const mn = num(m.min);
if (mn != null) vm.min = vm.min == null ? mn : Math.min(vm.min, mn);
const mx = num(m.max);
if (mx != null) vm.max = vm.max == null ? mx : Math.max(vm.max, mx);
if (m.first_date && (!vm.firstDate || dateVal(String(m.first_date)) < dateVal(vm.firstDate))) {
vm.firstDate = String(m.first_date);
}
if (m.last_date && (!vm.lastDate || dateVal(String(m.last_date)) > dateVal(vm.lastDate))) {
vm.lastDate = String(m.last_date);
}
for (const txn of period.txns ?? []) {
if (txn?.id != null) {
if (seenTxnIds.has(txn.id)) continue;
seenTxnIds.add(txn.id);
}
acc.txns.push(txn);
const c = txn?.account?.currency;
if (c) currency = c;
}
}
}
return [...byPeriod.entries()]
.map(([key, acc]) => {
const vm = acc.metrics;
vm.avg = vm.count ? Math.round((vm.sum / vm.count) * 100) / 100 : null;
if (acc.sources > 1) {
const dates = acc.txns
.map((t) => {
try {
return parseOccurredAt(t?.occurred_at).getTime();
} catch {
return NaN;
}
})
.filter((t) => !Number.isNaN(t))
.sort((a, b) => a - b);
if (dates.length >= 2) {
let gapSum = 0;
for (let i = 0; i < dates.length - 1; i += 1) gapSum += (dates[i + 1] - dates[i]) / 86400000;
const cadence = Math.round((gapSum / (dates.length - 1)) * 100) / 100;
vm.cadence = cadence > 0 ? cadence : null;
vm.frequency = cadence > 0 ? Math.round((1 / cadence) * 100) / 100 : null;
} else {
vm.cadence = null;
vm.frequency = null;
}
} else {
vm.cadence = acc.apiCadence;
vm.frequency = acc.apiFrequency;
}
return { key, metrics: vm, txns: acc.txns, currency };
})
.sort((a, b) => b.key.localeCompare(a.key));
}
export function sliceSummary(groups: ReportPeriodGroup[]): SliceSummary {
const outflows = groups.reduce((s, g) => s + g.metrics.outflows, 0);
const inflows = groups.reduce((s, g) => s + g.metrics.inflows, 0);
const sum = groups.reduce((s, g) => s + g.metrics.sum, 0);
const count = groups.reduce((s, g) => s + g.metrics.count, 0);
export function aggregateSlice(groups: ReportGroupLike[], filter: SliceFilter): SliceSummary {
let sum = 0;
let count = 0;
let spent = 0;
let income = 0;
let min: number | null = null;
let max: number | null = null;
let firstDate: string | null = null;
let lastDate: string | null = null;
let currency = "INR";
const txns: any[] = [];
for (const g of groups) {
if (g.metrics.min != null) min = min == null ? g.metrics.min : Math.min(min, g.metrics.min);
if (g.metrics.max != null) max = max == null ? g.metrics.max : Math.max(max, g.metrics.max);
if (g.metrics.firstDate && (!firstDate || dateVal(g.metrics.firstDate) < dateVal(firstDate))) {
firstDate = g.metrics.firstDate;
const seen = new Set<string>();
for (const group of groups) {
if (!groupMatches(group, filter)) continue;
const m = group.metrics ?? {};
if (typeof m.sum === "number") sum += m.sum;
if (typeof m.count === "number") count += m.count;
if (typeof m.min === "number") min = min === null ? m.min : Math.min(min, m.min);
if (typeof m.max === "number") max = max === null ? m.max : Math.max(max, m.max);
if (m.first_date && (!firstDate || dateVal(String(m.first_date)) < dateVal(firstDate))) {
firstDate = String(m.first_date);
}
if (g.metrics.lastDate && (!lastDate || dateVal(g.metrics.lastDate) > dateVal(lastDate))) {
lastDate = g.metrics.lastDate;
if (m.last_date && (!lastDate || dateVal(String(m.last_date)) > dateVal(lastDate))) {
lastDate = String(m.last_date);
}
for (const txn of group.txns ?? []) {
if (txn?.id != null) {
if (seen.has(txn.id)) continue;
seen.add(txn.id);
}
txns.push(txn);
const amt = Number(txn?.amount ?? 0);
if (amt < 0) spent += Math.abs(amt);
else income += amt;
const c = txn?.account?.currency;
if (c) currency = c;
}
if (g.currency) currency = g.currency;
txns.push(...g.txns);
}
return { outflows, inflows, sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, currency };
return { sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, spent, income, currency };
}
export function buildPivot(groups: ReportGroupLike[], periodOrder: string[], payeeOrder: string[]): PivotTable {
const payees = payeeOrder.filter((payee) =>
groups.some((g) => parseCacheKey(g.key).payee?.label === payee),
);
const totals = payees.map((payee) => ({ payee, sum: 0, count: 0 }));
const rows: PivotRow[] = [];
for (const period of periodOrder) {
const periodGroups = groups.filter((g) => parseCacheKey(g.key).period?.label === period);
if (periodGroups.length === 0) continue;
const cells = payees.map((payee, i) => {
const cellGroups = periodGroups.filter((g) => parseCacheKey(g.key).payee?.label === payee);
const sum = cellGroups.reduce((s, g) => s + (g.metrics?.sum ?? 0), 0);
const count = cellGroups.reduce((s, g) => s + (g.metrics?.count ?? 0), 0);
totals[i].sum += sum;
totals[i].count += count;
return { payee, sum, count };
});
rows.push({
period,
cells,
periodSum: cells.reduce((s, c) => s + c.sum, 0),
periodCount: cells.reduce((s, c) => s + c.count, 0),
});
}
return { rows, payees, totals };
}
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
const reportsRes = resources.find((r) => r.name === "reports");
if (!reportsRes) return null;
const find = (name: string) => reportsRes.fields.find((f) => f.name === name);
const name = find("name");
const groupLabel = find("group_label");
const granularity = find("granularity");
const periodLabel = find("period_label");
const payee = find("payee");
const entityCount = find("entity_count");
const generatedAt = find("generated_at");
if (!name || !generatedAt) return null;
return { name, generatedAt };
}
export type ReportDim = "period" | "payee" | "tag";
export interface DimensionBar {
key: string;
sum: number;
count: number;
}
/**
* Bar-chart rows for a given dimension. "period" reuses the period groups;
* "payee"/"tag" fold each bucket's metrics into every value listed under
* group_key[dim] — safe because server buckets are disjoint slices.
*/
export function buildDimensionBars(buckets: any[], filter: SliceFilter, dim: ReportDim): DimensionBar[] {
if (dim === "period") {
return buildPeriodGroups(buckets, filter).map((g) => ({
key: g.key,
sum: g.metrics.sum,
count: g.metrics.count,
}));
}
const acc = new Map<string, DimensionBar>();
for (const bucket of buckets ?? []) {
if (!bucketMatches(bucket, filter)) continue;
const keys: string[] = bucket.group_key?.[dim] ?? [];
for (const period of bucket.series?.[filter.granularity] ?? []) {
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
const m = period.metrics ?? {};
const sum = typeof m.sum === "number" ? m.sum : 0;
const count = typeof m.count === "number" ? m.count : 0;
for (const k of keys) {
const cur = acc.get(k);
if (cur) {
cur.sum += sum;
cur.count += count;
} else {
acc.set(k, { key: k, sum, count });
}
}
}
}
return [...acc.values()].sort((a, b) => Math.abs(b.sum) - Math.abs(a.sum));
if (!groupLabel || !granularity || !periodLabel || !payee || !entityCount || !generatedAt) return null;
return { groupLabel, granularity, periodLabel, payee, entityCount, generatedAt };
}

View File

@@ -14,83 +14,20 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import { formatCurrency } from "../../../react-openapi";
import type { ExpenseItem, TxnFieldConfigs } from "../types";
import { computeTxnMetrics, groupByDate, groupByPeriod } from "../utils/transactions";
import type { ListGroupMetrics, ListPeriodGroup, PeriodGranularity } from "../utils/transactions";
import { groupByDate, groupByMonth } from "../utils/transactions";
import { monthLabel } from "../utils/dates";
import { TransactionRow } from "./TransactionRow";
import { StatCard } from "./StatCard";
interface TransactionListProps {
items?: ExpenseItem[];
fields: TxnFieldConfigs;
granularity?: PeriodGranularity;
showMetrics?: boolean;
groups?: ListPeriodGroup[];
}
function cadenceRow(cadenceDays: number | null, frequency: number | null): { label: string; value: string } {
const fmt = (v: number) => (Number.isInteger(v) ? String(v) : v.toFixed(2));
if (cadenceDays != null && cadenceDays < 1) {
return { label: "Frequency", value: `${frequency == null ? "—" : fmt(frequency)} /day` };
}
return {
label: "Cadence",
value: cadenceDays == null ? "—" : `${fmt(cadenceDays)} days`,
};
}
function txnFallbackMetrics(items: ExpenseItem[]): ListGroupMetrics {
const t = computeTxnMetrics(items);
return {
sum: t.sum,
count: t.count,
avg: t.avg,
min: t.min,
max: t.max,
cadence: t.cadenceDays,
frequency: t.frequency,
};
}
function GroupMetrics({
items,
currency,
metrics,
}: {
items: ExpenseItem[];
currency: string;
metrics?: ListGroupMetrics;
}) {
const m = metrics ?? txnFallbackMetrics(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) },
cadenceRow(m.cadence, m.frequency),
];
return (
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", width: "100%" }}>
{rows.map((row) => (
<StatCard key={row.label} label={row.label} value={row.value} />
))}
</Box>
);
fields: TxnFieldConfigs;
}
export function TransactionList({
items,
fields,
granularity = "monthly",
showMetrics = false,
groups: externalGroups,
}: TransactionListProps) {
export function TransactionList({ items, fields }: 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<ListPeriodGroup[]>(
() => externalGroups ?? groupByPeriod(items ?? [], granularity),
[externalGroups, items, granularity],
);
const groups = useMemo(() => groupByMonth(items), [items]);
const listRef = useRef<HTMLDivElement>(null);
const pillRef = useRef<HTMLDivElement>(null);
const didInitOpenMonth = useRef(false);
@@ -198,34 +135,28 @@ export function TransactionList({
px: 2,
py: 1,
"& .MuiAccordionSummary-content": {
flexDirection: "column",
alignItems: "stretch",
gap: 0.75,
alignItems: "center",
gap: 1.5,
minWidth: 0,
},
}}
>
<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} metrics={group.metrics} />
)}
<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>
</AccordionSummary>
<AccordionDetails sx={{ p: 1.5, pt: 1 }}>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
@@ -325,7 +256,7 @@ export function TransactionList({
}}
>
<Typography variant="caption" fontWeight={700} color="text.secondary">
{activeMonth ? (groups.find((g) => g.key === activeMonth)?.label ?? activeMonth) : ""}
{activeMonth ? monthLabel(activeMonth) : ""}
</Typography>
<KeyboardArrowDownIcon sx={{ fontSize: 14, color: "text.secondary" }} />
</Box>
@@ -345,7 +276,7 @@ export function TransactionList({
onClick={() => handleSelectMonth(group.key)}
>
<ListItemText
primary={group.label}
primary={monthLabel(group.key)}
secondary={`${group.items.length} transactions`}
/>
</MenuItem>

View File

@@ -11,6 +11,14 @@ export interface ExpenseItem {
updated_at?: string;
}
export interface GroupedMonth {
key: string;
items: ExpenseItem[];
spent: number;
income: number;
currency: string;
}
export interface TxnFieldConfigs {
entity: FieldConfig;
amount: FieldConfig;

View File

@@ -1,5 +1,5 @@
import type { ExpenseItem } from "../types";
import { dateLabel, monthKey, monthLabel, parseOccurredAt } from "./dates";
import type { ExpenseItem, GroupedMonth } from "../types";
import { dateLabel, monthKey, parseOccurredAt } from "./dates";
export function isExpense(item: ExpenseItem): boolean {
return (item.amount ?? 0) < 0;
@@ -29,77 +29,10 @@ export function groupByDate(items: ExpenseItem[]): DateGroup[] {
}));
}
export type PeriodGranularity = "weekly" | "monthly" | "quarterly" | "yearly";
export interface PeriodGroup {
key: string;
label: string;
items: ExpenseItem[];
spent: number;
income: number;
currency: string;
}
/** Metrics verbatim from the API's ReportMetrics (camelCased). */
export interface ListGroupMetrics {
sum: number;
count: number;
avg: number | null;
min: number | null;
max: number | null;
cadence: number | null;
frequency: number | null;
}
export interface ListPeriodGroup extends PeriodGroup {
metrics?: ListGroupMetrics;
}
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[] {
export function groupByMonth(items: ExpenseItem[]): GroupedMonth[] {
const map = new Map<string, ExpenseItem[]>();
for (const item of items) {
const key = periodKey(item.occurred_at, granularity);
const key = monthKey(item.occurred_at);
const list = map.get(key) ?? [];
list.push(item);
map.set(key, list);
@@ -112,50 +45,7 @@ export function groupByPeriod(items: ExpenseItem[], granularity: PeriodGranulari
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 };
return { key, 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;
frequency: 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, frequency: 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;
}
const frequency = cadenceDays != null && cadenceDays > 0 ? Math.round((1 / cadenceDays) * 100) / 100 : null;
return {
sum,
count: amounts.length,
avg: sum / amounts.length,
min: Math.min(...amounts),
max: Math.max(...amounts),
cadenceDays,
frequency,
};
}

View File

@@ -7,10 +7,7 @@ export type FetchRequestStatus =
| "completed"
| "failed";
export type SourceType = "file" | "pdf" | "xlsx" | "csv" | "email";
export interface FileSource {
type?: SourceType;
path: string;
bank: string;
raw_lines?: string[];
@@ -20,20 +17,7 @@ export interface FileSource {
txn_dicts_count?: number;
}
export interface PdfSource extends FileSource {
type: "pdf";
}
export interface XlsxSource extends FileSource {
type: "xlsx";
}
export interface CsvSource extends FileSource {
type: "csv";
}
export interface EmailSource {
type: "email";
bank: string;
from_email?: string;
subject?: string;
@@ -42,15 +26,12 @@ export interface EmailSource {
txn_dicts_count?: number;
}
export type PipelineType = "heuristic" | "llm" | "llama_parse";
export type TrustFallback = "amount" | "balance";
export type PipelineType = "heuristic" | "llm" | "llama_parser";
export interface FetchRequestCreate {
source: PdfSource | XlsxSource | CsvSource | EmailSource;
source: FileSource | EmailSource;
account_name: string;
pipeline?: PipelineType;
trust_fallback?: TrustFallback | null;
payor_username?: string;
start_date?: string;
end_date?: string;
@@ -132,7 +113,7 @@ export interface SSEEvent {
export interface FetchRequestFilters {
status?: FetchRequestStatus[];
account_name?: string;
source_type?: SourceType;
source_type?: "file" | "email";
}
export function formatApiError(err: any): string {

View File

@@ -5,9 +5,6 @@ export type {
FetchRequestStatus,
FetchRequestFilters,
FileSource,
PdfSource,
XlsxSource,
SourceType,
EmailSource,
UploadResult,
PendingAmbiguity,
@@ -18,7 +15,6 @@ export type {
SSEEventStatus,
ProgressMessage,
PipelineType,
TrustFallback,
} from "./fetch-requests.models";
export { RETRY_MAX, formatApiError } from "./fetch-requests.models";
export {