## Title Stripe-style UI overhaul + Expenses feed with month grouping ## Summary Rework the khata-ui frontend to a Stripe-grade design system and add a rich, monthly-grouped Expenses experience driven by react-openapi's shared, spec-configured field renderers. ## Highlights ### Design overhaul - New design system: single indigo (#635BFF), 6px radius, Inter type scale, streamlined surfaces/inputs/feedback tokens - Sticky app bar with brand-left header + inline footer, route titles - Split-panel auth pages, Stripe-style Home hero + feature cards - Toast provider + shared PageHeader/EmptyState UI primitives - Admin polish: right-aligned numerics, row-hover actions, skeletons, richer empty states, breadcrumbed fetch-request flows ### Expenses page - Monthly grouped feed with stat cards (total spent / this month / income) - Month cards as single-open accordions with red-spent / green-income totals - Flat transaction rows: logo, name/date, account, amount (no accordion) - Floating month–year selector pill (scroll-spy) that expands + scrolls to the selected month - Strict DD-MM-YYYY date parsing (day-first), no format guessing ### Shared react-openapi fields - New `CurrencyField` + `formatCurrency` (cached Intl, sign-colored, sign-less amounts; form editing reuses NumberField) - `resourceConfig.fieldTypes` override mechanism (amount → currency) - Expenses page rendered via ListCellRenderer / DetailFieldRenderer / applyDisplayFormat — zero custom field renderers - `resolveMediaUrl` resolves relative `/uploads/...` against the API base for every image field (Admin + Expenses logos) ### Fixes - Perf: memoized rows, formatter caches, single-open accordions — cuts slow-click INP and DOM-nesting warnings - Removed unused @mui/x-data-grid@7, which hoisted @mui/system@7 and crashed Box/createTheme at runtime (v5/v7 mix) ## Commits (10) -9808a1fdesign overhaul + expenses page -d6856a5fix expenses list performance + dom nesting -3dd833ashared currency field + expenses rendered from react-openapi fields -e8c585bfix expenses grouping to parse occurred_at as DD-MM-YYYY strictly -cc940eeexpense list: split month totals, sticky headers + month pill -47d799fexpense list: clickable month pill + fix scroll-to-month -537aef9resolve relative media URLs against the API base in react-openapi -8e9a13dexpense list: replace accordion with flat Stripe-style rows -62dd06cexpense list: month accordions + month-year selector; drop unused x-data-grid -806bd42dropped amount sign from CurrencyField.tsx Reviewed-on: #15 Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com> Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
377 lines
13 KiB
TypeScript
377 lines
13 KiB
TypeScript
import React, { useMemo, useState, useEffect, useRef } from "react";
|
|
import { useParams, useNavigate } from "react-router-dom";
|
|
import {
|
|
Box,
|
|
Container,
|
|
Paper,
|
|
Typography,
|
|
Button,
|
|
Chip,
|
|
CircularProgress,
|
|
Alert,
|
|
Divider,
|
|
} from "@mui/material";
|
|
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, useAppContext, DetailFieldRenderer, applyDisplayFormat } from "../../react-openapi";
|
|
import { useQuery } 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";
|
|
import { PageHeader } from "../ui/PageHeader";
|
|
import { useToast } from "../ui/Toast";
|
|
|
|
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" }} />;
|
|
}
|
|
}
|
|
|
|
function Section({ title, children, action }: { title: string; children: React.ReactNode; action?: React.ReactNode }) {
|
|
return (
|
|
<Paper sx={{ p: 3, borderRadius: 3, mb: 3 }} variant="outlined">
|
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
|
|
<Typography variant="subtitle1" fontWeight={700} sx={{ flex: 1 }}>
|
|
{title}
|
|
</Typography>
|
|
{action}
|
|
</Box>
|
|
{children}
|
|
</Paper>
|
|
);
|
|
}
|
|
|
|
export default function FetchRequestDetail() {
|
|
const { id } = useParams<{ id: string }>();
|
|
const navigate = useNavigate();
|
|
const { get, patch, resource } = useResource("fetch-requests");
|
|
const { resources: allResources } = useAppContext();
|
|
const [stepStats, setStepStats] = useState<Record<string, number>>({});
|
|
const [liveParsedCount, setLiveParsedCount] = useState<number | undefined>(undefined);
|
|
const [retrying, setRetrying] = useState(false);
|
|
const { showToast } = useToast();
|
|
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 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") {
|
|
showToast(parsed.message.error || "Fetch request failed", "error");
|
|
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 || !patch || retrying) return;
|
|
setRetrying(true);
|
|
try {
|
|
await patch(id, { status: "pending" });
|
|
refetchRequest();
|
|
} catch (err: any) {
|
|
showToast(formatApiError(err), "error");
|
|
} finally {
|
|
setRetrying(false);
|
|
}
|
|
};
|
|
|
|
const req = fetchRequest as any;
|
|
const retryCount = req?.retry_count ?? 0;
|
|
const isRetryExhausted = retryCount >= RETRY_MAX;
|
|
const status = (req?.status ?? "pending") as FetchRequestStatus;
|
|
const detailFields = (resource?.orderedFields ?? []).filter(
|
|
(f) => f.name !== "source",
|
|
);
|
|
|
|
const displayTitle = useMemo(() => {
|
|
if (!resource || !req) return "";
|
|
const resolved = Object.fromEntries(
|
|
resource.orderedFields.map((field) => {
|
|
const value = req[field.name];
|
|
if (field.fk && typeof value === "object" && value != null) {
|
|
const target = allResources.find((r) => r.name === field.fk!.resource);
|
|
if (target) return [field.name, applyDisplayFormat(value, target.displayFormat)];
|
|
}
|
|
return [field.name, value];
|
|
}),
|
|
);
|
|
return applyDisplayFormat(resolved, resource.displayFormat);
|
|
}, [resource, req, allResources]);
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<Box sx={{ display: "flex", justifyContent: "center", p: 8 }}>
|
|
<CircularProgress />
|
|
</Box>
|
|
);
|
|
}
|
|
|
|
if (fetchError || !fetchRequest) {
|
|
return (
|
|
<Container sx={{ mt: 4 }}>
|
|
<PageHeader
|
|
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests", path: "/fetch-requests" }, { label: "Details" }]}
|
|
title="Fetch Request"
|
|
/>
|
|
<Alert severity="error">Failed to load fetch request</Alert>
|
|
</Container>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<Container maxWidth="lg" sx={{ py: 4 }}>
|
|
<PageHeader
|
|
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests", path: "/fetch-requests" }, { label: displayTitle }]}
|
|
title={displayTitle}
|
|
subtitle="Live pipeline status, progress events, and ambiguity resolution for this import."
|
|
/>
|
|
|
|
<Section
|
|
title="Overview"
|
|
action={
|
|
<Chip
|
|
icon={statusIcons[status] as any}
|
|
label={status.replace(/_/g, " ")}
|
|
color={statusColors[status]}
|
|
sx={{ textTransform: "capitalize" }}
|
|
/>
|
|
}
|
|
>
|
|
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2, flexWrap: "wrap" }}>
|
|
<Chip
|
|
label={"path" in (req.source ?? {}) ? "File" : "Email"}
|
|
size="small"
|
|
variant="outlined"
|
|
color={"path" in (req.source ?? {}) ? "primary" : "secondary"}
|
|
/>
|
|
<Typography variant="caption" color="text.secondary">
|
|
ID: {req.id}
|
|
</Typography>
|
|
</Box>
|
|
|
|
<Box sx={{ display: "flex", gap: 4, flexWrap: "wrap", mb: 2 }}>
|
|
{detailFields.map((field) => {
|
|
const value = req[field.name];
|
|
let fmt = resource?.displayFormat;
|
|
if (field.fk && typeof value === "object" && value != null) {
|
|
const target = allResources.find((r) => r.name === field.fk!.resource);
|
|
if (target) fmt = target.displayFormat;
|
|
}
|
|
return (
|
|
<DetailFieldRenderer
|
|
key={field.name}
|
|
field={field}
|
|
value={value}
|
|
displayFormat={fmt}
|
|
/>
|
|
);
|
|
})}
|
|
</Box>
|
|
|
|
<Divider sx={{ my: 2 }} />
|
|
|
|
<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={retrying}
|
|
>
|
|
Retry
|
|
</Button>
|
|
)}
|
|
</Box>
|
|
</Section>
|
|
|
|
{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}
|
|
/>
|
|
|
|
<Section
|
|
title="Progress Events"
|
|
action={
|
|
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
|
<Box
|
|
sx={{
|
|
width: 8,
|
|
height: 8,
|
|
borderRadius: "50%",
|
|
bgcolor: sseConnected ? "success.main" : "error.main",
|
|
}}
|
|
/>
|
|
<Typography variant="caption" color="text.secondary">
|
|
{sseConnected ? "Connected" : "Disconnected"}
|
|
</Typography>
|
|
</Box>
|
|
}
|
|
>
|
|
<Box
|
|
ref={feedRef}
|
|
sx={{
|
|
maxHeight: 300,
|
|
overflowY: "auto",
|
|
display: "flex",
|
|
flexDirection: "column",
|
|
gap: 1,
|
|
pr: 0.5,
|
|
}}
|
|
>
|
|
{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.25,
|
|
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>
|
|
</Section>
|
|
|
|
<AmbiguityResolver fetchRequestId={id!} />
|
|
</Container>
|
|
);
|
|
}
|