Compare commits
9 Commits
1.2.0
...
6b340d89f6
| Author | SHA1 | Date | |
|---|---|---|---|
| 6b340d89f6 | |||
| 79808d6d3e | |||
| f865f7dec2 | |||
| fc3a48a367 | |||
| f9759e3968 | |||
| 47c00a06a8 | |||
| a107029b90 | |||
| baa9b296cb | |||
| f08bc72037 |
@@ -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";
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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";
|
||||||
|
|||||||
@@ -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}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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 };
|
|
||||||
}
|
|
||||||
@@ -136,10 +136,7 @@ export function extractFields(schemaName: string, schema: any, schemas: Record<s
|
|||||||
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"],
|
||||||
|
|||||||
@@ -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 {
|
||||||
@@ -108,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;
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
@@ -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}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
<Box>
|
||||||
<Button type="submit" variant="contained" startIcon={<AddIcon />} disabled={submitting}>
|
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
|
||||||
{submitting ? "Generating…" : "Generate"}
|
Granularities
|
||||||
</Button>
|
</Typography>
|
||||||
|
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||||
|
{granularityChoices.map((g) => (
|
||||||
|
<Chip
|
||||||
|
key={g}
|
||||||
|
label={g}
|
||||||
|
clickable
|
||||||
|
color={granularities.includes(g) ? "primary" : "default"}
|
||||||
|
variant={granularities.includes(g) ? "filled" : "outlined"}
|
||||||
|
onClick={() => toggle(granularities, g, setGranularities)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Typography variant="subtitle2" sx={{ mb: 0.5 }}>
|
||||||
|
Group dimensions
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||||
|
{dimChoices.map((d) => (
|
||||||
|
<Chip
|
||||||
|
key={d}
|
||||||
|
label={d}
|
||||||
|
clickable
|
||||||
|
color={groupDims.includes(d) ? "primary" : "default"}
|
||||||
|
variant={groupDims.includes(d) ? "filled" : "outlined"}
|
||||||
|
onClick={() => toggle(groupDims, d, setGroupDims)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "flex-start" }}>
|
||||||
|
<FormControl size="small" sx={{ width: 200 }}>
|
||||||
|
<InputLabel id="flow-label">Flow</InputLabel>
|
||||||
|
<Select labelId="flow-label" label="Flow" value={flow} onChange={(e) => setFlow(e.target.value)}>
|
||||||
|
{FLOW_OPTIONS.map((f) => (
|
||||||
|
<MenuItem key={f} value={f}>
|
||||||
|
{f}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
<FormControlLabel
|
||||||
|
control={<Checkbox checked={ignoreSelf} onChange={(e) => setIgnoreSelf(e.target.checked)} />}
|
||||||
|
label="Ignore self-transfers"
|
||||||
|
sx={{ mt: 0.25 }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Autocomplete
|
||||||
|
multiple
|
||||||
|
freeSolo
|
||||||
|
size="small"
|
||||||
|
options={accountOptions}
|
||||||
|
value={accounts}
|
||||||
|
onChange={(_, newVal) => setAccounts(newVal)}
|
||||||
|
renderInput={(params) => (
|
||||||
|
<TextField {...params} label="Accounts" placeholder="Restrict to accounts (empty = all)" />
|
||||||
|
)}
|
||||||
|
sx={{ maxWidth: 420 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label="Start date"
|
||||||
|
placeholder="DD-MM-YYYY"
|
||||||
|
value={startDate}
|
||||||
|
onChange={(e) => setStartDate(e.target.value)}
|
||||||
|
error={Boolean(dateErrors.start)}
|
||||||
|
helperText={dateErrors.start ?? "Inclusive start (empty = unbounded)"}
|
||||||
|
sx={{ width: 200 }}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label="End date"
|
||||||
|
placeholder="DD-MM-YYYY"
|
||||||
|
value={endDate}
|
||||||
|
onChange={(e) => setEndDate(e.target.value)}
|
||||||
|
error={Boolean(dateErrors.end)}
|
||||||
|
helperText={dateErrors.end ?? "Inclusive end (empty = unbounded)"}
|
||||||
|
sx={{ width: 200 }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label="Min amount"
|
||||||
|
placeholder="e.g. 500"
|
||||||
|
value={minAmount}
|
||||||
|
onChange={(e) => setMinAmount(e.target.value)}
|
||||||
|
sx={{ width: 200 }}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
size="small"
|
||||||
|
label="Max amount"
|
||||||
|
placeholder="e.g. 5000"
|
||||||
|
value={maxAmount}
|
||||||
|
onChange={(e) => setMaxAmount(e.target.value)}
|
||||||
|
sx={{ width: 200 }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
||||||
|
<Button variant="contained" startIcon={<AddIcon />} onClick={handleSubmit} disabled={submitting}>
|
||||||
|
{submitting ? "Generating…" : "Generate"}
|
||||||
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -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 KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
|
|
||||||
import { FkMultiSelectField, useResource, formatCurrency } from "../../react-openapi";
|
import { FkMultiSelectField, useResource, formatCurrency } 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 || "…"}`
|
||||||
@@ -344,157 +276,53 @@ 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={{
|
<Typography variant="body2" color="text.secondary">
|
||||||
position: "relative",
|
No data for this slice. Try another granularity, period or payer.
|
||||||
display: "flex",
|
</Typography>
|
||||||
alignItems: "stretch",
|
</Paper>
|
||||||
width: "fit-content",
|
) : (
|
||||||
maxWidth: "100%",
|
<Paper variant="outlined" sx={{ borderRadius: 2, p: 2, mb: 2.5 }}>
|
||||||
border: "1px solid",
|
{bars.map((b) => (
|
||||||
borderColor: "divider",
|
<Box key={b.periodId} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
||||||
borderRadius: "999px",
|
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
||||||
p: 0.5,
|
{b.periodId}
|
||||||
backgroundColor: "background.default",
|
</Typography>
|
||||||
}}
|
|
||||||
>
|
|
||||||
<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
|
<Box
|
||||||
key={d.id}
|
|
||||||
component="button"
|
|
||||||
type="button"
|
|
||||||
disabled={d.count <= 1}
|
|
||||||
onClick={() => setDim(d.id)}
|
|
||||||
sx={{
|
sx={{
|
||||||
position: "relative",
|
height: 20,
|
||||||
zIndex: 1,
|
borderRadius: 1,
|
||||||
flex: 1,
|
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
||||||
border: "none",
|
opacity: 0.85,
|
||||||
background: "transparent",
|
minWidth: 4,
|
||||||
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" },
|
|
||||||
}}
|
}}
|
||||||
>
|
style={{ width: `${maxBar ? Math.max((b.sum / maxBar) * 100, 2) : 2}%` }}
|
||||||
{d.label}
|
/>
|
||||||
</Box>
|
<Typography variant="body2" fontWeight={600}>
|
||||||
);
|
{formatCurrency(b.sum, slice.currency)}
|
||||||
})}
|
</Typography>
|
||||||
</Box>
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{b.count} txn{b.count === 1 ? "" : "s"}
|
||||||
{visibleBars.length === 0 ? (
|
</Typography>
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mt: 1.5 }}>
|
|
||||||
<Typography variant="body2" color="text.secondary">
|
|
||||||
No data for this slice. Try another granularity, period or payer.
|
|
||||||
</Typography>
|
|
||||||
</Paper>
|
|
||||||
) : (
|
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, 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>
|
</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>
|
||||||
|
|||||||
@@ -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 = {
|
sum: 0,
|
||||||
metrics: {
|
count: 0,
|
||||||
outflows: 0,
|
firstDate: null,
|
||||||
inflows: 0,
|
lastDate: null,
|
||||||
sum: 0,
|
};
|
||||||
count: 0,
|
cur.sum += typeof m.sum === "number" ? m.sum : 0;
|
||||||
avg: null,
|
cur.count += typeof m.count === "number" ? m.count : 0;
|
||||||
min: null,
|
if (m.first_date && (!cur.firstDate || dateVal(String(m.first_date)) < dateVal(cur.firstDate))) {
|
||||||
max: null,
|
cur.firstDate = String(m.first_date);
|
||||||
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;
|
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))) {
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
byPeriod.set(period.period_id, cur);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return [...byPeriod.values()];
|
||||||
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 {
|
export function aggregateSlice(buckets: any[], filter: SliceFilter): SliceSummary {
|
||||||
const outflows = groups.reduce((s, g) => s + g.metrics.outflows, 0);
|
let sum = 0;
|
||||||
const inflows = groups.reduce((s, g) => s + g.metrics.inflows, 0);
|
let count = 0;
|
||||||
const sum = groups.reduce((s, g) => s + g.metrics.sum, 0);
|
let spent = 0;
|
||||||
const count = groups.reduce((s, g) => s + g.metrics.count, 0);
|
let income = 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 (m.last_date && (!lastDate || dateVal(String(m.last_date)) > dateVal(lastDate))) {
|
||||||
|
lastDate = String(m.last_date);
|
||||||
|
}
|
||||||
|
for (const txn of period.txns ?? []) {
|
||||||
|
if (txn?.id != null) {
|
||||||
|
if (seen.has(txn.id)) continue;
|
||||||
|
seen.add(txn.id);
|
||||||
|
}
|
||||||
|
txns.push(txn);
|
||||||
|
const amt = Number(txn?.amount ?? 0);
|
||||||
|
if (amt < 0) spent += Math.abs(amt);
|
||||||
|
else income += amt;
|
||||||
|
const c = txn?.account?.currency;
|
||||||
|
if (c) currency = c;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (g.metrics.lastDate && (!lastDate || dateVal(g.metrics.lastDate) > dateVal(lastDate))) {
|
|
||||||
lastDate = g.metrics.lastDate;
|
|
||||||
}
|
|
||||||
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 buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
||||||
@@ -241,48 +167,4 @@ export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFiel
|
|||||||
const generatedAt = find("generated_at");
|
const generatedAt = find("generated_at");
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
@@ -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 }}>
|
||||||
|
|||||||
@@ -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,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user