Compare commits
3 Commits
3837c9239e
...
main
| 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
|
||||||
|
|||||||
@@ -17,5 +17,6 @@ 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";
|
||||||
|
|||||||
@@ -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>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -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) : "";
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,6 +131,7 @@ 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,
|
||||||
|
|||||||
@@ -101,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;
|
||||||
|
|||||||
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);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
"&:hover": { borderColor: "primary.light" },
|
"&:hover": { borderColor: "primary.light" },
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, 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.name || report.id}
|
{report.name || report.id}
|
||||||
@@ -81,14 +81,15 @@ export function ReportList({ reports, loading, fields, selectedId, onView, onReg
|
|||||||
{amounts}
|
{amounts}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
{fields && (
|
|
||||||
<Box sx={{ color: "text.secondary" }}>
|
|
||||||
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
{fields && (
|
||||||
|
<Box sx={{ ml: "auto", flexShrink: 0, color: "text.secondary" }}>
|
||||||
|
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
|
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
|
||||||
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
||||||
View
|
View
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
|
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
|
||||||
import CloseIcon from "@mui/icons-material/Close";
|
import CloseIcon from "@mui/icons-material/Close";
|
||||||
import CachedIcon from "@mui/icons-material/Cached";
|
import CachedIcon from "@mui/icons-material/Cached";
|
||||||
import { FkMultiSelectField, 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 type { FieldConfig } from "../../react-openapi";
|
||||||
import { StatCard } from "../common/components/StatCard";
|
import { StatCard } from "../common/components/StatCard";
|
||||||
import { TransactionList } from "../common/components/TransactionList";
|
import { TransactionList } from "../common/components/TransactionList";
|
||||||
import type { TxnFieldConfigs } from "../common/types";
|
import type { TxnFieldConfigs } from "../common/types";
|
||||||
import type { ListPeriodGroup } from "../common/utils/transactions";
|
import type { ListPeriodGroup } from "../common/utils/transactions";
|
||||||
import { buildPeriodGroups, sliceSummary, FLOW_OPTIONS, apiErrorMessage } from "./types";
|
import { buildDimensionBars, buildPeriodGroups, sliceSummary, FLOW_OPTIONS, apiErrorMessage } from "./types";
|
||||||
|
import type { ReportDim } from "./types";
|
||||||
|
|
||||||
|
const MAX_VISIBLE_BARS = 10;
|
||||||
|
|
||||||
const periodField: FieldConfig = {
|
const periodField: FieldConfig = {
|
||||||
name: "period",
|
name: "period",
|
||||||
@@ -78,6 +83,7 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
const [reload, setReload] = useState(0);
|
const [reload, setReload] = useState(0);
|
||||||
const [granularity, setGranularity] = useState<string | null>(null);
|
const [granularity, setGranularity] = useState<string | null>(null);
|
||||||
const [flow, setFlow] = useState("outflows");
|
const [flow, setFlow] = useState("outflows");
|
||||||
|
const [dim, setDim] = useState<ReportDim>("period");
|
||||||
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
|
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
|
||||||
const [selectedPayees, setSelectedPayees] = useState<string[]>([]);
|
const [selectedPayees, setSelectedPayees] = useState<string[]>([]);
|
||||||
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||||
@@ -87,10 +93,14 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
const p: Record<string, any> = { flow };
|
const p: Record<string, any> = { flow };
|
||||||
if (granularity) p.granularity = [granularity];
|
if (granularity) p.granularity = [granularity];
|
||||||
if (selectedPeriods.length) p.period_ids = selectedPeriods;
|
if (selectedPeriods.length) p.period_ids = selectedPeriods;
|
||||||
|
// The active breakdown dim requests every cube value ("*") when its own
|
||||||
|
// filter is unselected, so bars show the full distribution.
|
||||||
if (selectedPayees.length) p.payee = selectedPayees;
|
if (selectedPayees.length) p.payee = selectedPayees;
|
||||||
|
else if (dim === "payee") p.payee = ["*"];
|
||||||
if (selectedTags.length) p.tags = selectedTags;
|
if (selectedTags.length) p.tags = selectedTags;
|
||||||
|
else if (dim === "tag") p.tags = ["*"];
|
||||||
return p;
|
return p;
|
||||||
}, [granularity, flow, selectedPeriods, selectedPayees, selectedTags]);
|
}, [granularity, flow, dim, selectedPeriods, selectedPayees, selectedTags]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let mounted = true;
|
let mounted = true;
|
||||||
@@ -145,6 +155,8 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
|
|
||||||
const periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]);
|
const periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]);
|
||||||
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]);
|
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]);
|
||||||
|
const bars = useMemo(() => buildDimensionBars(report?.buckets ?? [], filter, dim), [report, filter, dim]);
|
||||||
|
const visibleBars = useMemo(() => bars.slice(0, MAX_VISIBLE_BARS), [bars]);
|
||||||
const listGroups = useMemo<ListPeriodGroup[]>(
|
const listGroups = useMemo<ListPeriodGroup[]>(
|
||||||
() =>
|
() =>
|
||||||
periodGroups.map((g) => ({
|
periodGroups.map((g) => ({
|
||||||
@@ -167,6 +179,32 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
[periodGroups],
|
[periodGroups],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const barsListRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [barScroll, setBarScroll] = useState({ canUp: false, canDown: false, overflow: false });
|
||||||
|
|
||||||
|
const updateBarScroll = useCallback(() => {
|
||||||
|
const el = barsListRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const overflow = el.scrollHeight > el.clientHeight + 2;
|
||||||
|
setBarScroll({
|
||||||
|
overflow,
|
||||||
|
canUp: overflow && el.scrollTop > 2,
|
||||||
|
canDown: overflow && el.scrollTop < el.scrollHeight - el.clientHeight - 2,
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = barsListRef.current;
|
||||||
|
if (el) el.scrollTop = 0;
|
||||||
|
updateBarScroll();
|
||||||
|
}, [dim, visibleBars.length, updateBarScroll]);
|
||||||
|
|
||||||
|
const scrollBarsByPage = useCallback((dir: number) => {
|
||||||
|
const el = barsListRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
el.scrollTo({ top: dir > 0 ? el.scrollHeight : 0, behavior: "smooth" });
|
||||||
|
}, []);
|
||||||
|
|
||||||
if (loading && !report) {
|
if (loading && !report) {
|
||||||
return (
|
return (
|
||||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
||||||
@@ -193,7 +231,16 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
if (!report) return null;
|
if (!report) return null;
|
||||||
|
|
||||||
const activeGranularity = granularity ?? report.granularities?.[0] ?? "";
|
const activeGranularity = granularity ?? report.granularities?.[0] ?? "";
|
||||||
const maxBar = periodGroups.reduce((m, g) => Math.max(m, g.metrics.sum), 0);
|
const maxBar = bars.reduce((m, b) => Math.max(m, Math.abs(b.sum)), 0);
|
||||||
|
const dimOptions: { id: ReportDim; label: string; count: number }[] = [
|
||||||
|
{ id: "period", label: "Period", count: report.period_ids?.length ?? 0 },
|
||||||
|
{ id: "payee", label: "Payees", count: report.payees?.length ?? 0 },
|
||||||
|
{ id: "tag", label: "Tags", count: report.tags?.length ?? 0 },
|
||||||
|
];
|
||||||
|
const activeDimIndex = Math.max(
|
||||||
|
0,
|
||||||
|
dimOptions.findIndex((d) => d.id === dim),
|
||||||
|
);
|
||||||
const range =
|
const range =
|
||||||
report.query?.start_date || report.query?.end_date
|
report.query?.start_date || report.query?.end_date
|
||||||
? `range ${report.query.start_date || "…"} → ${report.query.end_date || "…"}`
|
? `range ${report.query.start_date || "…"} → ${report.query.end_date || "…"}`
|
||||||
@@ -219,7 +266,7 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
</Typography>
|
</Typography>
|
||||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
flow {report.flow} · generated {report.generated_at ?? report.created_at}
|
flow {report.flow} · generated {formatDateTime(report.generated_at ?? report.created_at)}
|
||||||
</Typography>
|
</Typography>
|
||||||
{range && (
|
{range && (
|
||||||
<Typography variant="caption" color="text.disabled">
|
<Typography variant="caption" color="text.disabled">
|
||||||
@@ -303,39 +350,148 @@ export function ReportViewer({ id, version, fields, onClose, onRegenerated }: Re
|
|||||||
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{periodGroups.length === 0 ? (
|
<Box sx={{ mb: 2.5 }}>
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mb: 2.5 }}>
|
<Box
|
||||||
<Typography variant="body2" color="text.secondary">
|
sx={{
|
||||||
No data for this slice. Try another granularity, period or payer.
|
position: "relative",
|
||||||
</Typography>
|
display: "flex",
|
||||||
</Paper>
|
alignItems: "stretch",
|
||||||
) : (
|
width: "fit-content",
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 2, mb: 2.5 }}>
|
maxWidth: "100%",
|
||||||
{periodGroups.map((g) => (
|
border: "1px solid",
|
||||||
<Box key={g.key} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
borderColor: "divider",
|
||||||
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
borderRadius: "999px",
|
||||||
{g.key}
|
p: 0.5,
|
||||||
</Typography>
|
backgroundColor: "background.default",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Box
|
||||||
|
aria-hidden
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 4,
|
||||||
|
bottom: 4,
|
||||||
|
left: 4,
|
||||||
|
width: `calc((100% - 8px) / ${dimOptions.length})`,
|
||||||
|
borderRadius: "999px",
|
||||||
|
backgroundColor: "primary.main",
|
||||||
|
transform: `translateX(${activeDimIndex * 100}%)`,
|
||||||
|
transition: "transform 250ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{dimOptions.map((d) => {
|
||||||
|
const active = d.id === dim;
|
||||||
|
return (
|
||||||
<Box
|
<Box
|
||||||
|
key={d.id}
|
||||||
|
component="button"
|
||||||
|
type="button"
|
||||||
|
disabled={d.count <= 1}
|
||||||
|
onClick={() => setDim(d.id)}
|
||||||
sx={{
|
sx={{
|
||||||
height: 20,
|
position: "relative",
|
||||||
borderRadius: 1,
|
zIndex: 1,
|
||||||
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
flex: 1,
|
||||||
opacity: 0.85,
|
border: "none",
|
||||||
minWidth: 4,
|
background: "transparent",
|
||||||
|
px: 3,
|
||||||
|
py: 1,
|
||||||
|
borderRadius: "999px",
|
||||||
|
cursor: d.count <= 1 ? "default" : "pointer",
|
||||||
|
typography: "body2",
|
||||||
|
fontWeight: 700,
|
||||||
|
letterSpacing: "-0.01em",
|
||||||
|
color:
|
||||||
|
d.count <= 1
|
||||||
|
? "text.disabled"
|
||||||
|
: active
|
||||||
|
? "primary.contrastText"
|
||||||
|
: "text.secondary",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
transition: "color 160ms ease",
|
||||||
|
"&:focus-visible": { outline: "2px solid", outlineColor: "primary.main" },
|
||||||
}}
|
}}
|
||||||
style={{ width: `${maxBar ? Math.max((g.metrics.sum / maxBar) * 100, 2) : 2}%` }}
|
>
|
||||||
/>
|
{d.label}
|
||||||
<Typography variant="body2" fontWeight={600}>
|
</Box>
|
||||||
{formatCurrency(g.metrics.sum, slice.currency)}
|
);
|
||||||
</Typography>
|
})}
|
||||||
<Typography variant="caption" color="text.disabled">
|
</Box>
|
||||||
{g.metrics.count} txn{g.metrics.count === 1 ? "" : "s"}
|
|
||||||
</Typography>
|
{visibleBars.length === 0 ? (
|
||||||
|
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mt: 1.5 }}>
|
||||||
|
<Typography variant="body2" color="text.secondary">
|
||||||
|
No data for this slice. Try another granularity, period or payer.
|
||||||
|
</Typography>
|
||||||
|
</Paper>
|
||||||
|
) : (
|
||||||
|
<Paper variant="outlined" sx={{ borderRadius: 2, mt: 1.5 }}>
|
||||||
|
<Box sx={{ display: "flex", alignItems: "stretch" }}>
|
||||||
|
<Box
|
||||||
|
ref={barsListRef}
|
||||||
|
onScroll={updateBarScroll}
|
||||||
|
sx={{
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
maxHeight: 220,
|
||||||
|
overflowY: "auto",
|
||||||
|
py: 1,
|
||||||
|
px: 2,
|
||||||
|
scrollbarWidth: "none",
|
||||||
|
"&::-webkit-scrollbar": { display: "none" },
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{visibleBars.map((b) => (
|
||||||
|
<Box key={b.key} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
||||||
|
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
||||||
|
{b.key}
|
||||||
|
</Typography>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
height: 20,
|
||||||
|
borderRadius: 1,
|
||||||
|
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
||||||
|
opacity: 0.85,
|
||||||
|
minWidth: 4,
|
||||||
|
flexGrow: 0,
|
||||||
|
}}
|
||||||
|
style={{
|
||||||
|
width: `${maxBar ? Math.max((Math.abs(b.sum) / maxBar) * 100, 2) : 2}%`,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Typography variant="body2" fontWeight={600}>
|
||||||
|
{formatCurrency(b.sum, slice.currency)}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" color="text.disabled">
|
||||||
|
{b.count} txn{b.count === 1 ? "" : "s"}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
{barScroll.overflow && (
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 0.5, pr: 1.5 }}>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
aria-label="Scroll bars up"
|
||||||
|
disabled={!barScroll.canUp}
|
||||||
|
onClick={() => scrollBarsByPage(-1)}
|
||||||
|
>
|
||||||
|
<KeyboardArrowUpIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
aria-label="Scroll bars down"
|
||||||
|
disabled={!barScroll.canDown}
|
||||||
|
onClick={() => scrollBarsByPage(1)}
|
||||||
|
>
|
||||||
|
<KeyboardArrowDownIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
))}
|
</Paper>
|
||||||
</Paper>
|
)}
|
||||||
)}
|
</Box>
|
||||||
|
|
||||||
{slice.txns.length === 0 ? null : fields ? (
|
{slice.txns.length === 0 ? null : fields ? (
|
||||||
<TransactionList fields={fields} groups={listGroups} showMetrics />
|
<TransactionList fields={fields} groups={listGroups} showMetrics />
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
||||||
|
import { parseOccurredAt } from "../common/utils/dates";
|
||||||
|
|
||||||
export interface PeriodMetricsVM {
|
export interface PeriodMetricsVM {
|
||||||
outflows: number;
|
outflows: number;
|
||||||
@@ -79,8 +80,11 @@ export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function dateVal(value: string): number {
|
function dateVal(value: string): number {
|
||||||
const t = new Date(value).getTime();
|
try {
|
||||||
return Number.isNaN(t) ? 0 : t;
|
return parseOccurredAt(value).getTime();
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
||||||
@@ -175,7 +179,13 @@ export function buildPeriodGroups(buckets: any[], filter: SliceFilter): ReportPe
|
|||||||
vm.avg = vm.count ? Math.round((vm.sum / vm.count) * 100) / 100 : null;
|
vm.avg = vm.count ? Math.round((vm.sum / vm.count) * 100) / 100 : null;
|
||||||
if (acc.sources > 1) {
|
if (acc.sources > 1) {
|
||||||
const dates = acc.txns
|
const dates = acc.txns
|
||||||
.map((t) => new Date(t?.occurred_at ?? "").getTime())
|
.map((t) => {
|
||||||
|
try {
|
||||||
|
return parseOccurredAt(t?.occurred_at).getTime();
|
||||||
|
} catch {
|
||||||
|
return NaN;
|
||||||
|
}
|
||||||
|
})
|
||||||
.filter((t) => !Number.isNaN(t))
|
.filter((t) => !Number.isNaN(t))
|
||||||
.sort((a, b) => a - b);
|
.sort((a, b) => a - b);
|
||||||
if (dates.length >= 2) {
|
if (dates.length >= 2) {
|
||||||
@@ -232,3 +242,47 @@ export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFiel
|
|||||||
if (!name || !generatedAt) return null;
|
if (!name || !generatedAt) return null;
|
||||||
return { name, generatedAt };
|
return { name, generatedAt };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ReportDim = "period" | "payee" | "tag";
|
||||||
|
|
||||||
|
export interface DimensionBar {
|
||||||
|
key: string;
|
||||||
|
sum: number;
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bar-chart rows for a given dimension. "period" reuses the period groups;
|
||||||
|
* "payee"/"tag" fold each bucket's metrics into every value listed under
|
||||||
|
* group_key[dim] — safe because server buckets are disjoint slices.
|
||||||
|
*/
|
||||||
|
export function buildDimensionBars(buckets: any[], filter: SliceFilter, dim: ReportDim): DimensionBar[] {
|
||||||
|
if (dim === "period") {
|
||||||
|
return buildPeriodGroups(buckets, filter).map((g) => ({
|
||||||
|
key: g.key,
|
||||||
|
sum: g.metrics.sum,
|
||||||
|
count: g.metrics.count,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
const acc = new Map<string, DimensionBar>();
|
||||||
|
for (const bucket of buckets ?? []) {
|
||||||
|
if (!bucketMatches(bucket, filter)) continue;
|
||||||
|
const keys: string[] = bucket.group_key?.[dim] ?? [];
|
||||||
|
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
||||||
|
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
||||||
|
const m = period.metrics ?? {};
|
||||||
|
const sum = typeof m.sum === "number" ? m.sum : 0;
|
||||||
|
const count = typeof m.count === "number" ? m.count : 0;
|
||||||
|
for (const k of keys) {
|
||||||
|
const cur = acc.get(k);
|
||||||
|
if (cur) {
|
||||||
|
cur.sum += sum;
|
||||||
|
cur.count += count;
|
||||||
|
} else {
|
||||||
|
acc.set(k, { key: k, sum, count });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...acc.values()].sort((a, b) => Math.abs(b.sum) - Math.abs(a.sum));
|
||||||
|
}
|
||||||
@@ -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