Compare commits
6 Commits
46e666c6a5
...
617f6bea6c
| Author | SHA1 | Date | |
|---|---|---|---|
| 617f6bea6c | |||
| e1ae4f0ebe | |||
| 04aa16b564 | |||
| 99cc5afb7c | |||
| afddb3cfbc | |||
| b75505de25 |
@@ -7,5 +7,6 @@ export { FormFieldRenderer } from "./src/components/fields/FormFieldRenderer";
|
|||||||
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 type { FilterComponentProps } from "./src/context/useResource";
|
export type { FilterComponentProps } from "./src/context/useResource";
|
||||||
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship } from "./src/types";
|
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship } from "./src/types";
|
||||||
|
|||||||
58
react-openapi/src/hooks/useItemSse.ts
Normal file
58
react-openapi/src/hooks/useItemSse.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import { useEffect, useRef, useState, useCallback } from "react";
|
||||||
|
import { getApi } from "./useApi";
|
||||||
|
|
||||||
|
interface ItemSseHandlers {
|
||||||
|
onEvent: (data: any) => void;
|
||||||
|
onOpen?: () => void;
|
||||||
|
onError?: (evt: Event) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ItemSseResult {
|
||||||
|
connected: boolean;
|
||||||
|
events: any[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useItemSse(url: string | null, handlers: ItemSseHandlers): ItemSseResult {
|
||||||
|
const [connected, setConnected] = useState(false);
|
||||||
|
const [events, setEvents] = useState<any[]>([]);
|
||||||
|
const handlersRef = useRef(handlers);
|
||||||
|
handlersRef.current = handlers;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!url) return;
|
||||||
|
|
||||||
|
const api = getApi();
|
||||||
|
const baseUrl = (api.defaults.baseURL ?? "").replace(/\/+$/, "");
|
||||||
|
const fullUrl = baseUrl + url;
|
||||||
|
const es = new EventSource(fullUrl);
|
||||||
|
|
||||||
|
es.onopen = () => {
|
||||||
|
setConnected(true);
|
||||||
|
handlersRef.current.onOpen?.();
|
||||||
|
};
|
||||||
|
|
||||||
|
es.onmessage = (e) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(e.data);
|
||||||
|
setEvents((prev) => [...prev, data]);
|
||||||
|
handlersRef.current.onEvent(data);
|
||||||
|
} catch {
|
||||||
|
// ignore malformed JSON
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
es.onerror = (e) => {
|
||||||
|
setConnected(false);
|
||||||
|
handlersRef.current.onError?.(e);
|
||||||
|
};
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
es.close();
|
||||||
|
setConnected(false);
|
||||||
|
};
|
||||||
|
}, [url]);
|
||||||
|
|
||||||
|
const clearEvents = useCallback(() => setEvents([]), []);
|
||||||
|
|
||||||
|
return { connected, events };
|
||||||
|
}
|
||||||
@@ -1,339 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Container,
|
|
||||||
CircularProgress,
|
|
||||||
Alert,
|
|
||||||
TextField,
|
|
||||||
Paper,
|
|
||||||
Autocomplete,
|
|
||||||
Button
|
|
||||||
} from "@mui/material";
|
|
||||||
|
|
||||||
import DashboardView from "./components/Dashboard";
|
|
||||||
|
|
||||||
import {
|
|
||||||
DashboardState,
|
|
||||||
DashboardStateSetters,
|
|
||||||
DashboardFlow,
|
|
||||||
} from "./components/Dashboard";
|
|
||||||
|
|
||||||
import { configuration } from "./dashboard-config";
|
|
||||||
import {
|
|
||||||
useReport,
|
|
||||||
prepareReport,
|
|
||||||
} from "./features/report";
|
|
||||||
import { useReportSnapshotsList } from "./features/report-snapshots";
|
|
||||||
|
|
||||||
function formatSnapshotDate(iso: string) {
|
|
||||||
const d = new Date(iso);
|
|
||||||
return d.toLocaleString(undefined, {
|
|
||||||
year: "numeric",
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Dashboard() {
|
|
||||||
const [state, setState] = React.useState<DashboardState>({
|
|
||||||
flow: "outflows",
|
|
||||||
periodType: "rolling",
|
|
||||||
selectedPeriodId: null,
|
|
||||||
selectedGroupKey: null,
|
|
||||||
comparison: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
const [appliedPayees, setAppliedPayees] = React.useState<string[]>([]);
|
|
||||||
const [appliedTags, setAppliedTags] = React.useState<string[]>([]);
|
|
||||||
|
|
||||||
const [payeeInput, setPayeeInput] = React.useState<string[]>([]);
|
|
||||||
const [tagsInput, setTagsInput] = React.useState<string[]>([]);
|
|
||||||
|
|
||||||
const [loadedPayees, setLoadedPayees] = React.useState<string[]>([]);
|
|
||||||
const [loadedTags, setLoadedTags] = React.useState<string[]>([]);
|
|
||||||
|
|
||||||
const [selectedSnapshotId, setSelectedSnapshotId] = React.useState<string | null>(null);
|
|
||||||
|
|
||||||
const { data: snapshotsData } = useReportSnapshotsList();
|
|
||||||
const snapshotOptions = React.useMemo(() => {
|
|
||||||
const options: { label: string; value: string | null }[] = [
|
|
||||||
{ label: "Latest (auto)", value: null },
|
|
||||||
];
|
|
||||||
if (snapshotsData?.items) {
|
|
||||||
for (const snap of snapshotsData.items) {
|
|
||||||
options.push({
|
|
||||||
label: `Snapshot from ${formatSnapshotDate(snap.created_at)}`,
|
|
||||||
value: snap.snapshot_id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return options;
|
|
||||||
}, [snapshotsData]);
|
|
||||||
|
|
||||||
const selectedSnapshotOption = snapshotOptions.find((o) => o.value === selectedSnapshotId) ?? snapshotOptions[0];
|
|
||||||
|
|
||||||
const report = useReport({
|
|
||||||
snapshot_id: selectedSnapshotId ?? undefined,
|
|
||||||
periods: ["daily", "weekly", "monthly", "all"],
|
|
||||||
flow: state.flow,
|
|
||||||
payee: appliedPayees.length > 0 ? appliedPayees : undefined,
|
|
||||||
tags: appliedTags.length > 0 ? appliedTags : undefined,
|
|
||||||
});
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (report.data) {
|
|
||||||
setLoadedPayees(prev => {
|
|
||||||
const pSet = new Set<string>(prev);
|
|
||||||
report.data.buckets.forEach((b: any) => {
|
|
||||||
Object.values(b.periods).forEach((periodArray: any) => {
|
|
||||||
periodArray?.forEach((p: any) => {
|
|
||||||
p.metric?.transactions?.forEach((t: any) => {
|
|
||||||
if (t.payee?.name) pSet.add(t.payee.name);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return Array.from(pSet).sort();
|
|
||||||
});
|
|
||||||
|
|
||||||
setLoadedTags(prev => {
|
|
||||||
const tSet = new Set<string>(prev);
|
|
||||||
report.data.buckets.forEach((b: any) => {
|
|
||||||
Object.values(b.periods).forEach((periodArray: any) => {
|
|
||||||
periodArray?.forEach((p: any) => {
|
|
||||||
p.metric?.transactions?.forEach((t: any) => {
|
|
||||||
t.tags?.forEach((tag: any) => tSet.add(tag.name || tag));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return Array.from(tSet).sort();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [report.data]);
|
|
||||||
|
|
||||||
const toggleFlow =
|
|
||||||
React.useCallback(() => {
|
|
||||||
setState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
|
|
||||||
flow:
|
|
||||||
prev.flow ===
|
|
||||||
"outflows"
|
|
||||||
? "inflows"
|
|
||||||
: "outflows",
|
|
||||||
|
|
||||||
selectedGroupKey:
|
|
||||||
null,
|
|
||||||
|
|
||||||
selectedPeriodId:
|
|
||||||
null,
|
|
||||||
}));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setFlow =
|
|
||||||
React.useCallback(
|
|
||||||
(
|
|
||||||
flow: DashboardFlow
|
|
||||||
) => {
|
|
||||||
setState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
|
|
||||||
flow,
|
|
||||||
|
|
||||||
selectedGroupKey:
|
|
||||||
null,
|
|
||||||
|
|
||||||
selectedPeriodId:
|
|
||||||
null,
|
|
||||||
}));
|
|
||||||
},
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const togglePeriodType =
|
|
||||||
React.useCallback(() => {
|
|
||||||
setState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
|
|
||||||
periodType:
|
|
||||||
prev.periodType ===
|
|
||||||
"rolling"
|
|
||||||
? "calendar"
|
|
||||||
: "rolling",
|
|
||||||
}));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const toggleComparison =
|
|
||||||
React.useCallback(() => {
|
|
||||||
setState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
|
|
||||||
comparison:
|
|
||||||
!prev.comparison,
|
|
||||||
}));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const setSelectedPeriodId =
|
|
||||||
React.useCallback(
|
|
||||||
(
|
|
||||||
selectedPeriodId: DashboardState["selectedPeriodId"]
|
|
||||||
) => {
|
|
||||||
setState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
|
|
||||||
selectedPeriodId,
|
|
||||||
}));
|
|
||||||
},
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const setSelectedGroupKey =
|
|
||||||
React.useCallback(
|
|
||||||
(
|
|
||||||
selectedGroupKey: DashboardState["selectedGroupKey"]
|
|
||||||
) => {
|
|
||||||
setState((prev) => ({
|
|
||||||
...prev,
|
|
||||||
|
|
||||||
selectedGroupKey,
|
|
||||||
}));
|
|
||||||
},
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const stateSetters: DashboardStateSetters =
|
|
||||||
React.useMemo(
|
|
||||||
() => ({
|
|
||||||
toggleFlow,
|
|
||||||
|
|
||||||
setFlow,
|
|
||||||
|
|
||||||
togglePeriodType,
|
|
||||||
|
|
||||||
toggleComparison,
|
|
||||||
|
|
||||||
setSelectedPeriodId,
|
|
||||||
|
|
||||||
setSelectedGroupKey,
|
|
||||||
}),
|
|
||||||
[
|
|
||||||
toggleFlow,
|
|
||||||
setFlow,
|
|
||||||
togglePeriodType,
|
|
||||||
toggleComparison,
|
|
||||||
setSelectedPeriodId,
|
|
||||||
setSelectedGroupKey,
|
|
||||||
]
|
|
||||||
);
|
|
||||||
|
|
||||||
const isLoading = report.isLoading;
|
|
||||||
const error = report.error;
|
|
||||||
|
|
||||||
if (isLoading && !report.data) {
|
|
||||||
return (
|
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
|
|
||||||
<CircularProgress />
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<Container sx={{ mt: 4 }}>
|
|
||||||
<Alert severity="error">{String(error)}</Alert>
|
|
||||||
</Container>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!report.data) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = prepareReport(report.data);
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Container>
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
mt: 4,
|
|
||||||
p: 2,
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: { xs: "column", sm: "row" },
|
|
||||||
gap: 2,
|
|
||||||
alignItems: { xs: "stretch", sm: "flex-end" },
|
|
||||||
borderRadius: 4,
|
|
||||||
mb: -2 // pull up to be closer to the dashboard container below
|
|
||||||
}}
|
|
||||||
elevation={0}
|
|
||||||
variant="outlined"
|
|
||||||
>
|
|
||||||
<Box sx={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: { sm: 250 } }}>
|
|
||||||
<Box sx={{ typography: 'caption', mb: 1, color: 'text.secondary' }}>
|
|
||||||
Filter by Payee
|
|
||||||
</Box>
|
|
||||||
<Autocomplete
|
|
||||||
multiple
|
|
||||||
freeSolo
|
|
||||||
options={loadedPayees}
|
|
||||||
value={payeeInput}
|
|
||||||
onChange={(_, val) => setPayeeInput(val as string[])}
|
|
||||||
renderInput={(params) => <TextField {...params} placeholder="Add payees..." />}
|
|
||||||
sx={{ '& .MuiOutlinedInput-root': { height: 'auto', minHeight: '2.5rem', py: 0.5 } }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
<Box sx={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: { sm: 250 } }}>
|
|
||||||
<Box sx={{ typography: 'caption', mb: 1, color: 'text.secondary' }}>
|
|
||||||
Filter by Tags
|
|
||||||
</Box>
|
|
||||||
<Autocomplete
|
|
||||||
multiple
|
|
||||||
freeSolo
|
|
||||||
options={loadedTags}
|
|
||||||
value={tagsInput}
|
|
||||||
onChange={(_, val) => setTagsInput(val as string[])}
|
|
||||||
renderInput={(params) => <TextField {...params} placeholder="Add tags..." />}
|
|
||||||
sx={{ '& .MuiOutlinedInput-root': { height: 'auto', minHeight: '2.5rem', py: 0.5 } }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
<Box sx={{ display: 'flex', flexDirection: 'column', minWidth: { sm: 220 } }}>
|
|
||||||
<Box sx={{ typography: 'caption', mb: 1, color: 'text.secondary' }}>
|
|
||||||
Snapshot
|
|
||||||
</Box>
|
|
||||||
<Autocomplete
|
|
||||||
options={snapshotOptions}
|
|
||||||
value={selectedSnapshotOption}
|
|
||||||
onChange={(_, option) => setSelectedSnapshotId(option?.value ?? null)}
|
|
||||||
getOptionLabel={(o) => o.label}
|
|
||||||
isOptionEqualToValue={(o, v) => o.value === v.value}
|
|
||||||
renderInput={(params) => <TextField {...params} placeholder="Select snapshot..." />}
|
|
||||||
sx={{ '& .MuiOutlinedInput-root': { height: 'auto', minHeight: '2.5rem', py: 0.5 } }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
size="large"
|
|
||||||
onClick={() => {
|
|
||||||
setAppliedPayees(payeeInput);
|
|
||||||
setAppliedTags(tagsInput);
|
|
||||||
}}
|
|
||||||
disabled={isLoading}
|
|
||||||
sx={{ height: 40, borderRadius: 2 }}
|
|
||||||
>
|
|
||||||
Apply
|
|
||||||
</Button>
|
|
||||||
</Paper>
|
|
||||||
</Container>
|
|
||||||
<DashboardView
|
|
||||||
config={configuration}
|
|
||||||
data={data}
|
|
||||||
state={state}
|
|
||||||
stateSetters={stateSetters}
|
|
||||||
isFetching={report.isFetching}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
194
src/FetchRequest/FetchRequestCreate.tsx
Normal file
194
src/FetchRequest/FetchRequestCreate.tsx
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
Box, Container, Typography, Paper, Button, Alert,
|
||||||
|
CircularProgress,
|
||||||
|
} from "@mui/material";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { useAppContext, useResource, ListCellRenderer, FormFieldRenderer, getApi, applyDisplayFormat } from "../../react-openapi";
|
||||||
|
import type { FieldConfig } from "../../react-openapi";
|
||||||
|
|
||||||
|
const CREATE_FIELDS = ["account", "format", "start_date", "end_date", "source"];
|
||||||
|
|
||||||
|
function FetchRequestList() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { list, resource } = useResource("fetch-requests");
|
||||||
|
const { resources: allResources } = useAppContext();
|
||||||
|
const [rows, setRows] = useState<any[] | null>(null);
|
||||||
|
|
||||||
|
const columns = useMemo(() => {
|
||||||
|
if (!resource) return [];
|
||||||
|
return resource.listColumns
|
||||||
|
.map((n) => resource.fields.find((f) => f.name === n))
|
||||||
|
.filter(Boolean) as FieldConfig[];
|
||||||
|
}, [resource]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!resource) return;
|
||||||
|
list({ limit: 20 }).then((res) => setRows(res.items ?? []));
|
||||||
|
}, [resource?.name]);
|
||||||
|
|
||||||
|
if (!rows) {
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
|
||||||
|
<CircularProgress size={24} />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return <Typography variant="body2" color="text.secondary">No fetch requests found.</Typography>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||||
|
{rows.map((row, i) => {
|
||||||
|
const displayFormat = resource?.displayFormat ?? "";
|
||||||
|
return (
|
||||||
|
<Paper
|
||||||
|
key={row.id ?? i}
|
||||||
|
variant="outlined"
|
||||||
|
sx={{ p: 2, cursor: "pointer", "&:hover": { borderColor: "primary.main" } }}
|
||||||
|
onClick={() => navigate(`/fetch-requests/${row.id}`)}
|
||||||
|
>
|
||||||
|
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center" }}>
|
||||||
|
{columns.map((col) => (
|
||||||
|
<Box key={col.name} sx={{ minWidth: 120 }}>
|
||||||
|
<Typography variant="caption" color="text.secondary" sx={{ display: "block" }}>
|
||||||
|
{col.label}
|
||||||
|
</Typography>
|
||||||
|
<ListCellRenderer
|
||||||
|
field={col}
|
||||||
|
value={row[col.name]}
|
||||||
|
displayFormat={col.fk
|
||||||
|
? (allResources.find((r) => r.name === col.fk!.resource)?.displayFormat ?? displayFormat)
|
||||||
|
: displayFormat}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function FetchRequestCreate() {
|
||||||
|
const { resources: allResources } = useAppContext();
|
||||||
|
const resource = useMemo(() => allResources.find((r) => r.name === "fetch-requests"), [allResources]);
|
||||||
|
const { create } = useResource("fetch-requests");
|
||||||
|
const [formData, setFormData] = useState<Record<string, any>>({});
|
||||||
|
const [fkOptions, setFkOptions] = useState<Record<string, { value: any; label: string }[]>>({});
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [result, setResult] = useState<{ severity: "success" | "error"; message: string } | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!resource) return;
|
||||||
|
resource.relationships.forEach((rel) => {
|
||||||
|
const targetRes = allResources.find((r) => r.name === rel.config.resource);
|
||||||
|
if (!targetRes) return;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const api = getApi();
|
||||||
|
const params: Record<string, any> = {};
|
||||||
|
if (targetRes.pagination) params.limit = 0;
|
||||||
|
const res = await api.get(targetRes.path, { params });
|
||||||
|
const items = targetRes.pagination
|
||||||
|
? (res.data.items ?? [])
|
||||||
|
: (Array.isArray(res.data) ? res.data : []);
|
||||||
|
const opts = items.map((item: any) => ({
|
||||||
|
value: item[targetRes.primaryKey],
|
||||||
|
label: applyDisplayFormat(item, targetRes.displayFormat),
|
||||||
|
}));
|
||||||
|
setFkOptions((prev) => ({ ...prev, [rel.fieldName]: opts }));
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to load FK options for ${rel.fieldName}:`, e);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
});
|
||||||
|
}, [resource]);
|
||||||
|
|
||||||
|
const formFields = useMemo(() => {
|
||||||
|
if (!resource) return [];
|
||||||
|
return resource.orderedFields.filter((f) => CREATE_FIELDS.includes(f.name));
|
||||||
|
}, [resource]);
|
||||||
|
|
||||||
|
const handleChange = (fieldName: string, value: any) => {
|
||||||
|
setFormData((prev) => ({ ...prev, [fieldName]: value }));
|
||||||
|
setResult(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setResult(null);
|
||||||
|
try {
|
||||||
|
const created = await create(formData);
|
||||||
|
const display = applyDisplayFormat(created, resource!.displayFormat);
|
||||||
|
setResult({ severity: "success", message: `Created: ${display}` });
|
||||||
|
setFormData({});
|
||||||
|
} catch (e: any) {
|
||||||
|
const detail = e?.response?.data?.detail;
|
||||||
|
const msg = Array.isArray(detail) ? detail.map((d: any) => d.msg).join("; ") : (detail ?? e?.message ?? "Unknown error");
|
||||||
|
setResult({ severity: "error", message: `Failed: ${msg}` });
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!resource) {
|
||||||
|
return (
|
||||||
|
<Alert severity="info">
|
||||||
|
The <strong>fetch-requests</strong> resource was not found in this spec.
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container maxWidth="lg" sx={{ py: 4 }}>
|
||||||
|
<Typography variant="h5" fontWeight={800} gutterBottom>
|
||||||
|
Fetch Requests
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Paper variant="outlined" sx={{ p: 3, mb: 4, borderRadius: 2, position: "relative", overflow: "hidden", "&::before": { content: '""', position: "absolute", left: 0, top: 0, bottom: 0, width: 4, bgcolor: "primary.main" } }}>
|
||||||
|
<Box sx={{ ml: 0.5, mb: 2.5 }}>
|
||||||
|
<Typography variant="subtitle1" fontWeight={700}>
|
||||||
|
New Fetch Request
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, maxWidth: 480 }}>
|
||||||
|
{formFields.map((field) => (
|
||||||
|
<FormFieldRenderer
|
||||||
|
key={field.name}
|
||||||
|
field={field}
|
||||||
|
value={formData[field.name] ?? ""}
|
||||||
|
onChange={(val) => handleChange(field.name, val)}
|
||||||
|
fkOptions={fkOptions[field.name]}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 2, gap: 1 }}>
|
||||||
|
<Button variant="outlined" onClick={() => { setFormData({}); setResult(null); }}>
|
||||||
|
Reset
|
||||||
|
</Button>
|
||||||
|
<Button variant="contained" onClick={handleSubmit} disabled={loading}>
|
||||||
|
{loading ? <CircularProgress size={20} sx={{ mr: 0.5 }} /> : null}
|
||||||
|
Create Fetch Request
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{result && (
|
||||||
|
<Alert severity={result.severity} sx={{ mt: 1 }} onClose={() => setResult(null)}>
|
||||||
|
{result.message}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</Paper>
|
||||||
|
|
||||||
|
<Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}>
|
||||||
|
Recent Fetch Requests
|
||||||
|
</Typography>
|
||||||
|
<FetchRequestList />
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
338
src/FetchRequest/FetchRequestDetail.tsx
Normal file
338
src/FetchRequest/FetchRequestDetail.tsx
Normal file
@@ -0,0 +1,338 @@
|
|||||||
|
import React, { useMemo, useState, useEffect, useRef } from "react";
|
||||||
|
import { useParams, useNavigate } from "react-router-dom";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Container,
|
||||||
|
Paper,
|
||||||
|
Typography,
|
||||||
|
Button,
|
||||||
|
Chip,
|
||||||
|
CircularProgress,
|
||||||
|
Alert,
|
||||||
|
IconButton,
|
||||||
|
Snackbar,
|
||||||
|
} from "@mui/material";
|
||||||
|
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
||||||
|
import ReplayIcon from "@mui/icons-material/Replay";
|
||||||
|
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
|
||||||
|
import ErrorIcon from "@mui/icons-material/Error";
|
||||||
|
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||||
|
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
|
||||||
|
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
|
||||||
|
import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord";
|
||||||
|
import { useResource, useItemSse, DetailFieldRenderer, applyDisplayFormat } from "../../react-openapi";
|
||||||
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
|
import { RETRY_MAX, formatApiError } from "../features/fetch-requests";
|
||||||
|
import type { FetchRequestStatus, SSEEvent, ProgressMessage } from "../features/fetch-requests";
|
||||||
|
import { PipelineStepper } from "./components/PipelineStepper";
|
||||||
|
import { AmbiguityResolver } from "./components/AmbiguityResolver";
|
||||||
|
|
||||||
|
const statusColors: Record<FetchRequestStatus, "default" | "primary" | "warning" | "info" | "success" | "error"> = {
|
||||||
|
pending: "default",
|
||||||
|
processing: "info",
|
||||||
|
paused: "warning",
|
||||||
|
raw_expenses_done: "primary",
|
||||||
|
enriched_done: "warning",
|
||||||
|
completed: "success",
|
||||||
|
failed: "error",
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusIcons: Record<FetchRequestStatus, React.ReactNode> = {
|
||||||
|
pending: <PlayArrowIcon sx={{ fontSize: 16 }} />,
|
||||||
|
processing: <CircularProgress size={14} />,
|
||||||
|
paused: <WarningAmberIcon sx={{ fontSize: 16 }} />,
|
||||||
|
raw_expenses_done: <CheckCircleIcon sx={{ fontSize: 16 }} />,
|
||||||
|
enriched_done: <CheckCircleIcon sx={{ fontSize: 16 }} />,
|
||||||
|
completed: <CheckCircleIcon sx={{ fontSize: 16 }} />,
|
||||||
|
failed: <ErrorIcon sx={{ fontSize: 16 }} />,
|
||||||
|
};
|
||||||
|
|
||||||
|
function formatProgressMessage(msg: ProgressMessage): string {
|
||||||
|
if (msg.lines !== undefined) return `${msg.lines} lines`;
|
||||||
|
if (msg.blocks !== undefined) return `${msg.blocks} blocks`;
|
||||||
|
if (msg.count !== undefined && msg.unit) return `${msg.count} ${msg.unit}`;
|
||||||
|
if (msg.count !== undefined) return `${msg.count} items`;
|
||||||
|
if (msg.raw_ocr_line) return `"${msg.raw_ocr_line.slice(0, 60)}${msg.raw_ocr_line.length > 60 ? "…" : ""}"`;
|
||||||
|
if (msg.error) return msg.error.slice(0, 80);
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function sseIcon(status: SSEEvent["status"]) {
|
||||||
|
switch (status) {
|
||||||
|
case "started": return <CircularProgress size={14} />;
|
||||||
|
case "completed": return <CheckCircleIcon sx={{ fontSize: 16, color: "success.main" }} />;
|
||||||
|
case "failed": return <ErrorIcon sx={{ fontSize: 16, color: "error.main" }} />;
|
||||||
|
case "skipped": return <RemoveCircleOutlineIcon sx={{ fontSize: 16, color: "text.disabled" }} />;
|
||||||
|
case "paused": return <WarningAmberIcon sx={{ fontSize: 16, color: "warning.main" }} />;
|
||||||
|
case "progress": return <FiberManualRecordIcon sx={{ fontSize: 14, color: "info.main" }} />;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function FetchRequestDetail() {
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { get, update, resource } = useResource("fetch-requests");
|
||||||
|
const [stepStats, setStepStats] = useState<Record<string, number>>({});
|
||||||
|
const [liveParsedCount, setLiveParsedCount] = useState<number | undefined>(undefined);
|
||||||
|
const [failNotif, setFailNotif] = useState<string | null>(null);
|
||||||
|
const feedRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const { data: fetchRequest, isLoading, error: fetchError, refetch: refetchRequest } = useQuery({
|
||||||
|
queryKey: ["fetch-requests", "detail", id],
|
||||||
|
queryFn: () => get(id!),
|
||||||
|
enabled: !!id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: ({ id: rid, data }: { id: string; data: any }) => update(rid, data),
|
||||||
|
});
|
||||||
|
|
||||||
|
const sseUrl = id ? `/fetch-requests/${id}/events` : null;
|
||||||
|
const { connected: sseConnected, events: sseEvents } = useItemSse(sseUrl, {
|
||||||
|
onEvent: (parsed: SSEEvent) => {
|
||||||
|
if (parsed.status === "progress" && parsed.message.count !== undefined) {
|
||||||
|
if (parsed.step === "txn_dicts") setLiveParsedCount(parsed.message.count);
|
||||||
|
if (parsed.step === "enrich") setStepStats((prev) => ({ ...prev, enrich_count: parsed.message.count! }));
|
||||||
|
if (parsed.step === "save_expenses") setStepStats((prev) => ({ ...prev, save_count: parsed.message.count! }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.status === "completed" && parsed.message.count !== undefined) {
|
||||||
|
const stats: Record<string, number> = {};
|
||||||
|
if (parsed.step === "raw_lines" && parsed.message.lines !== undefined) stats.raw_lines = parsed.message.lines;
|
||||||
|
if (parsed.step === "txn_blocks" && parsed.message.blocks !== undefined) stats.txn_blocks = parsed.message.blocks;
|
||||||
|
if (parsed.step === "txn_dicts") stats.txn_dicts = parsed.message.count;
|
||||||
|
if (parsed.step === "enrich") stats.enrich_count = parsed.message.count;
|
||||||
|
if (parsed.step === "save_expenses") stats.save_count = parsed.message.count;
|
||||||
|
if (Object.keys(stats).length) {
|
||||||
|
setStepStats((prev) => ({ ...prev, ...stats }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.status === "paused") {
|
||||||
|
refetchRequest();
|
||||||
|
}
|
||||||
|
if (parsed.status === "failed") {
|
||||||
|
setFailNotif(parsed.message.error || "Fetch request failed");
|
||||||
|
refetchRequest();
|
||||||
|
}
|
||||||
|
if (parsed.status === "completed" || parsed.step === "resume_extract") {
|
||||||
|
refetchRequest();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (feedRef.current) {
|
||||||
|
feedRef.current.scrollTop = feedRef.current.scrollHeight;
|
||||||
|
}
|
||||||
|
}, [sseEvents]);
|
||||||
|
|
||||||
|
const displayEvents = useMemo(() => {
|
||||||
|
const progressSteps = new Set(["txn_dicts", "enrich", "save_expenses"]);
|
||||||
|
const lastProgressIdx: Record<string, number> = {};
|
||||||
|
for (let i = sseEvents.length - 1; i >= 0; i--) {
|
||||||
|
const e = sseEvents[i];
|
||||||
|
if (progressSteps.has(e.step) && e.status === "progress" && lastProgressIdx[e.step] === undefined) {
|
||||||
|
lastProgressIdx[e.step] = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const terminalStatuses = new Set(["completed", "skipped", "paused", "failed"]);
|
||||||
|
return sseEvents.filter((e, i) => {
|
||||||
|
if (progressSteps.has(e.step) && e.status === "progress") return i === lastProgressIdx[e.step];
|
||||||
|
if (e.status === "started") {
|
||||||
|
return !sseEvents.slice(i + 1).some(
|
||||||
|
(later) => later.step === e.step && terminalStatuses.has(later.status),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}, [sseEvents]);
|
||||||
|
|
||||||
|
const handleRetry = async () => {
|
||||||
|
if (!id) return;
|
||||||
|
try {
|
||||||
|
await updateMutation.mutateAsync({ id, data: { status: "pending" } });
|
||||||
|
refetchRequest();
|
||||||
|
} catch (err: any) {
|
||||||
|
setFailNotif(formatApiError(err));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<Box sx={{ display: "flex", justifyContent: "center", p: 8 }}>
|
||||||
|
<CircularProgress />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fetchError || !fetchRequest) {
|
||||||
|
return (
|
||||||
|
<Container sx={{ mt: 4 }}>
|
||||||
|
<Button startIcon={<ArrowBackIcon />} onClick={() => navigate("/fetch-requests")} sx={{ mb: 2 }}>
|
||||||
|
Back
|
||||||
|
</Button>
|
||||||
|
<Alert severity="error">Failed to load fetch request</Alert>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = fetchRequest as any;
|
||||||
|
const retryCount = req.retry_count ?? 0;
|
||||||
|
const isRetryExhausted = retryCount >= RETRY_MAX;
|
||||||
|
const status = req.status as FetchRequestStatus;
|
||||||
|
|
||||||
|
const detailFields = (resource?.orderedFields ?? []).filter(
|
||||||
|
(f) => f.name !== "source",
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container sx={{ mt: 4, mb: 4 }}>
|
||||||
|
<Button startIcon={<ArrowBackIcon />} onClick={() => navigate("/fetch-requests")} sx={{ mb: 2 }}>
|
||||||
|
Back to Fetch Requests
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2, flexWrap: "wrap" }}>
|
||||||
|
<Chip
|
||||||
|
icon={statusIcons[status] as any}
|
||||||
|
label={status.replace(/_/g, " ")}
|
||||||
|
color={statusColors[status]}
|
||||||
|
/>
|
||||||
|
<Typography variant="h6" fontWeight={600}>{req.account_name}</Typography>
|
||||||
|
<Chip
|
||||||
|
label={"path" in (req.source ?? {}) ? "File" : "Email"}
|
||||||
|
size="small"
|
||||||
|
variant="outlined"
|
||||||
|
color={"path" in (req.source ?? {}) ? "primary" : "secondary"}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 4, flexWrap: "wrap", mb: 2 }}>
|
||||||
|
{detailFields.map((field) => (
|
||||||
|
<DetailFieldRenderer
|
||||||
|
key={field.name}
|
||||||
|
field={field}
|
||||||
|
value={req[field.name]}
|
||||||
|
displayFormat={resource?.displayFormat}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
||||||
|
<Box sx={{ flex: 1, maxWidth: 300 }}>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
Retries: {retryCount}/{RETRY_MAX}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
{status === "failed" && !isRetryExhausted && (
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
size="small"
|
||||||
|
startIcon={<ReplayIcon />}
|
||||||
|
onClick={handleRetry}
|
||||||
|
disabled={updateMutation.isPending}
|
||||||
|
>
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
|
||||||
|
{status === "failed" && req.error_message && (
|
||||||
|
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||||
|
{req.error_message}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
{isRetryExhausted && status === "failed" && (
|
||||||
|
<Alert severity="info" sx={{ mb: 3, borderRadius: 2 }}>
|
||||||
|
Max retries reached — no further retry attempts will be made.
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<PipelineStepper
|
||||||
|
fetchRequest={req}
|
||||||
|
sseEvents={sseEvents}
|
||||||
|
stepStats={stepStats}
|
||||||
|
liveParsedCount={liveParsedCount ?? 0}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Paper sx={{ borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1, p: 2, pb: 0 }}>
|
||||||
|
<Typography variant="subtitle1" fontWeight={600} sx={{ flex: 1 }}>
|
||||||
|
Progress Events
|
||||||
|
</Typography>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: 10,
|
||||||
|
height: 10,
|
||||||
|
borderRadius: "50%",
|
||||||
|
bgcolor: sseConnected ? "success.main" : "error.main",
|
||||||
|
flexShrink: 0,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{sseConnected ? "Connected" : "Disconnected"}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
<Box
|
||||||
|
ref={feedRef}
|
||||||
|
sx={{
|
||||||
|
maxHeight: 300,
|
||||||
|
overflowY: "auto",
|
||||||
|
p: 2,
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{displayEvents.length === 0 ? (
|
||||||
|
<Typography variant="body2" color="text.disabled" sx={{ textAlign: "center", py: 2 }}>
|
||||||
|
Waiting for events...
|
||||||
|
</Typography>
|
||||||
|
) : (
|
||||||
|
displayEvents.map((evt, i) => (
|
||||||
|
<Box
|
||||||
|
key={i}
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: 1.5,
|
||||||
|
p: 1,
|
||||||
|
borderRadius: 2,
|
||||||
|
bgcolor: "action.hover",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{sseIcon(evt.status)}
|
||||||
|
<Box sx={{ flex: 1 }}>
|
||||||
|
<Typography variant="body2" fontWeight={600}>
|
||||||
|
{evt.step.replace(/_/g, " ")}
|
||||||
|
</Typography>
|
||||||
|
{evt.message && formatProgressMessage(evt.message) && (
|
||||||
|
<Typography variant="caption" color="text.secondary">
|
||||||
|
{formatProgressMessage(evt.message)}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
|
||||||
|
<AmbiguityResolver fetchRequestId={id!} />
|
||||||
|
|
||||||
|
<Snackbar
|
||||||
|
open={!!failNotif}
|
||||||
|
autoHideDuration={6000}
|
||||||
|
onClose={() => setFailNotif(null)}
|
||||||
|
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
|
||||||
|
>
|
||||||
|
<Alert severity="error" onClose={() => setFailNotif(null)} sx={{ borderRadius: 2 }}>
|
||||||
|
{failNotif}
|
||||||
|
</Alert>
|
||||||
|
</Snackbar>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
121
src/FetchRequest/components/AmbiguityResolver.tsx
Normal file
121
src/FetchRequest/components/AmbiguityResolver.tsx
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
import React from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Paper,
|
||||||
|
Typography,
|
||||||
|
Button,
|
||||||
|
Alert,
|
||||||
|
} from "@mui/material";
|
||||||
|
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
|
||||||
|
import { useFetchRequestAmbiguities, useResolveAmbiguity } from "../../features/fetch-requests";
|
||||||
|
|
||||||
|
interface AmbiguityResolverProps {
|
||||||
|
fetchRequestId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AmbiguityResolver({ fetchRequestId }: AmbiguityResolverProps) {
|
||||||
|
const { data: ambiguities, refetch } = useFetchRequestAmbiguities(fetchRequestId);
|
||||||
|
const resolveMutation = useResolveAmbiguity();
|
||||||
|
|
||||||
|
const handleResolve = async (ambiguity: any, candidate: { amount: number; balance: number }) => {
|
||||||
|
await resolveMutation.mutateAsync({
|
||||||
|
ambiguityId: ambiguity.id,
|
||||||
|
payload: { chosen: { amount: candidate.amount, balance: candidate.balance } },
|
||||||
|
});
|
||||||
|
refetch();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!ambiguities || ambiguities.length === 0) return null;
|
||||||
|
|
||||||
|
const allResolved = ambiguities.every((a: any) => a.status === "resolved");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
|
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||||
|
Ambiguity Resolution
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{allResolved ? (
|
||||||
|
<Alert severity="success" sx={{ mb: 2, borderRadius: 2 }}>
|
||||||
|
All ambiguities resolved — pipeline will resume on next poll cycle
|
||||||
|
</Alert>
|
||||||
|
) : (
|
||||||
|
<Alert severity="warning" sx={{ mb: 2, borderRadius: 2 }}>
|
||||||
|
Pipeline paused — resolve ambiguities to continue
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||||
|
{ambiguities.map((ambiguity: any) => {
|
||||||
|
const isResolved = ambiguity.status === "resolved";
|
||||||
|
return (
|
||||||
|
<Paper
|
||||||
|
key={ambiguity.id}
|
||||||
|
sx={{
|
||||||
|
p: 2,
|
||||||
|
borderRadius: 3,
|
||||||
|
border: 1,
|
||||||
|
borderColor: isResolved ? "success.main" : "divider",
|
||||||
|
opacity: isResolved ? 0.8 : 1,
|
||||||
|
}}
|
||||||
|
variant="outlined"
|
||||||
|
>
|
||||||
|
<Box sx={{ fontFamily: "monospace", fontSize: "0.85rem", mb: 1.5, p: 1, bgcolor: "grey.900", borderRadius: 1, color: "grey.100" }}>
|
||||||
|
{ambiguity.line}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Box sx={{ display: "flex", gap: 3, mb: 1.5, flexWrap: "wrap" }}>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" color="text.secondary">OCR Amount</Typography>
|
||||||
|
<Typography variant="body2" sx={{ textDecoration: "line-through", color: "text.secondary" }}>
|
||||||
|
₹{ambiguity.ocr_amount}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" color="text.secondary">OCR Balance</Typography>
|
||||||
|
<Typography variant="body2" sx={{ textDecoration: "line-through", color: "text.secondary" }}>
|
||||||
|
₹{ambiguity.ocr_balance}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
<Box>
|
||||||
|
<Typography variant="caption" color="text.secondary">Previous Balance</Typography>
|
||||||
|
<Typography variant="body2">₹{ambiguity.prev_balance}</Typography>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{isResolved ? (
|
||||||
|
<Alert severity="success" sx={{ py: 0.5, borderRadius: 2 }} icon={<CheckCircleIcon />}>
|
||||||
|
Resolved: ₹{ambiguity.chosen?.amount} / ₹{ambiguity.chosen?.balance}
|
||||||
|
</Alert>
|
||||||
|
) : (
|
||||||
|
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||||
|
{ambiguity.candidates.map((candidate: any, ci: number) => {
|
||||||
|
const isCredit = candidate.amount > 0;
|
||||||
|
const isDebit = candidate.amount < 0;
|
||||||
|
const cColor = isCredit ? "success.main" : isDebit ? "error.main" : undefined;
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
key={ci}
|
||||||
|
variant="outlined"
|
||||||
|
size="small"
|
||||||
|
onClick={() => handleResolve(ambiguity, candidate)}
|
||||||
|
disabled={resolveMutation.isPending}
|
||||||
|
sx={{
|
||||||
|
borderColor: cColor,
|
||||||
|
color: cColor,
|
||||||
|
"&:hover": cColor ? { borderColor: cColor } : undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
₹{candidate.amount} / ₹{candidate.balance}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
209
src/FetchRequest/components/PipelineStepper.tsx
Normal file
209
src/FetchRequest/components/PipelineStepper.tsx
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
import React, { useMemo } from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Paper,
|
||||||
|
Typography,
|
||||||
|
Stepper,
|
||||||
|
Step,
|
||||||
|
StepLabel,
|
||||||
|
LinearProgress,
|
||||||
|
} from "@mui/material";
|
||||||
|
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
|
||||||
|
import ErrorIcon from "@mui/icons-material/Error";
|
||||||
|
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||||
|
import CircularProgress from "@mui/material/CircularProgress";
|
||||||
|
import type { FetchRequestStatus, SSEEvent, ProgressMessage } from "../../features/fetch-requests";
|
||||||
|
|
||||||
|
const STEP_LABELS = ["Extract", "Raw Expense", "Enrich", "Save"];
|
||||||
|
|
||||||
|
function computeProgressPercent(
|
||||||
|
status: FetchRequestStatus,
|
||||||
|
liveCount: number,
|
||||||
|
seenSteps: Set<string>,
|
||||||
|
stepStats: Record<string, number>,
|
||||||
|
txnBlockCount: number,
|
||||||
|
txnDictCount: number,
|
||||||
|
): number {
|
||||||
|
if (status === "pending") return 0;
|
||||||
|
if (status === "completed") return 100;
|
||||||
|
|
||||||
|
let pct = 0;
|
||||||
|
|
||||||
|
if (seenSteps.has("raw_lines") || seenSteps.has("txn_blocks")) pct += 10;
|
||||||
|
|
||||||
|
if (txnBlockCount > 0) {
|
||||||
|
const current = Math.max(liveCount, stepStats.txn_dicts ?? 0);
|
||||||
|
pct += Math.min(1, current / txnBlockCount) * 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (txnDictCount > 0) {
|
||||||
|
pct += Math.min(1, (stepStats.enrich_count ?? 0) / txnDictCount) * 50;
|
||||||
|
pct += Math.min(1, (stepStats.save_count ?? 0) / txnDictCount) * 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.round(Math.min(100, pct));
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeActiveStep(status: FetchRequestStatus, seenSteps: Set<string>): number {
|
||||||
|
if (status === "completed") return STEP_LABELS.length;
|
||||||
|
|
||||||
|
if (seenSteps.has("save_expenses/completed") || seenSteps.has("complete/completed")) return STEP_LABELS.length;
|
||||||
|
if (seenSteps.has("save_expenses") || seenSteps.has("complete")) return 3;
|
||||||
|
|
||||||
|
if (seenSteps.has("enrich/completed")) return 3;
|
||||||
|
if (seenSteps.has("enrich")) return 2;
|
||||||
|
|
||||||
|
if (seenSteps.has("txn_dicts/completed") || status === "raw_expenses_done") return 2;
|
||||||
|
if (seenSteps.has("txn_dicts")) return 1;
|
||||||
|
|
||||||
|
if (seenSteps.has("txn_blocks/completed")) return 1;
|
||||||
|
if (seenSteps.has("raw_lines") || seenSteps.has("txn_blocks")) return 0;
|
||||||
|
|
||||||
|
if (status === "processing" || status === "paused") return 0;
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeStepMessages(
|
||||||
|
fetchRequest: any,
|
||||||
|
stepStats: Record<string, number>,
|
||||||
|
liveParsedCount: number,
|
||||||
|
txnBlockCount: number,
|
||||||
|
): Record<number, string> {
|
||||||
|
const msgs: Record<number, string> = {};
|
||||||
|
const source = fetchRequest?.source;
|
||||||
|
|
||||||
|
const rawLineCount = stepStats.raw_lines ?? (source?.raw_lines?.length ?? 0);
|
||||||
|
if (rawLineCount) msgs[0] = `${rawLineCount}`;
|
||||||
|
|
||||||
|
const sourceDictCount = source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||||
|
const dictLive = liveParsedCount ?? stepStats.txn_dicts ?? 0;
|
||||||
|
const dictCurrent = Math.max(dictLive, sourceDictCount);
|
||||||
|
if (dictCurrent && txnBlockCount) msgs[1] = `${dictCurrent}/${txnBlockCount}`;
|
||||||
|
else if (dictCurrent) msgs[1] = `${dictCurrent}`;
|
||||||
|
|
||||||
|
const txnDictDenom = stepStats.txn_dicts ?? sourceDictCount;
|
||||||
|
if (stepStats.enrich_count && txnDictDenom) msgs[2] = `${stepStats.enrich_count}/${txnDictDenom}`;
|
||||||
|
else if (stepStats.enrich_count) msgs[2] = `${stepStats.enrich_count}`;
|
||||||
|
|
||||||
|
if (stepStats.save_count && txnDictDenom) msgs[3] = `${stepStats.save_count}/${txnDictDenom}`;
|
||||||
|
else if (stepStats.save_count) msgs[3] = `${stepStats.save_count}`;
|
||||||
|
|
||||||
|
return msgs;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PipelineStepperProps {
|
||||||
|
fetchRequest: any;
|
||||||
|
sseEvents: SSEEvent[];
|
||||||
|
stepStats: Record<string, number>;
|
||||||
|
liveParsedCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PipelineStepper({ fetchRequest, sseEvents, stepStats, liveParsedCount }: PipelineStepperProps) {
|
||||||
|
const status = (fetchRequest?.status ?? "pending") as FetchRequestStatus;
|
||||||
|
|
||||||
|
const seenSteps = useMemo(() => {
|
||||||
|
const steps = new Set<string>();
|
||||||
|
for (const evt of sseEvents) {
|
||||||
|
steps.add(evt.step);
|
||||||
|
if (evt.status === "completed") steps.add(`${evt.step}/completed`);
|
||||||
|
if (evt.status === "failed") steps.add(`${evt.step}/failed`);
|
||||||
|
if (evt.status === "started") steps.add(`${evt.step}/started`);
|
||||||
|
if (evt.status === "progress") steps.add(`${evt.step}/progress`);
|
||||||
|
}
|
||||||
|
return steps;
|
||||||
|
}, [sseEvents]);
|
||||||
|
|
||||||
|
const txnBlockCount = useMemo(() => {
|
||||||
|
const blocks = fetchRequest?.source?.txn_blocks;
|
||||||
|
if (!blocks) return 0;
|
||||||
|
return Object.values(blocks).reduce(
|
||||||
|
(sum: number, list: any) => sum + (Array.isArray(list) ? list.length : 0),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
}, [fetchRequest]);
|
||||||
|
|
||||||
|
const txnDictCount = useMemo(() => {
|
||||||
|
const source = fetchRequest?.source;
|
||||||
|
if (stepStats.txn_dicts && stepStats.txn_dicts > 0) return stepStats.txn_dicts;
|
||||||
|
return source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||||
|
}, [fetchRequest, stepStats]);
|
||||||
|
|
||||||
|
const displayParsedCount = useMemo(() => {
|
||||||
|
if (liveParsedCount && liveParsedCount > 0) return liveParsedCount;
|
||||||
|
const source = fetchRequest?.source;
|
||||||
|
const persistedCount = source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||||
|
if (persistedCount > 0) return persistedCount;
|
||||||
|
const dicts = source?.txn_dicts;
|
||||||
|
if (Array.isArray(dicts) && dicts.length > 0) return dicts.length;
|
||||||
|
return 0;
|
||||||
|
}, [liveParsedCount, fetchRequest]);
|
||||||
|
|
||||||
|
const activeStep = computeActiveStep(status, seenSteps);
|
||||||
|
const progressPercent = computeProgressPercent(status, displayParsedCount, seenSteps, stepStats, txnBlockCount, txnDictCount);
|
||||||
|
const stepMessages = computeStepMessages(fetchRequest, stepStats, liveParsedCount, txnBlockCount);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
|
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||||
|
Pipeline Progress
|
||||||
|
</Typography>
|
||||||
|
<Stepper activeStep={activeStep} alternativeLabel>
|
||||||
|
{STEP_LABELS.map((label, index) => {
|
||||||
|
const isCompleted = index < activeStep;
|
||||||
|
const isActive = index === activeStep;
|
||||||
|
const isPaused = status === "paused" && isActive;
|
||||||
|
const isFailed = status === "failed" && isActive;
|
||||||
|
|
||||||
|
let icon: React.ReactNode;
|
||||||
|
if (isCompleted) {
|
||||||
|
icon = <CheckCircleIcon sx={{ color: "success.main" }} />;
|
||||||
|
} else if (isFailed) {
|
||||||
|
icon = <ErrorIcon sx={{ color: "error.main" }} />;
|
||||||
|
} else if (isPaused) {
|
||||||
|
icon = <WarningAmberIcon sx={{ color: "warning.main" }} />;
|
||||||
|
} else if (isActive) {
|
||||||
|
icon = <CircularProgress size={20} />;
|
||||||
|
} else {
|
||||||
|
icon = <Typography variant="caption" color="text.disabled">{index + 1}</Typography>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Step key={label}>
|
||||||
|
<StepLabel
|
||||||
|
StepIconComponent={() => <Box sx={{ display: "flex", alignItems: "center" }}>{icon}</Box>}
|
||||||
|
>
|
||||||
|
<Typography variant="body2" fontWeight={600}>{label}</Typography>
|
||||||
|
{stepMessages[index] && (
|
||||||
|
<Typography variant="caption" color="text.secondary" sx={{ display: "block", lineHeight: 1.2 }}>
|
||||||
|
{stepMessages[index]}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</StepLabel>
|
||||||
|
</Step>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Stepper>
|
||||||
|
|
||||||
|
<Box sx={{ mt: 3, mb: 1 }}>
|
||||||
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 0.5 }}>
|
||||||
|
<Typography variant="caption" color="text.secondary">Overall Progress</Typography>
|
||||||
|
{["processing", "paused"].includes(status) && displayParsedCount > 0 && (
|
||||||
|
<Typography variant="caption" fontWeight={600} color="info.main">
|
||||||
|
Validated: {displayParsedCount} transactions
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
<LinearProgress
|
||||||
|
variant="determinate"
|
||||||
|
value={progressPercent}
|
||||||
|
color={status === "failed" ? "error" : status === "completed" ? "success" : "primary"}
|
||||||
|
sx={{ borderRadius: 1, height: 8, transition: "width 0.3s ease" }}
|
||||||
|
/>
|
||||||
|
<Typography variant="caption" color="text.secondary" sx={{ mt: 0.25, display: "block" }}>
|
||||||
|
{progressPercent}%
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
Stepper,
|
Stepper,
|
||||||
Step,
|
Step,
|
||||||
StepLabel,
|
StepLabel,
|
||||||
StepIcon,
|
|
||||||
LinearProgress,
|
LinearProgress,
|
||||||
IconButton,
|
IconButton,
|
||||||
Snackbar,
|
Snackbar,
|
||||||
@@ -35,7 +34,7 @@ import type {
|
|||||||
ProgressMessage,
|
ProgressMessage,
|
||||||
} from "./features/fetch-requests";
|
} from "./features/fetch-requests";
|
||||||
import { RETRY_MAX, formatApiError } from "./features/fetch-requests";
|
import { RETRY_MAX, formatApiError } from "./features/fetch-requests";
|
||||||
import { useAppContext, useResource } from "../react-openapi";
|
import { useAppContext, useResource, useItemSse } from "../react-openapi";
|
||||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
|
|
||||||
const statusColors: Record<FetchRequestStatus, "default" | "primary" | "warning" | "info" | "success" | "error"> = {
|
const statusColors: Record<FetchRequestStatus, "default" | "primary" | "warning" | "info" | "success" | "error"> = {
|
||||||
@@ -58,6 +57,8 @@ const statusIcons: Record<FetchRequestStatus, React.ReactNode> = {
|
|||||||
failed: <ErrorIcon sx={{ fontSize: 16 }} />,
|
failed: <ErrorIcon sx={{ fontSize: 16 }} />,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const stepLabels = ["Extract", "Raw Expense", "Enrich", "Save"];
|
||||||
|
|
||||||
function computeProgressPercent(
|
function computeProgressPercent(
|
||||||
status: FetchRequestStatus,
|
status: FetchRequestStatus,
|
||||||
liveCount: number,
|
liveCount: number,
|
||||||
@@ -86,8 +87,6 @@ function computeProgressPercent(
|
|||||||
return Math.round(Math.min(100, pct));
|
return Math.round(Math.min(100, pct));
|
||||||
}
|
}
|
||||||
|
|
||||||
const stepLabels = ["Extract", "Raw Expense", "Enrich", "Save"];
|
|
||||||
|
|
||||||
function computeActiveStep(status: FetchRequestStatus, seenSteps: Set<string>): number {
|
function computeActiveStep(status: FetchRequestStatus, seenSteps: Set<string>): number {
|
||||||
if (status === "completed") return stepLabels.length;
|
if (status === "completed") return stepLabels.length;
|
||||||
|
|
||||||
@@ -125,27 +124,13 @@ function sseIcon(status: SSEEvent["status"]) {
|
|||||||
case "failed": return <ErrorIcon sx={{ fontSize: 16, color: "error.main" }} />;
|
case "failed": return <ErrorIcon sx={{ fontSize: 16, color: "error.main" }} />;
|
||||||
case "skipped": return <RemoveCircleOutlineIcon sx={{ fontSize: 16, color: "text.disabled" }} />;
|
case "skipped": return <RemoveCircleOutlineIcon sx={{ fontSize: 16, color: "text.disabled" }} />;
|
||||||
case "paused": return <WarningAmberIcon sx={{ fontSize: 16, color: "warning.main" }} />;
|
case "paused": return <WarningAmberIcon sx={{ fontSize: 16, color: "warning.main" }} />;
|
||||||
case "progress": return (
|
case "progress": return <FiberManualRecordIcon sx={{ fontSize: 14, color: "info.main" }} />;
|
||||||
<FiberManualRecordIcon
|
|
||||||
sx={{ fontSize: 14, color: "info.main" }}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isMathValid(candidate: { amount: number; balance: number }, prevBalance: number) {
|
|
||||||
return (
|
|
||||||
candidate.balance === prevBalance + candidate.amount ||
|
|
||||||
candidate.balance === prevBalance - candidate.amount ||
|
|
||||||
Math.abs(candidate.balance - (prevBalance + candidate.amount)) < 0.01 ||
|
|
||||||
Math.abs(candidate.balance - (prevBalance - candidate.amount)) < 0.01
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 { config } = useAppContext();
|
|
||||||
const { get, update } = useResource("fetch-requests");
|
const { get, update } = useResource("fetch-requests");
|
||||||
|
|
||||||
const { data: fetchRequest, isLoading, error: fetchError, refetch: refetchRequest } = useQuery({
|
const { data: fetchRequest, isLoading, error: fetchError, refetch: refetchRequest } = useQuery({
|
||||||
@@ -159,59 +144,14 @@ export default function FetchRequestDetail() {
|
|||||||
const resolveMutation = useResolveAmbiguity();
|
const resolveMutation = useResolveAmbiguity();
|
||||||
const { data: ambiguities, refetch: refetchAmbiguities } = useFetchRequestAmbiguities(id!);
|
const { data: ambiguities, refetch: refetchAmbiguities } = useFetchRequestAmbiguities(id!);
|
||||||
|
|
||||||
const [sseEvents, setSseEvents] = React.useState<SSEEvent[]>([]);
|
|
||||||
const [sseConnected, setSseConnected] = React.useState(false);
|
|
||||||
const [liveParsedCount, setLiveParsedCount] = React.useState<number | undefined>(undefined);
|
|
||||||
const [stepStats, setStepStats] = React.useState<Record<string, number>>({});
|
const [stepStats, setStepStats] = React.useState<Record<string, number>>({});
|
||||||
|
const [liveParsedCount, setLiveParsedCount] = React.useState<number | undefined>(undefined);
|
||||||
const [failNotif, setFailNotif] = React.useState<string | null>(null);
|
const [failNotif, setFailNotif] = React.useState<string | null>(null);
|
||||||
const sseRef = React.useRef<EventSource | null>(null);
|
|
||||||
const feedRef = React.useRef<HTMLDivElement>(null);
|
const feedRef = React.useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
const txnBlockCount = React.useMemo(() => {
|
const sseUrl = id ? `/fetch-requests/${id}/events` : null;
|
||||||
const blocks = (fetchRequest as any)?.source?.txn_blocks;
|
const { connected: sseConnected, events: sseEvents } = useItemSse(sseUrl, {
|
||||||
if (!blocks) return 0;
|
onEvent: (parsed: SSEEvent) => {
|
||||||
return Object.values(blocks).reduce(
|
|
||||||
(sum: number, list: any) => sum + (Array.isArray(list) ? list.length : 0),
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
}, [fetchRequest]);
|
|
||||||
|
|
||||||
const stepMessages = React.useMemo(() => {
|
|
||||||
const msgs: Record<number, string> = {};
|
|
||||||
const source = (fetchRequest as any)?.source;
|
|
||||||
|
|
||||||
const rawLineCount = stepStats.raw_lines ?? (source?.raw_lines?.length ?? 0);
|
|
||||||
if (rawLineCount) msgs[0] = `${rawLineCount}`;
|
|
||||||
|
|
||||||
const sourceDictCount = source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
|
||||||
const dictLive = liveParsedCount ?? stepStats.txn_dicts ?? 0;
|
|
||||||
const dictCurrent = Math.max(dictLive, sourceDictCount);
|
|
||||||
if (dictCurrent && txnBlockCount) msgs[1] = `${dictCurrent}/${txnBlockCount}`;
|
|
||||||
else if (dictCurrent) msgs[1] = `${dictCurrent}`;
|
|
||||||
|
|
||||||
const txnDictDenom = stepStats.txn_dicts ?? sourceDictCount;
|
|
||||||
if (stepStats.enrich_count && txnDictDenom) msgs[2] = `${stepStats.enrich_count}/${txnDictDenom}`;
|
|
||||||
else if (stepStats.enrich_count) msgs[2] = `${stepStats.enrich_count}`;
|
|
||||||
|
|
||||||
if (stepStats.save_count && txnDictDenom) msgs[3] = `${stepStats.save_count}/${txnDictDenom}`;
|
|
||||||
else if (stepStats.save_count) msgs[3] = `${stepStats.save_count}`;
|
|
||||||
|
|
||||||
return msgs;
|
|
||||||
}, [fetchRequest, stepStats, liveParsedCount, txnBlockCount]);
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (!id || !config?.baseApiUrl) return;
|
|
||||||
const url = `${config.baseApiUrl}/fetch-requests/${id}/events`;
|
|
||||||
const es = new EventSource(url);
|
|
||||||
sseRef.current = es;
|
|
||||||
|
|
||||||
es.onopen = () => setSseConnected(true);
|
|
||||||
es.onerror = () => setSseConnected(false);
|
|
||||||
es.onmessage = (event) => {
|
|
||||||
try {
|
|
||||||
const parsed: SSEEvent = JSON.parse(event.data);
|
|
||||||
setSseEvents((prev) => [...prev, parsed]);
|
|
||||||
|
|
||||||
if (parsed.status === "progress" && parsed.message.count !== undefined) {
|
if (parsed.status === "progress" && parsed.message.count !== undefined) {
|
||||||
if (parsed.step === "txn_dicts") setLiveParsedCount(parsed.message.count);
|
if (parsed.step === "txn_dicts") setLiveParsedCount(parsed.message.count);
|
||||||
if (parsed.step === "enrich") setStepStats((prev) => ({ ...prev, enrich_count: parsed.message.count! }));
|
if (parsed.step === "enrich") setStepStats((prev) => ({ ...prev, enrich_count: parsed.message.count! }));
|
||||||
@@ -241,16 +181,8 @@ export default function FetchRequestDetail() {
|
|||||||
if (parsed.status === "completed" || parsed.step === "resume_extract") {
|
if (parsed.status === "completed" || parsed.step === "resume_extract") {
|
||||||
refetchRequest();
|
refetchRequest();
|
||||||
}
|
}
|
||||||
} catch {
|
},
|
||||||
// ignore malformed events
|
});
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
es.close();
|
|
||||||
sseRef.current = null;
|
|
||||||
};
|
|
||||||
}, [id, config?.baseApiUrl]);
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (feedRef.current) {
|
if (feedRef.current) {
|
||||||
@@ -258,27 +190,14 @@ export default function FetchRequestDetail() {
|
|||||||
}
|
}
|
||||||
}, [sseEvents]);
|
}, [sseEvents]);
|
||||||
|
|
||||||
const displayEvents = React.useMemo(() => {
|
const txnBlockCount = React.useMemo(() => {
|
||||||
const progressSteps = new Set(["txn_dicts", "enrich", "save_expenses"]);
|
const blocks = (fetchRequest as any)?.source?.txn_blocks;
|
||||||
const lastProgressIdx: Record<string, number> = {};
|
if (!blocks) return 0;
|
||||||
for (let i = sseEvents.length - 1; i >= 0; i--) {
|
return Object.values(blocks).reduce(
|
||||||
const e = sseEvents[i];
|
(sum: number, list: any) => sum + (Array.isArray(list) ? list.length : 0),
|
||||||
if (progressSteps.has(e.step) && e.status === "progress" && lastProgressIdx[e.step] === undefined) {
|
0,
|
||||||
lastProgressIdx[e.step] = i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const terminalStatuses = new Set(["completed", "skipped", "paused", "failed"]);
|
|
||||||
return sseEvents.filter((e, i) => {
|
|
||||||
if (progressSteps.has(e.step) && e.status === "progress") return i === lastProgressIdx[e.step];
|
|
||||||
if (e.status === "started") {
|
|
||||||
return !sseEvents.slice(i + 1).some(
|
|
||||||
(later) => later.step === e.step && terminalStatuses.has(later.status),
|
|
||||||
);
|
);
|
||||||
}
|
}, [fetchRequest]);
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}, [sseEvents]);
|
|
||||||
|
|
||||||
const seenSteps = React.useMemo(() => {
|
const seenSteps = React.useMemo(() => {
|
||||||
const steps = new Set<string>();
|
const steps = new Set<string>();
|
||||||
@@ -308,6 +227,29 @@ export default function FetchRequestDetail() {
|
|||||||
return source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
return source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||||
}, [fetchRequest, stepStats]);
|
}, [fetchRequest, stepStats]);
|
||||||
|
|
||||||
|
const stepMessages = React.useMemo(() => {
|
||||||
|
const msgs: Record<number, string> = {};
|
||||||
|
const source = (fetchRequest as any)?.source;
|
||||||
|
|
||||||
|
const rawLineCount = stepStats.raw_lines ?? (source?.raw_lines?.length ?? 0);
|
||||||
|
if (rawLineCount) msgs[0] = `${rawLineCount}`;
|
||||||
|
|
||||||
|
const sourceDictCount = source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||||
|
const dictLive = liveParsedCount ?? stepStats.txn_dicts ?? 0;
|
||||||
|
const dictCurrent = Math.max(dictLive, sourceDictCount);
|
||||||
|
if (dictCurrent && txnBlockCount) msgs[1] = `${dictCurrent}/${txnBlockCount}`;
|
||||||
|
else if (dictCurrent) msgs[1] = `${dictCurrent}`;
|
||||||
|
|
||||||
|
const txnDictDenom = stepStats.txn_dicts ?? sourceDictCount;
|
||||||
|
if (stepStats.enrich_count && txnDictDenom) msgs[2] = `${stepStats.enrich_count}/${txnDictDenom}`;
|
||||||
|
else if (stepStats.enrich_count) msgs[2] = `${stepStats.enrich_count}`;
|
||||||
|
|
||||||
|
if (stepStats.save_count && txnDictDenom) msgs[3] = `${stepStats.save_count}/${txnDictDenom}`;
|
||||||
|
else if (stepStats.save_count) msgs[3] = `${stepStats.save_count}`;
|
||||||
|
|
||||||
|
return msgs;
|
||||||
|
}, [fetchRequest, stepStats, liveParsedCount, txnBlockCount]);
|
||||||
|
|
||||||
const progressPercent = React.useMemo(
|
const progressPercent = React.useMemo(
|
||||||
() => computeProgressPercent(
|
() => computeProgressPercent(
|
||||||
(fetchRequest as any)?.status as FetchRequestStatus ?? "pending",
|
(fetchRequest as any)?.status as FetchRequestStatus ?? "pending",
|
||||||
@@ -320,6 +262,28 @@ export default function FetchRequestDetail() {
|
|||||||
[fetchRequest, displayParsedCount, seenSteps, stepStats, txnBlockCount, txnDictCount],
|
[fetchRequest, displayParsedCount, seenSteps, stepStats, txnBlockCount, txnDictCount],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const displayEvents = React.useMemo(() => {
|
||||||
|
const progressSteps = new Set(["txn_dicts", "enrich", "save_expenses"]);
|
||||||
|
const lastProgressIdx: Record<string, number> = {};
|
||||||
|
for (let i = sseEvents.length - 1; i >= 0; i--) {
|
||||||
|
const e = sseEvents[i];
|
||||||
|
if (progressSteps.has(e.step) && e.status === "progress" && lastProgressIdx[e.step] === undefined) {
|
||||||
|
lastProgressIdx[e.step] = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const terminalStatuses = new Set(["completed", "skipped", "paused", "failed"]);
|
||||||
|
return sseEvents.filter((e, i) => {
|
||||||
|
if (progressSteps.has(e.step) && e.status === "progress") return i === lastProgressIdx[e.step];
|
||||||
|
if (e.status === "started") {
|
||||||
|
return !sseEvents.slice(i + 1).some(
|
||||||
|
(later) => later.step === e.step && terminalStatuses.has(later.status),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}, [sseEvents]);
|
||||||
|
|
||||||
const handleRetry = async () => {
|
const handleRetry = async () => {
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
try {
|
try {
|
||||||
@@ -360,11 +324,8 @@ export default function FetchRequestDetail() {
|
|||||||
const activeStep = computeActiveStep(req.status as FetchRequestStatus, seenSteps);
|
const activeStep = computeActiveStep(req.status as FetchRequestStatus, seenSteps);
|
||||||
const retryCount = req.retry_count ?? 0;
|
const retryCount = req.retry_count ?? 0;
|
||||||
const isRetryExhausted = retryCount >= RETRY_MAX;
|
const isRetryExhausted = retryCount >= RETRY_MAX;
|
||||||
const pendingAmbiguities = ambiguities?.filter((a: any) => a.status === "pending") ?? [];
|
|
||||||
const resolvedAmbiguities = ambiguities?.filter((a: any) => a.status === "resolved") ?? [];
|
|
||||||
const hasAmbiguities = ambiguities && ambiguities.length > 0;
|
const hasAmbiguities = ambiguities && ambiguities.length > 0;
|
||||||
const allResolved = hasAmbiguities && pendingAmbiguities.length === 0;
|
const allResolved = hasAmbiguities && ambiguities.every((a: any) => a.status === "resolved");
|
||||||
const ambiguitiesLoading = !ambiguities;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container sx={{ mt: 4, mb: 4 }}>
|
<Container sx={{ mt: 4, mb: 4 }}>
|
||||||
@@ -372,6 +333,7 @@ export default function FetchRequestDetail() {
|
|||||||
Back to Fetch Requests
|
Back to Fetch Requests
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{/* Header Card */}
|
||||||
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2, flexWrap: "wrap" }}>
|
||||||
<Chip
|
<Chip
|
||||||
@@ -392,7 +354,7 @@ export default function FetchRequestDetail() {
|
|||||||
<Box>
|
<Box>
|
||||||
<Typography variant="caption" color="text.secondary">Date Range</Typography>
|
<Typography variant="caption" color="text.secondary">Date Range</Typography>
|
||||||
<Typography variant="body2">
|
<Typography variant="body2">
|
||||||
{(req as any).start_date ? new Date((req as any).start_date).toLocaleDateString() : "?"} → {(req as any).end_date ? new Date((req as any).end_date).toLocaleDateString() : "?"}
|
{req.start_date ? new Date(req.start_date).toLocaleDateString() : "?"} → {req.end_date ? new Date(req.end_date).toLocaleDateString() : "?"}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
<Box>
|
<Box>
|
||||||
@@ -407,11 +369,10 @@ export default function FetchRequestDetail() {
|
|||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
{/* Progress Bar */}
|
||||||
<Box sx={{ mb: 2 }}>
|
<Box sx={{ mb: 2 }}>
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 0.5 }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 0.5 }}>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">Overall Progress</Typography>
|
||||||
Overall Progress
|
|
||||||
</Typography>
|
|
||||||
{["processing", "paused"].includes(req.status) && displayParsedCount > 0 && (
|
{["processing", "paused"].includes(req.status) && displayParsedCount > 0 && (
|
||||||
<Typography variant="caption" fontWeight={600} color="info.main">
|
<Typography variant="caption" fontWeight={600} color="info.main">
|
||||||
Validated: {displayParsedCount} transactions
|
Validated: {displayParsedCount} transactions
|
||||||
@@ -429,6 +390,7 @@ export default function FetchRequestDetail() {
|
|||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
{/* Retry Counter */}
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
||||||
<Box sx={{ flex: 1, maxWidth: 300 }}>
|
<Box sx={{ flex: 1, maxWidth: 300 }}>
|
||||||
<Typography variant="caption" color="text.secondary">
|
<Typography variant="caption" color="text.secondary">
|
||||||
@@ -455,18 +417,19 @@ export default function FetchRequestDetail() {
|
|||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* Error Alerts */}
|
||||||
{req.status === "failed" && req.error_message && (
|
{req.status === "failed" && req.error_message && (
|
||||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||||
{req.error_message}
|
{req.error_message}
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isRetryExhausted && req.status === "failed" && (
|
{isRetryExhausted && req.status === "failed" && (
|
||||||
<Alert severity="info" sx={{ mb: 3, borderRadius: 2 }}>
|
<Alert severity="info" sx={{ mb: 3, borderRadius: 2 }}>
|
||||||
Max retries reached — no further retry attempts will be made.
|
Max retries reached — no further retry attempts will be made.
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Pipeline Stepper */}
|
||||||
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||||
Pipeline Progress
|
Pipeline Progress
|
||||||
@@ -491,17 +454,15 @@ export default function FetchRequestDetail() {
|
|||||||
icon = <Typography variant="caption" color="text.disabled">{index + 1}</Typography>;
|
icon = <Typography variant="caption" color="text.disabled">{index + 1}</Typography>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const stepMsg = stepMessages[index];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Step key={label}>
|
<Step key={label}>
|
||||||
<StepLabel
|
<StepLabel
|
||||||
StepIconComponent={() => <Box sx={{ display: "flex", alignItems: "center" }}>{icon}</Box>}
|
StepIconComponent={() => <Box sx={{ display: "flex", alignItems: "center" }}>{icon}</Box>}
|
||||||
>
|
>
|
||||||
<Typography variant="body2" fontWeight={600}>{label}</Typography>
|
<Typography variant="body2" fontWeight={600}>{label}</Typography>
|
||||||
{stepMsg && (
|
{stepMessages[index] && (
|
||||||
<Typography variant="caption" color="text.secondary" sx={{ display: "block", lineHeight: 1.2 }}>
|
<Typography variant="caption" color="text.secondary" sx={{ display: "block", lineHeight: 1.2 }}>
|
||||||
{stepMsg}
|
{stepMessages[index]}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</StepLabel>
|
</StepLabel>
|
||||||
@@ -511,6 +472,7 @@ export default function FetchRequestDetail() {
|
|||||||
</Stepper>
|
</Stepper>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* SSE Event Feed */}
|
||||||
<Paper sx={{ borderRadius: 4, mb: 3 }} variant="outlined">
|
<Paper sx={{ borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, p: 2, pb: 0 }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1, p: 2, pb: 0 }}>
|
||||||
<Typography variant="subtitle1" fontWeight={600} sx={{ flex: 1 }}>
|
<Typography variant="subtitle1" fontWeight={600} sx={{ flex: 1 }}>
|
||||||
@@ -568,15 +530,13 @@ export default function FetchRequestDetail() {
|
|||||||
</Typography>
|
</Typography>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
<Typography variant="caption" color="text.disabled">
|
|
||||||
{new Date().toLocaleTimeString()}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
</Box>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* Ambiguity Resolution */}
|
||||||
{hasAmbiguities && (
|
{hasAmbiguities && (
|
||||||
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||||
@@ -666,6 +626,7 @@ export default function FetchRequestDetail() {
|
|||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Snackbar
|
<Snackbar
|
||||||
open={!!failNotif}
|
open={!!failNotif}
|
||||||
autoHideDuration={6000}
|
autoHideDuration={6000}
|
||||||
|
|||||||
@@ -25,6 +25,12 @@ import {
|
|||||||
FormControl,
|
FormControl,
|
||||||
OutlinedInput,
|
OutlinedInput,
|
||||||
Autocomplete,
|
Autocomplete,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableContainer,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
import DeleteIcon from "@mui/icons-material/Delete";
|
||||||
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
||||||
@@ -36,9 +42,7 @@ import ErrorIcon from "@mui/icons-material/Error";
|
|||||||
import ScheduleIcon from "@mui/icons-material/Schedule";
|
import ScheduleIcon from "@mui/icons-material/Schedule";
|
||||||
import HourglassEmptyIcon from "@mui/icons-material/HourglassEmpty";
|
import HourglassEmptyIcon from "@mui/icons-material/HourglassEmpty";
|
||||||
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||||
import {
|
import { useUploadFile } from "./features/fetch-requests";
|
||||||
useUploadFile,
|
|
||||||
} from "./features/fetch-requests";
|
|
||||||
import type {
|
import type {
|
||||||
FetchRequest,
|
FetchRequest,
|
||||||
FetchRequestStatus,
|
FetchRequestStatus,
|
||||||
@@ -47,7 +51,7 @@ import type {
|
|||||||
} from "./features/fetch-requests";
|
} from "./features/fetch-requests";
|
||||||
import { RETRY_MAX, formatApiError } from "./features/fetch-requests";
|
import { RETRY_MAX, formatApiError } from "./features/fetch-requests";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useResource, FormFieldRenderer } from "../react-openapi";
|
import { useResource, FormFieldRenderer, applyDisplayFormat } from "../react-openapi";
|
||||||
import type { FieldConfig } from "../react-openapi";
|
import type { FieldConfig } from "../react-openapi";
|
||||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
|
|
||||||
@@ -81,18 +85,6 @@ const STATUS_OPTIONS: FetchRequestStatus[] = [
|
|||||||
"failed",
|
"failed",
|
||||||
];
|
];
|
||||||
|
|
||||||
function formatDate(iso: string) {
|
|
||||||
const d = new Date(iso);
|
|
||||||
return d.toLocaleString();
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDateRange(start?: string, end?: string) {
|
|
||||||
if (!start && !end) return "\u2014";
|
|
||||||
const s = start ? new Date(start).toLocaleDateString() : "?";
|
|
||||||
const e = end ? new Date(end).toLocaleDateString() : "?";
|
|
||||||
return `${s} \u2192 ${e}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function shortId(fp: string) {
|
function shortId(fp: string) {
|
||||||
return fp.length > 8 ? fp.slice(0, 8) + "\u2026" : fp;
|
return fp.length > 8 ? fp.slice(0, 8) + "\u2026" : fp;
|
||||||
}
|
}
|
||||||
@@ -118,8 +110,7 @@ export default function FetchRequests() {
|
|||||||
const [accountFilter, setAccountFilter] = React.useState("");
|
const [accountFilter, setAccountFilter] = React.useState("");
|
||||||
const [sourceFilter, setSourceFilter] = React.useState<"all" | "file" | "email">("all");
|
const [sourceFilter, setSourceFilter] = React.useState<"all" | "file" | "email">("all");
|
||||||
|
|
||||||
const fr = useResource("fetch-requests");
|
const { list, create, update, remove, resource: fetchRes } = useResource("fetch-requests");
|
||||||
const { list, create, update, remove, resource: fetchRes } = fr;
|
|
||||||
|
|
||||||
const { data: listData, isLoading, isFetching, refetch } = useQuery({
|
const { data: listData, isLoading, isFetching, refetch } = useQuery({
|
||||||
queryKey: ["fetch-requests", "list", { statusFilter, accountFilter, sourceFilter }],
|
queryKey: ["fetch-requests", "list", { statusFilter, accountFilter, sourceFilter }],
|
||||||
@@ -141,20 +132,15 @@ export default function FetchRequests() {
|
|||||||
|
|
||||||
const fields = fetchRes?.orderedFields ?? [];
|
const fields = fetchRes?.orderedFields ?? [];
|
||||||
const formatField: FieldConfig | undefined = fields.find(f => f.name === "format");
|
const formatField: FieldConfig | undefined = fields.find(f => f.name === "format");
|
||||||
const formatOptions: string[] = formatField?.enumValues ?? [];
|
|
||||||
const startDateField: FieldConfig | undefined = fields.find(f => f.name === "start_date");
|
const startDateField: FieldConfig | undefined = fields.find(f => f.name === "start_date");
|
||||||
const endDateField: FieldConfig | undefined = fields.find(f => f.name === "end_date");
|
const endDateField: FieldConfig | undefined = fields.find(f => f.name === "end_date");
|
||||||
const payorUsernameField: FieldConfig | undefined = fields.find(f => f.name === "payor_username");
|
const payorUsernameField: FieldConfig | undefined = fields.find(f => f.name === "payor_username");
|
||||||
|
|
||||||
const createMutation = useMutation({
|
const createMutation = useMutation({ mutationFn: (data: any) => create(data) });
|
||||||
mutationFn: (data: any) => create(data),
|
|
||||||
});
|
|
||||||
const updateMutation = useMutation({
|
const updateMutation = useMutation({
|
||||||
mutationFn: ({ id, data }: { id: string; data: any }) => update(id, data),
|
mutationFn: ({ id, data }: { id: string; data: any }) => update(id, data),
|
||||||
});
|
});
|
||||||
const deleteMutation = useMutation({
|
const deleteMutation = useMutation({ mutationFn: (id: string) => remove(id) });
|
||||||
mutationFn: (id: string) => remove(id),
|
|
||||||
});
|
|
||||||
const uploadMutation = useUploadFile();
|
const uploadMutation = useUploadFile();
|
||||||
|
|
||||||
const requests = listData?.items ?? [];
|
const requests = listData?.items ?? [];
|
||||||
@@ -199,7 +185,7 @@ export default function FetchRequests() {
|
|||||||
navigate(`/fetch-requests/${result.id}`);
|
navigate(`/fetch-requests/${result.id}`);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
if (err?.response?.status === 409) {
|
if (err?.response?.status === 409) {
|
||||||
setSnackbar({ message: "Duplicate \u2014 same fingerprint already exists", severity: "error" });
|
setSnackbar({ message: "Duplicate — same fingerprint already exists", severity: "error" });
|
||||||
} else {
|
} else {
|
||||||
setSnackbar({ message: formatApiError(err) || "Failed to create fetch request", severity: "error" });
|
setSnackbar({ message: formatApiError(err) || "Failed to create fetch request", severity: "error" });
|
||||||
}
|
}
|
||||||
@@ -238,14 +224,13 @@ export default function FetchRequests() {
|
|||||||
setDeleteTarget(null);
|
setDeleteTarget(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const sourceTypeOptions: ("all" | "file" | "email")[] = ["all", "file", "email"];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container sx={{ mt: 4, mb: 4 }}>
|
<Container sx={{ mt: 4, mb: 4 }}>
|
||||||
<Typography variant="h5" fontWeight="bold" gutterBottom>
|
<Typography variant="h5" fontWeight="bold" gutterBottom>
|
||||||
Fetch Request Pipeline
|
Fetch Request Pipeline
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
|
{/* Create Form */}
|
||||||
<Paper sx={{ p: 3, mb: 4, borderRadius: 4 }} variant="outlined">
|
<Paper sx={{ p: 3, mb: 4, borderRadius: 4 }} variant="outlined">
|
||||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||||
New Fetch Request
|
New Fetch Request
|
||||||
@@ -286,40 +271,14 @@ export default function FetchRequests() {
|
|||||||
Uploaded as: {uploadedPath}
|
Uploaded as: {uploadedPath}
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
{formatField ? (
|
{formatField && (
|
||||||
<FormFieldRenderer
|
<FormFieldRenderer field={formatField} value={format} onChange={setFormat} />
|
||||||
field={formatField}
|
|
||||||
value={format}
|
|
||||||
onChange={setFormat}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<FormControl size="small">
|
|
||||||
<InputLabel>Format</InputLabel>
|
|
||||||
<Select value={format} onChange={(e) => setFormat(e.target.value)} label="Format">
|
|
||||||
{formatOptions.map((opt) => (
|
|
||||||
<MenuItem key={opt} value={opt}>{opt}</MenuItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{formatField ? (
|
{formatField && (
|
||||||
<FormFieldRenderer
|
<FormFieldRenderer field={formatField} value={format} onChange={setFormat} />
|
||||||
field={formatField}
|
|
||||||
value={format}
|
|
||||||
onChange={setFormat}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<FormControl size="small">
|
|
||||||
<InputLabel>Format</InputLabel>
|
|
||||||
<Select value={format} onChange={(e) => setFormat(e.target.value)} label="Format">
|
|
||||||
{formatOptions.map((opt) => (
|
|
||||||
<MenuItem key={opt} value={opt}>{opt}</MenuItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
)}
|
||||||
<TextField label="From Email" value={fromEmail} onChange={(e) => setFromEmail(e.target.value)} size="small" />
|
<TextField label="From Email" value={fromEmail} onChange={(e) => setFromEmail(e.target.value)} size="small" />
|
||||||
<TextField label="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} size="small" />
|
<TextField label="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} size="small" />
|
||||||
@@ -334,58 +293,22 @@ export default function FetchRequests() {
|
|||||||
renderInput={(params) => (
|
renderInput={(params) => (
|
||||||
<TextField {...params} label="Account Name" size="small" required />
|
<TextField {...params} label="Account Name" size="small" required />
|
||||||
)}
|
)}
|
||||||
sx={{ "& .MuiOutlinedInput-root": { height: "auto", minHeight: "2.5rem" } }}
|
|
||||||
/>
|
/>
|
||||||
{payorUsernameField ? (
|
|
||||||
<FormFieldRenderer
|
{payorUsernameField && (
|
||||||
field={payorUsernameField}
|
<FormFieldRenderer field={payorUsernameField} value={payorUsername} onChange={setPayorUsername} />
|
||||||
value={payorUsername}
|
|
||||||
onChange={setPayorUsername}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<TextField label="Payor Username" value={payorUsername} onChange={(e) => setPayorUsername(e.target.value)} size="small" helperText="Default: aetos" />
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 2 }}>
|
<Box sx={{ display: "flex", gap: 2 }}>
|
||||||
{startDateField ? (
|
{startDateField && (
|
||||||
<Box sx={{ flex: 1 }}>
|
<Box sx={{ flex: 1 }}>
|
||||||
<FormFieldRenderer
|
<FormFieldRenderer field={startDateField} value={startDate} onChange={setStartDate} />
|
||||||
field={startDateField}
|
|
||||||
value={startDate}
|
|
||||||
onChange={setStartDate}
|
|
||||||
/>
|
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
|
||||||
<TextField
|
|
||||||
label="Start Date"
|
|
||||||
type="date"
|
|
||||||
value={startDate}
|
|
||||||
onChange={(e) => setStartDate(e.target.value)}
|
|
||||||
size="small"
|
|
||||||
InputLabelProps={{ shrink: true }}
|
|
||||||
inputProps={{ max: new Date().toISOString().split("T")[0] }}
|
|
||||||
sx={{ flex: 1 }}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
{endDateField ? (
|
{endDateField && (
|
||||||
<Box sx={{ flex: 1 }}>
|
<Box sx={{ flex: 1 }}>
|
||||||
<FormFieldRenderer
|
<FormFieldRenderer field={endDateField} value={endDate} onChange={setEndDate} />
|
||||||
field={endDateField}
|
|
||||||
value={endDate}
|
|
||||||
onChange={setEndDate}
|
|
||||||
/>
|
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
|
||||||
<TextField
|
|
||||||
label="End Date"
|
|
||||||
type="date"
|
|
||||||
value={endDate}
|
|
||||||
onChange={(e) => setEndDate(e.target.value)}
|
|
||||||
size="small"
|
|
||||||
InputLabelProps={{ shrink: true }}
|
|
||||||
inputProps={{ max: new Date().toISOString().split("T")[0] }}
|
|
||||||
sx={{ flex: 1 }}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
@@ -399,6 +322,7 @@ export default function FetchRequests() {
|
|||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* Filters */}
|
||||||
<Paper sx={{ borderRadius: 4, mb: 2, p: 2 }} variant="outlined">
|
<Paper sx={{ borderRadius: 4, mb: 2, p: 2 }} variant="outlined">
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
||||||
<FormControl size="small" sx={{ minWidth: 200 }}>
|
<FormControl size="small" sx={{ minWidth: 200 }}>
|
||||||
@@ -410,7 +334,7 @@ export default function FetchRequests() {
|
|||||||
input={<OutlinedInput label="Status" />}
|
input={<OutlinedInput label="Status" />}
|
||||||
renderValue={(selected) => (selected as string[]).join(", ")}
|
renderValue={(selected) => (selected as string[]).join(", ")}
|
||||||
>
|
>
|
||||||
{STATUS_OPTIONS.map((s: string) => (
|
{STATUS_OPTIONS.map((s) => (
|
||||||
<MenuItem key={s} value={s}>{s.replace(/_/g, " ")}</MenuItem>
|
<MenuItem key={s} value={s}>{s.replace(/_/g, " ")}</MenuItem>
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
@@ -422,7 +346,7 @@ export default function FetchRequests() {
|
|||||||
renderInput={(params) => (
|
renderInput={(params) => (
|
||||||
<TextField {...params} label="Account" size="small" sx={{ minWidth: 160 }} />
|
<TextField {...params} label="Account" size="small" sx={{ minWidth: 160 }} />
|
||||||
)}
|
)}
|
||||||
sx={{ minWidth: 160, "& .MuiOutlinedInput-root": { height: "auto", minHeight: "2.5rem" } }}
|
sx={{ minWidth: 160 }}
|
||||||
/>
|
/>
|
||||||
<ToggleButtonGroup
|
<ToggleButtonGroup
|
||||||
value={sourceFilter}
|
value={sourceFilter}
|
||||||
@@ -430,11 +354,9 @@ export default function FetchRequests() {
|
|||||||
onChange={(_, val) => val && setSourceFilter(val)}
|
onChange={(_, val) => val && setSourceFilter(val)}
|
||||||
size="small"
|
size="small"
|
||||||
>
|
>
|
||||||
{sourceTypeOptions.map((opt) => (
|
<ToggleButton value="all">All</ToggleButton>
|
||||||
<ToggleButton key={opt} value={opt}>
|
<ToggleButton value="file">File</ToggleButton>
|
||||||
{opt === "all" ? "All" : opt === "file" ? "File" : "Email"}
|
<ToggleButton value="email">Email</ToggleButton>
|
||||||
</ToggleButton>
|
|
||||||
))}
|
|
||||||
</ToggleButtonGroup>
|
</ToggleButtonGroup>
|
||||||
<Box sx={{ flex: 1 }} />
|
<Box sx={{ flex: 1 }} />
|
||||||
<IconButton onClick={() => refetch()} disabled={isFetching}>
|
<IconButton onClick={() => refetch()} disabled={isFetching}>
|
||||||
@@ -443,6 +365,7 @@ export default function FetchRequests() {
|
|||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
|
{/* List Table */}
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
|
<Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
|
||||||
<CircularProgress />
|
<CircularProgress />
|
||||||
@@ -452,41 +375,35 @@ export default function FetchRequests() {
|
|||||||
No fetch requests yet
|
No fetch requests yet
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
) : (
|
||||||
<Paper variant="outlined" sx={{ borderRadius: 4 }}>
|
<TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 4 }}>
|
||||||
<Box sx={{ overflowX: "auto" }}>
|
<Table size="small">
|
||||||
<Box component="table" sx={{ width: "100%", borderCollapse: "collapse" }}>
|
<TableHead>
|
||||||
<Box component="thead">
|
<TableRow>
|
||||||
<Box component="tr" sx={{ borderBottom: 1, borderColor: "divider" }}>
|
<TableCell>ID</TableCell>
|
||||||
{["ID", "Account", "Source", "Date Range", "Status", "Retries", "Created", "Actions"].map((h) => (
|
<TableCell>Account</TableCell>
|
||||||
<Box
|
<TableCell>Source</TableCell>
|
||||||
key={h}
|
<TableCell>Date Range</TableCell>
|
||||||
component="th"
|
<TableCell>Status</TableCell>
|
||||||
sx={{ px: 2, py: 1.5, textAlign: h === "Actions" ? "right" : "left", fontWeight: 600, fontSize: "0.8rem", color: "text.secondary", whiteSpace: "nowrap" }}
|
<TableCell>Retries</TableCell>
|
||||||
>
|
<TableCell>Created</TableCell>
|
||||||
{h}
|
<TableCell align="right">Actions</TableCell>
|
||||||
</Box>
|
</TableRow>
|
||||||
))}
|
</TableHead>
|
||||||
</Box>
|
<TableBody>
|
||||||
</Box>
|
|
||||||
<Box component="tbody">
|
|
||||||
{[...requests]
|
{[...requests]
|
||||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
|
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
|
||||||
.map((req: FetchRequest) => (
|
.map((req: FetchRequest) => (
|
||||||
<Box
|
<TableRow
|
||||||
key={req.id}
|
key={req.id}
|
||||||
component="tr"
|
hover
|
||||||
|
sx={{ cursor: "pointer" }}
|
||||||
onClick={() => navigate(`/fetch-requests/${req.id}`)}
|
onClick={() => navigate(`/fetch-requests/${req.id}`)}
|
||||||
sx={{
|
|
||||||
cursor: "pointer",
|
|
||||||
borderBottom: 1,
|
|
||||||
borderColor: "divider",
|
|
||||||
"&:hover": { bgcolor: "action.hover" },
|
|
||||||
"&:last-child": { borderBottom: 0 },
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5, fontFamily: "monospace", fontSize: "0.8rem" }}>
|
<TableCell>
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
|
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
|
||||||
|
<Typography variant="body2" sx={{ fontFamily: "monospace", fontSize: "0.8rem" }}>
|
||||||
{shortId(req.fingerprint)}
|
{shortId(req.fingerprint)}
|
||||||
|
</Typography>
|
||||||
<IconButton
|
<IconButton
|
||||||
size="small"
|
size="small"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
@@ -499,25 +416,22 @@ export default function FetchRequests() {
|
|||||||
<ContentCopyIcon sx={{ fontSize: 14 }} />
|
<ContentCopyIcon sx={{ fontSize: 14 }} />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</TableCell>
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5, fontSize: "0.875rem" }}>
|
<TableCell>{req.account_name}</TableCell>
|
||||||
{req.account_name}
|
<TableCell>
|
||||||
</Box>
|
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5 }}>
|
|
||||||
<Chip
|
<Chip
|
||||||
label={"path" in req.source ? "File" : "Email"}
|
label={"path" in req.source ? "File" : "Email"}
|
||||||
size="small"
|
size="small"
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
color={"path" in req.source ? "primary" : "secondary"}
|
color={"path" in req.source ? "primary" : "secondary"}
|
||||||
/>
|
/>
|
||||||
</Box>
|
</TableCell>
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5 }}>
|
<TableCell>
|
||||||
<Typography variant="body2" sx={{ fontSize: "0.8rem", whiteSpace: "nowrap" }}>
|
<Typography variant="body2" sx={{ fontSize: "0.8rem", whiteSpace: "nowrap" }}>
|
||||||
{formatDateRange((req as any).start_date, (req as any).end_date)}
|
{(req as any).start_date ? new Date((req as any).start_date).toLocaleDateString() : "?"} → {(req as any).end_date ? new Date((req as any).end_date).toLocaleDateString() : "?"}
|
||||||
</Typography>
|
</Typography>
|
||||||
</Box>
|
</TableCell>
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5 }}>
|
<TableCell>
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
|
|
||||||
<Tooltip title={req.error_message || req.status.replace(/_/g, " ")}>
|
<Tooltip title={req.error_message || req.status.replace(/_/g, " ")}>
|
||||||
<Chip
|
<Chip
|
||||||
icon={statusIcons[req.status] as any}
|
icon={statusIcons[req.status] as any}
|
||||||
@@ -526,69 +440,45 @@ export default function FetchRequests() {
|
|||||||
size="small"
|
size="small"
|
||||||
/>
|
/>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Box>
|
</TableCell>
|
||||||
</Box>
|
<TableCell>
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5 }}>
|
|
||||||
{(req.retry_count ?? 0) > 0 ? (
|
|
||||||
<Typography variant="body2" sx={{ fontSize: "0.8rem" }}>
|
<Typography variant="body2" sx={{ fontSize: "0.8rem" }}>
|
||||||
{req.retry_count}/{RETRY_MAX}
|
{(req.retry_count ?? 0) > 0 ? `${req.retry_count}/${RETRY_MAX}` : "—"}
|
||||||
</Typography>
|
</Typography>
|
||||||
) : (
|
</TableCell>
|
||||||
<Typography variant="body2" sx={{ fontSize: "0.8rem", color: "text.disabled" }}>
|
<TableCell>
|
||||||
\u2014
|
<Typography variant="body2" sx={{ fontSize: "0.8rem", whiteSpace: "nowrap" }}>
|
||||||
|
{new Date(req.created_at).toLocaleString()}
|
||||||
</Typography>
|
</Typography>
|
||||||
)}
|
</TableCell>
|
||||||
</Box>
|
<TableCell align="right">
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5, whiteSpace: "nowrap", fontSize: "0.8rem" }}>
|
|
||||||
{formatDate(req.created_at)}
|
|
||||||
</Box>
|
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5 }}>
|
|
||||||
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
|
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
|
||||||
{req.status === "paused" && (
|
{req.status === "paused" && (
|
||||||
<Tooltip title="Resolve ambiguities">
|
<Tooltip title="Resolve ambiguities">
|
||||||
<IconButton
|
<IconButton size="small" onClick={(e) => { e.stopPropagation(); navigate(`/fetch-requests/${req.id}`); }}>
|
||||||
size="small"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
navigate(`/fetch-requests/${req.id}`);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<WarningAmberIcon fontSize="small" color="warning" />
|
<WarningAmberIcon fontSize="small" color="warning" />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
{req.status === "failed" && (req.retry_count ?? 0) < RETRY_MAX && (
|
{req.status === "failed" && (req.retry_count ?? 0) < RETRY_MAX && (
|
||||||
<Tooltip title="Retry">
|
<Tooltip title="Retry">
|
||||||
<IconButton
|
<IconButton size="small" onClick={(e) => { e.stopPropagation(); handleRetry(req); }}>
|
||||||
size="small"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
handleRetry(req);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ReplayIcon fontSize="small" />
|
<ReplayIcon fontSize="small" />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
<Tooltip title="Delete">
|
<Tooltip title="Delete">
|
||||||
<IconButton
|
<IconButton size="small" onClick={(e) => { e.stopPropagation(); setDeleteTarget(req); }}>
|
||||||
size="small"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
setDeleteTarget(req);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<DeleteIcon fontSize="small" />
|
<DeleteIcon fontSize="small" />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</TableCell>
|
||||||
</Box>
|
</TableRow>
|
||||||
))}
|
))}
|
||||||
</Box>
|
</TableBody>
|
||||||
</Box>
|
</Table>
|
||||||
</Box>
|
</TableContainer>
|
||||||
</Paper>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Snackbar
|
<Snackbar
|
||||||
|
|||||||
@@ -101,9 +101,7 @@ export default function Header({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{[
|
{[
|
||||||
{ label: "Dashboard", path: "/dashboard" },
|
|
||||||
{ label: "Fetch", path: "/fetch-requests" },
|
{ label: "Fetch", path: "/fetch-requests" },
|
||||||
{ label: "Reports", path: "/reports" },
|
|
||||||
].map(({ label, path }) => (
|
].map(({ label, path }) => (
|
||||||
<Button
|
<Button
|
||||||
key={path}
|
key={path}
|
||||||
|
|||||||
@@ -1,303 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Container,
|
|
||||||
Paper,
|
|
||||||
Typography,
|
|
||||||
Button,
|
|
||||||
IconButton,
|
|
||||||
CircularProgress,
|
|
||||||
Alert,
|
|
||||||
Snackbar,
|
|
||||||
Dialog,
|
|
||||||
DialogTitle,
|
|
||||||
DialogContent,
|
|
||||||
DialogContentText,
|
|
||||||
DialogActions,
|
|
||||||
Chip,
|
|
||||||
TextField,
|
|
||||||
} from "@mui/material";
|
|
||||||
import DeleteIcon from "@mui/icons-material/Delete";
|
|
||||||
import AddCircleIcon from "@mui/icons-material/AddCircle";
|
|
||||||
import RefreshIcon from "@mui/icons-material/Refresh";
|
|
||||||
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
|
||||||
import { useResource } from "../react-openapi";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
interface ReportSnapshotQuery {
|
|
||||||
accounts?: string[];
|
|
||||||
ignore_self?: boolean;
|
|
||||||
start_date?: string;
|
|
||||||
end_date?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ReportSnapshot {
|
|
||||||
id: string;
|
|
||||||
snapshot_id: string;
|
|
||||||
created_at: string;
|
|
||||||
query?: ReportSnapshotQuery;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDate(iso: string) {
|
|
||||||
const d = new Date(iso);
|
|
||||||
return d.toLocaleString();
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ReportSnapshots() {
|
|
||||||
const [ignoreSelf, setIgnoreSelf] = React.useState(true);
|
|
||||||
const [startDate, setStartDate] = React.useState("");
|
|
||||||
const [endDate, setEndDate] = React.useState("");
|
|
||||||
const [minAmount, setMinAmount] = React.useState("");
|
|
||||||
const [maxAmount, setMaxAmount] = React.useState("");
|
|
||||||
const [snackbar, setSnackbar] = React.useState<{ message: string; severity: "success" | "error" } | null>(null);
|
|
||||||
const [deleteTarget, setDeleteTarget] = React.useState<ReportSnapshot | null>(null);
|
|
||||||
const [createdSnapshotId, setCreatedSnapshotId] = React.useState<string | null>(null);
|
|
||||||
|
|
||||||
const { list, create, remove } = useResource("reports");
|
|
||||||
|
|
||||||
const { data: listData, isLoading, isFetching, refetch } = useQuery({
|
|
||||||
queryKey: ["reports", "list"],
|
|
||||||
queryFn: () => list(),
|
|
||||||
});
|
|
||||||
const createMutation = useMutation({
|
|
||||||
mutationFn: (data: any) => create(data),
|
|
||||||
});
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const deleteMutation = useMutation({
|
|
||||||
mutationFn: (id: string) => remove(id),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["reports", "list"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const snapshots: ReportSnapshot[] = listData?.items ?? [];
|
|
||||||
|
|
||||||
const handleCreate = async () => {
|
|
||||||
try {
|
|
||||||
const payload: Record<string, any> = {};
|
|
||||||
if (ignoreSelf) payload.ignore_self = true;
|
|
||||||
if (startDate) payload.start_date = new Date(startDate).toISOString();
|
|
||||||
if (endDate) payload.end_date = new Date(endDate).toISOString();
|
|
||||||
if (minAmount) payload.min_amount = parseFloat(minAmount);
|
|
||||||
if (maxAmount) payload.max_amount = parseFloat(maxAmount);
|
|
||||||
|
|
||||||
const result = await createMutation.mutateAsync(payload);
|
|
||||||
const snapshotId = (result as any)?.snapshot_id;
|
|
||||||
if (snapshotId) {
|
|
||||||
setCreatedSnapshotId(snapshotId);
|
|
||||||
setSnackbar({ message: `Snapshot created: ${snapshotId}`, severity: "success" });
|
|
||||||
} else {
|
|
||||||
setSnackbar({ message: "Snapshot created", severity: "success" });
|
|
||||||
}
|
|
||||||
resetForm();
|
|
||||||
} catch (err: any) {
|
|
||||||
setSnackbar({ message: err?.response?.data?.detail || "Failed to create snapshot", severity: "error" });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetForm = () => {
|
|
||||||
setIgnoreSelf(true);
|
|
||||||
setStartDate("");
|
|
||||||
setEndDate("");
|
|
||||||
setMinAmount("");
|
|
||||||
setMaxAmount("");
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = async () => {
|
|
||||||
if (!deleteTarget) return;
|
|
||||||
try {
|
|
||||||
await deleteMutation.mutateAsync(deleteTarget.snapshot_id);
|
|
||||||
setSnackbar({ message: "Snapshot deleted", severity: "success" });
|
|
||||||
} catch {
|
|
||||||
setSnackbar({ message: "Failed to delete snapshot", severity: "error" });
|
|
||||||
}
|
|
||||||
setDeleteTarget(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Container sx={{ mt: 4, mb: 4 }}>
|
|
||||||
<Typography variant="h5" fontWeight="bold" gutterBottom>
|
|
||||||
Report Snapshots
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Paper sx={{ p: 3, mb: 4, borderRadius: 4 }} variant="outlined">
|
|
||||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
|
||||||
Generate New Snapshot
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
|
||||||
<Box sx={{ display: "flex", gap: 2 }}>
|
|
||||||
<Box sx={{ flex: 1 }}>
|
|
||||||
<TextField
|
|
||||||
label="Start Date"
|
|
||||||
type="date"
|
|
||||||
value={startDate}
|
|
||||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setStartDate(e.target.value)}
|
|
||||||
size="small"
|
|
||||||
InputLabelProps={{ shrink: true }}
|
|
||||||
inputProps={{ max: new Date().toISOString().split("T")[0] }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
<Box sx={{ flex: 1 }}>
|
|
||||||
<TextField
|
|
||||||
label="End Date"
|
|
||||||
type="date"
|
|
||||||
value={endDate}
|
|
||||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEndDate(e.target.value)}
|
|
||||||
size="small"
|
|
||||||
InputLabelProps={{ shrink: true }}
|
|
||||||
inputProps={{ max: new Date().toISOString().split("T")[0] }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box sx={{ display: "flex", gap: 2 }}>
|
|
||||||
<Box sx={{ flex: 1 }}>
|
|
||||||
<TextField
|
|
||||||
label="Min Amount"
|
|
||||||
type="number"
|
|
||||||
value={minAmount}
|
|
||||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMinAmount(e.target.value)}
|
|
||||||
size="small"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
<Box sx={{ flex: 1 }}>
|
|
||||||
<TextField
|
|
||||||
label="Max Amount"
|
|
||||||
type="number"
|
|
||||||
value={maxAmount}
|
|
||||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMaxAmount(e.target.value)}
|
|
||||||
size="small"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="contained"
|
|
||||||
startIcon={<AddCircleIcon />}
|
|
||||||
onClick={handleCreate}
|
|
||||||
disabled={createMutation.isPending}
|
|
||||||
>
|
|
||||||
{createMutation.isPending ? "Generating..." : "Generate Snapshot"}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{createdSnapshotId && (
|
|
||||||
<Alert severity="success" onClose={() => setCreatedSnapshotId(null)}>
|
|
||||||
Snapshot created: <strong>{createdSnapshotId}</strong>. Use it in the Dashboard snapshot selector.
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Paper sx={{ borderRadius: 4 }} variant="outlined">
|
|
||||||
<Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", p: 2, pb: 0 }}>
|
|
||||||
<Typography variant="subtitle1" fontWeight={600}>
|
|
||||||
Existing Snapshots
|
|
||||||
</Typography>
|
|
||||||
<IconButton onClick={() => refetch()} disabled={isFetching}>
|
|
||||||
<RefreshIcon />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{isLoading ? (
|
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
|
|
||||||
<CircularProgress />
|
|
||||||
</Box>
|
|
||||||
) : snapshots.length === 0 ? (
|
|
||||||
<Box sx={{ p: 4, textAlign: "center", color: "text.secondary" }}>
|
|
||||||
No snapshots yet
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<Box sx={{ overflowX: "auto" }}>
|
|
||||||
<Box component="table" sx={{ width: "100%", borderCollapse: "collapse" }}>
|
|
||||||
<Box component="thead">
|
|
||||||
<Box component="tr" sx={{ borderBottom: 1, borderColor: "divider" }}>
|
|
||||||
{["Snapshot ID", "Created", "Query", "Actions"].map((h) => (
|
|
||||||
<Box
|
|
||||||
key={h}
|
|
||||||
component="th"
|
|
||||||
sx={{ px: 2, py: 1.5, textAlign: h === "Actions" ? "right" : "left", fontWeight: 600, fontSize: "0.8rem", color: "text.secondary", whiteSpace: "nowrap" }}
|
|
||||||
>
|
|
||||||
{h}
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
<Box component="tbody">
|
|
||||||
{snapshots.map((snap: ReportSnapshot) => (
|
|
||||||
<Box
|
|
||||||
key={snap.id}
|
|
||||||
component="tr"
|
|
||||||
sx={{ borderBottom: 1, borderColor: "divider", "&:last-child": { borderBottom: 0 }, "&:hover": { bgcolor: "action.hover" } }}
|
|
||||||
>
|
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5, fontFamily: "monospace", fontSize: "0.8rem" }}>
|
|
||||||
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
|
|
||||||
{snap.snapshot_id}
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
onClick={() => {
|
|
||||||
navigator.clipboard.writeText(snap.snapshot_id);
|
|
||||||
setSnackbar({ message: "Copied!", severity: "success" });
|
|
||||||
}}
|
|
||||||
sx={{ opacity: 0.5, '&:hover': { opacity: 1 } }}
|
|
||||||
>
|
|
||||||
<ContentCopyIcon sx={{ fontSize: 14 }} />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5, fontSize: "0.875rem" }}>
|
|
||||||
{formatDate(snap.created_at)}
|
|
||||||
</Box>
|
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5 }}>
|
|
||||||
{snap.query ? (
|
|
||||||
<Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap" }}>
|
|
||||||
{snap.query.accounts && <Chip label={`${snap.query.accounts.length} account(s)`} size="small" variant="outlined" />}
|
|
||||||
{snap.query.ignore_self && <Chip label="ignore_self" size="small" variant="outlined" />}
|
|
||||||
{snap.query.start_date && <Chip label="start" size="small" variant="outlined" />}
|
|
||||||
{snap.query.end_date && <Chip label="end" size="small" variant="outlined" />}
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<Typography variant="body2" color="text.secondary">\u2014</Typography>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
<Box component="td" sx={{ px: 2, py: 1.5 }}>
|
|
||||||
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
|
|
||||||
<IconButton size="small" onClick={() => setDeleteTarget(snap)}>
|
|
||||||
<DeleteIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Snackbar
|
|
||||||
open={!!snackbar}
|
|
||||||
autoHideDuration={4000}
|
|
||||||
onClose={() => setSnackbar(null)}
|
|
||||||
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
|
|
||||||
>
|
|
||||||
{snackbar ? <Alert severity={snackbar.severity} onClose={() => setSnackbar(null)}>{snackbar.message}</Alert> : undefined}
|
|
||||||
</Snackbar>
|
|
||||||
|
|
||||||
<Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>
|
|
||||||
<DialogTitle>Delete Snapshot?</DialogTitle>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogContentText>
|
|
||||||
This will permanently delete the report snapshot.
|
|
||||||
</DialogContentText>
|
|
||||||
</DialogContent>
|
|
||||||
<DialogActions>
|
|
||||||
<Button onClick={() => setDeleteTarget(null)}>Cancel</Button>
|
|
||||||
<Button onClick={handleDelete} color="error" disabled={deleteMutation.isPending}>
|
|
||||||
{deleteMutation.isPending ? "Deleting..." : "Delete"}
|
|
||||||
</Button>
|
|
||||||
</DialogActions>
|
|
||||||
</Dialog>
|
|
||||||
</Container>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
ReportData,
|
|
||||||
GroupKey,
|
|
||||||
} from "../../features/report";
|
|
||||||
|
|
||||||
export type DashboardFlow = "outflows" | "inflows";
|
|
||||||
export type DashboardPeriodType = "rolling" | "calendar";
|
|
||||||
export type DashboardSelectedPeriodId = string | null;
|
|
||||||
|
|
||||||
export interface DashboardState {
|
|
||||||
flow: DashboardFlow;
|
|
||||||
periodType: DashboardPeriodType;
|
|
||||||
selectedPeriodId: DashboardSelectedPeriodId;
|
|
||||||
selectedGroupKey: GroupKey | null;
|
|
||||||
comparison: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardStateSetters {
|
|
||||||
setSelectedPeriodId: (id: DashboardSelectedPeriodId) => void;
|
|
||||||
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
|
|
||||||
toggleFlow: () => void;
|
|
||||||
togglePeriodType: () => void;
|
|
||||||
toggleComparison: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardSection {
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
component: React.ComponentType<any>;
|
|
||||||
summary?: string;
|
|
||||||
settings?: Record<string, any>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardConfig {
|
|
||||||
sections: DashboardSection[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DashboardViewProps {
|
|
||||||
config: DashboardConfig;
|
|
||||||
data: ReportData;
|
|
||||||
state: DashboardState;
|
|
||||||
stateSetters: DashboardStateSetters;
|
|
||||||
isFetching: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ColorScheme {
|
|
||||||
primary: string;
|
|
||||||
surface: string;
|
|
||||||
text: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ComponentProps extends DashboardSection {
|
|
||||||
reportData: ReportData;
|
|
||||||
|
|
||||||
state: DashboardState;
|
|
||||||
stateSetters: DashboardStateSetters;
|
|
||||||
isFetching: boolean;
|
|
||||||
|
|
||||||
colorScheme: ColorScheme;
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Container,
|
|
||||||
Grid,
|
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
Button
|
|
||||||
} from "@mui/material";
|
|
||||||
import { useTheme, alpha } from "@mui/material/styles";
|
|
||||||
import { DashboardViewProps } from "./Dashboard.models";
|
|
||||||
|
|
||||||
export default function DashboardView({
|
|
||||||
config,
|
|
||||||
data,
|
|
||||||
state,
|
|
||||||
stateSetters,
|
|
||||||
isFetching,
|
|
||||||
}: DashboardViewProps) {
|
|
||||||
const theme = useTheme();
|
|
||||||
|
|
||||||
const {
|
|
||||||
flow,
|
|
||||||
selectedGroupKey,
|
|
||||||
} = state;
|
|
||||||
|
|
||||||
const colorScheme = flow === "outflows" ? theme.palette.flows.outflows : theme.palette.flows.inflows;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Container
|
|
||||||
sx={{
|
|
||||||
mt: 4,
|
|
||||||
mb: 4,
|
|
||||||
background: `linear-gradient(180deg, ${alpha(colorScheme.primary, theme.palette.mode === "dark" ? 0.06 : 0.04)} 0%, transparent 100%)`,
|
|
||||||
borderRadius: 4,
|
|
||||||
p: 2,
|
|
||||||
transition: "background 0.3s ease",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: "center",
|
|
||||||
mb: 3,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ToggleButtonGroup
|
|
||||||
value={flow}
|
|
||||||
exclusive
|
|
||||||
onChange={stateSetters.toggleFlow}
|
|
||||||
sx={{
|
|
||||||
borderRadius: 3,
|
|
||||||
overflow: "hidden",
|
|
||||||
"& .MuiToggleButton-root": {
|
|
||||||
px: 3,
|
|
||||||
textTransform: "none",
|
|
||||||
color: "text.secondary",
|
|
||||||
},
|
|
||||||
"&.Mui-selected": {
|
|
||||||
bgcolor: colorScheme.primary,
|
|
||||||
color: "white",
|
|
||||||
borderColor: colorScheme.primary,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ToggleButton value="outflows">Outflows</ToggleButton>
|
|
||||||
<ToggleButton value="inflows">Inflows</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
{selectedGroupKey && Object.keys(selectedGroupKey).length > 0 && (
|
|
||||||
<Button
|
|
||||||
size="small"
|
|
||||||
sx={{ mt: 1, textTransform: "none" }}
|
|
||||||
onClick={() => stateSetters.setSelectedGroupKey(null)}
|
|
||||||
>
|
|
||||||
Clear Drill-down
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Grid container spacing={4}>
|
|
||||||
{config.sections.map((section) => {
|
|
||||||
const Component = section.component;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Grid key={section.id} size={12}>
|
|
||||||
<Component
|
|
||||||
{...section}
|
|
||||||
|
|
||||||
reportData={data}
|
|
||||||
|
|
||||||
state={state}
|
|
||||||
stateSetters={stateSetters}
|
|
||||||
isFetching={isFetching}
|
|
||||||
|
|
||||||
colorScheme={colorScheme}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Grid>
|
|
||||||
</Container>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { default } from "./Dashboard.view";
|
|
||||||
export * from "./Dashboard.models";
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
import { ReportData } from "../../features/report";
|
|
||||||
import {
|
|
||||||
mergeBucketPeriods,
|
|
||||||
getAmount,
|
|
||||||
PeriodKey,
|
|
||||||
} from "../report.helpers";
|
|
||||||
import { ChartDataPoint } from "./HistoryChart.models";
|
|
||||||
|
|
||||||
// ─── Tab → PeriodKey ─────────────────────────────────────────
|
|
||||||
|
|
||||||
const TAB_TO_KEY: Record<string, PeriodKey> = {
|
|
||||||
Daily: "daily",
|
|
||||||
Weekly: "weekly",
|
|
||||||
Monthly: "monthly",
|
|
||||||
"All Time": "all",
|
|
||||||
};
|
|
||||||
|
|
||||||
export function tabToKey(tab: string): PeriodKey {
|
|
||||||
return TAB_TO_KEY[tab] ?? "all";
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Comparison ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
function attachComparison(
|
|
||||||
points: ChartDataPoint[],
|
|
||||||
key: PeriodKey
|
|
||||||
): ChartDataPoint[] {
|
|
||||||
const getCompareIndex = (i: number) => {
|
|
||||||
if (key === "daily") return i - 7;
|
|
||||||
if (key === "weekly") return i - 4;
|
|
||||||
if (key === "monthly") return i - 12;
|
|
||||||
return -1;
|
|
||||||
};
|
|
||||||
|
|
||||||
return points.map((p, i) => {
|
|
||||||
const ci = getCompareIndex(i);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...p,
|
|
||||||
compare:
|
|
||||||
ci >= 0 && points[ci]
|
|
||||||
? {
|
|
||||||
id: points[ci].id,
|
|
||||||
label: points[ci].label,
|
|
||||||
amount: points[ci].amount,
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Main adapter ────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function buildChartData(
|
|
||||||
reportData: ReportData,
|
|
||||||
key: PeriodKey,
|
|
||||||
flow: "outflows" | "inflows",
|
|
||||||
comparison: boolean
|
|
||||||
): ChartDataPoint[] {
|
|
||||||
const merged = mergeBucketPeriods(reportData.buckets, key);
|
|
||||||
|
|
||||||
let points: ChartDataPoint[] = merged.map((p) => ({
|
|
||||||
id: p.id,
|
|
||||||
label: p.label,
|
|
||||||
amount: getAmount(p),
|
|
||||||
}));
|
|
||||||
|
|
||||||
if (comparison) {
|
|
||||||
points = attachComparison(points, key);
|
|
||||||
}
|
|
||||||
|
|
||||||
return points;
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
export interface _ChartDataPoint {
|
|
||||||
id: string;
|
|
||||||
label: string;
|
|
||||||
amount: number;
|
|
||||||
highlighted?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ChartDataPoint extends _ChartDataPoint {
|
|
||||||
compare?: _ChartDataPoint;
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import { ComponentProps } from "../Dashboard";
|
|
||||||
import { ChartDataPoint } from "./HistoryChart.models";
|
|
||||||
|
|
||||||
export interface HistoryChartProps extends ComponentProps {
|
|
||||||
settings: {
|
|
||||||
tabs: string[];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HistoryChartViewProps extends HistoryChartProps {
|
|
||||||
activeTab: string;
|
|
||||||
setActiveTab: (v: string) => void;
|
|
||||||
currentData: ChartDataPoint[];
|
|
||||||
visibleData: ChartDataPoint[];
|
|
||||||
maxAmount: number;
|
|
||||||
visibleCount: number;
|
|
||||||
startIndex: number;
|
|
||||||
setStartIndex: React.Dispatch<React.SetStateAction<number>>;
|
|
||||||
activeDataKey: string;
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import HistoryChartView from "./HistoryChart.view";
|
|
||||||
import { buildChartData, tabToKey } from "./HistoryChart.adapter";
|
|
||||||
import { HistoryChartProps } from "./HistoryChart.props";
|
|
||||||
|
|
||||||
|
|
||||||
export default function HistoryChart(props: HistoryChartProps) {
|
|
||||||
const {
|
|
||||||
settings,
|
|
||||||
reportData,
|
|
||||||
state,
|
|
||||||
stateSetters,
|
|
||||||
|
|
||||||
isFetching,
|
|
||||||
} = props;
|
|
||||||
|
|
||||||
const { flow, comparison, selectedPeriodId } = state;
|
|
||||||
const { setSelectedPeriodId } = stateSetters;
|
|
||||||
const { tabs } = settings;
|
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
|
|
||||||
const [startIndex, setStartIndex] = React.useState(0);
|
|
||||||
|
|
||||||
const activeDataKey = tabToKey(activeTab);
|
|
||||||
|
|
||||||
const currentData = React.useMemo(() => {
|
|
||||||
return buildChartData(reportData, activeDataKey, flow, comparison);
|
|
||||||
}, [reportData, activeDataKey, flow, comparison]);
|
|
||||||
|
|
||||||
const maxAmount =
|
|
||||||
currentData.length > 0
|
|
||||||
? Math.max(
|
|
||||||
...currentData.flatMap((d) =>
|
|
||||||
comparison
|
|
||||||
? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
|
|
||||||
: [d.amount]
|
|
||||||
),
|
|
||||||
1
|
|
||||||
)
|
|
||||||
: 1;
|
|
||||||
|
|
||||||
const visibleCountMap = {
|
|
||||||
daily: 7,
|
|
||||||
weekly: 6,
|
|
||||||
monthly: 4,
|
|
||||||
all: 4,
|
|
||||||
};
|
|
||||||
|
|
||||||
const visibleCount = visibleCountMap[activeDataKey] ?? 4;
|
|
||||||
|
|
||||||
const total = currentData.length;
|
|
||||||
|
|
||||||
const clampedStartIndex = Math.min(
|
|
||||||
startIndex,
|
|
||||||
Math.max(total - visibleCount, 0)
|
|
||||||
);
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (startIndex !== clampedStartIndex) {
|
|
||||||
setStartIndex(clampedStartIndex);
|
|
||||||
}
|
|
||||||
}, [startIndex, clampedStartIndex]);
|
|
||||||
|
|
||||||
const visibleData = currentData.slice(
|
|
||||||
clampedStartIndex,
|
|
||||||
clampedStartIndex + visibleCount
|
|
||||||
);
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
setSelectedPeriodId(null);
|
|
||||||
}, [activeTab]);
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (
|
|
||||||
selectedPeriodId &&
|
|
||||||
!visibleData.some((p) => p.id === selectedPeriodId)
|
|
||||||
) {
|
|
||||||
setSelectedPeriodId(null);
|
|
||||||
}
|
|
||||||
}, [visibleData, selectedPeriodId]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<HistoryChartView
|
|
||||||
{...props}
|
|
||||||
activeTab={activeTab}
|
|
||||||
setActiveTab={setActiveTab}
|
|
||||||
currentData={currentData}
|
|
||||||
visibleData={visibleData}
|
|
||||||
maxAmount={maxAmount}
|
|
||||||
visibleCount={visibleCount}
|
|
||||||
startIndex={clampedStartIndex}
|
|
||||||
setStartIndex={setStartIndex}
|
|
||||||
activeDataKey={activeDataKey}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { ChartDataPoint } from "./HistoryChart.models";
|
|
||||||
|
|
||||||
export const formatDisplay = (
|
|
||||||
point: ChartDataPoint,
|
|
||||||
tab: string,
|
|
||||||
comparison: boolean
|
|
||||||
) => {
|
|
||||||
const base = point.amount;
|
|
||||||
const cmp = point.compare?.amount ?? 0;
|
|
||||||
|
|
||||||
const formatShort = (val: number) => {
|
|
||||||
if (tab === "monthly" && val >= 100000) {
|
|
||||||
return `${(val / 100000).toFixed(2)}L`;
|
|
||||||
}
|
|
||||||
if (tab === "weekly" && val >= 1000) {
|
|
||||||
return `${(val / 1000).toFixed(1)}K`;
|
|
||||||
}
|
|
||||||
return val.toLocaleString("en-IN");
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!comparison) return `₹ ${formatShort(base)}`;
|
|
||||||
|
|
||||||
const diff = base - cmp;
|
|
||||||
const sign = diff >= 0 ? "+" : "-";
|
|
||||||
|
|
||||||
return `₹ ${formatShort(base)} (${sign}${formatShort(Math.abs(diff))})`;
|
|
||||||
};
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Typography,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
ToggleButton,
|
|
||||||
Paper
|
|
||||||
} from "@mui/material";
|
|
||||||
import { useTheme, alpha } from "@mui/material/styles";
|
|
||||||
import IconButton from "@mui/material/IconButton";
|
|
||||||
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
|
|
||||||
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
|
|
||||||
import {
|
|
||||||
HistoryChartViewProps,
|
|
||||||
} from "./HistoryChart.props";
|
|
||||||
import { formatDisplay } from "./HistoryChart.utils";
|
|
||||||
|
|
||||||
export default function HistoryChartView({
|
|
||||||
title,
|
|
||||||
summary,
|
|
||||||
settings,
|
|
||||||
|
|
||||||
state,
|
|
||||||
stateSetters,
|
|
||||||
isFetching,
|
|
||||||
|
|
||||||
colorScheme,
|
|
||||||
|
|
||||||
activeTab,
|
|
||||||
setActiveTab,
|
|
||||||
currentData,
|
|
||||||
visibleData,
|
|
||||||
maxAmount,
|
|
||||||
visibleCount,
|
|
||||||
startIndex,
|
|
||||||
setStartIndex,
|
|
||||||
activeDataKey,
|
|
||||||
}: HistoryChartViewProps) {
|
|
||||||
|
|
||||||
const { flow, periodType, selectedPeriodId, comparison } = state;
|
|
||||||
const { togglePeriodType, setSelectedPeriodId, toggleComparison } = stateSetters;
|
|
||||||
|
|
||||||
const theme = useTheme();
|
|
||||||
const isDark = theme.palette.mode === "dark";
|
|
||||||
|
|
||||||
const total = currentData.length;
|
|
||||||
const maxStartIndex = Math.max(total - visibleCount, 0);
|
|
||||||
const clampedStartIndex = Math.min(startIndex, maxStartIndex);
|
|
||||||
|
|
||||||
const handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => {
|
|
||||||
if (newTab !== null) setActiveTab(newTab);
|
|
||||||
};
|
|
||||||
|
|
||||||
const canGoLeft = clampedStartIndex > 0;
|
|
||||||
const canGoRight = clampedStartIndex < maxStartIndex;
|
|
||||||
|
|
||||||
const handlePrev = () => {
|
|
||||||
if (!canGoLeft) return;
|
|
||||||
setStartIndex((prev) => Math.max(prev - visibleCount, 0));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleNext = () => {
|
|
||||||
if (!canGoRight) return;
|
|
||||||
setStartIndex((prev) => {
|
|
||||||
const next = prev + visibleCount;
|
|
||||||
return Math.min(next, maxStartIndex);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: { xs: 2.5, sm: 4 },
|
|
||||||
borderRadius: 4,
|
|
||||||
width: "100%",
|
|
||||||
boxShadow: "none",
|
|
||||||
border: "1px solid",
|
|
||||||
borderColor: "divider",
|
|
||||||
bgcolor: isDark ? "background.paper" : colorScheme.surface,
|
|
||||||
opacity: isFetching ? 0.6 : 1,
|
|
||||||
transition: "opacity 0.3s ease",
|
|
||||||
pointerEvents: isFetching ? "none" : "auto",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography variant="h6" fontWeight={700} gutterBottom>
|
|
||||||
{title}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
{summary && (
|
|
||||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
|
|
||||||
{summary}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<ToggleButtonGroup value={activeTab} exclusive onChange={handleTabChange} fullWidth sx={{ mb: 4 }}>
|
|
||||||
{settings.tabs.map((tab) => (
|
|
||||||
<ToggleButton key={tab} value={tab}>
|
|
||||||
{tab}
|
|
||||||
</ToggleButton>
|
|
||||||
))}
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}>
|
|
||||||
<ToggleButtonGroup value={periodType} exclusive onChange={togglePeriodType} size="small">
|
|
||||||
<ToggleButton value="rolling">Rolling</ToggleButton>
|
|
||||||
<ToggleButton value="calendar">Calendar</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
<ToggleButton
|
|
||||||
value="compare"
|
|
||||||
selected={comparison}
|
|
||||||
onChange={toggleComparison}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
Compare
|
|
||||||
</ToggleButton>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{currentData.length > 0 ? (
|
|
||||||
<Box sx={{ position: "relative", mt: 4 }}>
|
|
||||||
{canGoLeft && (
|
|
||||||
<IconButton onClick={handlePrev} size="small" sx={{ position: "absolute", left: 0, top: "50%" }}>
|
|
||||||
<ChevronLeftIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box sx={{ display: "flex", alignItems: "flex-end", height: 220, mt: 4 }}>
|
|
||||||
{visibleData.map((point) => {
|
|
||||||
const currentHeight = (point.amount / maxAmount) * 100;
|
|
||||||
const compareHeight = comparison
|
|
||||||
? ((point.compare?.amount ?? 0) / maxAmount) * 100
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
const isSelected = selectedPeriodId === point.id;
|
|
||||||
const display = formatDisplay(point, activeDataKey, comparison);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
key={point.id}
|
|
||||||
onClick={() =>
|
|
||||||
setSelectedPeriodId(isSelected ? null : point.id)
|
|
||||||
}
|
|
||||||
sx={{
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: "center",
|
|
||||||
cursor: "pointer",
|
|
||||||
height: "100%"
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box sx={{ display: "flex", alignItems: "flex-end", gap: 1, height: "100%" }}>
|
|
||||||
{comparison && (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
width: 8,
|
|
||||||
height: `${compareHeight}%`,
|
|
||||||
bgcolor: alpha(colorScheme.primary, 0.4),
|
|
||||||
borderRadius: "4px 4px 0 0"
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
width: 12,
|
|
||||||
height: `${currentHeight}%`,
|
|
||||||
bgcolor: isSelected ? "warning.main" : colorScheme.primary,
|
|
||||||
borderRadius: "4px 4px 0 0"
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Typography variant="caption">
|
|
||||||
{point.label}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
{comparison && point.compare && (
|
|
||||||
<Typography variant="caption" color="text.secondary">
|
|
||||||
{point.compare.label}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Typography variant="caption">
|
|
||||||
{display}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{canGoRight && (
|
|
||||||
<IconButton onClick={handleNext} size="small" sx={{ position: "absolute", right: 0, top: "50%" }}>
|
|
||||||
<ChevronRightIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<Box sx={{ height: 200, display: "flex", alignItems: "center", justifyContent: "center" }}>
|
|
||||||
<Typography color="text.secondary">No Data Available</Typography>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { default } from "./HistoryChart";
|
|
||||||
export * from "./HistoryChart.models";
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { ReportData, GroupKey } from "../../features/report";
|
|
||||||
import {
|
|
||||||
formatCurrency,
|
|
||||||
extractFilteredTransactions,
|
|
||||||
} from "../report.helpers";
|
|
||||||
import { LatestItem } from "./LatestItems.models";
|
|
||||||
|
|
||||||
// ─── Main adapter ────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function buildLatestItems(
|
|
||||||
reportData: ReportData,
|
|
||||||
selectedPeriodId: string | null | undefined,
|
|
||||||
selectedGroupKey: GroupKey | null | undefined,
|
|
||||||
flow: "outflows" | "inflows"
|
|
||||||
): LatestItem[] {
|
|
||||||
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
|
|
||||||
|
|
||||||
return txns
|
|
||||||
.sort(
|
|
||||||
(a, b) =>
|
|
||||||
new Date(b.occurred_at).getTime() -
|
|
||||||
new Date(a.occurred_at).getTime()
|
|
||||||
)
|
|
||||||
.map((t, index) => ({
|
|
||||||
id: index + 1,
|
|
||||||
title: t.payee.name,
|
|
||||||
subtitle: t.tags.map((tag) => tag.name).join(", "),
|
|
||||||
amount: formatCurrency(t.amount),
|
|
||||||
timeAgo: new Date(t.occurred_at).toLocaleDateString("en-IN"),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
export interface LatestItem {
|
|
||||||
id: string | number;
|
|
||||||
title: string;
|
|
||||||
subtitle: string;
|
|
||||||
amount: string;
|
|
||||||
timeAgo: string;
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { ComponentProps } from "../Dashboard";
|
|
||||||
import { LatestItem } from "./LatestItems.models";
|
|
||||||
|
|
||||||
export interface LatestItemsProps extends ComponentProps {}
|
|
||||||
|
|
||||||
export interface LatestItemsViewProps extends LatestItemsProps {
|
|
||||||
items: LatestItem[];
|
|
||||||
canExpand: boolean;
|
|
||||||
onExpand: () => void;
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import { buildLatestItems } from "./LatestItems.adapter";
|
|
||||||
import LatestItemsView from "./LatestItems.view";
|
|
||||||
import { LatestItemsProps } from "./LatestItems.props";
|
|
||||||
|
|
||||||
export default function LatestItems(props: LatestItemsProps) {
|
|
||||||
const {
|
|
||||||
reportData,
|
|
||||||
state,
|
|
||||||
stateSetters,
|
|
||||||
isFetching,
|
|
||||||
} = props;
|
|
||||||
|
|
||||||
const { flow, selectedPeriodId, selectedGroupKey } = state;
|
|
||||||
const [visibleCount, setVisibleCount] = React.useState(5);
|
|
||||||
|
|
||||||
// Reset count when flow changes to start clean
|
|
||||||
React.useEffect(() => {
|
|
||||||
setVisibleCount(5);
|
|
||||||
}, [flow]);
|
|
||||||
|
|
||||||
const allItems = React.useMemo(() => {
|
|
||||||
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, flow);
|
|
||||||
}, [reportData, selectedPeriodId, selectedGroupKey, flow]);
|
|
||||||
|
|
||||||
const visibleItems = React.useMemo(() => {
|
|
||||||
return allItems.slice(0, visibleCount);
|
|
||||||
}, [allItems, visibleCount]);
|
|
||||||
|
|
||||||
const canExpand = visibleCount < allItems.length;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<LatestItemsView
|
|
||||||
{...props}
|
|
||||||
items={visibleItems}
|
|
||||||
canExpand={canExpand}
|
|
||||||
onExpand={() => setVisibleCount((prev) => prev + 5)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
List,
|
|
||||||
ListItem,
|
|
||||||
ListItemAvatar,
|
|
||||||
ListItemText,
|
|
||||||
Avatar,
|
|
||||||
Typography,
|
|
||||||
Box,
|
|
||||||
IconButton,
|
|
||||||
} from "@mui/material";
|
|
||||||
import { alpha } from "@mui/material/styles";
|
|
||||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
|
||||||
import { LatestItemsViewProps } from "./LatestItems.props";
|
|
||||||
|
|
||||||
export default function LatestItemsView({
|
|
||||||
items,
|
|
||||||
title,
|
|
||||||
canExpand,
|
|
||||||
onExpand,
|
|
||||||
isFetching,
|
|
||||||
colorScheme,
|
|
||||||
}: LatestItemsViewProps) {
|
|
||||||
const accentColor = colorScheme?.primary || "";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2, opacity: isFetching ? 0.6 : 1, transition: "opacity 0.3s ease", pointerEvents: isFetching ? "none" : "auto" }}>
|
|
||||||
<Box sx={{ mb: 2, px: 2 }}>
|
|
||||||
<Typography variant="h6" fontWeight="bold">
|
|
||||||
{title}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<List disablePadding>
|
|
||||||
{items.map((item, index) => (
|
|
||||||
<ListItem
|
|
||||||
key={item.id}
|
|
||||||
sx={{
|
|
||||||
px: { xs: 1, sm: 2 },
|
|
||||||
py: 2,
|
|
||||||
mb: index !== items.length - 1 ? 1 : 0,
|
|
||||||
borderRadius: 3,
|
|
||||||
"&:hover": { bgcolor: "action.hover" },
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ListItemAvatar>
|
|
||||||
<Avatar
|
|
||||||
variant="rounded"
|
|
||||||
sx={{
|
|
||||||
bgcolor: alpha(accentColor, 0.13),
|
|
||||||
width: 48,
|
|
||||||
height: 48,
|
|
||||||
borderRadius: 3,
|
|
||||||
mr: 2,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</ListItemAvatar>
|
|
||||||
|
|
||||||
<ListItemText
|
|
||||||
primary={
|
|
||||||
<Typography variant="subtitle1" fontWeight={600}>
|
|
||||||
{item.title}
|
|
||||||
</Typography>
|
|
||||||
}
|
|
||||||
secondary={
|
|
||||||
<Typography variant="body2" color="text.secondary">
|
|
||||||
{item.subtitle}
|
|
||||||
</Typography>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Box sx={{ textAlign: "right" }}>
|
|
||||||
<Typography variant="subtitle1" fontWeight={700}>
|
|
||||||
{item.amount}
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="caption" color="text.secondary">
|
|
||||||
{item.timeAgo}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
</ListItem>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{canExpand && (
|
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", mt: 2 }}>
|
|
||||||
<IconButton size="small" onClick={onExpand}>
|
|
||||||
<ExpandMoreIcon />
|
|
||||||
</IconButton>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</List>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { default } from "./LatestItems";
|
|
||||||
export * from "./LatestItems.models";
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import { ComponentProps } from "../Dashboard";
|
|
||||||
|
|
||||||
export interface ProgressCardProps extends ComponentProps {
|
|
||||||
settings: {
|
|
||||||
compact: boolean;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ProgressCardViewProps extends ProgressCardProps {
|
|
||||||
progressAmount: number;
|
|
||||||
totalAmount: number;
|
|
||||||
selected: boolean;
|
|
||||||
onClick: () => void;
|
|
||||||
}
|
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Typography,
|
|
||||||
Paper,
|
|
||||||
LinearProgress,
|
|
||||||
Divider,
|
|
||||||
linearProgressClasses
|
|
||||||
} from "@mui/material";
|
|
||||||
import { useTheme, alpha } from "@mui/material/styles";
|
|
||||||
import { getPercentage, formatCurrency } from "../report.helpers";
|
|
||||||
import { ProgressCardViewProps } from "./ProgressCard.props";
|
|
||||||
|
|
||||||
export default function ProgressCardView({
|
|
||||||
title,
|
|
||||||
settings,
|
|
||||||
|
|
||||||
isFetching,
|
|
||||||
|
|
||||||
colorScheme,
|
|
||||||
|
|
||||||
progressAmount,
|
|
||||||
totalAmount,
|
|
||||||
selected,
|
|
||||||
onClick,
|
|
||||||
}: ProgressCardViewProps) {
|
|
||||||
const theme = useTheme();
|
|
||||||
|
|
||||||
const percentage = getPercentage(progressAmount, totalAmount);
|
|
||||||
const formattedProgress = formatCurrency(progressAmount);
|
|
||||||
const formattedTotal = formatCurrency(totalAmount);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper
|
|
||||||
elevation={settings.compact ? 2 : 4}
|
|
||||||
onClick={onClick}
|
|
||||||
sx={{
|
|
||||||
width: "100%",
|
|
||||||
p: settings.compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
|
|
||||||
borderRadius: settings.compact ? 3 : 4,
|
|
||||||
transform: selected ? "scale(1.02)" : "scale(1)",
|
|
||||||
transition: "transform 0.2s ease, box-shadow 0.2s ease",
|
|
||||||
bgcolor: colorScheme.surface,
|
|
||||||
color: colorScheme.text,
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: settings.compact ? "flex-start" : "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
position: "relative",
|
|
||||||
overflow: "hidden",
|
|
||||||
border: selected
|
|
||||||
? `2px solid ${colorScheme.primary}`
|
|
||||||
: "1px solid",
|
|
||||||
borderColor: selected ? colorScheme.primary : "divider",
|
|
||||||
boxShadow: "none",
|
|
||||||
opacity: isFetching ? 0.6 : 1,
|
|
||||||
pointerEvents: isFetching ? "none" : "auto",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography
|
|
||||||
variant={settings.compact ? "body2" : "subtitle1"}
|
|
||||||
fontWeight={700}
|
|
||||||
sx={{
|
|
||||||
opacity: 0.95,
|
|
||||||
mb: settings.compact ? 1.5 : 2,
|
|
||||||
width: "100%",
|
|
||||||
overflow: "hidden",
|
|
||||||
textOverflow: "ellipsis",
|
|
||||||
whiteSpace: "nowrap",
|
|
||||||
letterSpacing: 0.5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{title}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Box sx={{ mb: settings.compact ? 2 : 3, width: "100%" }}>
|
|
||||||
<Typography
|
|
||||||
variant={settings.compact ? "h5" : "h3"}
|
|
||||||
fontWeight={900}
|
|
||||||
sx={{
|
|
||||||
mb: 0.5,
|
|
||||||
lineHeight: 1.2,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{formattedProgress}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Divider
|
|
||||||
sx={{
|
|
||||||
my: 1,
|
|
||||||
borderColor: "divider",
|
|
||||||
width: "100%",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Typography
|
|
||||||
variant={settings.compact ? "caption" : "body2"}
|
|
||||||
sx={{
|
|
||||||
opacity: 0.85,
|
|
||||||
fontWeight: 500,
|
|
||||||
display: "block",
|
|
||||||
color: alpha(colorScheme.text, 0.85),
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
of {formattedTotal}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box sx={{ width: "100%", mt: "auto" }}>
|
|
||||||
<LinearProgress
|
|
||||||
variant="determinate"
|
|
||||||
value={percentage}
|
|
||||||
sx={{
|
|
||||||
height: settings.compact ? 6 : 10,
|
|
||||||
borderRadius: 5,
|
|
||||||
[`&.${linearProgressClasses.colorPrimary}`]: {
|
|
||||||
backgroundColor: alpha(theme.palette.divider, 0.5),
|
|
||||||
},
|
|
||||||
[`& .${linearProgressClasses.bar}`]: {
|
|
||||||
borderRadius: 5,
|
|
||||||
backgroundColor: colorScheme.primary,
|
|
||||||
boxShadow: `0 0 8px ${alpha(colorScheme.primary, 0.4)}`,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { GroupKey, ReportData } from "../../features/report";
|
|
||||||
import {
|
|
||||||
extractFilteredTransactions,
|
|
||||||
aggregateTransactions,
|
|
||||||
} from "../report.helpers";
|
|
||||||
|
|
||||||
export interface PayeeItem {
|
|
||||||
name: string;
|
|
||||||
amount: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function extractTopPayees(
|
|
||||||
reportData: ReportData,
|
|
||||||
flow: "outflows" | "inflows",
|
|
||||||
selectedPeriodId?: string | null,
|
|
||||||
selectedGroupKey?: GroupKey | null
|
|
||||||
): { items: PayeeItem[]; total: number } {
|
|
||||||
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
|
|
||||||
|
|
||||||
const { items, total } = aggregateTransactions(txns, (txn) => {
|
|
||||||
if (txn.payee && txn.payee.name) {
|
|
||||||
return [txn.payee.name];
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
items,
|
|
||||||
total,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import { Box, Paper, Typography } from "@mui/material";
|
|
||||||
import ProgressCardView from "./ProgressCard.view";
|
|
||||||
import { extractTopPayees } from "./TopPayees.adapter";
|
|
||||||
import { ProgressCardProps } from "./ProgressCard.props";
|
|
||||||
|
|
||||||
export default function TopPayees(props: ProgressCardProps) {
|
|
||||||
const {
|
|
||||||
title,
|
|
||||||
|
|
||||||
reportData,
|
|
||||||
state,
|
|
||||||
stateSetters,
|
|
||||||
|
|
||||||
isFetching,
|
|
||||||
} = props
|
|
||||||
const { flow, selectedPeriodId, selectedGroupKey } = state;
|
|
||||||
const { setSelectedGroupKey } = stateSetters;
|
|
||||||
|
|
||||||
const { items, total } = React.useMemo(() => {
|
|
||||||
return extractTopPayees(reportData, flow, selectedPeriodId, selectedGroupKey);
|
|
||||||
}, [reportData, flow, selectedPeriodId, selectedGroupKey]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: { xs: 2.5, sm: 4 },
|
|
||||||
borderRadius: 4,
|
|
||||||
width: "100%",
|
|
||||||
boxShadow: "none",
|
|
||||||
border: "1px solid",
|
|
||||||
borderColor: "divider",
|
|
||||||
bgcolor: "background.paper",
|
|
||||||
opacity: isFetching ? 0.6 : 1,
|
|
||||||
transition: "opacity 0.3s ease",
|
|
||||||
pointerEvents: isFetching ? "none" : "auto",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography variant="h6" fontWeight={700} gutterBottom>
|
|
||||||
{title}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "grid",
|
|
||||||
gridTemplateColumns: {
|
|
||||||
xs: "1fr",
|
|
||||||
sm: "repeat(2, 1fr)",
|
|
||||||
md: "repeat(4, 1fr)",
|
|
||||||
},
|
|
||||||
gap: 2,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{items.map((item) => {
|
|
||||||
const isSelected = !!selectedGroupKey?.payee?.includes(item.name);
|
|
||||||
return (
|
|
||||||
<ProgressCardView
|
|
||||||
{...props}
|
|
||||||
key={item.name}
|
|
||||||
title={item.name}
|
|
||||||
progressAmount={item.amount}
|
|
||||||
totalAmount={total}
|
|
||||||
selected={isSelected}
|
|
||||||
onClick={() => {
|
|
||||||
if (setSelectedGroupKey) {
|
|
||||||
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};
|
|
||||||
|
|
||||||
if (isSelected) {
|
|
||||||
delete newKey.payee;
|
|
||||||
} else {
|
|
||||||
newKey.payee = [item.name];
|
|
||||||
}
|
|
||||||
|
|
||||||
setSelectedGroupKey(Object.keys(newKey).length ? newKey : null);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { ReportData, GroupKey } from "../../features/report";
|
|
||||||
import {
|
|
||||||
extractFilteredTransactions,
|
|
||||||
aggregateTransactions,
|
|
||||||
} from "../report.helpers";
|
|
||||||
|
|
||||||
export interface TagItem {
|
|
||||||
tag: string;
|
|
||||||
amount: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function extractTopTags(
|
|
||||||
reportData: ReportData,
|
|
||||||
flow: "outflows" | "inflows",
|
|
||||||
selectedPeriodId?: string | null,
|
|
||||||
selectedGroupKey?: GroupKey | null
|
|
||||||
): { items: TagItem[]; total: number } {
|
|
||||||
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
|
|
||||||
|
|
||||||
const { items, total } = aggregateTransactions(txns, (txn) => {
|
|
||||||
if (txn.tags && txn.tags.length > 0) {
|
|
||||||
return txn.tags.map((t) => (typeof t === "string" ? t : t.name));
|
|
||||||
}
|
|
||||||
return ["Untagged"];
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
items: items.map((item) => ({ tag: item.name, amount: item.amount })),
|
|
||||||
total,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import { Box, Paper, Typography } from "@mui/material";
|
|
||||||
import ProgressCardView from "./ProgressCard.view";
|
|
||||||
import { extractTopTags } from "./TopTags.adapter";
|
|
||||||
import { ProgressCardProps } from "./ProgressCard.props";
|
|
||||||
|
|
||||||
export default function TopTags(props: ProgressCardProps) {
|
|
||||||
const {
|
|
||||||
title,
|
|
||||||
|
|
||||||
reportData,
|
|
||||||
state,
|
|
||||||
stateSetters,
|
|
||||||
|
|
||||||
isFetching,
|
|
||||||
} = props
|
|
||||||
const { flow, selectedPeriodId, selectedGroupKey } = state;
|
|
||||||
const { setSelectedGroupKey } = stateSetters;
|
|
||||||
|
|
||||||
const { items, total } = React.useMemo(() => {
|
|
||||||
return extractTopTags(reportData, flow, selectedPeriodId, selectedGroupKey);
|
|
||||||
}, [reportData, flow, selectedPeriodId, selectedGroupKey]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: { xs: 2.5, sm: 4 },
|
|
||||||
borderRadius: 4,
|
|
||||||
width: "100%",
|
|
||||||
boxShadow: "none",
|
|
||||||
border: "1px solid",
|
|
||||||
borderColor: "divider",
|
|
||||||
bgcolor: "background.paper",
|
|
||||||
opacity: isFetching ? 0.6 : 1,
|
|
||||||
transition: "opacity 0.3s ease",
|
|
||||||
pointerEvents: isFetching ? "none" : "auto",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography variant="h6" fontWeight={700} gutterBottom>
|
|
||||||
{title}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "grid",
|
|
||||||
gridTemplateColumns: {
|
|
||||||
xs: "1fr",
|
|
||||||
sm: "repeat(2, 1fr)",
|
|
||||||
md: "repeat(4, 1fr)",
|
|
||||||
},
|
|
||||||
gap: 2,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{items.map((item) => {
|
|
||||||
const isSelected = !!selectedGroupKey?.tags?.includes(item.tag);
|
|
||||||
return (
|
|
||||||
<ProgressCardView
|
|
||||||
{...props}
|
|
||||||
key={item.tag}
|
|
||||||
title={item.tag}
|
|
||||||
progressAmount={item.amount}
|
|
||||||
totalAmount={total}
|
|
||||||
selected={isSelected}
|
|
||||||
onClick={() => {
|
|
||||||
if (setSelectedGroupKey) {
|
|
||||||
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};
|
|
||||||
|
|
||||||
if (isSelected) {
|
|
||||||
delete newKey.tags;
|
|
||||||
} else {
|
|
||||||
newKey.tags = [item.tag];
|
|
||||||
}
|
|
||||||
|
|
||||||
setSelectedGroupKey(Object.keys(newKey).length ? newKey : null);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
export { default } from "./ProgressCard.view";
|
|
||||||
export * from "./ProgressCard.props";
|
|
||||||
@@ -1,230 +0,0 @@
|
|||||||
import {
|
|
||||||
ReportPeriod,
|
|
||||||
ReportBucket,
|
|
||||||
GroupKey,
|
|
||||||
PeriodType,
|
|
||||||
ReportData,
|
|
||||||
Transaction,
|
|
||||||
} from "../features/report";
|
|
||||||
|
|
||||||
// ─── Types ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export type PeriodKey = PeriodType;
|
|
||||||
|
|
||||||
export type DecoratedPeriod = ReportPeriod & {
|
|
||||||
id: string;
|
|
||||||
label: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
// ─── Period helpers ───────────────────────────────────────────
|
|
||||||
|
|
||||||
const PREFIX_TO_KEY: Record<string, PeriodKey> = {
|
|
||||||
D: "daily",
|
|
||||||
W: "weekly",
|
|
||||||
M: "monthly",
|
|
||||||
ALL: "all",
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Derive the period key from a decorated-period id.
|
|
||||||
* E.g. `"W:2026-04-28_2026-05-04"` → `"weekly"`
|
|
||||||
*/
|
|
||||||
export function periodIdToKey(periodId: string): PeriodKey {
|
|
||||||
const prefix = periodId.split(":")[0];
|
|
||||||
return PREFIX_TO_KEY[prefix] ?? "all";
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Metric helpers ───────────────────────────────────────────
|
|
||||||
|
|
||||||
export function getAmount(period: ReportPeriod): number {
|
|
||||||
return period.metric.sum;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeMetric(a: ReportPeriod["metric"], b: ReportPeriod["metric"]) {
|
|
||||||
const sum = a.sum + b.sum;
|
|
||||||
const count = a.count + b.count;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...a,
|
|
||||||
sum,
|
|
||||||
count,
|
|
||||||
average: count > 0 ? sum / count : 0,
|
|
||||||
transactions:
|
|
||||||
a.transactions || b.transactions
|
|
||||||
? [...(a.transactions || []), ...(b.transactions || [])]
|
|
||||||
: undefined,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Merge periods with the same id across all buckets, summing
|
|
||||||
* their metrics and concatenating transactions.
|
|
||||||
*
|
|
||||||
* Returns sorted by start date ascending.
|
|
||||||
*/
|
|
||||||
export function mergeBucketPeriods(
|
|
||||||
buckets: ReportBucket[],
|
|
||||||
key: PeriodKey
|
|
||||||
): DecoratedPeriod[] {
|
|
||||||
const map = new Map<string, DecoratedPeriod>();
|
|
||||||
|
|
||||||
for (const bucket of buckets) {
|
|
||||||
const periods = (bucket.periods[key] || []) as DecoratedPeriod[];
|
|
||||||
|
|
||||||
for (const p of periods) {
|
|
||||||
const existing = map.get(p.id);
|
|
||||||
|
|
||||||
if (!existing) {
|
|
||||||
map.set(p.id, {
|
|
||||||
...p,
|
|
||||||
metric: { ...p.metric },
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
map.set(p.id, {
|
|
||||||
...existing,
|
|
||||||
metric: mergeMetric(existing.metric, p.metric),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Array.from(map.values()).sort(
|
|
||||||
(a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Formatting ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
export const formatCurrency = (val: number) => {
|
|
||||||
const absVal = Math.abs(val);
|
|
||||||
if (absVal >= 100000) {
|
|
||||||
return `₹ ${(val / 100000).toFixed(2)}L`;
|
|
||||||
}
|
|
||||||
if (absVal >= 1000) {
|
|
||||||
return `₹ ${(val / 1000).toFixed(2)}k`;
|
|
||||||
}
|
|
||||||
return `₹ ${val.toFixed(2)}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getPercentage = (progressAmount: number, totalAmount: number) => {
|
|
||||||
if (!totalAmount) return 0;
|
|
||||||
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
|
|
||||||
};
|
|
||||||
|
|
||||||
// ─── Group filtering ──────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a bucket's group_key matches the selected GroupKey.
|
|
||||||
* Every dimension present in `selected` must exist in the bucket
|
|
||||||
* and contain all the selected values.
|
|
||||||
*/
|
|
||||||
export function matchesGroupKey(
|
|
||||||
bucket: ReportBucket,
|
|
||||||
selected: GroupKey
|
|
||||||
): boolean {
|
|
||||||
for (const [dim, values] of Object.entries(selected)) {
|
|
||||||
const bucketValues = bucket.group_key[dim];
|
|
||||||
if (!bucketValues) return false;
|
|
||||||
if (!(values as string[]).every((v) => bucketValues.includes(v)))
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return only buckets matching the selected group key,
|
|
||||||
* or all buckets if no selection.
|
|
||||||
*/
|
|
||||||
export function filterBuckets(
|
|
||||||
buckets: ReportBucket[],
|
|
||||||
selectedGroupKey: GroupKey | null
|
|
||||||
): ReportBucket[] {
|
|
||||||
if (!selectedGroupKey) return buckets;
|
|
||||||
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function extractFilteredTransactions(
|
|
||||||
reportData: ReportData,
|
|
||||||
selectedPeriodId: string | null | undefined,
|
|
||||||
selectedGroupKey: GroupKey | null | undefined
|
|
||||||
): Transaction[] {
|
|
||||||
let txns: Transaction[] = [];
|
|
||||||
|
|
||||||
if (selectedPeriodId) {
|
|
||||||
const key = periodIdToKey(selectedPeriodId);
|
|
||||||
const periods = mergeBucketPeriods(reportData.buckets, key);
|
|
||||||
const selected = periods.find((p) => p.id === selectedPeriodId);
|
|
||||||
txns = selected?.metric.transactions || [];
|
|
||||||
} else {
|
|
||||||
const periods = mergeBucketPeriods(reportData.buckets, "all");
|
|
||||||
if (periods.length > 0) {
|
|
||||||
const period = periods.reduce((latest, p) =>
|
|
||||||
new Date(p.start).getTime() > new Date(latest.start).getTime()
|
|
||||||
? p
|
|
||||||
: latest
|
|
||||||
, periods[0]);
|
|
||||||
txns = period?.metric.transactions || [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (selectedGroupKey) {
|
|
||||||
txns = txns.filter((txn) => {
|
|
||||||
let match = true;
|
|
||||||
if (selectedGroupKey.tags && selectedGroupKey.tags.length > 0) {
|
|
||||||
if (!txn.tags) {
|
|
||||||
match = false;
|
|
||||||
} else {
|
|
||||||
const txnTags = txn.tags.map((t: any) =>
|
|
||||||
typeof t === "string" ? t : t.name
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
!selectedGroupKey.tags.every((selectedTag) =>
|
|
||||||
txnTags.includes(selectedTag)
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
match = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (match && selectedGroupKey.payee && selectedGroupKey.payee.length > 0) {
|
|
||||||
if (!txn.payee || !txn.payee.name) {
|
|
||||||
match = false;
|
|
||||||
} else {
|
|
||||||
if (!selectedGroupKey.payee.includes(txn.payee.name)) {
|
|
||||||
match = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return match;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return txns;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function aggregateTransactions(
|
|
||||||
transactions: Transaction[],
|
|
||||||
keyExtractor: (txn: Transaction) => string[],
|
|
||||||
limit = 4
|
|
||||||
): { items: { name: string; amount: number }[]; total: number } {
|
|
||||||
const map = new Map<string, number>();
|
|
||||||
|
|
||||||
for (const txn of transactions) {
|
|
||||||
const keys = keyExtractor(txn);
|
|
||||||
for (const key of keys) {
|
|
||||||
map.set(key, (map.get(key) || 0) + txn.amount);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const items = Array.from(map.entries()).map(([name, amount]) => ({
|
|
||||||
name,
|
|
||||||
amount,
|
|
||||||
}));
|
|
||||||
|
|
||||||
items.sort((a, b) => b.amount - a.amount);
|
|
||||||
|
|
||||||
const top = items.slice(0, limit);
|
|
||||||
const total = top.reduce((sum, item) => sum + item.amount, 0);
|
|
||||||
|
|
||||||
return { items: top, total };
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import HistoryChart from "./components/HistoryChart";
|
|
||||||
import LatestItems from "./components/LatestItems";
|
|
||||||
import { DashboardConfig } from "./components/Dashboard";
|
|
||||||
import TopTags from "./components/ProgressCard/TopTags";
|
|
||||||
import TopPayees from "./components/ProgressCard/TopPayees";
|
|
||||||
|
|
||||||
export const configuration: DashboardConfig = {
|
|
||||||
sections: [
|
|
||||||
{
|
|
||||||
id: "breakdown",
|
|
||||||
title: "Breakdown",
|
|
||||||
summary: "Interactive chronological tracking",
|
|
||||||
component: HistoryChart,
|
|
||||||
settings: {
|
|
||||||
tabs: ["Weekly", "Monthly"],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "top-categories",
|
|
||||||
title: 'Top Categories',
|
|
||||||
component: TopTags,
|
|
||||||
settings: {
|
|
||||||
compact: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "top-payees",
|
|
||||||
title: 'Top Payees',
|
|
||||||
component: TopPayees,
|
|
||||||
settings: {
|
|
||||||
compact: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "items",
|
|
||||||
title: 'Recent Transactions',
|
|
||||||
component: LatestItems,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
@@ -1,49 +1,7 @@
|
|||||||
import { useResource, getApi } from "../../../react-openapi";
|
import { getApi } from "../../../react-openapi";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import type { ResolveAmbiguityPayload } from "./fetch-requests.models";
|
import type { ResolveAmbiguityPayload } from "./fetch-requests.models";
|
||||||
|
|
||||||
export function useFetchRequestsList(params?: {
|
|
||||||
status?: string;
|
|
||||||
account_name?: string;
|
|
||||||
source_type?: string;
|
|
||||||
}) {
|
|
||||||
const { list } = useResource("fetch-requests");
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["fetch-requests", "list", params],
|
|
||||||
queryFn: () => list(params),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useFetchRequest(id: string) {
|
|
||||||
const { get } = useResource("fetch-requests");
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["fetch-requests", "detail", id],
|
|
||||||
queryFn: () => get(id),
|
|
||||||
enabled: !!id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useCreateFetchRequest() {
|
|
||||||
const { create } = useResource("fetch-requests");
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (data: any) => create(data),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useUpdateFetchRequest() {
|
|
||||||
const { update } = useResource("fetch-requests");
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: ({ id, data }: { id: string; data: any }) => update(id, data),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useDeleteFetchRequest() {
|
|
||||||
const { remove } = useResource("fetch-requests");
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (id: string) => remove(id),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useUploadFile() {
|
export function useUploadFile() {
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (file: File) => {
|
mutationFn: async (file: File) => {
|
||||||
@@ -66,9 +24,7 @@ export function useFetchRequestAmbiguities(fetchRequestId: string) {
|
|||||||
queryKey: ["fetch-requests", fetchRequestId, "ambiguities"],
|
queryKey: ["fetch-requests", fetchRequestId, "ambiguities"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const api = getApi();
|
const api = getApi();
|
||||||
const res = await api.get(
|
const res = await api.get(`/fetch-requests/${fetchRequestId}/ambiguities`);
|
||||||
`/fetch-requests/${fetchRequestId}/ambiguities`
|
|
||||||
);
|
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
enabled: !!fetchRequestId,
|
enabled: !!fetchRequestId,
|
||||||
@@ -87,10 +43,7 @@ export function useResolveAmbiguity() {
|
|||||||
payload: ResolveAmbiguityPayload;
|
payload: ResolveAmbiguityPayload;
|
||||||
}) => {
|
}) => {
|
||||||
const api = getApi();
|
const api = getApi();
|
||||||
const res = await api.post(
|
const res = await api.post(`/ambiguities/${ambiguityId}/resolve`, payload);
|
||||||
`/ambiguities/${ambiguityId}/resolve`,
|
|
||||||
payload
|
|
||||||
);
|
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
onSuccess: (data: any) => {
|
onSuccess: (data: any) => {
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
export type {
|
|
||||||
ReportSnapshot,
|
|
||||||
ReportQuery,
|
|
||||||
} from "./report-snapshots.models";
|
|
||||||
export {
|
|
||||||
useReportSnapshotsList,
|
|
||||||
useCreateSnapshot,
|
|
||||||
useDeleteSnapshot,
|
|
||||||
} from "./useReportSnapshots";
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
export interface ReportQuery {
|
|
||||||
accounts?: string[] | null;
|
|
||||||
ignore_self?: boolean | null;
|
|
||||||
start_date?: string | null;
|
|
||||||
end_date?: string | null;
|
|
||||||
min_amount?: number | null;
|
|
||||||
max_amount?: number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ReportSnapshot {
|
|
||||||
id: string;
|
|
||||||
snapshot_id: string;
|
|
||||||
created_at: string;
|
|
||||||
query?: ReportQuery;
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import { useResource } from "../../../react-openapi";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
export function useReportSnapshotsList() {
|
|
||||||
const { list } = useResource("reports");
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["reports", "list"],
|
|
||||||
queryFn: () => list(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useCreateSnapshot() {
|
|
||||||
const { create } = useResource("reports");
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (data: any) => create(data),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useDeleteSnapshot() {
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const { remove } = useResource("reports");
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (id: string) => remove(id),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["reports", "list"] });
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
export {
|
|
||||||
useReport
|
|
||||||
} from './useReport'
|
|
||||||
export type {
|
|
||||||
Transaction,
|
|
||||||
ReportData,
|
|
||||||
ReportBucket,
|
|
||||||
ReportPeriod,
|
|
||||||
ReportQuery,
|
|
||||||
GroupKey,
|
|
||||||
PeriodType,
|
|
||||||
} from './report.models'
|
|
||||||
export {
|
|
||||||
prepareReport
|
|
||||||
} from './report.utils'
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
export interface Payor {
|
|
||||||
id?: string;
|
|
||||||
name: string;
|
|
||||||
username: string;
|
|
||||||
email: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Payee {
|
|
||||||
type: "merchant" | "person" | "transfer" | "other";
|
|
||||||
name: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Account {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
number: string;
|
|
||||||
type: "cash" | "bank" | "credit_card" | "wallet" | "other";
|
|
||||||
currency: string;
|
|
||||||
is_active?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Tag {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
icon: string;
|
|
||||||
parent_id?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Transaction {
|
|
||||||
id: string;
|
|
||||||
payor: Payor;
|
|
||||||
payee: Payee;
|
|
||||||
amount: number;
|
|
||||||
account: Account;
|
|
||||||
tags: Tag[];
|
|
||||||
occurred_at: string;
|
|
||||||
created_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Metrics
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
export interface ReportMetric {
|
|
||||||
sum: number;
|
|
||||||
count: number;
|
|
||||||
average: number;
|
|
||||||
transactions?: Transaction[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Period
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
export type PeriodType = "daily" | "weekly" | "monthly" | "all";
|
|
||||||
|
|
||||||
export interface ReportPeriod {
|
|
||||||
start: string;
|
|
||||||
end: string;
|
|
||||||
metric: ReportMetric;
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Group (bucket)
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
export type GroupKey = {
|
|
||||||
[dimension: string]: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface ReportBucket {
|
|
||||||
group_key: GroupKey;
|
|
||||||
|
|
||||||
periods: {
|
|
||||||
daily?: ReportPeriod[];
|
|
||||||
weekly?: ReportPeriod[];
|
|
||||||
monthly?: ReportPeriod[];
|
|
||||||
all?: ReportPeriod[];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Report Query
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
export interface ReportQuery {
|
|
||||||
accounts?: string[] | null;
|
|
||||||
ignore_self?: boolean | null;
|
|
||||||
start_date?: string | null;
|
|
||||||
end_date?: string | null;
|
|
||||||
min_amount?: number | null;
|
|
||||||
max_amount?: number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------
|
|
||||||
// Final Report
|
|
||||||
// -----------------------------
|
|
||||||
|
|
||||||
export interface ReportData {
|
|
||||||
snapshot_id?: string | null;
|
|
||||||
|
|
||||||
flow?: "inflows" | "outflows" | null;
|
|
||||||
|
|
||||||
periods: PeriodType[];
|
|
||||||
|
|
||||||
tags?: string[] | null;
|
|
||||||
payee?: string[] | null;
|
|
||||||
|
|
||||||
buckets: ReportBucket[];
|
|
||||||
|
|
||||||
query: ReportQuery;
|
|
||||||
}
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
import {
|
|
||||||
ReportData,
|
|
||||||
ReportPeriod,
|
|
||||||
PeriodType,
|
|
||||||
} from "./report.models";
|
|
||||||
|
|
||||||
/* ---------- ID BUILDING ---------- */
|
|
||||||
|
|
||||||
function formatDate(d: Date): string {
|
|
||||||
const y = d.getUTCFullYear();
|
|
||||||
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
|
||||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
|
||||||
return `${y}-${m}-${day}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildPeriodId(
|
|
||||||
type: PeriodType,
|
|
||||||
start: Date,
|
|
||||||
end: Date
|
|
||||||
): string {
|
|
||||||
const s = formatDate(start);
|
|
||||||
const e = formatDate(end);
|
|
||||||
|
|
||||||
switch (type) {
|
|
||||||
case "daily":
|
|
||||||
return `D:${s}_${e}`;
|
|
||||||
case "weekly":
|
|
||||||
return `W:${s}_${e}`;
|
|
||||||
case "monthly":
|
|
||||||
return `M:${s}_${e}`;
|
|
||||||
case "all":
|
|
||||||
return `ALL:${s}_${e}`;
|
|
||||||
default:
|
|
||||||
return `${s}_${e}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------- LABEL BUILDING ---------- */
|
|
||||||
|
|
||||||
const dayFmt = new Intl.DateTimeFormat("en-GB", {
|
|
||||||
day: "numeric",
|
|
||||||
month: "short",
|
|
||||||
timeZone: "UTC",
|
|
||||||
});
|
|
||||||
|
|
||||||
const monthDayFmt = new Intl.DateTimeFormat("en-GB", {
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
timeZone: "UTC",
|
|
||||||
});
|
|
||||||
|
|
||||||
const monthFmt = new Intl.DateTimeFormat("en-GB", {
|
|
||||||
month: "short",
|
|
||||||
timeZone: "UTC",
|
|
||||||
});
|
|
||||||
|
|
||||||
const yearFmt = new Intl.DateTimeFormat("en-GB", {
|
|
||||||
year: "numeric",
|
|
||||||
timeZone: "UTC",
|
|
||||||
});
|
|
||||||
|
|
||||||
function buildLabel(
|
|
||||||
type: PeriodType,
|
|
||||||
start: Date,
|
|
||||||
end: Date
|
|
||||||
): string {
|
|
||||||
switch (type) {
|
|
||||||
case "daily":
|
|
||||||
return dayFmt.format(start);
|
|
||||||
|
|
||||||
case "weekly": {
|
|
||||||
const sDay = start.getUTCDate();
|
|
||||||
const m = monthFmt.format(start);
|
|
||||||
return `${sDay} ${m}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
case "monthly":
|
|
||||||
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------- MAIN ---------- */
|
|
||||||
|
|
||||||
function decoratePeriods(
|
|
||||||
type: PeriodType,
|
|
||||||
periods: ReportPeriod[]
|
|
||||||
): (ReportPeriod & { id: string; label: string })[] {
|
|
||||||
return periods.map((p) => ({
|
|
||||||
...p,
|
|
||||||
id: buildPeriodId(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
|
|
||||||
label: buildLabel(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function prepareReport(reportData: ReportData): ReportData {
|
|
||||||
return {
|
|
||||||
...reportData,
|
|
||||||
buckets: reportData.buckets.map((bucket) => {
|
|
||||||
const newPeriods: typeof bucket.periods = {};
|
|
||||||
|
|
||||||
for (const type of reportData.periods) {
|
|
||||||
const arr = bucket.periods[type];
|
|
||||||
if (arr) {
|
|
||||||
newPeriods[type] = decoratePeriods(type, arr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...bucket,
|
|
||||||
periods: newPeriods,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { useResource } from "../../../react-openapi";
|
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
export interface ReportParams {
|
|
||||||
snapshot_id?: string;
|
|
||||||
periods?: ("daily" | "weekly" | "monthly" | "all")[];
|
|
||||||
flow?: "inflows" | "outflows";
|
|
||||||
payee?: string[];
|
|
||||||
tags?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useReport(params: ReportParams) {
|
|
||||||
const { get } = useResource("reports");
|
|
||||||
|
|
||||||
const { snapshot_id, ...queryParams } = params;
|
|
||||||
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["reports", "read", params],
|
|
||||||
queryFn: () =>
|
|
||||||
get(snapshot_id ?? "latest", queryParams),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -12,10 +12,8 @@ import {
|
|||||||
Toolbar
|
Toolbar
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import Home from './Home';
|
import Home from './Home';
|
||||||
import Dashboard from './Dashboard';
|
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
||||||
import FetchRequests from './FetchRequests';
|
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
|
||||||
import FetchRequestDetail from './FetchRequestDetail';
|
|
||||||
import ReportSnapshots from './ReportSnapshots';
|
|
||||||
import { RequireAuth } from './RequireAuth';
|
import { RequireAuth } from './RequireAuth';
|
||||||
import { AppProvider, Admin } from '../react-openapi';
|
import { AppProvider, Admin } from '../react-openapi';
|
||||||
import { Buffer } from 'buffer';
|
import { Buffer } from 'buffer';
|
||||||
@@ -39,10 +37,8 @@ const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;
|
|||||||
const routerMapping = [
|
const routerMapping = [
|
||||||
{ path: "/", component: Home, headerTitle: "Home" },
|
{ path: "/", component: Home, headerTitle: "Home" },
|
||||||
{ path: "/home", component: Home, headerTitle: "Home" },
|
{ path: "/home", component: Home, headerTitle: "Home" },
|
||||||
{ path: "/dashboard", component: Dashboard, headerTitle: "Dashboard" },
|
|
||||||
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
||||||
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
||||||
{ path: "/reports", component: ReportSnapshots, headerTitle: "Reports" },
|
|
||||||
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user