Compare commits
2 Commits
6b340d89f6
...
1.2.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 9377460e79 | |||
| 2add23efe7 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -14,3 +14,4 @@ dist
|
|||||||
dist-ssr
|
dist-ssr
|
||||||
*.local
|
*.local
|
||||||
.idea
|
.idea
|
||||||
|
tsconfig.tsbuildinfo
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ 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,6 +6,7 @@ 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";
|
||||||
@@ -81,6 +82,17 @@ 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,4 +3,5 @@ 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";
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
82
react-openapi/src/hooks/useFkFieldOptions.ts
Normal file
82
react-openapi/src/hooks/useFkFieldOptions.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
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,7 +136,10 @@ 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),
|
||||||
enumValues: prop.enum,
|
// Lift enum constraints from array items so arrays-of-enum can render
|
||||||
|
// as multi-selects (e.g. ReportQuery.granularities).
|
||||||
|
enumValues: prop.enum ?? (prop.type === "array" ? prop.items?.enum : undefined),
|
||||||
|
defaultValue: prop.default,
|
||||||
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,6 +85,8 @@ 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 {
|
||||||
@@ -106,6 +108,8 @@ 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,7 +29,9 @@ export async function sanitizePayload(
|
|||||||
|
|
||||||
const val = result[key];
|
const val = result[key];
|
||||||
|
|
||||||
if (field.fk) {
|
// FK fields whose wire value is a plain target property (fk.value, e.g.
|
||||||
|
// account names) are already in wire format — no id→object resolution.
|
||||||
|
if (field.fk && !field.fk.value) {
|
||||||
if (val == null || val === "") {
|
if (val == null || val === "") {
|
||||||
result[key] = null;
|
result[key] = null;
|
||||||
} else if (resolveFk) {
|
} else if (resolveFk) {
|
||||||
|
|||||||
@@ -1,22 +1,32 @@
|
|||||||
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,
|
CircularProgress, IconButton, Tooltip,
|
||||||
} 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 { 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", "start_date", "end_date", "source"];
|
const CREATE_FIELDS = ["account", "bank", "pipeline", "start_date", "end_date", "source"];
|
||||||
|
|
||||||
function FetchRequestList() {
|
function FetchRequestList() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { list, resource } = useResource("fetch-requests");
|
const { list, remove, 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 [];
|
||||||
@@ -30,6 +40,26 @@ 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 }}>
|
||||||
@@ -82,6 +112,18 @@ function FetchRequestList() {
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
))}
|
))}
|
||||||
|
<Box sx={{ ml: "auto", 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>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
@@ -94,6 +136,7 @@ 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);
|
||||||
@@ -143,6 +186,10 @@ 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");
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ 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";
|
||||||
@@ -18,6 +19,7 @@ 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";
|
||||||
@@ -85,11 +87,12 @@ 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, resource } = useResource("fetch-requests");
|
const { get, patch, remove, 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);
|
||||||
|
|
||||||
@@ -174,6 +177,26 @@ 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;
|
||||||
@@ -286,6 +309,20 @@ 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>
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,12 @@ function computeProgressPercent(
|
|||||||
|
|
||||||
let pct = 0;
|
let pct = 0;
|
||||||
|
|
||||||
if (seenSteps.has("raw_lines") || seenSteps.has("txn_blocks")) pct += 10;
|
if (
|
||||||
|
seenSteps.has("raw_lines") ||
|
||||||
|
seenSteps.has("txn_blocks")
|
||||||
|
) {
|
||||||
|
pct += 10;
|
||||||
|
}
|
||||||
|
|
||||||
if (txnBlockCount > 0) {
|
if (txnBlockCount > 0) {
|
||||||
const current = Math.max(liveCount, stepStats.txn_dicts ?? 0);
|
const current = Math.max(liveCount, stepStats.txn_dicts ?? 0);
|
||||||
|
|||||||
@@ -1,131 +1,85 @@
|
|||||||
import React, { useEffect, useMemo, useState } from "react";
|
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
Paper,
|
Paper,
|
||||||
Typography,
|
Typography,
|
||||||
TextField,
|
|
||||||
Button,
|
Button,
|
||||||
MenuItem,
|
Grid,
|
||||||
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 { useResource, useAppContext, applyDisplayFormat } from "../../react-openapi";
|
import {
|
||||||
|
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 { isDdmmyyyy } from "../common/utils/dates";
|
import { apiErrorMessage } from "./types";
|
||||||
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, resources } = useAppContext();
|
const { schemas } = useAppContext();
|
||||||
const { create } = useResource("reports");
|
const { create, loading: submitting } = useResource("reports");
|
||||||
const { list: listAccounts } = useResource("accounts");
|
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
|
|
||||||
const [name, setName] = useState("");
|
const [formData, setFormData] = useState<Record<string, any>>({});
|
||||||
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 granularityChoices = useMemo(() => {
|
const fields: FieldConfig[] = useMemo(() => {
|
||||||
const enums = granularityOptions(schemas);
|
const schema = schemas?.ReportQuery;
|
||||||
return enums.length ? enums : ALL_GRANULARITIES;
|
if (!schema) return [];
|
||||||
|
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 accountsRes = resources.find((r) => r.name === "accounts");
|
const { fkOptions, fkLoading, loadFkOnOpen } = useFkFieldOptions(fields);
|
||||||
const accountsFormat = accountsRes?.displayFormat ?? "{name}";
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
setFormData((prev) => {
|
||||||
listAccounts({ limit: 0 }).then((res) => {
|
const next = { ...prev };
|
||||||
if (!mounted) return;
|
let changed = false;
|
||||||
const names = (res.items ?? [])
|
for (const f of fields) {
|
||||||
.map((it: any) => applyDisplayFormat(it, accountsFormat))
|
if (next[f.name] === undefined && f.defaultValue !== undefined) {
|
||||||
.filter((n: string) => n);
|
next[f.name] = Array.isArray(f.defaultValue) ? [...f.defaultValue] : f.defaultValue;
|
||||||
setAccountOptions([...new Set(names)].sort((a, b) => a.localeCompare(b)));
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed ? next : prev;
|
||||||
});
|
});
|
||||||
return () => {
|
}, [fields]);
|
||||||
mounted = false;
|
|
||||||
};
|
|
||||||
}, [listAccounts, accountsFormat]);
|
|
||||||
|
|
||||||
const toggle = (list: string[], value: string, setter: (v: string[]) => void) =>
|
const handleChange = useCallback((name: string, value: any) => {
|
||||||
setter(list.includes(value) ? list.filter((v) => v !== value) : [...list, value]);
|
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||||
|
|
||||||
const validateDates = (): boolean => {
|
|
||||||
const errs: { start?: string; end?: string } = {};
|
|
||||||
if (startDate && !isDdmmyyyy(startDate)) errs.start = "Use DD-MM-YYYY";
|
|
||||||
if (endDate && !isDdmmyyyy(endDate)) errs.end = "Use DD-MM-YYYY";
|
|
||||||
setDateErrors(errs);
|
|
||||||
return Object.keys(errs).length === 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
const parseAmount = (value: string): number | null => {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (!trimmed) return null;
|
|
||||||
const n = Number(trimmed);
|
|
||||||
return Number.isFinite(n) ? n : null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
|
||||||
if (!validateDates()) return;
|
|
||||||
setError(null);
|
setError(null);
|
||||||
const min = parseAmount(minAmount);
|
}, []);
|
||||||
const max = parseAmount(maxAmount);
|
|
||||||
if (minAmount.trim() && min === null) {
|
const buildPayload = (): Record<string, any> => {
|
||||||
setError("Min amount must be a number");
|
const payload: Record<string, any> = {};
|
||||||
return;
|
for (const f of fields) {
|
||||||
|
const v = formData[f.name];
|
||||||
|
if (v === undefined || v === null || v === "") continue;
|
||||||
|
if (Array.isArray(v) && v.length === 0) continue;
|
||||||
|
payload[f.name] = v;
|
||||||
}
|
}
|
||||||
if (maxAmount.trim() && max === null) {
|
return payload;
|
||||||
setError("Max amount must be a number");
|
};
|
||||||
return;
|
|
||||||
}
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
if (min !== null && max !== null && min > max) {
|
e.preventDefault();
|
||||||
setError("Min amount cannot exceed max amount");
|
setError(null);
|
||||||
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(payload);
|
const created = await create(buildPayload());
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -145,130 +99,27 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
|||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
<Box component="form" onSubmit={handleSubmit}>
|
||||||
<TextField
|
<Grid container spacing={2}>
|
||||||
size="small"
|
{fields.map((field) => (
|
||||||
label="Name"
|
<Grid item xs={12} sm={6} md={4} key={field.name}>
|
||||||
placeholder="e.g. Monthly spending"
|
<FormFieldRenderer
|
||||||
value={name}
|
field={field}
|
||||||
onChange={(e) => setName(e.target.value)}
|
value={formData[field.name]}
|
||||||
sx={{ maxWidth: 420 }}
|
onChange={(val) => handleChange(field.name, val)}
|
||||||
/>
|
fkOptions={fkOptions[field.name]}
|
||||||
|
fkLoading={fkLoading[field.name]}
|
||||||
<Box>
|
onFkOpen={loadFkOnOpen}
|
||||||
<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>
|
||||||
</Box>
|
))}
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
||||||
|
<Button type="submit" variant="contained" startIcon={<AddIcon />} disabled={submitting}>
|
||||||
|
{submitting ? "Generating…" : "Generate"}
|
||||||
|
</Button>
|
||||||
</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,14 +1,19 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
|
import { 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 { toPeriodGranularity } from "../common/utils/transactions";
|
import type { ListPeriodGroup } from "../common/utils/transactions";
|
||||||
import { aggregateSlice, periodSlices, FLOW_OPTIONS, apiErrorMessage } from "./types";
|
import { buildDimensionBars, buildPeriodGroups, sliceSummary, 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",
|
||||||
@@ -78,6 +83,7 @@ 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[]>([]);
|
||||||
@@ -87,10 +93,14 @@ 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, selectedPeriods, selectedPayees, selectedTags]);
|
}, [granularity, flow, dim, selectedPeriods, selectedPayees, selectedTags]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
@@ -143,8 +153,57 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
|
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
|
||||||
);
|
);
|
||||||
|
|
||||||
const slice = useMemo(() => aggregateSlice(report?.buckets ?? [], filter), [report, filter]);
|
const periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]);
|
||||||
const bars = useMemo(() => periodSlices(report?.buckets ?? [], filter), [report, filter]);
|
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]);
|
||||||
|
const bars = useMemo(() => buildDimensionBars(report?.buckets ?? [], filter, dim), [report, filter, dim]);
|
||||||
|
const visibleBars = useMemo(() => bars.slice(0, MAX_VISIBLE_BARS), [bars]);
|
||||||
|
const listGroups = useMemo<ListPeriodGroup[]>(
|
||||||
|
() =>
|
||||||
|
periodGroups.map((g) => ({
|
||||||
|
key: g.key,
|
||||||
|
label: g.key,
|
||||||
|
items: g.txns,
|
||||||
|
spent: g.metrics.outflows,
|
||||||
|
income: g.metrics.inflows,
|
||||||
|
currency: g.currency,
|
||||||
|
metrics: {
|
||||||
|
sum: g.metrics.sum,
|
||||||
|
count: g.metrics.count,
|
||||||
|
avg: g.metrics.avg,
|
||||||
|
min: g.metrics.min,
|
||||||
|
max: g.metrics.max,
|
||||||
|
cadence: g.metrics.cadence,
|
||||||
|
frequency: g.metrics.frequency,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
[periodGroups],
|
||||||
|
);
|
||||||
|
|
||||||
|
const 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 (
|
||||||
@@ -172,7 +231,16 @@ 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, b.sum), 0);
|
const maxBar = bars.reduce((m, b) => Math.max(m, Math.abs(b.sum)), 0);
|
||||||
|
const dimOptions: { id: ReportDim; label: string; count: number }[] = [
|
||||||
|
{ id: "period", label: "Period", count: report.period_ids?.length ?? 0 },
|
||||||
|
{ id: "payee", label: "Payees", count: report.payees?.length ?? 0 },
|
||||||
|
{ id: "tag", label: "Tags", count: report.tags?.length ?? 0 },
|
||||||
|
];
|
||||||
|
const activeDimIndex = Math.max(
|
||||||
|
0,
|
||||||
|
dimOptions.findIndex((d) => d.id === dim),
|
||||||
|
);
|
||||||
const range =
|
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 || "…"}`
|
||||||
@@ -276,53 +344,157 @@ 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.spent, slice.currency)} color="error.main" />
|
<StatCard label="Outflows" value={formatCurrency(slice.outflows, slice.currency)} color="error.main" />
|
||||||
<StatCard label="Inflows" value={formatCurrency(slice.income, slice.currency)} color="success.main" />
|
<StatCard label="Inflows" value={formatCurrency(slice.inflows, slice.currency)} color="success.main" />
|
||||||
<StatCard label="Net" value={formatCurrency(slice.income - slice.spent, slice.currency)} color="info.main" />
|
<StatCard label="Net" value={formatCurrency(slice.inflows - slice.outflows, 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>
|
||||||
|
|
||||||
{bars.length === 0 ? (
|
<Box sx={{ mb: 2.5 }}>
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mb: 2.5 }}>
|
<Box
|
||||||
<Typography variant="body2" color="text.secondary">
|
sx={{
|
||||||
No data for this slice. Try another granularity, period or payer.
|
position: "relative",
|
||||||
</Typography>
|
display: "flex",
|
||||||
</Paper>
|
alignItems: "stretch",
|
||||||
) : (
|
width: "fit-content",
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 2, mb: 2.5 }}>
|
maxWidth: "100%",
|
||||||
{bars.map((b) => (
|
border: "1px solid",
|
||||||
<Box key={b.periodId} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
borderColor: "divider",
|
||||||
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
borderRadius: "999px",
|
||||||
{b.periodId}
|
p: 0.5,
|
||||||
</Typography>
|
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
|
<Box
|
||||||
|
key={d.id}
|
||||||
|
component="button"
|
||||||
|
type="button"
|
||||||
|
disabled={d.count <= 1}
|
||||||
|
onClick={() => setDim(d.id)}
|
||||||
sx={{
|
sx={{
|
||||||
height: 20,
|
position: "relative",
|
||||||
borderRadius: 1,
|
zIndex: 1,
|
||||||
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
flex: 1,
|
||||||
opacity: 0.85,
|
border: "none",
|
||||||
minWidth: 4,
|
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" },
|
||||||
}}
|
}}
|
||||||
style={{ width: `${maxBar ? Math.max((b.sum / maxBar) * 100, 2) : 2}%` }}
|
>
|
||||||
/>
|
{d.label}
|
||||||
<Typography variant="body2" fontWeight={600}>
|
</Box>
|
||||||
{formatCurrency(b.sum, slice.currency)}
|
);
|
||||||
</Typography>
|
})}
|
||||||
<Typography variant="caption" color="text.disabled">
|
</Box>
|
||||||
{b.count} txn{b.count === 1 ? "" : "s"}
|
|
||||||
</Typography>
|
{visibleBars.length === 0 ? (
|
||||||
|
<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
|
<TransactionList fields={fields} groups={listGroups} showMetrics />
|
||||||
items={slice.txns}
|
|
||||||
fields={fields}
|
|
||||||
granularity={toPeriodGranularity(activeGranularity)}
|
|
||||||
showMetrics
|
|
||||||
/>
|
|
||||||
) : null}
|
) : null}
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|||||||
@@ -1,6 +1,30 @@
|
|||||||
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;
|
||||||
@@ -9,8 +33,6 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,14 +43,6 @@ 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;
|
||||||
@@ -51,14 +65,6 @@ 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[] {
|
||||||
@@ -74,8 +80,11 @@ export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function dateVal(value: string): number {
|
function dateVal(value: string): number {
|
||||||
const t = new Date(value).getTime();
|
try {
|
||||||
return Number.isNaN(t) ? 0 : t;
|
return parseOccurredAt(value).getTime();
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
||||||
@@ -85,78 +94,143 @@ function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function periodSlices(buckets: any[], filter: SliceFilter): PeriodSlice[] {
|
function num(v: any): number | null {
|
||||||
const byPeriod = new Map<string, PeriodSlice>();
|
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
||||||
for (const bucket of buckets ?? []) {
|
|
||||||
if (!bucketMatches(bucket, filter)) continue;
|
|
||||||
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
|
||||||
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
|
||||||
const m = period.metrics ?? {};
|
|
||||||
const cur = byPeriod.get(period.period_id) ?? {
|
|
||||||
periodId: period.period_id,
|
|
||||||
sum: 0,
|
|
||||||
count: 0,
|
|
||||||
firstDate: null,
|
|
||||||
lastDate: null,
|
|
||||||
};
|
|
||||||
cur.sum += typeof m.sum === "number" ? m.sum : 0;
|
|
||||||
cur.count += typeof m.count === "number" ? m.count : 0;
|
|
||||||
if (m.first_date && (!cur.firstDate || dateVal(String(m.first_date)) < dateVal(cur.firstDate))) {
|
|
||||||
cur.firstDate = String(m.first_date);
|
|
||||||
}
|
|
||||||
if (m.last_date && (!cur.lastDate || dateVal(String(m.last_date)) > dateVal(cur.lastDate))) {
|
|
||||||
cur.lastDate = String(m.last_date);
|
|
||||||
}
|
|
||||||
byPeriod.set(period.period_id, cur);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return [...byPeriod.values()];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function aggregateSlice(buckets: any[], filter: SliceFilter): SliceSummary {
|
/**
|
||||||
let sum = 0;
|
* Groups cube periods by their canonical period_id, merging buckets per
|
||||||
let count = 0;
|
* period. The server returns disjoint slices, so additive metric merge is
|
||||||
let spent = 0;
|
* safe; txn ids are deduped defensively. Metrics come verbatim from the API
|
||||||
let income = 0;
|
* except when multiple buckets contribute to one period — then cadence and
|
||||||
let min: number | null = null;
|
* frequency are re-derived from the merged txn dates.
|
||||||
let max: number | null = null;
|
*/
|
||||||
let firstDate: string | null = null;
|
export function buildPeriodGroups(buckets: any[], filter: SliceFilter): ReportPeriodGroup[] {
|
||||||
let lastDate: string | null = null;
|
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";
|
let currency = "INR";
|
||||||
const txns: any[] = [];
|
|
||||||
const seen = new Set<string>();
|
|
||||||
|
|
||||||
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 ?? {};
|
||||||
if (typeof m.sum === "number") sum += m.sum;
|
let acc = byPeriod.get(period.period_id);
|
||||||
if (typeof m.count === "number") count += m.count;
|
if (!acc) {
|
||||||
if (typeof m.min === "number") min = min === null ? m.min : Math.min(min, m.min);
|
acc = {
|
||||||
if (typeof m.max === "number") max = max === null ? m.max : Math.max(max, m.max);
|
metrics: {
|
||||||
if (m.first_date && (!firstDate || dateVal(String(m.first_date)) < dateVal(firstDate))) {
|
outflows: 0,
|
||||||
firstDate = String(m.first_date);
|
inflows: 0,
|
||||||
|
sum: 0,
|
||||||
|
count: 0,
|
||||||
|
avg: null,
|
||||||
|
min: null,
|
||||||
|
max: null,
|
||||||
|
firstDate: null,
|
||||||
|
lastDate: null,
|
||||||
|
cadence: null,
|
||||||
|
frequency: null,
|
||||||
|
},
|
||||||
|
txns: [],
|
||||||
|
sources: 0,
|
||||||
|
apiCadence: num(m.cadence),
|
||||||
|
apiFrequency: num(m.frequency),
|
||||||
|
};
|
||||||
|
byPeriod.set(period.period_id, acc);
|
||||||
}
|
}
|
||||||
if (m.last_date && (!lastDate || dateVal(String(m.last_date)) > dateVal(lastDate))) {
|
acc.sources += 1;
|
||||||
lastDate = String(m.last_date);
|
const vm = acc.metrics;
|
||||||
|
vm.outflows += m.outflows ?? 0;
|
||||||
|
vm.inflows += m.inflows ?? 0;
|
||||||
|
vm.sum += m.sum ?? 0;
|
||||||
|
vm.count += m.count ?? 0;
|
||||||
|
const mn = num(m.min);
|
||||||
|
if (mn != null) vm.min = vm.min == null ? mn : Math.min(vm.min, mn);
|
||||||
|
const mx = num(m.max);
|
||||||
|
if (mx != null) vm.max = vm.max == null ? mx : Math.max(vm.max, mx);
|
||||||
|
if (m.first_date && (!vm.firstDate || dateVal(String(m.first_date)) < dateVal(vm.firstDate))) {
|
||||||
|
vm.firstDate = String(m.first_date);
|
||||||
|
}
|
||||||
|
if (m.last_date && (!vm.lastDate || dateVal(String(m.last_date)) > dateVal(vm.lastDate))) {
|
||||||
|
vm.lastDate = String(m.last_date);
|
||||||
}
|
}
|
||||||
for (const txn of period.txns ?? []) {
|
for (const txn of period.txns ?? []) {
|
||||||
if (txn?.id != null) {
|
if (txn?.id != null) {
|
||||||
if (seen.has(txn.id)) continue;
|
if (seenTxnIds.has(txn.id)) continue;
|
||||||
seen.add(txn.id);
|
seenTxnIds.add(txn.id);
|
||||||
}
|
}
|
||||||
txns.push(txn);
|
acc.txns.push(txn);
|
||||||
const amt = Number(txn?.amount ?? 0);
|
|
||||||
if (amt < 0) spent += Math.abs(amt);
|
|
||||||
else income += amt;
|
|
||||||
const c = txn?.account?.currency;
|
const c = txn?.account?.currency;
|
||||||
if (c) currency = c;
|
if (c) currency = c;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, spent, income, currency };
|
return [...byPeriod.entries()]
|
||||||
|
.map(([key, acc]) => {
|
||||||
|
const vm = acc.metrics;
|
||||||
|
vm.avg = vm.count ? Math.round((vm.sum / vm.count) * 100) / 100 : null;
|
||||||
|
if (acc.sources > 1) {
|
||||||
|
const dates = acc.txns
|
||||||
|
.map((t) => {
|
||||||
|
try {
|
||||||
|
return parseOccurredAt(t?.occurred_at).getTime();
|
||||||
|
} catch {
|
||||||
|
return NaN;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((t) => !Number.isNaN(t))
|
||||||
|
.sort((a, b) => a - b);
|
||||||
|
if (dates.length >= 2) {
|
||||||
|
let gapSum = 0;
|
||||||
|
for (let i = 0; i < dates.length - 1; i += 1) gapSum += (dates[i + 1] - dates[i]) / 86400000;
|
||||||
|
const cadence = Math.round((gapSum / (dates.length - 1)) * 100) / 100;
|
||||||
|
vm.cadence = cadence > 0 ? cadence : null;
|
||||||
|
vm.frequency = cadence > 0 ? Math.round((1 / cadence) * 100) / 100 : null;
|
||||||
|
} else {
|
||||||
|
vm.cadence = null;
|
||||||
|
vm.frequency = null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
vm.cadence = acc.apiCadence;
|
||||||
|
vm.frequency = acc.apiFrequency;
|
||||||
|
}
|
||||||
|
return { key, metrics: vm, txns: acc.txns, currency };
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.key.localeCompare(a.key));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sliceSummary(groups: ReportPeriodGroup[]): SliceSummary {
|
||||||
|
const outflows = groups.reduce((s, g) => s + g.metrics.outflows, 0);
|
||||||
|
const inflows = groups.reduce((s, g) => s + g.metrics.inflows, 0);
|
||||||
|
const sum = groups.reduce((s, g) => s + g.metrics.sum, 0);
|
||||||
|
const count = groups.reduce((s, g) => s + g.metrics.count, 0);
|
||||||
|
let min: number | null = null;
|
||||||
|
let max: number | null = null;
|
||||||
|
let firstDate: string | null = null;
|
||||||
|
let lastDate: string | null = null;
|
||||||
|
let currency = "INR";
|
||||||
|
const txns: any[] = [];
|
||||||
|
for (const g of groups) {
|
||||||
|
if (g.metrics.min != null) min = min == null ? g.metrics.min : Math.min(min, g.metrics.min);
|
||||||
|
if (g.metrics.max != null) max = max == null ? g.metrics.max : Math.max(max, g.metrics.max);
|
||||||
|
if (g.metrics.firstDate && (!firstDate || dateVal(g.metrics.firstDate) < dateVal(firstDate))) {
|
||||||
|
firstDate = g.metrics.firstDate;
|
||||||
|
}
|
||||||
|
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 };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
||||||
@@ -168,3 +242,47 @@ 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));
|
||||||
|
}
|
||||||
@@ -15,31 +15,58 @@ 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 { PeriodGranularity } from "../utils/transactions";
|
import type { ListGroupMetrics, ListPeriodGroup, 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 GroupMetrics({ items, currency }: { items: ExpenseItem[]; currency: string }) {
|
function cadenceRow(cadenceDays: number | null, frequency: number | null): { label: string; value: string } {
|
||||||
const m = computeTxnMetrics(items);
|
const fmt = (v: number) => (Number.isInteger(v) ? String(v) : v.toFixed(2));
|
||||||
|
if (cadenceDays != null && cadenceDays < 1) {
|
||||||
|
return { label: "Frequency", value: `${frequency == null ? "—" : fmt(frequency)} /day` };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
label: "Cadence",
|
||||||
|
value: cadenceDays == null ? "—" : `${fmt(cadenceDays)} days`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function txnFallbackMetrics(items: ExpenseItem[]): ListGroupMetrics {
|
||||||
|
const t = computeTxnMetrics(items);
|
||||||
|
return {
|
||||||
|
sum: t.sum,
|
||||||
|
count: t.count,
|
||||||
|
avg: t.avg,
|
||||||
|
min: t.min,
|
||||||
|
max: t.max,
|
||||||
|
cadence: t.cadenceDays,
|
||||||
|
frequency: t.frequency,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function GroupMetrics({
|
||||||
|
items,
|
||||||
|
currency,
|
||||||
|
metrics,
|
||||||
|
}: {
|
||||||
|
items: ExpenseItem[];
|
||||||
|
currency: string;
|
||||||
|
metrics?: ListGroupMetrics;
|
||||||
|
}) {
|
||||||
|
const m = metrics ?? txnFallbackMetrics(items);
|
||||||
const rows: { label: string; value: string }[] = [
|
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%" }}>
|
||||||
@@ -50,11 +77,20 @@ function GroupMetrics({ items, currency }: { items: ExpenseItem[]; currency: str
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TransactionList({ items, fields, granularity = "monthly", showMetrics = false }: TransactionListProps) {
|
export function TransactionList({
|
||||||
|
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(() => groupByPeriod(items, granularity), [items, granularity]);
|
const groups = useMemo<ListPeriodGroup[]>(
|
||||||
|
() => 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);
|
||||||
@@ -187,7 +223,9 @@ export function TransactionList({ items, fields, granularity = "monthly", showMe
|
|||||||
{formatCurrency(group.income, group.currency)}
|
{formatCurrency(group.income, group.currency)}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
{showMetrics && <GroupMetrics items={group.items} currency={group.currency} />}
|
{showMetrics && (
|
||||||
|
<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,10 +40,19 @@ export interface PeriodGroup {
|
|||||||
currency: string;
|
currency: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toPeriodGranularity(value?: string): PeriodGranularity {
|
/** Metrics verbatim from the API's ReportMetrics (camelCased). */
|
||||||
return value === "weekly" || value === "monthly" || value === "quarterly" || value === "yearly"
|
export interface ListGroupMetrics {
|
||||||
? value
|
sum: number;
|
||||||
: "monthly";
|
count: number;
|
||||||
|
avg: number | null;
|
||||||
|
min: number | null;
|
||||||
|
max: number | null;
|
||||||
|
cadence: number | null;
|
||||||
|
frequency: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListPeriodGroup extends PeriodGroup {
|
||||||
|
metrics?: ListGroupMetrics;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isoWeekKey(d: Date): string {
|
function isoWeekKey(d: Date): string {
|
||||||
@@ -115,12 +124,13 @@ 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 };
|
const empty = { sum: 0, count: 0, avg: null, min: null, max: null, cadenceDays: null, frequency: null };
|
||||||
if (amounts.length === 0) {
|
if (amounts.length === 0) {
|
||||||
return empty;
|
return empty;
|
||||||
}
|
}
|
||||||
@@ -138,6 +148,7 @@ 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,
|
||||||
@@ -145,5 +156,6 @@ 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,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,7 @@ export interface EmailSource {
|
|||||||
txn_dicts_count?: number;
|
txn_dicts_count?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PipelineType = "heuristic" | "llm" | "llama_parser";
|
export type PipelineType = "heuristic" | "llm" | "llama_parse";
|
||||||
|
|
||||||
export interface FetchRequestCreate {
|
export interface FetchRequestCreate {
|
||||||
source: FileSource | EmailSource;
|
source: FileSource | EmailSource;
|
||||||
|
|||||||
Reference in New Issue
Block a user