9 Commits

Author SHA1 Message Date
6b340d89f6 refactor: revamp for older report logic with benefits of newer one 2026-08-20 19:52:43 +05:30
79808d6d3e feat: redesign per-group stats strip in accordion summary
Replace the dated First/Last pills with a Cadence metric computed from
consecutive transaction dates (mirrors backend ReportMetrics.cadence_days)
and render the group stats as spaced StatCards (Sum/Avg/Min/Max/Cadence)
in the collapsed accordion header, matching the Outflows/Inflows layout.
2026-08-20 17:10:48 +05:30
f865f7dec2 feat: show per-group report stats in collapsed accordion header
Move the Sum/Count/Avg/Min/Max/First/Last metric row from inside the
expanded accordion details into the accordion summary as a second row,
so group stats are visible while the group is collapsed. Second row
renders compact label-value pairs instead of pills; summary content is
now a two-row column.
2026-08-20 16:37:05 +05:30
fc3a48a367 refactor: reuse FkMultiSelectField for report period/payee selectors
Export FkMultiSelectField from react-openapi and use it directly in the
report viewer for the Period/Payee dimension filters instead of the
custom OptionMultiSelect component, gaining the admin panel's QoL
behavior (no close-on-click, selected-first with tick marks, chips).
Feed it fabricated FieldConfigs plus fkOptions derived from the report's
metadata.group_options; delete the standalone OptionMultiSelect.
2026-08-20 16:20:06 +05:30
f9759e3968 feat: add per-group metric strip in report transaction list
Compute Sum/Count/Avg/Min/Max/First/Last per accordion group in the
report view (mirroring backend ReportMetrics.compute_metrics signed
semantics) via new computeTxnMetrics helper and a showMetrics prop on
TransactionList. Remove the now-redundant top-level metric strip from
ReportViewer and restore its Outflows/Inflows/Transactions stat cards.
2026-08-20 16:03:12 +05:30
47c00a06a8 feat: group report transactions by report granularity
Make the outer accordion grouping in TransactionList granularity-aware
instead of hardcoded months. TransactionList accepts a granularity prop
(weekly/monthly/quarterly/yearly, default monthly); ReportViewer passes
the report's granularity so a weekly report buckets transactions by ISO
week, quarterly by quarter, yearly by year. Expense page keeps monthly
grouping. Add periodKey/periodLabel/groupByPeriod/toPeriodGranularity to
src/common/utils/transactions.ts and drop the dead groupByMonth/
GroupedMonth helpers.
2026-08-20 14:37:52 +05:30
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
25 changed files with 450 additions and 1089 deletions

1
.gitignore vendored
View File

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

View File

