Compare commits
3 Commits
47c00a06a8
...
1.2.2
| Author | SHA1 | Date | |
|---|---|---|---|
| 2dd7f64f2b | |||
| 9377460e79 | |||
| 2add23efe7 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -14,3 +14,4 @@ dist
|
|||||||
dist-ssr
|
dist-ssr
|
||||||
*.local
|
*.local
|
||||||
.idea
|
.idea
|
||||||
|
tsconfig.tsbuildinfo
|
||||||
|
|||||||
@@ -5,12 +5,18 @@ 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 { SseStreamView } from "./src/components/SseStreamView";
|
export { SseStreamView } from "./src/components/SseStreamView";
|
||||||
export { SseConnectionStatus } from "./src/components/SseConnectionStatus";
|
export { SseConnectionStatus } from "./src/components/SseConnectionStatus";
|
||||||
export { getApi } from "./src/hooks/useApi";
|
export { getApi } from "./src/hooks/useApi";
|
||||||
export { useItemSse } from "./src/hooks/useItemSse";
|
export { useItemSse } from "./src/hooks/useItemSse";
|
||||||
export { sanitizePayload } from "./src/utils/sanitize-payload";
|
export { sanitizePayload } from "./src/utils/sanitize-payload";
|
||||||
export type { FkResolver } from "./src/utils/sanitize-payload";
|
export type { FkResolver } from "./src/utils/sanitize-payload";
|
||||||
|
export { formatDate, formatDateTime } from "./src/utils/datetime";
|
||||||
export type { FilterComponentProps } from "./src/context/useResource";
|
export type { FilterComponentProps } from "./src/context/useResource";
|
||||||
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship, ProfileOperation, ProfileComponents, AuthConfig } from "./src/types";
|
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship, ProfileOperation, ProfileComponents, AuthConfig } from "./src/types";
|
||||||
|
|||||||
@@ -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,6 +3,7 @@ import { useNavigate } from "react-router-dom";
|
|||||||
import { Box, Typography, Chip, Avatar, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
|
import { Box, Typography, Chip, Avatar, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
|
||||||
import type { FieldConfig } from "../../types";
|
import type { FieldConfig } from "../../types";
|
||||||
import { applyDisplayFormat, resolveMediaUrl } from "./utils";
|
import { applyDisplayFormat, resolveMediaUrl } from "./utils";
|
||||||
|
import { formatByFieldFormat } from "../../utils/datetime";
|
||||||
import { InlineRefField } from "./renderers/InlineRefField";
|
import { InlineRefField } from "./renderers/InlineRefField";
|
||||||
import { CurrencyField } from "./renderers/CurrencyField";
|
import { CurrencyField } from "./renderers/CurrencyField";
|
||||||
import { extractFields } from "../../transformers/field-config";
|
import { extractFields } from "../../transformers/field-config";
|
||||||
@@ -57,7 +58,7 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
|
|||||||
{sf.label}
|
{sf.label}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="body2">
|
<Typography variant="body2">
|
||||||
{fv == null ? "—" : typeof fv === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(fv, sf.inlineDisplayFormat) : JSON.stringify(fv)) : String(fv)}
|
{fv == null ? "—" : typeof fv === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(fv, sf.inlineDisplayFormat) : JSON.stringify(fv)) : formatByFieldFormat(fv, sf.format)}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
</Grid>
|
</Grid>
|
||||||
@@ -153,5 +154,5 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
|
|||||||
return <Typography variant="body2">{applyDisplayFormat(value, displayFormat ?? "")}</Typography>;
|
return <Typography variant="body2">{applyDisplayFormat(value, displayFormat ?? "")}</Typography>;
|
||||||
}
|
}
|
||||||
|
|
||||||
return <Typography variant="body2">{String(value)}</Typography>;
|
return <Typography variant="body2">{formatByFieldFormat(value, field.format)}</Typography>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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";
|
||||||
|
|||||||
@@ -10,11 +10,26 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function DateField({ field, value, onChange, error }: Props) {
|
export function DateField({ field, value, onChange, error }: Props) {
|
||||||
const inputType = field.format === "date" ? "date" : "datetime-local";
|
// `x-edit-as: date` renders a date-time field as a plain date picker;
|
||||||
|
// the picked day is submitted as midnight so the stored type is intact.
|
||||||
|
const editAsDate = field.format === "date" || field.editAs === "date";
|
||||||
|
|
||||||
const normalized = field.format === "date-time" && typeof value === "string"
|
const inputType = editAsDate ? "date" : "datetime-local";
|
||||||
? value.replace(/\.\d+Z$/, "").replace(/Z$/, "")
|
|
||||||
: value;
|
const normalized = (() => {
|
||||||
|
if (field.format !== "date-time" || typeof value !== "string") return value;
|
||||||
|
if (editAsDate) return value.slice(0, 10);
|
||||||
|
return value.replace(/\.\d+Z$/, "").replace(/Z$/, "");
|
||||||
|
})();
|
||||||
|
|
||||||
|
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const v = e.target.value;
|
||||||
|
if (editAsDate && field.format === "date-time" && /^\d{4}-\d{2}-\d{2}$/.test(v)) {
|
||||||
|
onChange(`${v}T00:00:00`);
|
||||||
|
} else {
|
||||||
|
onChange(v);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TextField
|
<TextField
|
||||||
@@ -22,7 +37,7 @@ export function DateField({ field, value, onChange, error }: Props) {
|
|||||||
label={field.label}
|
label={field.label}
|
||||||
type={inputType}
|
type={inputType}
|
||||||
value={normalized ?? ""}
|
value={normalized ?? ""}
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={handleChange}
|
||||||
error={!!error}
|
error={!!error}
|
||||||
helperText={error || field.description || undefined}
|
helperText={error || field.description || undefined}
|
||||||
placeholder={field.description || undefined}
|
placeholder={field.description || undefined}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React, { useState } from "react";
|
|||||||
import { Box, Typography, Chip, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
|
import { Box, Typography, Chip, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
|
||||||
import type { FieldConfig } from "../../../types";
|
import type { FieldConfig } from "../../../types";
|
||||||
import { applyDisplayFormat } from "../utils";
|
import { applyDisplayFormat } from "../utils";
|
||||||
|
import { formatByFieldFormat } from "../../../utils/datetime";
|
||||||
import { extractFields } from "../../../transformers/field-config";
|
import { extractFields } from "../../../transformers/field-config";
|
||||||
import { useAppContext } from "../../../context/AppContext";
|
import { useAppContext } from "../../../context/AppContext";
|
||||||
|
|
||||||
@@ -68,7 +69,7 @@ export function InlineRefField({ field, value }: Props) {
|
|||||||
<Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ mb: 0.25, display: "block" }}>
|
<Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ mb: 0.25, display: "block" }}>
|
||||||
{sf.label}
|
{sf.label}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="body2">{value?.[sf.name] == null ? "—" : typeof value[sf.name] === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(value[sf.name], sf.inlineDisplayFormat) : JSON.stringify(value[sf.name])) : String(value[sf.name])}</Typography>
|
<Typography variant="body2">{value?.[sf.name] == null ? "—" : typeof value[sf.name] === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(value[sf.name], sf.inlineDisplayFormat) : JSON.stringify(value[sf.name])) : formatByFieldFormat(value[sf.name], sf.format)}</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
</Grid>
|
</Grid>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { formatIsoLike } from "../../utils/datetime";
|
||||||
|
|
||||||
function getNested(obj: any, path: string): any {
|
function getNested(obj: any, path: string): any {
|
||||||
return path.split(".").reduce((o, k) => o?.[k], obj);
|
return path.split(".").reduce((o, k) => o?.[k], obj);
|
||||||
}
|
}
|
||||||
@@ -6,7 +8,7 @@ export function applyDisplayFormat(item: any, format: string): string {
|
|||||||
if (!item || typeof item !== "object") return String(item ?? "");
|
if (!item || typeof item !== "object") return String(item ?? "");
|
||||||
return format.replace(/\{([\w.]+)\}/g, (_, key) => {
|
return format.replace(/\{([\w.]+)\}/g, (_, key) => {
|
||||||
const val = getNested(item, key);
|
const val = getNested(item, key);
|
||||||
return val != null ? String(val) : "";
|
return val != null ? formatIsoLike(val) : "";
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,24 @@ import axios, { AxiosInstance } from "axios";
|
|||||||
let apiClient: AxiosInstance | null = null;
|
let apiClient: AxiosInstance | null = null;
|
||||||
let _onUnauthorized: (() => void) | undefined;
|
let _onUnauthorized: (() => void) | undefined;
|
||||||
|
|
||||||
|
function serializeParams(params: Record<string, any>): string {
|
||||||
|
const searchParams = new URLSearchParams();
|
||||||
|
for (const [key, value] of Object.entries(params ?? {})) {
|
||||||
|
if (value === undefined || value === null) continue;
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
for (const item of value) searchParams.append(key, String(item));
|
||||||
|
} else if (typeof value === "object") {
|
||||||
|
for (const [nestedKey, nestedValue] of Object.entries(value)) {
|
||||||
|
if (nestedValue === undefined || nestedValue === null) continue;
|
||||||
|
searchParams.append(`${key}[${nestedKey}]`, String(nestedValue));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
searchParams.append(key, String(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return searchParams.toString();
|
||||||
|
}
|
||||||
|
|
||||||
export function initApi(baseUrl: string, getToken?: () => string | null, onUnauthorized?: () => void): AxiosInstance {
|
export function initApi(baseUrl: string, getToken?: () => string | null, onUnauthorized?: () => void): AxiosInstance {
|
||||||
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
||||||
_onUnauthorized = onUnauthorized;
|
_onUnauthorized = onUnauthorized;
|
||||||
@@ -14,6 +32,7 @@ export function initApi(baseUrl: string, getToken?: () => string | null, onUnaut
|
|||||||
apiClient = axios.create({
|
apiClient = axios.create({
|
||||||
baseURL: baseUrl,
|
baseURL: baseUrl,
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
|
paramsSerializer: serializeParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
apiClient.interceptors.request.use((config) => {
|
apiClient.interceptors.request.use((config) => {
|
||||||
|
|||||||
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 };
|
||||||
|
}
|
||||||
@@ -64,6 +64,7 @@ function extractOneOfOptions(schema: any, schemas: Record<string, any>, discrimi
|
|||||||
description: prop["x-description"] ?? "",
|
description: prop["x-description"] ?? "",
|
||||||
type: prop.type ?? "string",
|
type: prop.type ?? "string",
|
||||||
format: prop.format,
|
format: prop.format,
|
||||||
|
editAs: prop["x-edit-as"],
|
||||||
order: prop["x-order"] ?? Infinity,
|
order: prop["x-order"] ?? Infinity,
|
||||||
hidden: prop["x-hidden"] ?? {},
|
hidden: prop["x-hidden"] ?? {},
|
||||||
filterable: prop["x-filterable"] ?? false,
|
filterable: prop["x-filterable"] ?? false,
|
||||||
@@ -130,13 +131,17 @@ export function extractFields(schemaName: string, schema: any, schemas: Record<s
|
|||||||
description: prop["x-description"] ?? "",
|
description: prop["x-description"] ?? "",
|
||||||
type: isRef && refSchema ? "object" : isOneOf ? "object" : (prop.type ?? "string"),
|
type: isRef && refSchema ? "object" : isOneOf ? "object" : (prop.type ?? "string"),
|
||||||
format: prop.format,
|
format: prop.format,
|
||||||
|
editAs: prop["x-edit-as"],
|
||||||
order: prop["x-order"] ?? Infinity,
|
order: prop["x-order"] ?? Infinity,
|
||||||
hidden: prop["x-hidden"] ?? {},
|
hidden: prop["x-hidden"] ?? {},
|
||||||
filterable: prop["x-filterable"] ?? false,
|
filterable: prop["x-filterable"] ?? false,
|
||||||
sortable: prop["x-sortable"] ?? false,
|
sortable: prop["x-sortable"] ?? false,
|
||||||
readOnly: prop.readOnly ?? false,
|
readOnly: prop.readOnly ?? false,
|
||||||
required: requiredFields.includes(name),
|
required: requiredFields.includes(name),
|
||||||
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 {
|
||||||
@@ -99,6 +101,8 @@ export interface FieldConfig {
|
|||||||
description: string;
|
description: string;
|
||||||
type: string;
|
type: string;
|
||||||
format?: string;
|
format?: string;
|
||||||
|
/** `x-edit-as: date` — edit a `date-time` field with a plain date input; submits midnight. */
|
||||||
|
editAs?: string;
|
||||||
order: number;
|
order: number;
|
||||||
hidden: { form?: boolean; list?: boolean; detail?: boolean };
|
hidden: { form?: boolean; list?: boolean; detail?: boolean };
|
||||||
filterable: boolean;
|
filterable: boolean;
|
||||||
@@ -106,6 +110,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;
|
||||||
|
|||||||
63
react-openapi/src/utils/datetime.ts
Normal file
63
react-openapi/src/utils/datetime.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
/**
|
||||||
|
* Zero-dependency date/time display helpers.
|
||||||
|
*
|
||||||
|
* Only ISO-shaped strings ("2026-08-24", "2026-08-24T09:07:25[.f][Z]") are
|
||||||
|
* reformatted; anything else (DD-MM-YYYY expense strings, free text) passes
|
||||||
|
* through untouched. Naive strings without a zone are parsed as clock time
|
||||||
|
* so the displayed wall time matches what the backend stored.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||||
|
const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
|
||||||
|
|
||||||
|
function parseIso(value: any): Date | null {
|
||||||
|
if (typeof value !== "string") return null;
|
||||||
|
if (!ISO_DATE.test(value) && !ISO_DATETIME.test(value)) return null;
|
||||||
|
const d = new Date(value);
|
||||||
|
return isNaN(d.getTime()) ? null : d;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DATE_FMT = new Intl.DateTimeFormat("en-IN", { day: "numeric", month: "short", year: "numeric" });
|
||||||
|
const DATETIME_FMT = new Intl.DateTimeFormat("en-IN", {
|
||||||
|
day: "numeric",
|
||||||
|
month: "short",
|
||||||
|
year: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
function fallback(value: any): string {
|
||||||
|
return typeof value === "string" ? value : value != null ? String(value) : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2026-08-24" -> "24 Aug 2026"; non-ISO values pass through. */
|
||||||
|
export function formatDate(value: any): string {
|
||||||
|
const d = parseIso(value);
|
||||||
|
return d ? DATE_FMT.format(d) : fallback(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2026-08-24T09:07:25" -> "24 Aug 2026, 09:07"; non-ISO values pass through. */
|
||||||
|
export function formatDateTime(value: any): string {
|
||||||
|
const d = parseIso(value);
|
||||||
|
return d ? DATETIME_FMT.format(d) : fallback(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Route by OpenAPI field format ("date" | "date-time"); other formats render plainly. */
|
||||||
|
export function formatByFieldFormat(value: any, format?: string): string {
|
||||||
|
if (format === "date") return formatDate(value);
|
||||||
|
if (format === "date-time") return formatDateTime(value);
|
||||||
|
return fallback(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Metadata-free variant for display-format templates ({key} interpolation):
|
||||||
|
* reformats a scalar only when it happens to be ISO-shaped.
|
||||||
|
*/
|
||||||
|
export function formatIsoLike(value: any): string {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
if (ISO_DATETIME.test(value)) return formatDateTime(value);
|
||||||
|
if (ISO_DATE.test(value)) return formatDate(value);
|
||||||
|
}
|
||||||
|
return fallback(value);
|
||||||
|
}
|
||||||
@@ -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) {
|
||||||
|
|||||||
@@ -110,12 +110,12 @@ export default function Expense() {
|
|||||||
<>
|
<>
|
||||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
||||||
<StatCard
|
<StatCard
|
||||||
label="Total spent"
|
label="Outflows"
|
||||||
value={formatCurrency(summary.totalSpent, summary.currency)}
|
value={formatCurrency(summary.totalSpent, summary.currency)}
|
||||||
hint={`${summary.monthItems.length} transaction${summary.monthItems.length === 1 ? "" : "s"} this month`}
|
hint={`${summary.monthItems.length} transaction${summary.monthItems.length === 1 ? "" : "s"} this month`}
|
||||||
/>
|
/>
|
||||||
<StatCard label="This month" value={formatCurrency(summary.monthTotal, summary.currency)} hint={summary.thisMonth} />
|
<StatCard label="This month" value={formatCurrency(summary.monthTotal, summary.currency)} hint={summary.thisMonth} />
|
||||||
<StatCard label="Income" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
<StatCard label="Inflows" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{fieldConfigs && <TransactionList items={sorted} fields={fieldConfigs} />}
|
{fieldConfigs && <TransactionList items={sorted} fields={fieldConfigs} />}
|
||||||
|
|||||||
@@ -1,22 +1,60 @@
|
|||||||
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 { alpha } from "@mui/material/styles";
|
||||||
import { useAppContext, useResource, ListCellRenderer, FormFieldRenderer, getApi, applyDisplayFormat } from "../../react-openapi";
|
import { useAppContext, useResource, ListCellRenderer, FormFieldRenderer, getApi, applyDisplayFormat } from "../../react-openapi";
|
||||||
import type { FieldConfig } from "../../react-openapi";
|
import type { FieldConfig } from "../../react-openapi";
|
||||||
import { PageHeader } from "../ui/PageHeader";
|
import { PageHeader } from "../ui/PageHeader";
|
||||||
import { EmptyState } from "../ui/EmptyState";
|
import { EmptyState } from "../ui/EmptyState";
|
||||||
|
import { formatApiError } from "../features/fetch-requests";
|
||||||
|
import { useToast } from "../ui/Toast";
|
||||||
|
|
||||||
const CREATE_FIELDS = ["account", "bank", "pipeline", "start_date", "end_date", "source"];
|
const CREATE_FIELDS = ["account", "bank", "pipeline", "trust_fallback", "start_date", "end_date", "source"];
|
||||||
|
|
||||||
|
// Two-pane form partition — explicit names, spec order is unreliable.
|
||||||
|
// Grid stretch keeps both panes equal-height regardless of which source
|
||||||
|
// variant is active (email adds From/Subject under the type select).
|
||||||
|
const SOURCE_PANE_FIELDS = ["account", "bank"];
|
||||||
|
const POLICY_PANE_FIELDS = ["start_date", "end_date", "pipeline", "trust_fallback"];
|
||||||
|
|
||||||
|
const glassSx = (theme: any) => ({
|
||||||
|
backgroundColor: alpha(theme.palette.background.default, 0.72),
|
||||||
|
backdropFilter: "blur(8px)",
|
||||||
|
borderColor: "divider",
|
||||||
|
boxShadow: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
function GlassPanel({ title, children }: { title: string; children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<Paper variant="outlined" sx={(theme) => ({ p: 3, borderRadius: 3, ...glassSx(theme) })}>
|
||||||
|
<Typography
|
||||||
|
variant="overline"
|
||||||
|
sx={{ display: "block", mb: 2, color: "text.secondary", letterSpacing: 1.2, lineHeight: 1.4 }}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>{children}</Box>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
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 +68,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 }}>
|
||||||
@@ -58,30 +116,63 @@ function FetchRequestList() {
|
|||||||
<Paper
|
<Paper
|
||||||
key={row.id ?? i}
|
key={row.id ?? i}
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
sx={{
|
sx={(theme) => ({
|
||||||
p: 2,
|
p: 2,
|
||||||
cursor: "pointer",
|
cursor: "pointer",
|
||||||
borderRadius: 2,
|
borderRadius: 3,
|
||||||
transition: "border-color 160ms ease, box-shadow 160ms ease",
|
transition: "border-color 160ms ease, box-shadow 160ms ease, background-color 160ms ease",
|
||||||
"&:hover": { borderColor: "primary.main", boxShadow: 1 },
|
"&:hover": {
|
||||||
}}
|
borderColor: "primary.main",
|
||||||
|
boxShadow: 1,
|
||||||
|
backgroundColor: alpha(theme.palette.background.default, 0.9),
|
||||||
|
},
|
||||||
|
...glassSx(theme),
|
||||||
|
})}
|
||||||
onClick={() => navigate(`/fetch-requests/${row.id}`)}
|
onClick={() => navigate(`/fetch-requests/${row.id}`)}
|
||||||
>
|
>
|
||||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center" }}>
|
<Box sx={{ display: "flex", gap: 2, alignItems: "center" }}>
|
||||||
{columns.map((col) => (
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center", flex: 1, minWidth: 0 }}>
|
||||||
<Box key={col.name} sx={{ minWidth: 120 }}>
|
{columns
|
||||||
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
|
.filter((col) => col.name !== "created_at")
|
||||||
{col.label}
|
.map((col) => (
|
||||||
</Typography>
|
<Box key={col.name} sx={{ minWidth: 120 }}>
|
||||||
<ListCellRenderer
|
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
|
||||||
field={col}
|
{col.label}
|
||||||
value={row[col.name]}
|
</Typography>
|
||||||
displayFormat={col.fk
|
<ListCellRenderer
|
||||||
? (allResources.find((r) => r.name === col.fk!.resource)?.displayFormat ?? displayFormat)
|
field={col}
|
||||||
: displayFormat}
|
value={row[col.name]}
|
||||||
/>
|
displayFormat={col.fk
|
||||||
</Box>
|
? (allResources.find((r) => r.name === col.fk!.resource)?.displayFormat ?? displayFormat)
|
||||||
))}
|
: displayFormat}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
{(() => {
|
||||||
|
const dateCol = columns.find((col) => col.name === "created_at");
|
||||||
|
if (!dateCol) return null;
|
||||||
|
return (
|
||||||
|
<Box sx={{ flexShrink: 0, textAlign: "right" }}>
|
||||||
|
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
|
||||||
|
{dateCol.label}
|
||||||
|
</Typography>
|
||||||
|
<ListCellRenderer field={dateCol} value={row.created_at} displayFormat={displayFormat} />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
<Box sx={{ flexShrink: 0 }}>
|
||||||
|
<Tooltip title="Delete fetch request">
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="error"
|
||||||
|
disabled={deletingId === row.id || row.status === "processing"}
|
||||||
|
onClick={(e) => handleDelete(e, row.id)}
|
||||||
|
>
|
||||||
|
<DeleteOutlineIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Tooltip>
|
||||||
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
@@ -94,6 +185,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 +235,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");
|
||||||
@@ -160,59 +256,90 @@ export default function FetchRequestCreate() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const renderPaneFields = (names: string[]) =>
|
||||||
|
names.map((name) => {
|
||||||
|
const field = formFields.find((f) => f.name === name);
|
||||||
|
if (!field) return null;
|
||||||
|
return (
|
||||||
|
<FormFieldRenderer
|
||||||
|
key={field.name}
|
||||||
|
field={field}
|
||||||
|
value={formData[field.name] ?? ""}
|
||||||
|
onChange={(val) => handleChange(field.name, val)}
|
||||||
|
fkOptions={fkOptions[field.name]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container maxWidth="lg" sx={{ py: 4 }}>
|
<Box sx={{ position: "relative" }}>
|
||||||
<PageHeader
|
{/* Decorative gradient backdrop — gives the frosted panes something to blur. */}
|
||||||
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests" }]}
|
<Box
|
||||||
title="Fetch Requests"
|
aria-hidden
|
||||||
subtitle="Import transactions from bank statements or email and track pipeline progress."
|
sx={{
|
||||||
|
position: "fixed",
|
||||||
|
inset: 0,
|
||||||
|
zIndex: 0,
|
||||||
|
pointerEvents: "none",
|
||||||
|
background: (theme) =>
|
||||||
|
[
|
||||||
|
`radial-gradient(640px circle at 12% 8%, ${alpha(theme.palette.primary.main, 0.14)}, transparent 70%)`,
|
||||||
|
`radial-gradient(900px circle at 88% 92%, ${alpha(theme.palette.primary.main, 0.09)}, transparent 70%)`,
|
||||||
|
`radial-gradient(520px circle at 78% 22%, ${alpha(theme.palette.primary.light, 0.07)}, transparent 70%)`,
|
||||||
|
].join(", "),
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
<Container maxWidth="lg" sx={{ py: 4, position: "relative", zIndex: 1 }}>
|
||||||
|
<PageHeader
|
||||||
|
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests" }]}
|
||||||
|
title="Fetch Requests"
|
||||||
|
subtitle="Import transactions from bank statements or email and track pipeline progress."
|
||||||
|
/>
|
||||||
|
|
||||||
<Paper
|
<Box id="new-fetch-request" sx={{ mb: 4 }}>
|
||||||
id="new-fetch-request"
|
<Typography variant="subtitle1" fontWeight={700} gutterBottom>
|
||||||
variant="outlined"
|
New Fetch Request
|
||||||
sx={{ p: 3, mb: 4, borderRadius: 3 }}
|
</Typography>
|
||||||
>
|
<Typography variant="body2" color="text.secondary" sx={{ mb: 2.5, maxWidth: 560, lineHeight: 1.6 }}>
|
||||||
<Typography variant="subtitle1" fontWeight={700} gutterBottom>
|
Choose an account, pipeline, and a file or email source to kick off an import.
|
||||||
New Fetch Request
|
</Typography>
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3, maxWidth: 520, lineHeight: 1.6 }}>
|
|
||||||
Choose an account, pipeline, and a file or email source to kick off an import.
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, maxWidth: 520 }}>
|
<Box
|
||||||
{formFields.map((field) => (
|
sx={{
|
||||||
<FormFieldRenderer
|
display: "grid",
|
||||||
key={field.name}
|
gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
|
||||||
field={field}
|
gap: 2,
|
||||||
value={formData[field.name] ?? ""}
|
}}
|
||||||
onChange={(val) => handleChange(field.name, val)}
|
>
|
||||||
fkOptions={fkOptions[field.name]}
|
<GlassPanel title="Source & Account">
|
||||||
/>
|
{renderPaneFields(SOURCE_PANE_FIELDS)}
|
||||||
))}
|
{renderPaneFields(["source"])}
|
||||||
|
</GlassPanel>
|
||||||
|
<GlassPanel title="Window & Policy">{renderPaneFields(POLICY_PANE_FIELDS)}</GlassPanel>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, gap: 1.5 }}>
|
||||||
|
<Button variant="outlined" onClick={() => { setFormData({}); setResult(null); }}>
|
||||||
|
Reset
|
||||||
|
</Button>
|
||||||
|
<Button variant="contained" onClick={handleSubmit} disabled={loading} sx={{ minWidth: 180 }}>
|
||||||
|
{loading ? <CircularProgress size={20} sx={{ mr: 0.5 }} /> : null}
|
||||||
|
Create Fetch Request
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{result && (
|
||||||
|
<Alert severity={result.severity} sx={{ mt: 2 }} onClose={() => setResult(null)}>
|
||||||
|
{result.message}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, gap: 1.5 }}>
|
<Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}>
|
||||||
<Button variant="outlined" onClick={() => { setFormData({}); setResult(null); }}>
|
Recent Fetch Requests
|
||||||
Reset
|
</Typography>
|
||||||
</Button>
|
<FetchRequestList />
|
||||||
<Button variant="contained" onClick={handleSubmit} disabled={loading} sx={{ minWidth: 180 }}>
|
</Container>
|
||||||
{loading ? <CircularProgress size={20} sx={{ mr: 0.5 }} /> : null}
|
</Box>
|
||||||
Create Fetch Request
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{result && (
|
|
||||||
<Alert severity={result.severity} sx={{ mt: 2 }} onClose={() => setResult(null)}>
|
|
||||||
{result.message}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}>
|
|
||||||
Recent Fetch Requests
|
|
||||||
</Typography>
|
|
||||||
<FetchRequestList />
|
|
||||||
</Container>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,114 +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,
|
||||||
IconButton,
|
Grid,
|
||||||
MenuItem,
|
|
||||||
Select,
|
|
||||||
FormControl,
|
|
||||||
InputLabel,
|
|
||||||
Autocomplete,
|
|
||||||
Alert,
|
Alert,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import AddIcon from "@mui/icons-material/Add";
|
import AddIcon from "@mui/icons-material/Add";
|
||||||
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
|
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 { isDdmmyyyy } from "../common/utils/dates";
|
import { apiErrorMessage } from "./types";
|
||||||
import { apiErrorMessage, groupTypeEnum, periodHints } from "./types";
|
|
||||||
|
|
||||||
interface GroupRow {
|
|
||||||
id: number;
|
|
||||||
group_type: string;
|
|
||||||
group_value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GenerateReportPanelProps {
|
interface GenerateReportPanelProps {
|
||||||
onGenerated: (reports: any[]) => void;
|
onGenerated: (report: any) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
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: listEntities } = useResource("entities");
|
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
|
|
||||||
const [rows, setRows] = useState<GroupRow[]>([{ id: 1, group_type: "monthly", group_value: "*" }]);
|
const [formData, setFormData] = useState<Record<string, any>>({});
|
||||||
const [startDate, setStartDate] = useState("");
|
|
||||||
const [endDate, setEndDate] = useState("");
|
|
||||||
const [submitting, setSubmitting] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [entityNames, setEntityNames] = useState<string[]>([]);
|
|
||||||
const [dateErrors, setDateErrors] = useState<{ start?: string; end?: string }>({});
|
|
||||||
|
|
||||||
const types = useMemo(() => groupTypeEnum(schemas), [schemas]);
|
const fields: FieldConfig[] = useMemo(() => {
|
||||||
const entitiesRes = resources.find((r) => r.name === "entities");
|
const schema = schemas?.ReportQuery;
|
||||||
const entitiesFormat = entitiesRes?.displayFormat ?? "{name}";
|
if (!schema) return [];
|
||||||
|
return extractFields("ReportQuery", schema, schemas).sort(
|
||||||
|
(a, b) => a.order - b.order || a.name.localeCompare(b.name)
|
||||||
|
);
|
||||||
|
}, [schemas]);
|
||||||
|
|
||||||
|
const { fkOptions, fkLoading, loadFkOnOpen } = useFkFieldOptions(fields);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
setFormData((prev) => {
|
||||||
listEntities({ 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, entitiesFormat))
|
if (next[f.name] === undefined && f.defaultValue !== undefined) {
|
||||||
.filter((n: string) => n);
|
next[f.name] = Array.isArray(f.defaultValue) ? [...f.defaultValue] : f.defaultValue;
|
||||||
setEntityNames([...new Set(names)].sort((a, b) => a.localeCompare(b)));
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed ? next : prev;
|
||||||
});
|
});
|
||||||
return () => {
|
}, [fields]);
|
||||||
mounted = false;
|
|
||||||
};
|
|
||||||
}, [listEntities, entitiesFormat]);
|
|
||||||
|
|
||||||
const isPayee = (type: string) => type === "payee";
|
const handleChange = useCallback((name: string, value: any) => {
|
||||||
|
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||||
|
setError(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const valueOptions = (row: GroupRow): string[] => ["*", ...(isPayee(row.group_type) ? entityNames : [])];
|
const buildPayload = (): Record<string, any> => {
|
||||||
|
const payload: Record<string, any> = {};
|
||||||
const valueHint = (row: GroupRow): string =>
|
for (const f of fields) {
|
||||||
isPayee(row.group_type) ? "Entity name, or * for all payees" : `e.g. ${periodHints(row.group_type).join(", ")}, or *`;
|
const v = formData[f.name];
|
||||||
|
if (v === undefined || v === null || v === "") continue;
|
||||||
const nextRowId = () => Math.max(0, ...rows.map((r) => r.id)) + 1;
|
if (Array.isArray(v) && v.length === 0) continue;
|
||||||
|
payload[f.name] = v;
|
||||||
const addRow = () => setRows((rs) => [...rs, { id: nextRowId(), group_type: "monthly", group_value: "*" }]);
|
}
|
||||||
|
return payload;
|
||||||
const removeRow = (id: number) => setRows((rs) => rs.filter((r) => r.id !== id));
|
|
||||||
|
|
||||||
const updateRow = (id: number, patch: Partial<GroupRow>) =>
|
|
||||||
setRows((rs) => rs.map((r) => (r.id === id ? { ...r, ...patch } : r)));
|
|
||||||
|
|
||||||
const validateDates = (): boolean => {
|
|
||||||
const errs: { start?: string; end?: string } = {};
|
|
||||||
if (startDate && !isDdmmyyyy(startDate)) errs.start = "Use DD-MM-YYYY";
|
|
||||||
if (endDate && !isDdmmyyyy(endDate)) errs.end = "Use DD-MM-YYYY";
|
|
||||||
setDateErrors(errs);
|
|
||||||
return Object.keys(errs).length === 0;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
if (!validateDates()) return;
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
const groups = rows
|
|
||||||
.filter((r) => r.group_type && r.group_value.trim())
|
|
||||||
.map(({ group_type, group_value }) => ({ group_type, group_value: group_value.trim() }));
|
|
||||||
if (groups.length === 0) {
|
|
||||||
setError("At least one group is required");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setSubmitting(true);
|
|
||||||
const payload: Record<string, any> = { groups };
|
|
||||||
if (startDate.trim()) payload.start_date = startDate.trim();
|
|
||||||
if (endDate.trim()) payload.end_date = endDate.trim();
|
|
||||||
try {
|
try {
|
||||||
const created = await create(payload);
|
const created = await create(buildPayload());
|
||||||
const list = Array.isArray(created) ? created : created ? [created] : [];
|
showToast(`Generated snapshot ${created?.name ? `“${created.name}”` : ""}`.trim() || "Generated snapshot");
|
||||||
showToast(`Generated ${list.length} report${list.length === 1 ? "" : "s"}`);
|
onGenerated(created);
|
||||||
onGenerated(list);
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(apiErrorMessage(e));
|
setError(apiErrorMessage(e));
|
||||||
} finally {
|
|
||||||
setSubmitting(false);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -118,8 +89,8 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
|||||||
Generate report
|
Generate report
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5, mb: 2 }}>
|
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5, mb: 2 }}>
|
||||||
Choose the dimensions to snapshot. At least one group is required — with no period dimension the server
|
Define the snapshot's scope. Granularity, payee and tag are sliced at view time — the cube is built once and
|
||||||
snapshots weekly, monthly and quarterly.
|
every combination stays cheap to read.
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -128,83 +99,27 @@ export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
|||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
<Box component="form" onSubmit={handleSubmit}>
|
||||||
{rows.map((row) => (
|
<Grid container spacing={2}>
|
||||||
<Box key={row.id} sx={{ display: "flex", gap: 1.5, alignItems: "flex-start" }}>
|
{fields.map((field) => (
|
||||||
<FormControl size="small" sx={{ width: 180, flexShrink: 0 }}>
|
<Grid item xs={12} sm={6} md={4} key={field.name}>
|
||||||
<InputLabel id={`group-type-${row.id}`}>Type</InputLabel>
|
<FormFieldRenderer
|
||||||
<Select
|
field={field}
|
||||||
labelId={`group-type-${row.id}`}
|
value={formData[field.name]}
|
||||||
label="Type"
|
onChange={(val) => handleChange(field.name, val)}
|
||||||
value={row.group_type}
|
fkOptions={fkOptions[field.name]}
|
||||||
onChange={(e) => updateRow(row.id, { group_type: e.target.value, group_value: "*" })}
|
fkLoading={fkLoading[field.name]}
|
||||||
>
|
onFkOpen={loadFkOnOpen}
|
||||||
{types.map((t) => (
|
/>
|
||||||
<MenuItem key={t} value={t}>
|
</Grid>
|
||||||
{t}
|
))}
|
||||||
</MenuItem>
|
</Grid>
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
<Autocomplete
|
|
||||||
freeSolo
|
|
||||||
size="small"
|
|
||||||
sx={{ flex: 1, minWidth: 240 }}
|
|
||||||
options={valueOptions(row)}
|
|
||||||
value={row.group_value}
|
|
||||||
onInputChange={(_, newVal) => updateRow(row.id, { group_value: newVal ?? "" })}
|
|
||||||
renderInput={(params) => (
|
|
||||||
<TextField {...params} label="Value" helperText={valueHint(row)} />
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
aria-label="Remove group"
|
|
||||||
disabled={rows.length === 1}
|
|
||||||
onClick={() => removeRow(row.id)}
|
|
||||||
sx={{ mt: 0.25 }}
|
|
||||||
>
|
|
||||||
<RemoveCircleOutlineIcon />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Button startIcon={<AddIcon />} size="small" sx={{ mt: 1 }} onClick={addRow}>
|
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
||||||
Add dimension
|
<Button type="submit" variant="contained" startIcon={<AddIcon />} disabled={submitting}>
|
||||||
</Button>
|
{submitting ? "Generating…" : "Generate"}
|
||||||
|
</Button>
|
||||||
<Box sx={{ display: "flex", gap: 1.5, mt: 2, flexWrap: "wrap" }}>
|
</Box>
|
||||||
<TextField
|
|
||||||
size="small"
|
|
||||||
label="Start date"
|
|
||||||
placeholder="DD-MM-YYYY"
|
|
||||||
value={startDate}
|
|
||||||
onChange={(e) => setStartDate(e.target.value)}
|
|
||||||
error={Boolean(dateErrors.start)}
|
|
||||||
helperText={dateErrors.start ?? "Inclusive start (empty = unbounded)"}
|
|
||||||
sx={{ width: 200 }}
|
|
||||||
/>
|
|
||||||
<TextField
|
|
||||||
size="small"
|
|
||||||
label="End date"
|
|
||||||
placeholder="DD-MM-YYYY"
|
|
||||||
value={endDate}
|
|
||||||
onChange={(e) => setEndDate(e.target.value)}
|
|
||||||
error={Boolean(dateErrors.end)}
|
|
||||||
helperText={dateErrors.end ?? "Inclusive end (empty = unbounded)"}
|
|
||||||
sx={{ width: 200 }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
startIcon={<AddIcon />}
|
|
||||||
onClick={handleSubmit}
|
|
||||||
disabled={submitting}
|
|
||||||
>
|
|
||||||
{submitting ? "Generating…" : "Generate"}
|
|
||||||
</Button>
|
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { Container, Box, Paper, Typography, Alert } from "@mui/material";
|
import {
|
||||||
|
Container,
|
||||||
|
Box,
|
||||||
|
Paper,
|
||||||
|
Typography,
|
||||||
|
Alert,
|
||||||
|
Accordion,
|
||||||
|
AccordionSummary,
|
||||||
|
AccordionDetails,
|
||||||
|
} from "@mui/material";
|
||||||
|
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||||
import AssessmentIcon from "@mui/icons-material/Assessment";
|
import AssessmentIcon from "@mui/icons-material/Assessment";
|
||||||
import { useResource, useAppContext, formatCurrency } from "../../react-openapi";
|
import { useResource, useAppContext } from "../../react-openapi";
|
||||||
import { useToast } from "../ui/Toast";
|
import { useToast } from "../ui/Toast";
|
||||||
import { PageHeader } from "../ui/PageHeader";
|
import { PageHeader } from "../ui/PageHeader";
|
||||||
import { EmptyState } from "../ui/EmptyState";
|
import { EmptyState } from "../ui/EmptyState";
|
||||||
@@ -35,22 +45,19 @@ export default function Report() {
|
|||||||
}, [load]);
|
}, [load]);
|
||||||
|
|
||||||
const handleGenerated = useCallback(
|
const handleGenerated = useCallback(
|
||||||
(created: any[]) => {
|
(created: any) => {
|
||||||
load();
|
load();
|
||||||
if (created?.[0]?.id) setSelectedId(created[0].id);
|
if (created?.id) setSelectedId(created.id);
|
||||||
},
|
},
|
||||||
[load],
|
[load],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleRegenerate = useCallback(
|
const handleRegenerate = useCallback(
|
||||||
async (report: any) => {
|
async (report: any) => {
|
||||||
const payload: Record<string, any> = { groups: report.groups ?? [] };
|
|
||||||
if (report.start_date) payload.start_date = report.start_date;
|
|
||||||
if (report.end_date) payload.end_date = report.end_date;
|
|
||||||
try {
|
try {
|
||||||
await create(payload);
|
const created = await create(report.query ?? {});
|
||||||
showToast("Report regenerated");
|
showToast("Report regenerated");
|
||||||
setSelectedId(report.id);
|
setSelectedId(created?.id ?? report.id);
|
||||||
setViewerVersion((v) => v + 1);
|
setViewerVersion((v) => v + 1);
|
||||||
load();
|
load();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -76,9 +83,9 @@ export default function Report() {
|
|||||||
|
|
||||||
const summary = useMemo(() => {
|
const summary = useMemo(() => {
|
||||||
const rows = reports ?? [];
|
const rows = reports ?? [];
|
||||||
const txnCount = rows.reduce((s, r) => s + (r.txn_count ?? 0), 0);
|
const granularities = new Set<string>();
|
||||||
const total = rows.reduce((s, r) => s + (typeof r.metrics?.sum === "number" ? r.metrics.sum : 0), 0);
|
for (const r of rows) for (const g of r.query?.granularities ?? []) granularities.add(g);
|
||||||
return { count: rows.length, txnCount, total };
|
return { count: rows.length, granularities: [...granularities].join(", ") };
|
||||||
}, [reports]);
|
}, [reports]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -86,7 +93,7 @@ export default function Report() {
|
|||||||
<PageHeader
|
<PageHeader
|
||||||
crumbs={[{ label: "Home", path: "/" }, { label: "Reports" }]}
|
crumbs={[{ label: "Home", path: "/" }, { label: "Reports" }]}
|
||||||
title="Reports"
|
title="Reports"
|
||||||
subtitle="Generate period/payee snapshots from the reporting API and slice the cached data."
|
subtitle="Build an immutable snapshot cube once, then slice by granularity, period, payee and tag at view time."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -97,37 +104,70 @@ export default function Report() {
|
|||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
||||||
<StatCard label="Reports" value={summary.count.toLocaleString("en-IN")} />
|
<StatCard label="Reports" value={summary.count.toLocaleString("en-IN")} />
|
||||||
<StatCard label="Transactions covered" value={summary.txnCount.toLocaleString("en-IN")} />
|
<StatCard label="Granularities covered" value={summary.granularities || "—"} />
|
||||||
<StatCard label="Total" value={formatCurrency(summary.total, "INR")} />
|
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<GenerateReportPanel onGenerated={handleGenerated} />
|
<GenerateReportPanel onGenerated={handleGenerated} />
|
||||||
|
|
||||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em", mb: 1.5 }}>
|
<Accordion
|
||||||
Saved reports
|
disableGutters
|
||||||
</Typography>
|
defaultExpanded
|
||||||
|
sx={{
|
||||||
{reports !== null && reports.length === 0 ? (
|
border: "1px solid",
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 3 }}>
|
borderColor: "divider",
|
||||||
<EmptyState
|
borderRadius: 2,
|
||||||
icon={<AssessmentIcon />}
|
overflow: "hidden",
|
||||||
title="No reports yet"
|
boxShadow: "none",
|
||||||
description="Generate your first report above — pick a granularity and payee (a payee-only or wildcard config snapshots weekly, monthly and quarterly)."
|
backgroundColor: "background.paper",
|
||||||
/>
|
"&:before": { display: "none" },
|
||||||
</Paper>
|
mb: 4,
|
||||||
) : (
|
}}
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2.5, mb: 4 }}>
|
>
|
||||||
<ReportList
|
<AccordionSummary
|
||||||
reports={reports ?? []}
|
expandIcon={<ExpandMoreIcon />}
|
||||||
loading={loading}
|
sx={{
|
||||||
fields={reportFields}
|
px: 2.5,
|
||||||
selectedId={selectedId}
|
py: 1,
|
||||||
onView={(id) => setSelectedId(id)}
|
"& .MuiAccordionSummary-content": {
|
||||||
onRegenerate={handleRegenerate}
|
alignItems: "center",
|
||||||
onDelete={handleDelete}
|
gap: 1.5,
|
||||||
/>
|
minWidth: 0,
|
||||||
</Box>
|
},
|
||||||
)}
|
}}
|
||||||
|
>
|
||||||
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
|
Saved reports
|
||||||
|
</Typography>
|
||||||
|
{reports !== null && (
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{reports.length} report{reports.length === 1 ? "" : "s"}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</AccordionSummary>
|
||||||
|
<AccordionDetails sx={{ px: 2.5, pb: 2.5, pt: 0 }}>
|
||||||
|
{reports !== null && reports.length === 0 ? (
|
||||||
|
<Paper variant="outlined" sx={{ borderRadius: 3 }}>
|
||||||
|
<EmptyState
|
||||||
|
icon={<AssessmentIcon />}
|
||||||
|
title="No reports yet"
|
||||||
|
description="Generate your first snapshot above — choose granularities and grouping dimensions, then slice the cached cube by period, payee and tag."
|
||||||
|
/>
|
||||||
|
</Paper>
|
||||||
|
) : (
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}>
|
||||||
|
<ReportList
|
||||||
|
reports={reports ?? []}
|
||||||
|
loading={loading}
|
||||||
|
fields={reportFields}
|
||||||
|
selectedId={selectedId}
|
||||||
|
onView={(id) => setSelectedId(id)}
|
||||||
|
onRegenerate={handleRegenerate}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</AccordionDetails>
|
||||||
|
</Accordion>
|
||||||
|
|
||||||
{selectedId && (
|
{selectedId && (
|
||||||
<ReportViewer
|
<ReportViewer
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Box, Paper, Typography, Button, IconButton, Skeleton, Tooltip } from "@
|
|||||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
||||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||||
import CachedIcon from "@mui/icons-material/Cached";
|
import CachedIcon from "@mui/icons-material/Cached";
|
||||||
import { ListCellRenderer, formatCurrency } from "../../react-openapi";
|
import { ListCellRenderer } from "../../react-openapi";
|
||||||
import type { ReportFieldConfigs } from "./types";
|
import type { ReportFieldConfigs } from "./types";
|
||||||
|
|
||||||
interface ReportListProps {
|
interface ReportListProps {
|
||||||
@@ -30,10 +30,14 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
return (
|
return (
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||||
{reports.map((report) => {
|
{reports.map((report) => {
|
||||||
const sum = typeof report.metrics?.sum === "number" ? report.metrics.sum : null;
|
const q = report.query ?? {};
|
||||||
const range =
|
const range = q.start_date || q.end_date ? `range ${q.start_date || "…"} → ${q.end_date || "…"}` : null;
|
||||||
report.start_date || report.end_date
|
const dims = Array.isArray(q.group_dims) ? q.group_dims.join(", ") : "";
|
||||||
? `range ${report.start_date || "…"} → ${report.end_date || "…"}`
|
const granularities = Array.isArray(q.granularities) ? q.granularities.join(", ") : "";
|
||||||
|
const accounts = Array.isArray(q.accounts) ? `${q.accounts.length} account${q.accounts.length === 1 ? "" : "s"}` : "all accounts";
|
||||||
|
const amounts =
|
||||||
|
q.min_amount != null || q.max_amount != null
|
||||||
|
? `amount ${q.min_amount ?? "0"} → ${q.max_amount ?? "∞"}`
|
||||||
: null;
|
: null;
|
||||||
return (
|
return (
|
||||||
<Paper
|
<Paper
|
||||||
@@ -47,23 +51,20 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
"&:hover": { borderColor: "primary.light" },
|
"&:hover": { borderColor: "primary.light" },
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
||||||
<Box sx={{ flex: "1 1 260px", minWidth: 0 }}>
|
<Box sx={{ flex: "1 1 260px", minWidth: 0 }}>
|
||||||
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}>
|
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}>
|
||||||
{report.group_label}
|
{report.name || report.id}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.25 }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.25 }}>
|
||||||
{fields && (
|
|
||||||
<ListCellRenderer field={fields.granularity} value={report.granularity} />
|
|
||||||
)}
|
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.period_label}
|
{granularities}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.disabled">
|
<Typography variant="caption" color="text.disabled">
|
||||||
/
|
/
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.payee}
|
{dims}
|
||||||
</Typography>
|
</Typography>
|
||||||
{range && (
|
{range && (
|
||||||
<Typography variant="caption" color="text.disabled">
|
<Typography variant="caption" color="text.disabled">
|
||||||
@@ -73,27 +74,21 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
</Box>
|
</Box>
|
||||||
<Box sx={{ display: "flex", gap: 1.5, mt: 0.5 }}>
|
<Box sx={{ display: "flex", gap: 1.5, mt: 0.5 }}>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.entity_count ?? 0} entities
|
{accounts}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.secondary">
|
{amounts && (
|
||||||
{report.txn_count ?? 0} txns
|
<Typography variant="caption" color="text.secondary">
|
||||||
</Typography>
|
{amounts}
|
||||||
<Typography variant="caption" color="text.secondary">
|
</Typography>
|
||||||
{report.expense_count ?? 0} expenses
|
|
||||||
</Typography>
|
|
||||||
{fields && (
|
|
||||||
<Box sx={{ color: "text.secondary" }}>
|
|
||||||
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
|
||||||
</Box>
|
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box sx={{ flexShrink: 0, textAlign: "right" }}>
|
{fields && (
|
||||||
<Typography variant="body1" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
<Box sx={{ ml: "auto", flexShrink: 0, color: "text.secondary" }}>
|
||||||
{sum != null ? formatCurrency(sum, "INR") : "—"}
|
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
||||||
</Typography>
|
</Box>
|
||||||
</Box>
|
)}
|
||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
|
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
|
||||||
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
||||||
|
|||||||
@@ -1,29 +1,61 @@
|
|||||||
import React, { useEffect, useMemo, useState } from "react";
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import {
|
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
|
||||||
Box,
|
|
||||||
Paper,
|
|
||||||
Typography,
|
|
||||||
Button,
|
|
||||||
IconButton,
|
|
||||||
Alert,
|
|
||||||
Skeleton,
|
|
||||||
TextField,
|
|
||||||
Autocomplete,
|
|
||||||
Table,
|
|
||||||
TableBody,
|
|
||||||
TableCell,
|
|
||||||
TableContainer,
|
|
||||||
TableHead,
|
|
||||||
TableRow,
|
|
||||||
} from "@mui/material";
|
|
||||||
import CloseIcon from "@mui/icons-material/Close";
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
import CachedIcon from "@mui/icons-material/Cached";
|
import CachedIcon from "@mui/icons-material/Cached";
|
||||||
import { useAppContext, useResource, formatCurrency } from "../../react-openapi";
|
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||||
|
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
|
||||||
|
import { FkMultiSelectField, useResource, formatCurrency, formatDateTime } from "../../react-openapi";
|
||||||
|
import type { FieldConfig } from "../../react-openapi";
|
||||||
import { 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, buildPivot, metricLabels } from "./types";
|
import { buildDimensionBars, buildPeriodGroups, sliceSummary, FLOW_OPTIONS, apiErrorMessage } from "./types";
|
||||||
|
import type { ReportDim } from "./types";
|
||||||
|
|
||||||
|
const MAX_VISIBLE_BARS = 10;
|
||||||
|
|
||||||
|
const periodField: FieldConfig = {
|
||||||
|
name: "period",
|
||||||
|
label: "Period",
|
||||||
|
description: "",
|
||||||
|
type: "string",
|
||||||
|
order: 0,
|
||||||
|
hidden: {},
|
||||||
|
filterable: true,
|
||||||
|
sortable: false,
|
||||||
|
readOnly: false,
|
||||||
|
required: false,
|
||||||
|
isArray: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const payeeField: FieldConfig = {
|
||||||
|
name: "payee",
|
||||||
|
label: "Payee",
|
||||||
|
description: "",
|
||||||
|
type: "string",
|
||||||
|
order: 0,
|
||||||
|
hidden: {},
|
||||||
|
filterable: true,
|
||||||
|
sortable: false,
|
||||||
|
readOnly: false,
|
||||||
|
required: false,
|
||||||
|
isArray: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const tagField: FieldConfig = {
|
||||||
|
name: "tag",
|
||||||
|
label: "Tag",
|
||||||
|
description: "",
|
||||||
|
type: "string",
|
||||||
|
order: 0,
|
||||||
|
hidden: {},
|
||||||
|
filterable: true,
|
||||||
|
sortable: false,
|
||||||
|
readOnly: false,
|
||||||
|
required: false,
|
||||||
|
isArray: true,
|
||||||
|
};
|
||||||
|
|
||||||
interface ReportViewerProps {
|
interface ReportViewerProps {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -33,31 +65,60 @@ interface ReportViewerProps {
|
|||||||
onRegenerated: (report: any) => void;
|
onRegenerated: (report: any) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function snapshotGranularities(report: any): string[] {
|
||||||
|
const fromQuery = report?.query?.granularities;
|
||||||
|
if (Array.isArray(fromQuery) && fromQuery.length) return fromQuery;
|
||||||
|
const fromResponse = report?.granularities;
|
||||||
|
if (Array.isArray(fromResponse) && fromResponse.length) return fromResponse;
|
||||||
|
const series = report?.buckets?.[0]?.series;
|
||||||
|
return series ? Object.keys(series) : [];
|
||||||
|
}
|
||||||
|
|
||||||
export function ReportViewer({ id, version, fields, onClose, onRegenerated }: ReportViewerProps) {
|
export function ReportViewer({ id, version, fields, onClose, onRegenerated }: ReportViewerProps) {
|
||||||
const { schemas } = useAppContext();
|
|
||||||
const { get } = useResource("reports");
|
const { get } = useResource("reports");
|
||||||
|
|
||||||
const [report, setReport] = useState<any | null>(null);
|
const [report, setReport] = useState<any | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [reload, setReload] = useState(0);
|
const [reload, setReload] = useState(0);
|
||||||
const [selectedPeriod, setSelectedPeriod] = useState("*");
|
const [granularity, setGranularity] = useState<string | null>(null);
|
||||||
const [selectedPayee, setSelectedPayee] = useState("*");
|
const [flow, setFlow] = useState("outflows");
|
||||||
|
const [dim, setDim] = useState<ReportDim>("period");
|
||||||
|
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
|
||||||
|
const [selectedPayees, setSelectedPayees] = useState<string[]>([]);
|
||||||
|
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||||
|
const prevGranularity = useRef<string | null>(null);
|
||||||
|
|
||||||
|
const params = useMemo(() => {
|
||||||
|
const p: Record<string, any> = { flow };
|
||||||
|
if (granularity) p.granularity = [granularity];
|
||||||
|
if (selectedPeriods.length) p.period_ids = selectedPeriods;
|
||||||
|
// The active breakdown dim requests every cube value ("*") when its own
|
||||||
|
// filter is unselected, so bars show the full distribution.
|
||||||
|
if (selectedPayees.length) p.payee = selectedPayees;
|
||||||
|
else if (dim === "payee") p.payee = ["*"];
|
||||||
|
if (selectedTags.length) p.tags = selectedTags;
|
||||||
|
else if (dim === "tag") p.tags = ["*"];
|
||||||
|
return p;
|
||||||
|
}, [granularity, flow, dim, selectedPeriods, selectedPayees, selectedTags]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
get(id)
|
const previous = prevGranularity.current;
|
||||||
|
get(id, params)
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setReport(res);
|
setReport(res);
|
||||||
setSelectedPeriod("*");
|
const options = snapshotGranularities(res);
|
||||||
setSelectedPayee("*");
|
if (granularity === null && options.length) setGranularity(options[0]);
|
||||||
|
if (previous !== null && previous !== granularity) setSelectedPeriods([]);
|
||||||
|
prevGranularity.current = granularity;
|
||||||
})
|
})
|
||||||
.catch((e: any) => {
|
.catch((e: any) => {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setError(e?.response?.data?.detail ?? e?.message ?? "Failed to load report");
|
setError(apiErrorMessage(e));
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
if (mounted) setLoading(false);
|
if (mounted) setLoading(false);
|
||||||
@@ -65,47 +126,86 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
return () => {
|
return () => {
|
||||||
mounted = false;
|
mounted = false;
|
||||||
};
|
};
|
||||||
}, [id, version, reload, get]);
|
}, [id, version, reload, params, get, granularity]);
|
||||||
|
|
||||||
const data = useMemo(() => (Array.isArray(report?.data) ? report.data : null), [report]);
|
const granularityOptions = useMemo(() => snapshotGranularities(report), [report]);
|
||||||
|
|
||||||
const groupOptions = useMemo(() => {
|
const periodOptions = useMemo(
|
||||||
const options = report?.metadata?.group_options;
|
() => (Array.isArray(report?.period_ids) ? report.period_ids.map((label: string) => ({ value: label, label })) : []),
|
||||||
if (!options || typeof options !== "object") return { period: [], payee: [] };
|
[report],
|
||||||
return {
|
);
|
||||||
period: Array.isArray(options.period) ? options.period.map(String) : [],
|
const payeeOptions = useMemo(
|
||||||
payee: Array.isArray(options.payee) ? options.payee.map(String) : [],
|
() => (Array.isArray(report?.payees) ? report.payees.map((label: string) => ({ value: label, label })) : []),
|
||||||
};
|
[report],
|
||||||
}, [report]);
|
);
|
||||||
|
const tagOptions = useMemo(
|
||||||
const slice = useMemo(
|
() => (Array.isArray(report?.tags) ? report.tags.map((label: string) => ({ value: label, label })) : []),
|
||||||
() => aggregateSlice(data ?? [], { period: selectedPeriod, payee: selectedPayee }),
|
[report],
|
||||||
[data, selectedPeriod, selectedPayee],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const pivot = useMemo(
|
const filter = useMemo(
|
||||||
() => buildPivot(data ?? [], groupOptions.period, groupOptions.payee),
|
() => ({
|
||||||
[data, groupOptions],
|
granularity: granularity ?? granularityOptions[0] ?? "",
|
||||||
|
periods: selectedPeriods,
|
||||||
|
payees: selectedPayees,
|
||||||
|
tags: selectedTags,
|
||||||
|
}),
|
||||||
|
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
|
||||||
);
|
);
|
||||||
|
|
||||||
const metrics = useMemo(() => {
|
const periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]);
|
||||||
const labels = metricLabels(schemas);
|
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]);
|
||||||
const displayKeys = ["sum", "count", "avg", "min", "max", "first_date", "last_date"];
|
const bars = useMemo(() => buildDimensionBars(report?.buckets ?? [], filter, dim), [report, filter, dim]);
|
||||||
return labels.filter((l) => displayKeys.includes(l.key));
|
const visibleBars = useMemo(() => bars.slice(0, MAX_VISIBLE_BARS), [bars]);
|
||||||
}, [schemas]);
|
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 metricValue = (key: string): string | null => {
|
const barsListRef = useRef<HTMLDivElement>(null);
|
||||||
if (key === "sum") return formatCurrency(slice.sum, slice.currency);
|
const [barScroll, setBarScroll] = useState({ canUp: false, canDown: false, overflow: false });
|
||||||
if (key === "count") return slice.count.toLocaleString("en-IN");
|
|
||||||
if (key === "avg") return slice.avg == null ? null : formatCurrency(slice.avg, slice.currency);
|
|
||||||
if (key === "min") return slice.min == null ? null : formatCurrency(slice.min, slice.currency);
|
|
||||||
if (key === "max") return slice.max == null ? null : formatCurrency(slice.max, slice.currency);
|
|
||||||
if (key === "first_date") return slice.firstDate;
|
|
||||||
if (key === "last_date") return slice.lastDate;
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) {
|
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) {
|
||||||
return (
|
return (
|
||||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
||||||
<Skeleton variant="text" width={220} height={28} />
|
<Skeleton variant="text" width={220} height={28} />
|
||||||
@@ -130,6 +230,22 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
|
|
||||||
if (!report) return null;
|
if (!report) return null;
|
||||||
|
|
||||||
|
const activeGranularity = granularity ?? report.granularities?.[0] ?? "";
|
||||||
|
const maxBar = bars.reduce((m, b) => Math.max(m, Math.abs(b.sum)), 0);
|
||||||
|
const dimOptions: { id: ReportDim; label: string; count: number }[] = [
|
||||||
|
{ id: "period", label: "Period", count: report.period_ids?.length ?? 0 },
|
||||||
|
{ id: "payee", label: "Payees", count: report.payees?.length ?? 0 },
|
||||||
|
{ id: "tag", label: "Tags", count: report.tags?.length ?? 0 },
|
||||||
|
];
|
||||||
|
const activeDimIndex = Math.max(
|
||||||
|
0,
|
||||||
|
dimOptions.findIndex((d) => d.id === dim),
|
||||||
|
);
|
||||||
|
const range =
|
||||||
|
report.query?.start_date || report.query?.end_date
|
||||||
|
? `range ${report.query.start_date || "…"} → ${report.query.end_date || "…"}`
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 3, overflow: "hidden" }}>
|
<Paper variant="outlined" sx={{ borderRadius: 3, overflow: "hidden" }}>
|
||||||
<Box
|
<Box
|
||||||
@@ -146,146 +262,241 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
>
|
>
|
||||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
{report.group_label}
|
{report.name}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
{report.granularity} · {report.period_label} · {report.payee}
|
flow {report.flow} · generated {formatDateTime(report.generated_at ?? report.created_at)}
|
||||||
</Typography>
|
</Typography>
|
||||||
<Typography variant="caption" color="text.disabled">
|
{range && (
|
||||||
{report.entity_count ?? 0} entities · {report.txn_count ?? 0} txns · {report.expense_count ?? 0} expenses
|
|
||||||
</Typography>
|
|
||||||
{report.start_date || report.end_date ? (
|
|
||||||
<Typography variant="caption" color="text.disabled">
|
<Typography variant="caption" color="text.disabled">
|
||||||
range {report.start_date || "…"} → {report.end_date || "…"}
|
{range}
|
||||||
</Typography>
|
</Typography>
|
||||||
) : null}
|
)}
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{report.payees?.length ?? 0} payees · {report.tags?.length ?? 0} tags
|
||||||
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
<IconButton aria-label="Regenerate report" onClick={() => onRegenerated(report)}>
|
||||||
|
<CachedIcon />
|
||||||
|
</IconButton>
|
||||||
<IconButton aria-label="Close report" onClick={onClose}>
|
<IconButton aria-label="Close report" onClick={onClose}>
|
||||||
<CloseIcon />
|
<CloseIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{data === null ? (
|
<Box sx={{ p: 2.5 }}>
|
||||||
<Box sx={{ p: 3 }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "center", mb: 2 }}>
|
||||||
<Alert severity="info" sx={{ borderRadius: 2, mb: 2 }}>
|
<Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap" }}>
|
||||||
The cached data for this report has expired. Regenerate it to rebuild the snapshot.
|
{granularityOptions.map((g: string) => (
|
||||||
</Alert>
|
<Chip
|
||||||
<Button variant="contained" startIcon={<CachedIcon />} onClick={() => onRegenerated(report)}>
|
key={g}
|
||||||
Regenerate
|
label={g}
|
||||||
</Button>
|
clickable
|
||||||
|
size="small"
|
||||||
|
color={activeGranularity === g ? "primary" : "default"}
|
||||||
|
variant={activeGranularity === g ? "filled" : "outlined"}
|
||||||
|
onClick={() => setGranularity(g)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
<FormControl size="small" sx={{ width: 140 }}>
|
||||||
|
<InputLabel id="viewer-flow-label">Flow</InputLabel>
|
||||||
|
<Select labelId="viewer-flow-label" label="Flow" value={flow} onChange={(e) => setFlow(e.target.value)}>
|
||||||
|
{FLOW_OPTIONS.map((f) => (
|
||||||
|
<MenuItem key={f} value={f}>
|
||||||
|
{f}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
|
||||||
<Box sx={{ p: 2.5 }}>
|
|
||||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
|
|
||||||
<Autocomplete
|
|
||||||
size="small"
|
|
||||||
sx={{ width: 220 }}
|
|
||||||
options={["*", ...groupOptions.period]}
|
|
||||||
value={selectedPeriod}
|
|
||||||
onChange={(_, v) => setSelectedPeriod(v ?? "*")}
|
|
||||||
disabled={groupOptions.period.length === 0}
|
|
||||||
renderInput={(params) => <TextField {...params} label="Period" />}
|
|
||||||
/>
|
|
||||||
<Autocomplete
|
|
||||||
size="small"
|
|
||||||
sx={{ width: 220 }}
|
|
||||||
options={["*", ...groupOptions.payee]}
|
|
||||||
value={selectedPayee}
|
|
||||||
onChange={(_, v) => setSelectedPayee(v ?? "*")}
|
|
||||||
disabled={groupOptions.payee.length === 0}
|
|
||||||
renderInput={(params) => <TextField {...params} label="Payee" />}
|
|
||||||
/>
|
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ alignSelf: "center" }}>
|
|
||||||
Showing {slice.count} transactions across {slice.txns.length} rows
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
|
||||||
<StatCard label="Spent" value={formatCurrency(slice.spent, slice.currency)} color="error.main" />
|
<Box sx={{ width: 260 }}>
|
||||||
<StatCard label="Income" value={formatCurrency(slice.income, slice.currency)} color="success.main" />
|
<FkMultiSelectField
|
||||||
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
field={{ ...periodField, readOnly: periodOptions.length === 0 }}
|
||||||
|
fkOptions={periodOptions}
|
||||||
|
value={selectedPeriods}
|
||||||
|
onChange={setSelectedPeriods}
|
||||||
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
<Box sx={{ width: 260 }}>
|
||||||
|
<FkMultiSelectField
|
||||||
|
field={{ ...payeeField, readOnly: payeeOptions.length === 0 }}
|
||||||
|
fkOptions={payeeOptions}
|
||||||
|
value={selectedPayees}
|
||||||
|
onChange={setSelectedPayees}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Box sx={{ width: 260 }}>
|
||||||
|
<FkMultiSelectField
|
||||||
|
field={{ ...tagField, readOnly: tagOptions.length === 0 }}
|
||||||
|
fkOptions={tagOptions}
|
||||||
|
value={selectedTags}
|
||||||
|
onChange={setSelectedTags}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
<Typography variant="body2" color="text.secondary" sx={{ alignSelf: "center" }}>
|
||||||
|
{slice.txns.length} transactions · {slice.count} rows
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 3 }}>
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}>
|
||||||
{metrics.map((m) => {
|
<StatCard label="Outflows" value={formatCurrency(slice.outflows, slice.currency)} color="error.main" />
|
||||||
const value = metricValue(m.key);
|
<StatCard label="Inflows" value={formatCurrency(slice.inflows, slice.currency)} color="success.main" />
|
||||||
if (value == null) return null;
|
<StatCard label="Net" value={formatCurrency(slice.inflows - slice.outflows, slice.currency)} color="info.main" />
|
||||||
|
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ mb: 2.5 }}>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: "relative",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "stretch",
|
||||||
|
width: "fit-content",
|
||||||
|
maxWidth: "100%",
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: "divider",
|
||||||
|
borderRadius: "999px",
|
||||||
|
p: 0.5,
|
||||||
|
backgroundColor: "background.default",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
aria-hidden
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 4,
|
||||||
|
bottom: 4,
|
||||||
|
left: 4,
|
||||||
|
width: `calc((100% - 8px) / ${dimOptions.length})`,
|
||||||
|
borderRadius: "999px",
|
||||||
|
backgroundColor: "primary.main",
|
||||||
|
transform: `translateX(${activeDimIndex * 100}%)`,
|
||||||
|
transition: "transform 250ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{dimOptions.map((d) => {
|
||||||
|
const active = d.id === dim;
|
||||||
return (
|
return (
|
||||||
<Paper key={m.key} variant="outlined" sx={{ px: 1.5, py: 1, borderRadius: 2 }}>
|
<Box
|
||||||
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
|
key={d.id}
|
||||||
{m.label}
|
component="button"
|
||||||
</Typography>
|
type="button"
|
||||||
<Typography variant="body2" fontWeight={600}>
|
disabled={d.count <= 1}
|
||||||
{value}
|
onClick={() => setDim(d.id)}
|
||||||
</Typography>
|
sx={{
|
||||||
</Paper>
|
position: "relative",
|
||||||
|
zIndex: 1,
|
||||||
|
flex: 1,
|
||||||
|
border: "none",
|
||||||
|
background: "transparent",
|
||||||
|
px: 3,
|
||||||
|
py: 1,
|
||||||
|
borderRadius: "999px",
|
||||||
|
cursor: d.count <= 1 ? "default" : "pointer",
|
||||||
|
typography: "body2",
|
||||||
|
fontWeight: 700,
|
||||||
|
letterSpacing: "-0.01em",
|
||||||
|
color:
|
||||||
|
d.count <= 1
|
||||||
|
? "text.disabled"
|
||||||
|
: active
|
||||||
|
? "primary.contrastText"
|
||||||
|
: "text.secondary",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
transition: "color 160ms ease",
|
||||||
|
"&:focus-visible": { outline: "2px solid", outlineColor: "primary.main" },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{d.label}
|
||||||
|
</Box>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{selectedPeriod === "*" && selectedPayee === "*" && pivot.rows.length > 0 && (
|
{visibleBars.length === 0 ? (
|
||||||
<TableContainer
|
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mt: 1.5 }}>
|
||||||
component={Paper}
|
|
||||||
variant="outlined"
|
|
||||||
sx={{ borderRadius: 2, mb: 3, overflowX: "auto" }}
|
|
||||||
>
|
|
||||||
<Table size="small">
|
|
||||||
<TableHead>
|
|
||||||
<TableRow>
|
|
||||||
<TableCell sx={{ fontWeight: 700 }}>Period</TableCell>
|
|
||||||
{pivot.payees.map((payee) => (
|
|
||||||
<TableCell key={payee} align="right" sx={{ fontWeight: 700 }}>
|
|
||||||
{payee}
|
|
||||||
</TableCell>
|
|
||||||
))}
|
|
||||||
<TableCell align="right" sx={{ fontWeight: 700 }}>
|
|
||||||
Total
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
</TableHead>
|
|
||||||
<TableBody>
|
|
||||||
{pivot.rows.map((row) => (
|
|
||||||
<TableRow key={row.period} sx={{ "&:last-child td": { borderBottom: 0 } }}>
|
|
||||||
<TableCell sx={{ fontWeight: 600 }}>{row.period}</TableCell>
|
|
||||||
{row.cells.map((cell) => (
|
|
||||||
<TableCell key={cell.payee} align="right">
|
|
||||||
{cell.sum === 0 ? "—" : formatCurrency(cell.sum, slice.currency)}
|
|
||||||
</TableCell>
|
|
||||||
))}
|
|
||||||
<TableCell align="right" sx={{ fontWeight: 700 }}>
|
|
||||||
{formatCurrency(row.periodSum, slice.currency)}
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
))}
|
|
||||||
<TableRow>
|
|
||||||
<TableCell sx={{ fontWeight: 700 }}>Total</TableCell>
|
|
||||||
{pivot.totals.map((t) => (
|
|
||||||
<TableCell key={t.payee} align="right" sx={{ fontWeight: 700 }}>
|
|
||||||
{formatCurrency(t.sum, slice.currency)}
|
|
||||||
</TableCell>
|
|
||||||
))}
|
|
||||||
<TableCell align="right" sx={{ fontWeight: 700 }}>
|
|
||||||
{formatCurrency(pivot.rows.reduce((s, r) => s + r.periodSum, 0), slice.currency)}
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
|
||||||
</TableContainer>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{slice.txns.length === 0 ? (
|
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3 }}>
|
|
||||||
<Typography variant="body2" color="text.secondary">
|
<Typography variant="body2" color="text.secondary">
|
||||||
No transactions in this slice.
|
No data for this slice. Try another granularity, period or payer.
|
||||||
</Typography>
|
</Typography>
|
||||||
</Paper>
|
</Paper>
|
||||||
) : fields ? (
|
) : (
|
||||||
<TransactionList items={slice.txns} fields={fields} granularity={toPeriodGranularity(report.granularity)} />
|
<Paper variant="outlined" sx={{ borderRadius: 2, mt: 1.5 }}>
|
||||||
) : null}
|
<Box sx={{ display: "flex", alignItems: "stretch" }}>
|
||||||
|
<Box
|
||||||
|
ref={barsListRef}
|
||||||
|
onScroll={updateBarScroll}
|
||||||
|
sx={{
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
maxHeight: 220,
|
||||||
|
overflowY: "auto",
|
||||||
|
py: 1,
|
||||||
|
px: 2,
|
||||||
|
scrollbarWidth: "none",
|
||||||
|
"&::-webkit-scrollbar": { display: "none" },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{visibleBars.map((b) => (
|
||||||
|
<Box key={b.key} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
||||||
|
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
||||||
|
{b.key}
|
||||||
|
</Typography>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
height: 20,
|
||||||
|
borderRadius: 1,
|
||||||
|
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
||||||
|
opacity: 0.85,
|
||||||
|
minWidth: 4,
|
||||||
|
flexGrow: 0,
|
||||||
|
}}
|
||||||
|
style={{
|
||||||
|
width: `${maxBar ? Math.max((Math.abs(b.sum) / maxBar) * 100, 2) : 2}%`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Typography variant="body2" fontWeight={600}>
|
||||||
|
{formatCurrency(b.sum, slice.currency)}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{b.count} txn{b.count === 1 ? "" : "s"}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
{barScroll.overflow && (
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 0.5, pr: 1.5 }}>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
aria-label="Scroll bars up"
|
||||||
|
disabled={!barScroll.canUp}
|
||||||
|
onClick={() => scrollBarsByPage(-1)}
|
||||||
|
>
|
||||||
|
<KeyboardArrowUpIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
aria-label="Scroll bars down"
|
||||||
|
disabled={!barScroll.canDown}
|
||||||
|
onClick={() => scrollBarsByPage(1)}
|
||||||
|
>
|
||||||
|
<KeyboardArrowDownIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
|
||||||
|
{slice.txns.length === 0 ? null : fields ? (
|
||||||
|
<TransactionList fields={fields} groups={listGroups} showMetrics />
|
||||||
|
) : null}
|
||||||
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,25 +1,30 @@
|
|||||||
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
||||||
import { parseDdmmyyyy } from "../common/utils/dates";
|
import { parseOccurredAt } from "../common/utils/dates";
|
||||||
|
|
||||||
export interface ParsedGroupKey {
|
export interface PeriodMetricsVM {
|
||||||
period?: { granularity: string; label: string };
|
outflows: number;
|
||||||
payee?: { label: string };
|
inflows: number;
|
||||||
range?: { start?: string; end?: string };
|
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 ReportGroupLike {
|
export interface ReportPeriodGroup {
|
||||||
key: string;
|
key: string;
|
||||||
group_label?: string;
|
metrics: PeriodMetricsVM;
|
||||||
metrics?: Record<string, any>;
|
txns: any[];
|
||||||
txns?: any[];
|
currency: string;
|
||||||
}
|
|
||||||
|
|
||||||
export interface SliceFilter {
|
|
||||||
period?: string;
|
|
||||||
payee?: 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;
|
||||||
@@ -28,36 +33,18 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PivotCell {
|
export interface SliceFilter {
|
||||||
payee: string;
|
granularity: string;
|
||||||
sum: number;
|
periods?: string[];
|
||||||
count: number;
|
payees?: string[];
|
||||||
}
|
tags?: string[];
|
||||||
|
|
||||||
export interface PivotRow {
|
|
||||||
period: string;
|
|
||||||
cells: PivotCell[];
|
|
||||||
periodSum: number;
|
|
||||||
periodCount: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PivotTable {
|
|
||||||
rows: PivotRow[];
|
|
||||||
payees: string[];
|
|
||||||
totals: PivotCell[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ReportFieldConfigs {
|
export interface ReportFieldConfigs {
|
||||||
groupLabel: FieldConfig;
|
name: FieldConfig;
|
||||||
granularity: FieldConfig;
|
|
||||||
periodLabel: FieldConfig;
|
|
||||||
payee: FieldConfig;
|
|
||||||
entityCount: FieldConfig;
|
|
||||||
generatedAt: FieldConfig;
|
generatedAt: FieldConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,23 +54,6 @@ export interface MetricLabel {
|
|||||||
order: number;
|
order: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Split a concrete cache key into its dimension parts, e.g. `period:monthly:2026-Jan|payee:Zepto`. */
|
|
||||||
export function parseCacheKey(key: string): ParsedGroupKey {
|
|
||||||
const out: ParsedGroupKey = {};
|
|
||||||
for (const dim of key.split("|")) {
|
|
||||||
if (!dim) continue;
|
|
||||||
const [name, ...rest] = dim.split(":");
|
|
||||||
if (name === "period" && rest.length >= 2) {
|
|
||||||
out.period = { granularity: rest[0], label: rest.slice(1).join(":") };
|
|
||||||
} else if (name === "payee" && rest.length >= 1) {
|
|
||||||
out.payee = { label: rest.join(":") };
|
|
||||||
} else if (name === "range" && rest.length >= 1) {
|
|
||||||
out.range = { start: rest[0] || undefined, end: rest[1] || undefined };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function apiErrorMessage(e: any): string {
|
export function apiErrorMessage(e: any): string {
|
||||||
if (e?.response?.data) {
|
if (e?.response?.data) {
|
||||||
const d = e.response.data;
|
const d = e.response.data;
|
||||||
@@ -95,14 +65,7 @@ export function apiErrorMessage(e: any): string {
|
|||||||
return e?.message ?? "Request failed";
|
return e?.message ?? "Request failed";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function groupTypeEnum(schemas: Record<string, any>): string[] {
|
export const FLOW_OPTIONS = ["both", "inflows", "outflows"];
|
||||||
return schemas?.GroupSpec?.properties?.group_type?.enum ?? [];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function groupValueFk(schemas: Record<string, any>): { resource?: string; prefetch?: boolean } | null {
|
|
||||||
const fk = schemas?.GroupSpec?.properties?.group_value?.["x-fk"];
|
|
||||||
return fk && typeof fk === "object" ? fk : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
||||||
const props: Record<string, any> = schemas?.ReportMetrics?.properties ?? {};
|
const props: Record<string, any> = schemas?.ReportMetrics?.properties ?? {};
|
||||||
@@ -116,123 +79,210 @@ export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
|||||||
.sort((a, b) => a.order - b.order);
|
.sort((a, b) => a.order - b.order);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function periodHints(granularity: string): string[] {
|
|
||||||
const y = new Date().getFullYear();
|
|
||||||
switch (granularity) {
|
|
||||||
case "weekly":
|
|
||||||
return [`${y}-W01`, `${y}-W26`];
|
|
||||||
case "monthly":
|
|
||||||
return [`${y}-Jan`, `${y}-Feb`];
|
|
||||||
case "quarterly":
|
|
||||||
return [`${y}-Jan-Mar`, `${y}-Apr-Jun`];
|
|
||||||
case "yearly":
|
|
||||||
return [`${y - 1}`, `${y}`];
|
|
||||||
default:
|
|
||||||
return [`${y}-Jan`, `${y}-W01`, `${y}-Jan-Mar`, `${y}`];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function dateVal(value: string): number {
|
function dateVal(value: string): number {
|
||||||
try {
|
try {
|
||||||
return parseDdmmyyyy(value).getTime();
|
return parseOccurredAt(value).getTime();
|
||||||
} catch {
|
} catch {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function groupMatches(group: ReportGroupLike, filter: SliceFilter): boolean {
|
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
||||||
const key = parseCacheKey(group.key);
|
const gk = bucket?.group_key ?? {};
|
||||||
if (filter.period && filter.period !== "*") {
|
if (filter.payees?.length && !(gk.payee ?? []).some((p: string) => filter.payees?.includes(p))) return false;
|
||||||
if (!key.period || key.period.label !== filter.period) return false;
|
if (filter.tags?.length && !(gk.tag ?? []).some((t: string) => filter.tags?.includes(t))) return false;
|
||||||
}
|
|
||||||
if (filter.payee && filter.payee !== "*") {
|
|
||||||
if (!key.payee || key.payee.label !== filter.payee) return false;
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function aggregateSlice(groups: ReportGroupLike[], filter: SliceFilter): SliceSummary {
|
function num(v: any): number | null {
|
||||||
let sum = 0;
|
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
||||||
let count = 0;
|
}
|
||||||
let spent = 0;
|
|
||||||
let income = 0;
|
/**
|
||||||
|
* Groups cube periods by their canonical period_id, merging buckets per
|
||||||
|
* period. The server returns disjoint slices, so additive metric merge is
|
||||||
|
* safe; txn ids are deduped defensively. Metrics come verbatim from the API
|
||||||
|
* except when multiple buckets contribute to one period — then cadence and
|
||||||
|
* frequency are re-derived from the merged txn dates.
|
||||||
|
*/
|
||||||
|
export function buildPeriodGroups(buckets: any[], filter: SliceFilter): ReportPeriodGroup[] {
|
||||||
|
interface Acc {
|
||||||
|
metrics: PeriodMetricsVM;
|
||||||
|
txns: any[];
|
||||||
|
sources: number;
|
||||||
|
apiCadence: number | null;
|
||||||
|
apiFrequency: number | null;
|
||||||
|
}
|
||||||
|
const byPeriod = new Map<string, Acc>();
|
||||||
|
const seenTxnIds = new Set<string>();
|
||||||
|
let currency = "INR";
|
||||||
|
|
||||||
|
for (const bucket of buckets ?? []) {
|
||||||
|
if (!bucketMatches(bucket, filter)) continue;
|
||||||
|
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
||||||
|
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
||||||
|
const m = period.metrics ?? {};
|
||||||
|
let acc = byPeriod.get(period.period_id);
|
||||||
|
if (!acc) {
|
||||||
|
acc = {
|
||||||
|
metrics: {
|
||||||
|
outflows: 0,
|
||||||
|
inflows: 0,
|
||||||
|
sum: 0,
|
||||||
|
count: 0,
|
||||||
|
avg: null,
|
||||||
|
min: null,
|
||||||
|
max: null,
|
||||||
|
firstDate: null,
|
||||||
|
lastDate: null,
|
||||||
|
cadence: null,
|
||||||
|
frequency: null,
|
||||||
|
},
|
||||||
|
txns: [],
|
||||||
|
sources: 0,
|
||||||
|
apiCadence: num(m.cadence),
|
||||||
|
apiFrequency: num(m.frequency),
|
||||||
|
};
|
||||||
|
byPeriod.set(period.period_id, acc);
|
||||||
|
}
|
||||||
|
acc.sources += 1;
|
||||||
|
const vm = acc.metrics;
|
||||||
|
vm.outflows += m.outflows ?? 0;
|
||||||
|
vm.inflows += m.inflows ?? 0;
|
||||||
|
vm.sum += m.sum ?? 0;
|
||||||
|
vm.count += m.count ?? 0;
|
||||||
|
const mn = num(m.min);
|
||||||
|
if (mn != null) vm.min = vm.min == null ? mn : Math.min(vm.min, mn);
|
||||||
|
const mx = num(m.max);
|
||||||
|
if (mx != null) vm.max = vm.max == null ? mx : Math.max(vm.max, mx);
|
||||||
|
if (m.first_date && (!vm.firstDate || dateVal(String(m.first_date)) < dateVal(vm.firstDate))) {
|
||||||
|
vm.firstDate = String(m.first_date);
|
||||||
|
}
|
||||||
|
if (m.last_date && (!vm.lastDate || dateVal(String(m.last_date)) > dateVal(vm.lastDate))) {
|
||||||
|
vm.lastDate = String(m.last_date);
|
||||||
|
}
|
||||||
|
for (const txn of period.txns ?? []) {
|
||||||
|
if (txn?.id != null) {
|
||||||
|
if (seenTxnIds.has(txn.id)) continue;
|
||||||
|
seenTxnIds.add(txn.id);
|
||||||
|
}
|
||||||
|
acc.txns.push(txn);
|
||||||
|
const c = txn?.account?.currency;
|
||||||
|
if (c) currency = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...byPeriod.entries()]
|
||||||
|
.map(([key, acc]) => {
|
||||||
|
const vm = acc.metrics;
|
||||||
|
vm.avg = vm.count ? Math.round((vm.sum / vm.count) * 100) / 100 : null;
|
||||||
|
if (acc.sources > 1) {
|
||||||
|
const dates = acc.txns
|
||||||
|
.map((t) => {
|
||||||
|
try {
|
||||||
|
return parseOccurredAt(t?.occurred_at).getTime();
|
||||||
|
} catch {
|
||||||
|
return NaN;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((t) => !Number.isNaN(t))
|
||||||
|
.sort((a, b) => a - b);
|
||||||
|
if (dates.length >= 2) {
|
||||||
|
let gapSum = 0;
|
||||||
|
for (let i = 0; i < dates.length - 1; i += 1) gapSum += (dates[i + 1] - dates[i]) / 86400000;
|
||||||
|
const cadence = Math.round((gapSum / (dates.length - 1)) * 100) / 100;
|
||||||
|
vm.cadence = cadence > 0 ? cadence : null;
|
||||||
|
vm.frequency = cadence > 0 ? Math.round((1 / cadence) * 100) / 100 : null;
|
||||||
|
} else {
|
||||||
|
vm.cadence = null;
|
||||||
|
vm.frequency = null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
vm.cadence = acc.apiCadence;
|
||||||
|
vm.frequency = acc.apiFrequency;
|
||||||
|
}
|
||||||
|
return { key, metrics: vm, txns: acc.txns, currency };
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.key.localeCompare(a.key));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sliceSummary(groups: ReportPeriodGroup[]): SliceSummary {
|
||||||
|
const outflows = groups.reduce((s, g) => s + g.metrics.outflows, 0);
|
||||||
|
const inflows = groups.reduce((s, g) => s + g.metrics.inflows, 0);
|
||||||
|
const sum = groups.reduce((s, g) => s + g.metrics.sum, 0);
|
||||||
|
const count = groups.reduce((s, g) => s + g.metrics.count, 0);
|
||||||
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[] = [];
|
||||||
const seen = new Set<string>();
|
for (const g of groups) {
|
||||||
|
if (g.metrics.min != null) min = min == null ? g.metrics.min : Math.min(min, g.metrics.min);
|
||||||
for (const group of groups) {
|
if (g.metrics.max != null) max = max == null ? g.metrics.max : Math.max(max, g.metrics.max);
|
||||||
if (!groupMatches(group, filter)) continue;
|
if (g.metrics.firstDate && (!firstDate || dateVal(g.metrics.firstDate) < dateVal(firstDate))) {
|
||||||
const m = group.metrics ?? {};
|
firstDate = g.metrics.firstDate;
|
||||||
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))) {
|
if (g.metrics.lastDate && (!lastDate || dateVal(g.metrics.lastDate) > dateVal(lastDate))) {
|
||||||
lastDate = String(m.last_date);
|
lastDate = g.metrics.lastDate;
|
||||||
}
|
|
||||||
for (const txn of group.txns ?? []) {
|
|
||||||
if (txn?.id != null) {
|
|
||||||
if (seen.has(txn.id)) continue;
|
|
||||||
seen.add(txn.id);
|
|
||||||
}
|
|
||||||
txns.push(txn);
|
|
||||||
const amt = Number(txn?.amount ?? 0);
|
|
||||||
if (amt < 0) spent += Math.abs(amt);
|
|
||||||
else income += amt;
|
|
||||||
const c = txn?.account?.currency;
|
|
||||||
if (c) currency = c;
|
|
||||||
}
|
}
|
||||||
|
if (g.currency) currency = g.currency;
|
||||||
|
txns.push(...g.txns);
|
||||||
}
|
}
|
||||||
|
return { outflows, inflows, sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, currency };
|
||||||
return { sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, spent, income, currency };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildPivot(groups: ReportGroupLike[], periodOrder: string[], payeeOrder: string[]): PivotTable {
|
|
||||||
const payees = payeeOrder.filter((payee) =>
|
|
||||||
groups.some((g) => parseCacheKey(g.key).payee?.label === payee),
|
|
||||||
);
|
|
||||||
const totals = payees.map((payee) => ({ payee, sum: 0, count: 0 }));
|
|
||||||
const rows: PivotRow[] = [];
|
|
||||||
|
|
||||||
for (const period of periodOrder) {
|
|
||||||
const periodGroups = groups.filter((g) => parseCacheKey(g.key).period?.label === period);
|
|
||||||
if (periodGroups.length === 0) continue;
|
|
||||||
const cells = payees.map((payee, i) => {
|
|
||||||
const cellGroups = periodGroups.filter((g) => parseCacheKey(g.key).payee?.label === payee);
|
|
||||||
const sum = cellGroups.reduce((s, g) => s + (g.metrics?.sum ?? 0), 0);
|
|
||||||
const count = cellGroups.reduce((s, g) => s + (g.metrics?.count ?? 0), 0);
|
|
||||||
totals[i].sum += sum;
|
|
||||||
totals[i].count += count;
|
|
||||||
return { payee, sum, count };
|
|
||||||
});
|
|
||||||
rows.push({
|
|
||||||
period,
|
|
||||||
cells,
|
|
||||||
periodSum: cells.reduce((s, c) => s + c.sum, 0),
|
|
||||||
periodCount: cells.reduce((s, c) => s + c.count, 0),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return { rows, payees, totals };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
||||||
const reportsRes = resources.find((r) => r.name === "reports");
|
const reportsRes = resources.find((r) => r.name === "reports");
|
||||||
if (!reportsRes) return null;
|
if (!reportsRes) return null;
|
||||||
const find = (name: string) => reportsRes.fields.find((f) => f.name === name);
|
const find = (name: string) => reportsRes.fields.find((f) => f.name === name);
|
||||||
const groupLabel = find("group_label");
|
const name = find("name");
|
||||||
const granularity = find("granularity");
|
|
||||||
const periodLabel = find("period_label");
|
|
||||||
const payee = find("payee");
|
|
||||||
const entityCount = find("entity_count");
|
|
||||||
const generatedAt = find("generated_at");
|
const generatedAt = find("generated_at");
|
||||||
if (!groupLabel || !granularity || !periodLabel || !payee || !entityCount || !generatedAt) return null;
|
if (!name || !generatedAt) return null;
|
||||||
return { groupLabel, granularity, periodLabel, payee, entityCount, 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));
|
||||||
}
|
}
|
||||||
@@ -14,21 +14,83 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
|||||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
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 { 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";
|
||||||
|
|
||||||
interface TransactionListProps {
|
interface TransactionListProps {
|
||||||
items: ExpenseItem[];
|
items?: ExpenseItem[];
|
||||||
fields: TxnFieldConfigs;
|
fields: TxnFieldConfigs;
|
||||||
granularity?: PeriodGranularity;
|
granularity?: PeriodGranularity;
|
||||||
|
showMetrics?: boolean;
|
||||||
|
groups?: ListPeriodGroup[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function TransactionList({ items, fields, granularity = "monthly" }: TransactionListProps) {
|
function cadenceRow(cadenceDays: number | null, frequency: number | null): { label: string; value: string } {
|
||||||
|
const fmt = (v: number) => (Number.isInteger(v) ? String(v) : v.toFixed(2));
|
||||||
|
if (cadenceDays != null && cadenceDays < 1) {
|
||||||
|
return { label: "Frequency", value: `${frequency == null ? "—" : fmt(frequency)} /day` };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
label: "Cadence",
|
||||||
|
value: cadenceDays == null ? "—" : `${fmt(cadenceDays)} days`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function txnFallbackMetrics(items: ExpenseItem[]): ListGroupMetrics {
|
||||||
|
const t = computeTxnMetrics(items);
|
||||||
|
return {
|
||||||
|
sum: t.sum,
|
||||||
|
count: t.count,
|
||||||
|
avg: t.avg,
|
||||||
|
min: t.min,
|
||||||
|
max: t.max,
|
||||||
|
cadence: t.cadenceDays,
|
||||||
|
frequency: t.frequency,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function GroupMetrics({
|
||||||
|
items,
|
||||||
|
currency,
|
||||||
|
metrics,
|
||||||
|
}: {
|
||||||
|
items: ExpenseItem[];
|
||||||
|
currency: string;
|
||||||
|
metrics?: ListGroupMetrics;
|
||||||
|
}) {
|
||||||
|
const m = metrics ?? txnFallbackMetrics(items);
|
||||||
|
const rows: { label: string; value: string }[] = [
|
||||||
|
{ label: "Sum", value: formatCurrency(m.sum, currency) },
|
||||||
|
{ label: "Avg", value: m.avg == null ? "—" : formatCurrency(m.avg, currency) },
|
||||||
|
{ label: "Min", value: m.min == null ? "—" : formatCurrency(m.min, currency) },
|
||||||
|
{ label: "Max", value: m.max == null ? "—" : formatCurrency(m.max, currency) },
|
||||||
|
cadenceRow(m.cadence, m.frequency),
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", width: "100%" }}>
|
||||||
|
{rows.map((row) => (
|
||||||
|
<StatCard key={row.label} label={row.label} value={row.value} />
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
@@ -136,28 +198,34 @@ export function TransactionList({ items, fields, granularity = "monthly" }: Tran
|
|||||||
px: 2,
|
px: 2,
|
||||||
py: 1,
|
py: 1,
|
||||||
"& .MuiAccordionSummary-content": {
|
"& .MuiAccordionSummary-content": {
|
||||||
alignItems: "center",
|
flexDirection: "column",
|
||||||
gap: 1.5,
|
alignItems: "stretch",
|
||||||
|
gap: 0.75,
|
||||||
minWidth: 0,
|
minWidth: 0,
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, minWidth: 0 }}>
|
||||||
{group.label}
|
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||||
</Typography>
|
{group.label}
|
||||||
<Typography variant="caption" color="text.secondary">
|
</Typography>
|
||||||
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
<Typography variant="caption" color="text.secondary">
|
||||||
</Typography>
|
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
||||||
<Box sx={{ flex: 1 }} />
|
</Typography>
|
||||||
<Typography variant="body2" fontWeight={700} color="error.main">
|
<Box sx={{ flex: 1 }} />
|
||||||
{formatCurrency(group.spent, group.currency)}
|
<Typography variant="body2" fontWeight={700} color="error.main">
|
||||||
</Typography>
|
{formatCurrency(group.spent, group.currency)}
|
||||||
<Typography variant="body2" color="text.disabled">
|
</Typography>
|
||||||
/
|
<Typography variant="body2" color="text.disabled">
|
||||||
</Typography>
|
/
|
||||||
<Typography variant="body2" fontWeight={700} color="success.main">
|
</Typography>
|
||||||
{formatCurrency(group.income, group.currency)}
|
<Typography variant="body2" fontWeight={700} color="success.main">
|
||||||
</Typography>
|
{formatCurrency(group.income, group.currency)}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
{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 {
|
||||||
@@ -107,3 +116,46 @@ export function groupByPeriod(items: ExpenseItem[], granularity: PeriodGranulari
|
|||||||
})
|
})
|
||||||
.sort((a, b) => b.key.localeCompare(a.key));
|
.sort((a, b) => b.key.localeCompare(a.key));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface TxnMetrics {
|
||||||
|
sum: number;
|
||||||
|
count: number;
|
||||||
|
avg: number | null;
|
||||||
|
min: number | null;
|
||||||
|
max: number | null;
|
||||||
|
cadenceDays: number | null;
|
||||||
|
frequency: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mirrors backend ReportMetrics.compute_metrics over a list of transactions. */
|
||||||
|
export function computeTxnMetrics(items: ExpenseItem[]): TxnMetrics {
|
||||||
|
const amounts = items.filter((it) => typeof it.amount === "number").map((it) => it.amount as number);
|
||||||
|
const empty = { sum: 0, count: 0, avg: null, min: null, max: null, cadenceDays: null, frequency: null };
|
||||||
|
if (amounts.length === 0) {
|
||||||
|
return empty;
|
||||||
|
}
|
||||||
|
const dates = items
|
||||||
|
.map((it) => it.occurred_at)
|
||||||
|
.filter((d): d is string => !!d)
|
||||||
|
.map((d) => parseOccurredAt(d).getTime())
|
||||||
|
.sort((a, b) => a - b);
|
||||||
|
const sum = amounts.reduce((s, a) => s + a, 0);
|
||||||
|
let cadenceDays: number | null = null;
|
||||||
|
if (dates.length >= 2) {
|
||||||
|
const gaps: number[] = [];
|
||||||
|
for (let i = 0; i < dates.length - 1; i += 1) {
|
||||||
|
gaps.push((dates[i + 1] - dates[i]) / 86400000);
|
||||||
|
}
|
||||||
|
cadenceDays = Math.round((gaps.reduce((s, g) => s + g, 0) / gaps.length) * 100) / 100;
|
||||||
|
}
|
||||||
|
const frequency = cadenceDays != null && cadenceDays > 0 ? Math.round((1 / cadenceDays) * 100) / 100 : null;
|
||||||
|
return {
|
||||||
|
sum,
|
||||||
|
count: amounts.length,
|
||||||
|
avg: sum / amounts.length,
|
||||||
|
min: Math.min(...amounts),
|
||||||
|
max: Math.max(...amounts),
|
||||||
|
cadenceDays,
|
||||||
|
frequency,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -7,7 +7,10 @@ export type FetchRequestStatus =
|
|||||||
| "completed"
|
| "completed"
|
||||||
| "failed";
|
| "failed";
|
||||||
|
|
||||||
|
export type SourceType = "file" | "pdf" | "xlsx" | "csv" | "email";
|
||||||
|
|
||||||
export interface FileSource {
|
export interface FileSource {
|
||||||
|
type?: SourceType;
|
||||||
path: string;
|
path: string;
|
||||||
bank: string;
|
bank: string;
|
||||||
raw_lines?: string[];
|
raw_lines?: string[];
|
||||||
@@ -17,7 +20,20 @@ export interface FileSource {
|
|||||||
txn_dicts_count?: number;
|
txn_dicts_count?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PdfSource extends FileSource {
|
||||||
|
type: "pdf";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface XlsxSource extends FileSource {
|
||||||
|
type: "xlsx";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CsvSource extends FileSource {
|
||||||
|
type: "csv";
|
||||||
|
}
|
||||||
|
|
||||||
export interface EmailSource {
|
export interface EmailSource {
|
||||||
|
type: "email";
|
||||||
bank: string;
|
bank: string;
|
||||||
from_email?: string;
|
from_email?: string;
|
||||||
subject?: string;
|
subject?: string;
|
||||||
@@ -26,12 +42,15 @@ 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 type TrustFallback = "amount" | "balance";
|
||||||
|
|
||||||
export interface FetchRequestCreate {
|
export interface FetchRequestCreate {
|
||||||
source: FileSource | EmailSource;
|
source: PdfSource | XlsxSource | CsvSource | EmailSource;
|
||||||
account_name: string;
|
account_name: string;
|
||||||
pipeline?: PipelineType;
|
pipeline?: PipelineType;
|
||||||
|
trust_fallback?: TrustFallback | null;
|
||||||
payor_username?: string;
|
payor_username?: string;
|
||||||
start_date?: string;
|
start_date?: string;
|
||||||
end_date?: string;
|
end_date?: string;
|
||||||
@@ -113,7 +132,7 @@ export interface SSEEvent {
|
|||||||
export interface FetchRequestFilters {
|
export interface FetchRequestFilters {
|
||||||
status?: FetchRequestStatus[];
|
status?: FetchRequestStatus[];
|
||||||
account_name?: string;
|
account_name?: string;
|
||||||
source_type?: "file" | "email";
|
source_type?: SourceType;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatApiError(err: any): string {
|
export function formatApiError(err: any): string {
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ export type {
|
|||||||
FetchRequestStatus,
|
FetchRequestStatus,
|
||||||
FetchRequestFilters,
|
FetchRequestFilters,
|
||||||
FileSource,
|
FileSource,
|
||||||
|
PdfSource,
|
||||||
|
XlsxSource,
|
||||||
|
SourceType,
|
||||||
EmailSource,
|
EmailSource,
|
||||||
UploadResult,
|
UploadResult,
|
||||||
PendingAmbiguity,
|
PendingAmbiguity,
|
||||||
@@ -15,6 +18,7 @@ export type {
|
|||||||
SSEEventStatus,
|
SSEEventStatus,
|
||||||
ProgressMessage,
|
ProgressMessage,
|
||||||
PipelineType,
|
PipelineType,
|
||||||
|
TrustFallback,
|
||||||
} from "./fetch-requests.models";
|
} from "./fetch-requests.models";
|
||||||
export { RETRY_MAX, formatApiError } from "./fetch-requests.models";
|
export { RETRY_MAX, formatApiError } from "./fetch-requests.models";
|
||||||
export {
|
export {
|
||||||
|
|||||||
Reference in New Issue
Block a user