266 lines
9.3 KiB
TypeScript
266 lines
9.3 KiB
TypeScript
import React, { useEffect, useMemo, useState } from "react";
|
|
import {
|
|
Box, Container, Typography, Paper, Button, Alert,
|
|
CircularProgress, IconButton, Tooltip,
|
|
} from "@mui/material";
|
|
import { useNavigate } from "react-router-dom";
|
|
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
|
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
|
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";
|
|
import { formatApiError } from "../features/fetch-requests";
|
|
import { useToast } from "../ui/Toast";
|
|
|
|
const CREATE_FIELDS = ["account", "bank", "pipeline", "trust_fallback", "start_date", "end_date", "source"];
|
|
|
|
function FetchRequestList() {
|
|
const navigate = useNavigate();
|
|
const { list, remove, resource } = useResource("fetch-requests");
|
|
const { resources: allResources } = useAppContext();
|
|
const [rows, setRows] = useState<any[] | null>(null);
|
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
|
const { showToast } = useToast();
|
|
|
|
const reload = () => {
|
|
if (!resource) return;
|
|
list({ limit: 20 }).then((res) => setRows(res.items ?? []));
|
|
};
|
|
|
|
const columns = useMemo(() => {
|
|
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]);
|
|
|
|
const handleDelete = async (e: React.MouseEvent, id: string) => {
|
|
e.stopPropagation();
|
|
if (
|
|
!window.confirm(
|
|
"Delete this fetch request along with all its expenses and ambiguities? This cannot be undone.",
|
|
)
|
|
)
|
|
return;
|
|
setDeletingId(id);
|
|
try {
|
|
await remove(id);
|
|
showToast("Fetch request deleted");
|
|
reload();
|
|
} catch (err: any) {
|
|
showToast(formatApiError(err), "error");
|
|
} finally {
|
|
setDeletingId(null);
|
|
}
|
|
};
|
|
|
|
if (!rows) {
|
|
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 sx={{ ml: "auto", flexShrink: 0 }}>
|
|
<Tooltip title="Delete fetch request">
|
|
<IconButton
|
|
size="small"
|
|
color="error"
|
|
disabled={deletingId === row.id || row.status === "processing"}
|
|
onClick={(e) => handleDelete(e, row.id)}
|
|
>
|
|
<DeleteOutlineIcon fontSize="small" />
|
|
</IconButton>
|
|
</Tooltip>
|
|
</Box>
|
|
</Box>
|
|
</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 navigate = useNavigate();
|
|
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({});
|
|
const newId = (created as any)?.id;
|
|
if (newId) {
|
|
navigate(`/fetch-requests/${newId}`);
|
|
}
|
|
} 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>
|
|
);
|
|
}
|