@@ -5,10 +5,6 @@ export { useAppContext } from "./src/context/AppContext";
export { useResource } from "./src/context/useResource"; export { useResource } from "./src/context/useResource";
export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields"; export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields";
export { FormFieldRenderer } from "./src/components/fields/FormFieldRenderer"; 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 { CurrencyField, formatCurrency } from "./src/components/fields/renderers/CurrencyField";
export { FkMultiSelectField } from "./src/components/fields/renderers/FkMultiSelectField"; export { FkMultiSelectField } from "./src/components/fields/renderers/FkMultiSelectField";
export { SseStreamView } from "./src/components/SseStreamView"; export { SseStreamView } from "./src/components/SseStreamView";
@@ -17,6 +13,5 @@ export { getApi } from "./src/hooks/useApi";
export { useItemSse } from "./src/hooks/useItemSse"; export { useItemSse } from "./src/hooks/useItemSse";
export { sanitizePayload } from "./src/utils/sanitize-payload"; export { sanitizePayload } from "./src/utils/sanitize-payload";
export type { FkResolver } 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 { FilterComponentProps } from "./src/context/useResource";
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship, ProfileOperation, ProfileComponents, AuthConfig } from "./src/types"; 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 { DateField } from "./renderers/DateField";
import { BooleanField } from "./renderers/BooleanField"; import { BooleanField } from "./renderers/BooleanField";
import { EnumField } from "./renderers/EnumField"; import { EnumField } from "./renderers/EnumField";
import { MultiEnumField } from "./renderers/MultiEnumField";
import { FkSelectField } from "./renderers/FkSelectField"; import { FkSelectField } from "./renderers/FkSelectField";
import { FkMultiSelectField } from "./renderers/FkMultiSelectField"; import { FkMultiSelectField } from "./renderers/FkMultiSelectField";
import { FileUploadField } from "./renderers/FileUploadField"; 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) { if (field.enumValues) {
return ( return (
<EnumField <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 { Box, Typography, Chip, Avatar, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
import type { FieldConfig } from "../../types"; import type { FieldConfig } from "../../types";
import { applyDisplayFormat, resolveMediaUrl } from "./utils"; import { applyDisplayFormat, resolveMediaUrl } from "./utils";
import { formatByFieldFormat } from "../../utils/datetime";
import { InlineRefField } from "./renderers/InlineRefField"; import { InlineRefField } from "./renderers/InlineRefField";
import { CurrencyField } from "./renderers/CurrencyField"; import { CurrencyField } from "./renderers/CurrencyField";
import { extractFields } from "../../transformers/field-config"; import { extractFields } from "../../transformers/field-config";
@@ -58,7 +57,7 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
{sf.label} {sf.label}
</Typography> </Typography>
<Typography variant="body2"> <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> </Typography>
</Box> </Box>
</Grid> </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">{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 { DetailFieldRenderer } from "./DetailFieldRenderer";
export { applyDisplayFormat } from "./utils"; export { applyDisplayFormat } from "./utils";
export { JsonField } from "./renderers/JsonField"; export { JsonField } from "./renderers/JsonField";
export { MultiEnumField } from "./renderers/MultiEnumField";
export { CurrencyField, formatCurrency } from "./renderers/CurrencyField"; export { CurrencyField, formatCurrency } from "./renderers/CurrencyField";

View File

@@ -10,26 +10,11 @@ interface Props {
} }
export function DateField({ field, value, onChange, error }: Props) { export function DateField({ field, value, onChange, error }: Props) {
// `x-edit-as: date` renders a date-time field as a plain date picker; const inputType = field.format === "date" ? "date" : "datetime-local";
// the picked day is submitted as midnight so the stored type is intact.
const editAsDate = field.format === "date" || field.editAs === "date";
const inputType = editAsDate ? "date" : "datetime-local"; const normalized = field.format === "date-time" && typeof value === "string"
? value.replace(/\.\d+Z$/, "").replace(/Z$/, "")
const normalized = (() => { : value;
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);
}
};
return ( return (
<TextField <TextField
@@ -37,7 +22,7 @@ export function DateField({ field, value, onChange, error }: Props) {
label={field.label} label={field.label}
type={inputType} type={inputType}
value={normalized ?? ""} value={normalized ?? ""}
onChange={handleChange} onChange={(e) => onChange(e.target.value)}
error={!!error} error={!!error}
helperText={error || field.description || undefined} helperText={error || field.description || undefined}
placeholder={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 { Box, Typography, Chip, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
import type { FieldConfig } from "../../../types"; import type { FieldConfig } from "../../../types";
import { applyDisplayFormat } from "../utils"; import { applyDisplayFormat } from "../utils";
import { formatByFieldFormat } from "../../../utils/datetime";
import { extractFields } from "../../../transformers/field-config"; import { extractFields } from "../../../transformers/field-config";
import { useAppContext } from "../../../context/AppContext"; 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" }}> <Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ mb: 0.25, display: "block" }}>
{sf.label} {sf.label}
</Typography> </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> </Box>
</Grid> </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 { function getNested(obj: any, path: string): any {
return path.split(".").reduce((o, k) => o?.[k], obj); 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 ?? ""); if (!item || typeof item !== "object") return String(item ?? "");
return format.replace(/\{([\w.]+)\}/g, (_, key) => { return format.replace(/\{([\w.]+)\}/g, (_, key) => {
const val = getNested(item, key); const val = getNested(item, key);
return val != null ? formatIsoLike(val) : ""; return val != null ? String(val) : "";
}); });
} }

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

View File

@@ -85,8 +85,6 @@ export interface ResourceConfig {
export interface FKFieldConfig { export interface FKFieldConfig {
resource: string; resource: string;
prefetch: boolean; prefetch: boolean;
/** Target property used as the wire value (defaults to the target's primary key). */
value?: string;
} }
export interface OneOfOption { export interface OneOfOption {
@@ -101,8 +99,6 @@ export interface FieldConfig {
description: string; description: string;
type: string; type: string;
format?: string; format?: string;
/** `x-edit-as: date` — edit a `date-time` field with a plain date input; submits midnight. */
editAs?: string;
order: number; order: number;
hidden: { form?: boolean; list?: boolean; detail?: boolean }; hidden: { form?: boolean; list?: boolean; detail?: boolean };
filterable: boolean; filterable: boolean;
@@ -110,8 +106,6 @@ export interface FieldConfig {
readOnly: boolean; readOnly: boolean;
required: boolean; required: boolean;
enumValues?: string[]; enumValues?: string[];
/** Schema-level `default` used to seed create-form state. */
defaultValue?: any;
fk?: FKFieldConfig; fk?: FKFieldConfig;
uiType?: string; uiType?: string;
uploadUrl?: 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]; const val = result[key];
// FK fields whose wire value is a plain target property (fk.value, e.g. if (field.fk) {
// account names) are already in wire format — no id→object resolution.
if (field.fk && !field.fk.value) {
if (val == null || val === "") { if (val == null || val === "") {
result[key] = null; result[key] = null;
} else if (resolveFk) { } else if (resolveFk) {

View File

@@ -1,60 +1,22 @@
import React, { useEffect, useMemo, useState } from "react"; import React, { useEffect, useMemo, useState } from "react";
import { import {
Box, Container, Typography, Paper, Button, Alert, Box, Container, Typography, Paper, Button, Alert,
CircularProgress, IconButton, Tooltip, CircularProgress,
} from "@mui/material"; } from "@mui/material";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong"; 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 { useAppContext, useResource, ListCellRenderer, FormFieldRenderer, getApi, applyDisplayFormat } from "../../react-openapi";
import type { FieldConfig } from "../../react-openapi"; import type { FieldConfig } from "../../react-openapi";
import { PageHeader } from "../ui/PageHeader"; import { PageHeader } from "../ui/PageHeader";
import { EmptyState } from "../ui/EmptyState"; 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"]; const CREATE_FIELDS = ["account", "bank", "pipeline", "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>
);
}
function FetchRequestList() { function FetchRequestList() {
const navigate = useNavigate(); const navigate = useNavigate();
const { list, remove, resource } = useResource("fetch-requests"); const { list, resource } = useResource("fetch-requests");
const { resources: allResources } = useAppContext(); const { resources: allResources } = useAppContext();
const [rows, setRows] = useState<any[] | null>(null); 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(() => { const columns = useMemo(() => {
if (!resource) return []; if (!resource) return [];
@@ -68,26 +30,6 @@ function FetchRequestList() {
list({ limit: 20 }).then((res) => setRows(res.items ?? [])); list({ limit: 20 }).then((res) => setRows(res.items ?? []));
}, [resource?.name]); }, [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) { if (!rows) {
return ( return (
<Box sx={{ display: "flex", justifyContent: "center", py: 6 }}> <Box sx={{ display: "flex", justifyContent: "center", py: 6 }}>
@@ -116,25 +58,17 @@ function FetchRequestList() {
<Paper <Paper
key={row.id ?? i} key={row.id ?? i}
variant="outlined" variant="outlined"
sx={(theme) => ({ sx={{
p: 2, p: 2,
cursor: "pointer", cursor: "pointer",
borderRadius: 3, borderRadius: 2,
transition: "border-color 160ms ease, box-shadow 160ms ease, background-color 160ms ease", transition: "border-color 160ms ease, box-shadow 160ms ease",
"&:hover": { "&:hover": { borderColor: "primary.main", boxShadow: 1 },
borderColor: "primary.main", }}
boxShadow: 1,
backgroundColor: alpha(theme.palette.background.default, 0.9),
},
...glassSx(theme),
})}
onClick={() => navigate(`/fetch-requests/${row.id}`)} onClick={() => navigate(`/fetch-requests/${row.id}`)}
> >
<Box sx={{ display: "flex", gap: 2, alignItems: "center" }}> <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center" }}>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center", flex: 1, minWidth: 0 }}> {columns.map((col) => (
{columns
.filter((col) => col.name !== "created_at")
.map((col) => (
<Box key={col.name} sx={{ minWidth: 120 }}> <Box key={col.name} sx={{ minWidth: 120 }}>
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}> <Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
{col.label} {col.label}
@@ -149,31 +83,6 @@ function FetchRequestList() {
</Box> </Box>
))} ))}
</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>
</Paper> </Paper>
); );
})} })}
@@ -185,7 +94,6 @@ export default function FetchRequestCreate() {
const { resources: allResources } = useAppContext(); const { resources: allResources } = useAppContext();
const resource = useMemo(() => allResources.find((r) => r.name === "fetch-requests"), [allResources]); const resource = useMemo(() => allResources.find((r) => r.name === "fetch-requests"), [allResources]);
const { create } = useResource("fetch-requests"); const { create } = useResource("fetch-requests");
const navigate = useNavigate();
const [formData, setFormData] = useState<Record<string, any>>({}); const [formData, setFormData] = useState<Record<string, any>>({});
const [fkOptions, setFkOptions] = useState<Record<string, { value: any; label: string }[]>>({}); const [fkOptions, setFkOptions] = useState<Record<string, { value: any; label: string }[]>>({});
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -235,10 +143,6 @@ export default function FetchRequestCreate() {
const display = applyDisplayFormat(created, resource!.displayFormat); const display = applyDisplayFormat(created, resource!.displayFormat);
setResult({ severity: "success", message: `Created: ${display}` }); setResult({ severity: "success", message: `Created: ${display}` });
setFormData({}); setFormData({});
const newId = (created as any)?.id;
if (newId) {
navigate(`/fetch-requests/${newId}`);
}
} catch (e: any) { } catch (e: any) {
const detail = e?.response?.data?.detail; const detail = e?.response?.data?.detail;
const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join("; ") : (detail ?? e?.message ?? "Unknown error"); const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join("; ") : (detail ?? e?.message ?? "Unknown error");
@@ -256,11 +160,28 @@ export default function FetchRequestCreate() {
); );
} }
const renderPaneFields = (names: string[]) =>
names.map((name) => {
const field = formFields.find((f) => f.name === name);
if (!field) return null;
return ( return (
<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."
/>
<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: "flex", flexDirection: "column", gap: 2, maxWidth: 520 }}>
{formFields.map((field) => (
<FormFieldRenderer <FormFieldRenderer
key={field.name} key={field.name}
field={field} field={field}
@@ -268,54 +189,7 @@ export default function FetchRequestCreate() {
onChange={(val) => handleChange(field.name, val)} onChange={(val) => handleChange(field.name, val)}
fkOptions={fkOptions[field.name]} 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, 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>
<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>
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, gap: 1.5 }}> <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, gap: 1.5 }}>
@@ -333,13 +207,12 @@ export default function FetchRequestCreate() {
{result.message} {result.message}
</Alert> </Alert>
)} )}
</Box> </Paper>
<Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}> <Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}>
Recent Fetch Requests Recent Fetch Requests
</Typography> </Typography>
<FetchRequestList /> <FetchRequestList />
</Container> </Container>
</Box>
); );
} }

View File

@@ -10,7 +10,6 @@ import {
CircularProgress, CircularProgress,
Alert, Alert,
Divider, Divider,
Tooltip,
} from "@mui/material"; } from "@mui/material";
import ReplayIcon from "@mui/icons-material/Replay"; import ReplayIcon from "@mui/icons-material/Replay";
import CheckCircleIcon from "@mui/icons-material/CheckCircle"; 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 PlayArrowIcon from "@mui/icons-material/PlayArrow";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline"; import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord"; import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import { useResource, useItemSse, useAppContext, DetailFieldRenderer, applyDisplayFormat } from "../../react-openapi"; import { useResource, useItemSse, useAppContext, DetailFieldRenderer, applyDisplayFormat } from "../../react-openapi";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { RETRY_MAX, formatApiError } from "../features/fetch-requests"; 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() { export default function FetchRequestDetail() {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const navigate = useNavigate(); const navigate = useNavigate();
const { get, patch, remove, resource } = useResource("fetch-requests"); const { get, patch, resource } = useResource("fetch-requests");
const { resources: allResources } = useAppContext(); const { resources: allResources } = useAppContext();
const [stepStats, setStepStats] = useState<Record<string, number>>({}); const [stepStats, setStepStats] = useState<Record<string, number>>({});
const [liveParsedCount, setLiveParsedCount] = useState<number | undefined>(undefined); const [liveParsedCount, setLiveParsedCount] = useState<number | undefined>(undefined);
const [retrying, setRetrying] = useState(false); const [retrying, setRetrying] = useState(false);
const [deleting, setDeleting] = useState(false);
const { showToast } = useToast(); const { showToast } = useToast();
const feedRef = useRef<HTMLDivElement>(null); 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 req = fetchRequest as any;
const retryCount = req?.retry_count ?? 0; const retryCount = req?.retry_count ?? 0;
const isRetryExhausted = retryCount >= RETRY_MAX; const isRetryExhausted = retryCount >= RETRY_MAX;
@@ -309,20 +286,6 @@ export default function FetchRequestDetail() {
Retry Retry
</Button> </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> </Box>
</Section> </Section>

View File

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

View File

@@ -1,85 +1,131 @@
import React, { useCallback, useEffect, useMemo, useState } from "react"; import React, { useEffect, useMemo, useState } from "react";
import { import {
Box, Box,
Paper, Paper,
Typography, Typography,
TextField,
Button, Button,
Grid, MenuItem,
Select,
FormControl,
InputLabel,
Autocomplete,
FormControlLabel,
Checkbox,
Chip,
Alert, Alert,
} from "@mui/material"; } from "@mui/material";
import AddIcon from "@mui/icons-material/Add"; import AddIcon from "@mui/icons-material/Add";
import { import { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
useResource,
useAppContext,
FormFieldRenderer,
extractFields,
useFkFieldOptions,
} from "../../react-openapi";
import type { FieldConfig } from "../../react-openapi";
import { useToast } from "../ui/Toast"; import { useToast } from "../ui/Toast";
import { apiErrorMessage } from "./types"; import { isDdmmyyyy } from "../common/utils/dates";
import { apiErrorMessage, granularityOptions, groupDimOptions, FLOW_OPTIONS } from "./types";
interface GenerateReportPanelProps { interface GenerateReportPanelProps {
onGenerated: (report: any) => void; onGenerated: (report: any) => void;
} }
const ALL_GRANULARITIES = ["weekly", "monthly", "quarterly"];
export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) { export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
const { schemas } = useAppContext(); const { schemas, resources } = useAppContext();
const { create, loading: submitting } = useResource("reports"); const { create } = useResource("reports");
const { list: listAccounts } = useResource("accounts");
const { showToast } = useToast(); const { showToast } = useToast();
const [formData, setFormData] = useState<Record<string, any>>({}); const [name, setName] = useState("");
const [granularities, setGranularities] = useState<string[]>(ALL_GRANULARITIES);
const [groupDims, setGroupDims] = useState<string[]>(["payee", "tag"]);
const [flow, setFlow] = useState("both");
const [accounts, setAccounts] = useState<string[]>([]);
const [ignoreSelf, setIgnoreSelf] = useState(true);
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [minAmount, setMinAmount] = useState("");
const [maxAmount, setMaxAmount] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [accountOptions, setAccountOptions] = useState<string[]>([]);
const [dateErrors, setDateErrors] = useState<{ start?: string; end?: string }>({});
const fields: FieldConfig[] = useMemo(() => { const granularityChoices = useMemo(() => {
const schema = schemas?.ReportQuery; const enums = granularityOptions(schemas);
if (!schema) return []; return enums.length ? enums : ALL_GRANULARITIES;
return extractFields("ReportQuery", schema, schemas).sort(
(a, b) => a.order - b.order || a.name.localeCompare(b.name)
);
}, [schemas]); }, [schemas]);
const dimChoices = useMemo(() => groupDimOptions(schemas), [schemas]);
const { fkOptions, fkLoading, loadFkOnOpen } = useFkFieldOptions(fields); const accountsRes = resources.find((r) => r.name === "accounts");
const accountsFormat = accountsRes?.displayFormat ?? "{name}";
useEffect(() => { useEffect(() => {
setFormData((prev) => { let mounted = true;
const next = { ...prev }; listAccounts({ limit: 0 }).then((res) => {
let changed = false; if (!mounted) return;
for (const f of fields) { const names = (res.items ?? [])
if (next[f.name] === undefined && f.defaultValue !== undefined) { .map((it: any) => applyDisplayFormat(it, accountsFormat))
next[f.name] = Array.isArray(f.defaultValue) ? [...f.defaultValue] : f.defaultValue; .filter((n: string) => n);
changed = true; setAccountOptions([...new Set(names)].sort((a, b) => a.localeCompare(b)));
}
}
return changed ? next : prev;
}); });
}, [fields]); return () => {
mounted = false;
};
}, [listAccounts, accountsFormat]);
const handleChange = useCallback((name: string, value: any) => { const toggle = (list: string[], value: string, setter: (v: string[]) => void) =>
setFormData((prev) => ({ ...prev, [name]: value })); setter(list.includes(value) ? list.filter((v) => v !== value) : [...list, value]);
setError(null);
}, []);
const buildPayload = (): Record<string, any> => { const validateDates = (): boolean => {
const payload: Record<string, any> = {}; const errs: { start?: string; end?: string } = {};
for (const f of fields) { if (startDate && !isDdmmyyyy(startDate)) errs.start = "Use DD-MM-YYYY";
const v = formData[f.name]; if (endDate && !isDdmmyyyy(endDate)) errs.end = "Use DD-MM-YYYY";
if (v === undefined || v === null || v === "") continue; setDateErrors(errs);
if (Array.isArray(v) && v.length === 0) continue; return Object.keys(errs).length === 0;
payload[f.name] = v;
}
return payload;
}; };
const handleSubmit = async (e: React.FormEvent) => { const parseAmount = (value: string): number | null => {
e.preventDefault(); const trimmed = value.trim();
if (!trimmed) return null;
const n = Number(trimmed);
return Number.isFinite(n) ? n : null;
};
const handleSubmit = async () => {
if (!validateDates()) return;
setError(null); setError(null);
const min = parseAmount(minAmount);
const max = parseAmount(maxAmount);
if (minAmount.trim() && min === null) {
setError("Min amount must be a number");
return;
}
if (maxAmount.trim() && max === null) {
setError("Max amount must be a number");
return;
}
if (min !== null && max !== null && min > max) {
setError("Min amount cannot exceed max amount");
return;
}
const payload: Record<string, any> = {
name: name.trim(),
granularities,
group_dims: groupDims,
flow,
ignore_self: ignoreSelf,
};
if (accounts.length) payload.accounts = accounts;
if (startDate.trim()) payload.start_date = startDate.trim();
if (endDate.trim()) payload.end_date = endDate.trim();
if (min !== null) payload.min_amount = min;
if (max !== null) payload.max_amount = max;
setSubmitting(true);
try { try {
const created = await create(buildPayload()); const created = await create(payload);
showToast(`Generated snapshot ${created?.name ? `“${created.name}”` : ""}`.trim() || "Generated snapshot"); showToast(`Generated snapshot ${created?.name ? `“${created.name}”` : ""}`.trim() || "Generated snapshot");
onGenerated(created); onGenerated(created);
} catch (e: any) { } catch (e: any) {
setError(apiErrorMessage(e)); setError(apiErrorMessage(e));
} finally {
setSubmitting(false);
} }
}; };
@@ -99,28 +145,131 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
</Alert> </Alert>
)} )}
<Box component="form" onSubmit={handleSubmit}> <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
<Grid container spacing={2}> <TextField
{fields.map((field) => ( size="small"
<Grid item xs={12} sm={6} md={4} key={field.name}> label="Name"
<FormFieldRenderer placeholder="e.g. Monthly spending"
field={field} value={name}
value={formData[field.name]} onChange={(e) => setName(e.target.value)}
onChange={(val) => handleChange(field.name, val)} sx={{ maxWidth: 420 }}
fkOptions={fkOptions[field.name]} />
fkLoading={fkLoading[field.name]}
onFkOpen={loadFkOnOpen} <Box>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
Granularities
</Typography>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
{granularityChoices.map((g) => (
<Chip
key={g}
label={g}
clickable
color={granularities.includes(g) ? "primary" : "default"}
variant={granularities.includes(g) ? "filled" : "outlined"}
onClick={() => toggle(granularities, g, setGranularities)}
/> />
</Grid>
))} ))}
</Grid> </Box>
</Box>
<Box>
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
Group dimensions
</Typography>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
{dimChoices.map((d) => (
<Chip
key={d}
label={d}
clickable
color={groupDims.includes(d) ? "primary" : "default"}
variant={groupDims.includes(d) ? "filled" : "outlined"}
onClick={() => toggle(groupDims, d, setGroupDims)}
/>
))}
</Box>
</Box>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "flex-start" }}>
<FormControl size="small" sx={{ width: 200 }}>
<InputLabel id="flow-label">Flow</InputLabel>
<Select labelId="flow-label" label="Flow" value={flow} onChange={(e) => setFlow(e.target.value)}>
{FLOW_OPTIONS.map((f) => (
<MenuItem key={f} value={f}>
{f}
</MenuItem>
))}
</Select>
</FormControl>
<FormControlLabel
control={<Checkbox checked={ignoreSelf} onChange={(e) => setIgnoreSelf(e.target.checked)} />}
label="Ignore self-transfers"
sx={{ mt: 0.25 }}
/>
</Box>
<Autocomplete
multiple
freeSolo
size="small"
options={accountOptions}
value={accounts}
onChange={(_, newVal) => setAccounts(newVal)}
renderInput={(params) => (
<TextField {...params} label="Accounts" placeholder="Restrict to accounts (empty = all)" />
)}
sx={{ maxWidth: 420 }}
/>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
<TextField
size="small"
label="Start date"
placeholder="DD-MM-YYYY"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
error={Boolean(dateErrors.start)}
helperText={dateErrors.start ?? "Inclusive start (empty = unbounded)"}
sx={{ width: 200 }}
/>
<TextField
size="small"
label="End date"
placeholder="DD-MM-YYYY"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
error={Boolean(dateErrors.end)}
helperText={dateErrors.end ?? "Inclusive end (empty = unbounded)"}
sx={{ width: 200 }}
/>
</Box>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
<TextField
size="small"
label="Min amount"
placeholder="e.g. 500"
value={minAmount}
onChange={(e) => setMinAmount(e.target.value)}
sx={{ width: 200 }}
/>
<TextField
size="small"
label="Max amount"
placeholder="e.g. 5000"
value={maxAmount}
onChange={(e) => setMaxAmount(e.target.value)}
sx={{ width: 200 }}
/>
</Box>
</Box>
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}> <Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
<Button type="submit" variant="contained" startIcon={<AddIcon />} disabled={submitting}> <Button variant="contained" startIcon={<AddIcon />} onClick={handleSubmit} disabled={submitting}>
{submitting ? "Generating…" : "Generate"} {submitting ? "Generating…" : "Generate"}
</Button> </Button>
</Box> </Box>
</Box>
</Paper> </Paper>
); );
} }

