Files
khata-ui/src/FetchRequest/FetchRequestCreate.tsx
Vishesh 'ironeagle' Bangotra 25ec534597 Stripe-style UI overhaul + Expenses feed with month grouping (#15)
## 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)
- 9808a1f design overhaul + expenses page
- d6856a5 fix expenses list performance + dom nesting
- 3dd833a shared currency field + expenses rendered from react-openapi fields
- e8c585b fix expenses grouping to parse occurred_at as DD-MM-YYYY strictly
- cc940ee expense list: split month totals, sticky headers + month pill
- 47d799f expense list: clickable month pill + fix scroll-to-month
- 537aef9 resolve relative media URLs against the API base in react-openapi
- 8e9a13d expense list: replace accordion with flat Stripe-style rows
- 62dd06c expense list: month accordions + month-year selector; drop unused x-data-grid
- 806bd42 dropped 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>
2026-08-18 13:51:28 +00:00

219 lines
7.7 KiB
TypeScript

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 ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
import { useAppContext, useResource, ListCellRenderer, FormFieldRenderer, getApi, applyDisplayFormat } from "../../react-openapi";
import type { FieldConfig } from "../../react-openapi";
import { PageHeader } from "../ui/PageHeader";
import { EmptyState } from "../ui/EmptyState";
const CREATE_FIELDS = ["account", "bank", "pipeline", "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: 6 }}>
<CircularProgress size={28} />
</Box>
);
}
if (rows.length === 0) {
return (
<EmptyState
icon={<ReceiptLongIcon />}
title="No fetch requests yet"
description="Upload a bank statement or configure email ingestion to import your first transactions."
actionLabel="New Fetch Request"
onAction={() => document.getElementById("new-fetch-request")?.scrollIntoView({ behavior: "smooth", block: "center" })}
/>
);
}
return (
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
{rows.map((row, i) => {
const displayFormat = resource?.displayFormat ?? "";
return (
<Paper
key={row.id ?? i}
variant="outlined"
sx={{
p: 2,
cursor: "pointer",
borderRadius: 2,
transition: "border-color 160ms ease, box-shadow 160ms ease",
"&:hover": { borderColor: "primary.main", boxShadow: 1 },
}}
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 }}>
<PageHeader
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests" }]}
title="Fetch Requests"
subtitle="Import transactions from bank statements or email and track pipeline progress."
/>
<Paper
id="new-fetch-request"
variant="outlined"
sx={{ p: 3, mb: 4, borderRadius: 3 }}
>
<Typography variant="subtitle1" fontWeight={700} gutterBottom>
New Fetch Request
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3, maxWidth: 520, lineHeight: 1.6 }}>
Choose an account, pipeline, and a file or email source to kick off an import.
</Typography>
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, maxWidth: 520 }}>
{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: 3, gap: 1.5 }}>
<Button variant="outlined" onClick={() => { setFormData({}); setResult(null); }}>
Reset
</Button>
<Button variant="contained" onClick={handleSubmit} disabled={loading} sx={{ minWidth: 180 }}>
{loading ? <CircularProgress size={20} sx={{ mr: 0.5 }} /> : null}
Create Fetch Request
</Button>
</Box>
{result && (
<Alert severity={result.severity} sx={{ mt: 2 }} onClose={() => setResult(null)}>
{result.message}
</Alert>
)}
</Paper>
<Typography variant="h6" fontWeight={700} sx={{ mb: 2 }}>
Recent Fetch Requests
</Typography>
<FetchRequestList />
</Container>
);
}