new FetchRequest
This commit is contained in:
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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user