View File

@@ -51,7 +51,7 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
"&:hover": { borderColor: "primary.light" }, "&: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 }}> <Box sx={{ flex: "1 1 260px", minWidth: 0 }}>
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}> <Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}>
{report.name || report.id} {report.name || report.id}
@@ -81,14 +81,13 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
{amounts} {amounts}
</Typography> </Typography>
)} )}
</Box>
</Box>
{fields && ( {fields && (
<Box sx={{ ml: "auto", flexShrink: 0, color: "text.secondary" }}> <Box sx={{ color: "text.secondary" }}>
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} /> <ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
</Box> </Box>
)} )}
</Box>
</Box>
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}> <Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}> <Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>

View File

@@ -1,19 +1,14 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import React, { useEffect, useMemo, useRef, useState } from "react";
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material"; import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close"; import CloseIcon from "@mui/icons-material/Close";
import CachedIcon from "@mui/icons-material/Cached"; import CachedIcon from "@mui/icons-material/Cached";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"; import { FkMultiSelectField, useResource, formatCurrency } from "../../react-openapi";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import { FkMultiSelectField, useResource, formatCurrency, formatDateTime } from "../../react-openapi";
import type { FieldConfig } from "../../react-openapi"; import type { FieldConfig } from "../../react-openapi";
import { StatCard } from "../common/components/StatCard"; import { StatCard } from "../common/components/StatCard";
import { TransactionList } from "../common/components/TransactionList"; import { TransactionList } from "../common/components/TransactionList";
import type { TxnFieldConfigs } from "../common/types"; import type { TxnFieldConfigs } from "../common/types";
import type { ListPeriodGroup } from "../common/utils/transactions"; import { toPeriodGranularity } from "../common/utils/transactions";
import { buildDimensionBars, buildPeriodGroups, sliceSummary, FLOW_OPTIONS, apiErrorMessage } from "./types"; import { aggregateSlice, periodSlices, FLOW_OPTIONS, apiErrorMessage } from "./types";
import type { ReportDim } from "./types";
const MAX_VISIBLE_BARS = 10;
const periodField: FieldConfig = { const periodField: FieldConfig = {
name: "period", name: "period",
@@ -83,7 +78,6 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
const [reload, setReload] = useState(0); const [reload, setReload] = useState(0);
const [granularity, setGranularity] = useState<string | null>(null); const [granularity, setGranularity] = useState<string | null>(null);
const [flow, setFlow] = useState("outflows"); const [flow, setFlow] = useState("outflows");
const [dim, setDim] = useState<ReportDim>("period");
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]); const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
const [selectedPayees, setSelectedPayees] = useState<string[]>([]); const [selectedPayees, setSelectedPayees] = useState<string[]>([]);
const [selectedTags, setSelectedTags] = useState<string[]>([]); const [selectedTags, setSelectedTags] = useState<string[]>([]);
@@ -93,14 +87,10 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
const p: Record<string, any> = { flow }; const p: Record<string, any> = { flow };
if (granularity) p.granularity = [granularity]; if (granularity) p.granularity = [granularity];
if (selectedPeriods.length) p.period_ids = selectedPeriods; 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; if (selectedPayees.length) p.payee = selectedPayees;
else if (dim === "payee") p.payee = ["*"];
if (selectedTags.length) p.tags = selectedTags; if (selectedTags.length) p.tags = selectedTags;
else if (dim === "tag") p.tags = ["*"];
return p; return p;
}, [granularity, flow, dim, selectedPeriods, selectedPayees, selectedTags]); }, [granularity, flow, selectedPeriods, selectedPayees, selectedTags]);
useEffect(() => { useEffect(() => {
let mounted = true; let mounted = true;
@@ -153,57 +143,8 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags], [granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
); );
const periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]); const slice = useMemo(() => aggregateSlice(report?.buckets ?? [], filter), [report, filter]);
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]); const bars = useMemo(() => periodSlices(report?.buckets ?? [], filter), [report, filter]);
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 barsListRef = useRef<HTMLDivElement>(null);
const [barScroll, setBarScroll] = useState({ canUp: false, canDown: false, overflow: false });
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 && !report) {
return ( return (
@@ -231,16 +172,7 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
if (!report) return null; if (!report) return null;
const activeGranularity = granularity ?? report.granularities?.[0] ?? ""; const activeGranularity = granularity ?? report.granularities?.[0] ?? "";
const maxBar = bars.reduce((m, b) => Math.max(m, Math.abs(b.sum)), 0); const maxBar = bars.reduce((m, b) => Math.max(m, 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 = const range =
report.query?.start_date || report.query?.end_date report.query?.start_date || report.query?.end_date
? `range ${report.query.start_date || "…"} → ${report.query.end_date || "…"}` ? `range ${report.query.start_date || "…"} → ${report.query.end_date || "…"}`
@@ -266,7 +198,7 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
</Typography> </Typography>
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}> <Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
<Typography variant="caption" color="text.secondary"> <Typography variant="caption" color="text.secondary">
flow {report.flow} · generated {formatDateTime(report.generated_at ?? report.created_at)} flow {report.flow} · generated {report.generated_at ?? report.created_at}
</Typography> </Typography>
{range && ( {range && (
<Typography variant="caption" color="text.disabled"> <Typography variant="caption" color="text.disabled">
@@ -344,107 +276,24 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
</Box> </Box>
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}> <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="Outflows" value={formatCurrency(slice.spent, slice.currency)} color="error.main" />
<StatCard label="Inflows" value={formatCurrency(slice.inflows, slice.currency)} color="success.main" /> <StatCard label="Inflows" value={formatCurrency(slice.income, slice.currency)} color="success.main" />
<StatCard label="Net" value={formatCurrency(slice.inflows - slice.outflows, slice.currency)} color="info.main" /> <StatCard label="Net" value={formatCurrency(slice.income - slice.spent, slice.currency)} color="info.main" />
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} /> <StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
</Box> </Box>
<Box sx={{ mb: 2.5 }}> {bars.length === 0 ? (
<Box <Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mb: 2.5 }}>
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;
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>
);
})}
</Box>
{visibleBars.length === 0 ? (
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mt: 1.5 }}>
<Typography variant="body2" color="text.secondary"> <Typography variant="body2" color="text.secondary">
No data for this slice. Try another granularity, period or payer. No data for this slice. Try another granularity, period or payer.
</Typography> </Typography>
</Paper> </Paper>
) : ( ) : (
<Paper variant="outlined" sx={{ borderRadius: 2, mt: 1.5 }}> <Paper variant="outlined" sx={{ borderRadius: 2, p: 2, mb: 2.5 }}>
<Box sx={{ display: "flex", alignItems: "stretch" }}> {bars.map((b) => (
<Box <Box key={b.periodId} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
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" }}> <Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
{b.key} {b.periodId}
</Typography> </Typography>
<Box <Box
sx={{ sx={{
@@ -453,11 +302,8 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
bgcolor: flow === "outflows" ? "error.main" : "success.main", bgcolor: flow === "outflows" ? "error.main" : "success.main",
opacity: 0.85, opacity: 0.85,
minWidth: 4, minWidth: 4,
flexGrow: 0,
}}
style={{
width: `${maxBar ? Math.max((Math.abs(b.sum) / maxBar) * 100, 2) : 2}%`,
}} }}
style={{ width: `${maxBar ? Math.max((b.sum / maxBar) * 100, 2) : 2}%` }}
/> />
<Typography variant="body2" fontWeight={600}> <Typography variant="body2" fontWeight={600}>
{formatCurrency(b.sum, slice.currency)} {formatCurrency(b.sum, slice.currency)}
@@ -467,34 +313,16 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
</Typography> </Typography>
</Box> </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> </Paper>
)} )}
</Box>
{slice.txns.length === 0 ? null : fields ? ( {slice.txns.length === 0 ? null : fields ? (
<TransactionList fields={fields} groups={listGroups} showMetrics /> <TransactionList
items={slice.txns}
fields={fields}
granularity={toPeriodGranularity(activeGranularity)}
showMetrics
/>
) : null} ) : null}
</Box> </Box>
</Paper> </Paper>

View File

@@ -1,30 +1,6 @@
import type { FieldConfig, ResourceConfig } from "../../react-openapi"; import type { FieldConfig, ResourceConfig } from "../../react-openapi";
import { parseOccurredAt } 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 ReportPeriodGroup {
key: string;
metrics: PeriodMetricsVM;
txns: any[];
currency: string;
}
export interface SliceSummary { export interface SliceSummary {
outflows: number;
inflows: number;
sum: number; sum: number;
count: number; count: number;
avg: number | null; avg: number | null;
@@ -33,6 +9,8 @@ export interface SliceSummary {
firstDate: string | null; firstDate: string | null;
lastDate: string | null; lastDate: string | null;
txns: any[]; txns: any[];
spent: number;
income: number;
currency: string; currency: string;
} }
@@ -43,6 +21,14 @@ export interface SliceFilter {
tags?: string[]; tags?: string[];
} }
export interface PeriodSlice {
periodId: string;
sum: number;
count: number;
firstDate: string | null;
lastDate: string | null;
}
export interface ReportFieldConfigs { export interface ReportFieldConfigs {
name: FieldConfig; name: FieldConfig;
generatedAt: FieldConfig; generatedAt: FieldConfig;
@@ -65,6 +51,14 @@ export function apiErrorMessage(e: any): string {
return e?.message ?? "Request failed"; return e?.message ?? "Request failed";
} }
export function granularityOptions(schemas: Record<string, any>): string[] {
return schemas?.ReportQuery?.properties?.granularities?.items?.enum ?? [];
}
export function groupDimOptions(schemas: Record<string, any>): string[] {
return schemas?.ReportQuery?.properties?.group_dims?.items?.enum ?? ["payee", "tag"];
}
export const FLOW_OPTIONS = ["both", "inflows", "outflows"]; export const FLOW_OPTIONS = ["both", "inflows", "outflows"];
export function metricLabels(schemas: Record<string, any>): MetricLabel[] { export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
@@ -80,11 +74,8 @@ export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
} }
function dateVal(value: string): number { function dateVal(value: string): number {
try { const t = new Date(value).getTime();
return parseOccurredAt(value).getTime(); return Number.isNaN(t) ? 0 : t;
} catch {
return 0;
}
} }
function bucketMatches(bucket: any, filter: SliceFilter): boolean { function bucketMatches(bucket: any, filter: SliceFilter): boolean {
@@ -94,143 +85,78 @@ function bucketMatches(bucket: any, filter: SliceFilter): boolean {
return true; return true;
} }
function num(v: any): number | null { export function periodSlices(buckets: any[], filter: SliceFilter): PeriodSlice[] {
return typeof v === "number" && Number.isFinite(v) ? v : null; const byPeriod = new Map<string, PeriodSlice>();
}
/**
* 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 ?? []) { for (const bucket of buckets ?? []) {
if (!bucketMatches(bucket, filter)) continue; if (!bucketMatches(bucket, filter)) continue;
for (const period of bucket.series?.[filter.granularity] ?? []) { for (const period of bucket.series?.[filter.granularity] ?? []) {
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue; if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
const m = period.metrics ?? {}; const m = period.metrics ?? {};
let acc = byPeriod.get(period.period_id); const cur = byPeriod.get(period.period_id) ?? {
if (!acc) { periodId: period.period_id,
acc = {
metrics: {
outflows: 0,
inflows: 0,
sum: 0, sum: 0,
count: 0, count: 0,
avg: null,
min: null,
max: null,
firstDate: null, firstDate: null,
lastDate: null, lastDate: null,
cadence: null,
frequency: null,
},
txns: [],
sources: 0,
apiCadence: num(m.cadence),
apiFrequency: num(m.frequency),
}; };
byPeriod.set(period.period_id, acc); cur.sum += typeof m.sum === "number" ? m.sum : 0;
cur.count += typeof m.count === "number" ? m.count : 0;
if (m.first_date && (!cur.firstDate || dateVal(String(m.first_date)) < dateVal(cur.firstDate))) {
cur.firstDate = String(m.first_date);
} }
acc.sources += 1; if (m.last_date && (!cur.lastDate || dateVal(String(m.last_date)) > dateVal(cur.lastDate))) {
const vm = acc.metrics; cur.lastDate = String(m.last_date);
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))) { byPeriod.set(period.period_id, cur);
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.values()];
} }
return [...byPeriod.entries()] export function aggregateSlice(buckets: any[], filter: SliceFilter): SliceSummary {
.map(([key, acc]) => { let sum = 0;
const vm = acc.metrics; let count = 0;
vm.avg = vm.count ? Math.round((vm.sum / vm.count) * 100) / 100 : null; let spent = 0;
if (acc.sources > 1) { let income = 0;
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);
let min: number | null = null; let min: number | null = null;
let max: number | null = null; let max: number | null = null;
let firstDate: string | null = null; let firstDate: string | null = null;
let lastDate: string | null = null; let lastDate: string | null = null;
let currency = "INR"; let currency = "INR";
const txns: any[] = []; const txns: any[] = [];
for (const g of groups) { const seen = new Set<string>();
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); for (const bucket of buckets ?? []) {
if (g.metrics.firstDate && (!firstDate || dateVal(g.metrics.firstDate) < dateVal(firstDate))) { if (!bucketMatches(bucket, filter)) continue;
firstDate = g.metrics.firstDate; for (const period of bucket.series?.[filter.granularity] ?? []) {
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
const m = period.metrics ?? {};
if (typeof m.sum === "number") sum += m.sum;
if (typeof m.count === "number") count += m.count;
if (typeof m.min === "number") min = min === null ? m.min : Math.min(min, m.min);
if (typeof m.max === "number") max = max === null ? m.max : Math.max(max, m.max);
if (m.first_date && (!firstDate || dateVal(String(m.first_date)) < dateVal(firstDate))) {
firstDate = String(m.first_date);
} }
if (g.metrics.lastDate && (!lastDate || dateVal(g.metrics.lastDate) > dateVal(lastDate))) { if (m.last_date && (!lastDate || dateVal(String(m.last_date)) > dateVal(lastDate))) {
lastDate = g.metrics.lastDate; lastDate = String(m.last_date);
} }
if (g.currency) currency = g.currency; for (const txn of period.txns ?? []) {
txns.push(...g.txns); if (txn?.id != null) {
if (seen.has(txn.id)) continue;
seen.add(txn.id);
} }
return { outflows, inflows, sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, currency }; txns.push(txn);
const amt = Number(txn?.amount ?? 0);
if (amt < 0) spent += Math.abs(amt);
else income += amt;
const c = txn?.account?.currency;
if (c) currency = c;
}
}
}
return { sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, spent, income, currency };
} }
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null { export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
@@ -242,47 +168,3 @@ export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFiel
if (!name || !generatedAt) return null; if (!name || !generatedAt) return null;
return { name, generatedAt }; 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));
}

View File

@@ -15,58 +15,31 @@ import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import { formatCurrency } from "../../../react-openapi"; import { formatCurrency } from "../../../react-openapi";
import type { ExpenseItem, TxnFieldConfigs } from "../types"; import type { ExpenseItem, TxnFieldConfigs } from "../types";
import { computeTxnMetrics, groupByDate, groupByPeriod } from "../utils/transactions"; import { computeTxnMetrics, groupByDate, groupByPeriod } from "../utils/transactions";
import type { ListGroupMetrics, ListPeriodGroup, PeriodGranularity } from "../utils/transactions"; import type { PeriodGranularity } from "../utils/transactions";
import { TransactionRow } from "./TransactionRow"; import { TransactionRow } from "./TransactionRow";
import { StatCard } from "./StatCard"; import { StatCard } from "./StatCard";
interface TransactionListProps { interface TransactionListProps {
items?: ExpenseItem[]; items: ExpenseItem[];
fields: TxnFieldConfigs; fields: TxnFieldConfigs;
granularity?: PeriodGranularity; granularity?: PeriodGranularity;
showMetrics?: boolean; showMetrics?: boolean;
groups?: ListPeriodGroup[];
} }
function cadenceRow(cadenceDays: number | null, frequency: number | null): { label: string; value: string } { function GroupMetrics({ items, currency }: { items: ExpenseItem[]; currency: string }) {
const fmt = (v: number) => (Number.isInteger(v) ? String(v) : v.toFixed(2)); const m = computeTxnMetrics(items);
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 }[] = [ const rows: { label: string; value: string }[] = [
{ label: "Sum", value: formatCurrency(m.sum, currency) }, { label: "Sum", value: formatCurrency(m.sum, currency) },
{ label: "Avg", value: m.avg == null ? "—" : formatCurrency(m.avg, currency) }, { label: "Avg", value: m.avg == null ? "—" : formatCurrency(m.avg, currency) },
{ label: "Min", value: m.min == null ? "—" : formatCurrency(m.min, currency) }, { label: "Min", value: m.min == null ? "—" : formatCurrency(m.min, currency) },
{ label: "Max", value: m.max == null ? "—" : formatCurrency(m.max, currency) }, { label: "Max", value: m.max == null ? "—" : formatCurrency(m.max, currency) },
cadenceRow(m.cadence, m.frequency), {
label: "Cadence",
value:
m.cadenceDays == null
? "—"
: `${Number.isInteger(m.cadenceDays) ? m.cadenceDays : m.cadenceDays.toFixed(2)} days`,
},
]; ];
return ( return (
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", width: "100%" }}> <Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", width: "100%" }}>
@@ -77,20 +50,11 @@ function GroupMetrics({
); );
} }
export function TransactionList({ export function TransactionList({ items, fields, granularity = "monthly", showMetrics = false }: TransactionListProps) {
items,
fields,
granularity = "monthly",
showMetrics = false,
groups: externalGroups,
}: TransactionListProps) {
const [activeMonth, setActiveMonth] = useState<string | null>(null); const [activeMonth, setActiveMonth] = useState<string | null>(null);
const [openMonth, setOpenMonth] = useState<string | null>(null); const [openMonth, setOpenMonth] = useState<string | null>(null);
const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null); const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
const groups = useMemo<ListPeriodGroup[]>( const groups = useMemo(() => groupByPeriod(items, granularity), [items, granularity]);
() => externalGroups ?? groupByPeriod(items ?? [], granularity),
[externalGroups, items, granularity],
);
const listRef = useRef<HTMLDivElement>(null); const listRef = useRef<HTMLDivElement>(null);
const pillRef = useRef<HTMLDivElement>(null); const pillRef = useRef<HTMLDivElement>(null);
const didInitOpenMonth = useRef(false); const didInitOpenMonth = useRef(false);
@@ -223,9 +187,7 @@ export function TransactionList({
{formatCurrency(group.income, group.currency)} {formatCurrency(group.income, group.currency)}
</Typography> </Typography>
</Box> </Box>
{showMetrics && ( {showMetrics && <GroupMetrics items={group.items} currency={group.currency} />}
<GroupMetrics items={group.items} currency={group.currency} metrics={group.metrics} />
)}
</AccordionSummary> </AccordionSummary>
<AccordionDetails sx={{ p: 1.5, pt: 1 }}> <AccordionDetails sx={{ p: 1.5, pt: 1 }}>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}> <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>

View File

@@ -40,19 +40,10 @@ export interface PeriodGroup {
currency: string; currency: string;
} }
/** Metrics verbatim from the API's ReportMetrics (camelCased). */ export function toPeriodGranularity(value?: string): PeriodGranularity {
export interface ListGroupMetrics { return value === "weekly" || value === "monthly" || value === "quarterly" || value === "yearly"
sum: number; ? value
count: number; : "monthly";
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 { function isoWeekKey(d: Date): string {
@@ -124,13 +115,12 @@ export interface TxnMetrics {
min: number | null; min: number | null;
max: number | null; max: number | null;
cadenceDays: number | null; cadenceDays: number | null;
frequency: number | null;
} }
/** Mirrors backend ReportMetrics.compute_metrics over a list of transactions. */ /** Mirrors backend ReportMetrics.compute_metrics over a list of transactions. */
export function computeTxnMetrics(items: ExpenseItem[]): TxnMetrics { export function computeTxnMetrics(items: ExpenseItem[]): TxnMetrics {
const amounts = items.filter((it) => typeof it.amount === "number").map((it) => it.amount as number); 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 }; const empty = { sum: 0, count: 0, avg: null, min: null, max: null, cadenceDays: null };
if (amounts.length === 0) { if (amounts.length === 0) {
return empty; return empty;
} }
@@ -148,7 +138,6 @@ export function computeTxnMetrics(items: ExpenseItem[]): TxnMetrics {
} }
cadenceDays = Math.round((gaps.reduce((s, g) => s + g, 0) / gaps.length) * 100) / 100; 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 { return {
sum, sum,
count: amounts.length, count: amounts.length,
@@ -156,6 +145,5 @@ export function computeTxnMetrics(items: ExpenseItem[]): TxnMetrics {
min: Math.min(...amounts), min: Math.min(...amounts),
max: Math.max(...amounts), max: Math.max(...amounts),
cadenceDays, cadenceDays,
frequency,
}; };
} }

View File

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

View File

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