report-fetch-request-ui (#7)
## MR: Fetch Request Pipeline, Report Snapshots, and Admin Filtering
### Summary
Adds fetch request pipeline UI, report snapshot manager, snapshot selector on dashboard, and client-side in-memory filtering for the admin panel. Also overhauls the Home page with feature cards and adds navigation links.
### Changes
**New Pages**
- `/fetch-requests` — Upload bank statements (two-step: upload file, then configure source) or configure email ingestion. Table shows fingerprint (with copy), source type, account, status (color-coded chip), and created date.
- `/reports` — Generate cached report snapshots with filters (ignore self, date range, amount range). Table shows snapshot ID (with copy), creation time, and query summary chips.
**Dashboard**
- Snapshot selector autocomplete dropdown (formatted "Snapshot from {date}"), passes `snapshot_id` to `useReport`
- Styled to match other filter controls (caption above, auto-height)
**Admin — In-Memory Filtering**
- `FilterBar` component: collapsible, Dashboard-style column layout with caption + autocomplete/range/date inputs per filterable field
- `FilterAutocomplete` component: multi-select, free solo, checkmark ticks, selected-first sort frozen while dropdown open (prevents scroll reset)
- `applyClientFilters` in `ResourceView`: handles number range, datetime range, array (object/string elements), non-relation objects, boolean, primitive exact match
- Config-driven via `filterOptions: { mode: "client", fields: [...] }` in `openapi-config.ts`
- Mobile view: each filter takes full width (`flex: "0 0 100%"`), no horizontal squeeze
- `rowCount` omitted in client pagination mode (suppresses MUI X warning)
**Navigation & Home**
- Header nav links: Dashboard, Fetch, Reports
- Home page redesign: gradient hero, "Import Data" CTA, 4 feature cards (Dashboard, Fetch Requests, Report Snapshots, Admin) with accent-colored hover effects
**React-OpenAPI Library**
- `filterOptions` (mode + fields) on `ResourceOverride` and `ResourceConfig` types
- `EnhancedTable` mobile pagination (10 per page with Prev/Next, prevents browser hang with 10000 records)
- `useResource` accepts `filterOptions` from loader
**Misc**
- `public/favicon.png` added, proper `image/png` type in index.html
- 24 files changed, ~1541 insertions, ~100 deletions
### Files Changed (24)
| File | Change |
|------|--------|
| `src/FetchRequests.tsx` | +336 — new page |
| `src/ReportSnapshots.tsx` | +273 — new page |
| `src/features/fetch-requests/` | +96 — models, hooks, index |
| `src/features/report-snapshots/` | +40 — models, hooks, index |
| `src/Dashboard.tsx` | +58 — snapshot selector |
| `src/Home.tsx` | +224 — redesign with feature cards |
| `src/Header.tsx` | +26 — nav links |
| `src/main.jsx` | +4 — routes |
| `react-openapi/components/FilterBar.tsx` | +313 — new component |
| `react-openapi/components/ResourceView.tsx` | +151 — client filtering |
| `react-openapi/components/EnhancedTable.tsx` | +62 — mobile pagination |
| `react-openapi/types/config.ts` | +7 — filterOptions type |
| `react-openapi/types/overrides.ts` | +5 — filterOptions type |
| `react-openapi/utils/openapi_loader.ts` | +8 — load filterOptions |
| `react-openapi/hooks/useResource.ts` | +6 — filterOptions passthrough |
| `react-openapi/index.ts` | +3 — exports |
| `src/openapi-config.ts` | +15 — expenses config |
| `src/features/report/useReport.ts` | +13 — snapshot_id support |
| `index.html` | +1 — favicon link |
| `public/favicon.png` | +2910 bytes |
Reviewed-on: #7
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
This commit is contained in:
@@ -49,8 +49,8 @@ export default function EnhancedTable({
|
||||
config,
|
||||
data,
|
||||
total,
|
||||
paginationModel,
|
||||
onPaginationModelChange,
|
||||
paginationModel: externalPaginationModel,
|
||||
onPaginationModelChange: externalOnPaginationModelChange,
|
||||
loading = false,
|
||||
onEdit,
|
||||
onDelete,
|
||||
@@ -60,6 +60,14 @@ export default function EnhancedTable({
|
||||
const theme = useTheme();
|
||||
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
|
||||
const navigate = useNavigate();
|
||||
|
||||
const isServer = config.filterOptions?.mode !== "client";
|
||||
const [internalPaginationModel, setInternalPaginationModel] = React.useState<GridPaginationModel>({
|
||||
page: 0,
|
||||
pageSize: 10,
|
||||
});
|
||||
const paginationModel = isServer ? externalPaginationModel : internalPaginationModel;
|
||||
const onPaginationModelChange = isServer ? externalOnPaginationModelChange : setInternalPaginationModel;
|
||||
|
||||
const columns: GridColDef[] = React.useMemo(() => {
|
||||
const cols: GridColDef[] = Object.entries(config.fields).map(([key, field]) => {
|
||||
@@ -122,6 +130,15 @@ export default function EnhancedTable({
|
||||
return cols;
|
||||
}, [config, onDelete, navigate, onNavigateToResource]);
|
||||
|
||||
const mobilePageSize = 10;
|
||||
const [mobilePage, setMobilePage] = React.useState(0);
|
||||
const mobileTotalPages = Math.ceil(data.length / mobilePageSize) || 1;
|
||||
const mobileData = data.slice(mobilePage * mobilePageSize, (mobilePage + 1) * mobilePageSize);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (mobilePage >= mobileTotalPages) setMobilePage(0);
|
||||
}, [data.length, mobilePage, mobileTotalPages]);
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Box>
|
||||
@@ -132,7 +149,7 @@ export default function EnhancedTable({
|
||||
</Button>
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{data.map((row) => (
|
||||
{mobileData.map((row) => (
|
||||
<Box key={row[config.primaryKey] || Math.random()}>
|
||||
<MobileCardRow
|
||||
row={row}
|
||||
@@ -145,6 +162,17 @@ export default function EnhancedTable({
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', gap: 1, mt: 2, flexWrap: 'wrap' }}>
|
||||
<Button size="small" disabled={mobilePage === 0} onClick={() => setMobilePage(mobilePage - 1)}>
|
||||
Previous
|
||||
</Button>
|
||||
<Typography variant="body2" sx={{ alignSelf: 'center', px: 1 }}>
|
||||
Page {mobilePage + 1} of {mobileTotalPages}
|
||||
</Typography>
|
||||
<Button size="small" disabled={mobilePage >= mobileTotalPages - 1} onClick={() => setMobilePage(mobilePage + 1)}>
|
||||
Next
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -161,20 +189,18 @@ export default function EnhancedTable({
|
||||
rows={data || []}
|
||||
columns={columns}
|
||||
autoHeight
|
||||
paginationMode={config.pagination ? 'server' : 'client'}
|
||||
rowCount={(() => {
|
||||
if (!config.pagination) return data.length;
|
||||
if (total !== undefined) return total;
|
||||
|
||||
// Graceful fallback for missing total count
|
||||
const page = paginationModel?.page || 0;
|
||||
const pageSize = paginationModel?.pageSize || 10;
|
||||
if (data.length < pageSize) {
|
||||
return page * pageSize + data.length;
|
||||
}
|
||||
// Enable 'Next' button by pretending there's at least one more page
|
||||
return (page + 2) * pageSize;
|
||||
})()}
|
||||
paginationMode={isServer ? 'server' : 'client'}
|
||||
{...(isServer ? {
|
||||
rowCount: (() => {
|
||||
if (total !== undefined) return total;
|
||||
const page = paginationModel?.page || 0;
|
||||
const pageSize = paginationModel?.pageSize || 10;
|
||||
if (data.length < pageSize) {
|
||||
return page * pageSize + data.length;
|
||||
}
|
||||
return (page + 2) * pageSize;
|
||||
})(),
|
||||
} : {})}
|
||||
loading={loading}
|
||||
paginationModel={paginationModel || { page: 0, pageSize: 10 }}
|
||||
onPaginationModelChange={onPaginationModelChange}
|
||||
@@ -234,7 +260,7 @@ function MobileCardRow({ row, config, onDelete, onNavigate, navigate }: any) {
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
|
||||
{field.label}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ fontWeight: 500, wordBreak: 'break-all' }}>
|
||||
<Typography variant="body2" component="div" sx={{ fontWeight: 500, wordBreak: 'break-all' }}>
|
||||
<FieldRenderer params={{ value: row[key], row }} field={field} fieldKey={key} config={config} onNavigate={onNavigate} navigate={navigate} isMobile />
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
313
react-openapi/components/FilterBar.tsx
Normal file
313
react-openapi/components/FilterBar.tsx
Normal file
@@ -0,0 +1,313 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Chip,
|
||||
Paper,
|
||||
TextField,
|
||||
Autocomplete,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import DoneIcon from "@mui/icons-material/Done";
|
||||
import FilterListIcon from "@mui/icons-material/FilterList";
|
||||
import { ResourceField, ResourceMode } from "../types/config";
|
||||
|
||||
function FilterAutocomplete({
|
||||
options,
|
||||
value,
|
||||
label,
|
||||
onChange,
|
||||
}: {
|
||||
options: string[];
|
||||
value: string[];
|
||||
label: string;
|
||||
onChange: (val: string[]) => void;
|
||||
}) {
|
||||
const listboxRef = React.useRef<HTMLUListElement>(null);
|
||||
const scrollPosRef = React.useRef(0);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [frozenValue, setFrozenValue] = React.useState<string[]>(value);
|
||||
|
||||
const toggleDropdown = () => {
|
||||
setOpen(prev => {
|
||||
const next = !prev;
|
||||
setFrozenValue(value);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
const sortedOptions = React.useMemo(() => {
|
||||
const sel = new Set(frozenValue);
|
||||
const picked: string[] = [];
|
||||
const rest: string[] = [];
|
||||
for (const o of options) {
|
||||
if (sel.has(o)) picked.push(o);
|
||||
else rest.push(o);
|
||||
}
|
||||
return [...picked, ...rest];
|
||||
}, [options, frozenValue]);
|
||||
|
||||
return (
|
||||
<Autocomplete
|
||||
multiple
|
||||
freeSolo
|
||||
disableCloseOnSelect
|
||||
open={open}
|
||||
onOpen={toggleDropdown}
|
||||
onClose={toggleDropdown}
|
||||
options={sortedOptions}
|
||||
value={value}
|
||||
getOptionKey={(option) => option}
|
||||
onChange={(_, val) => onChange(val.length > 0 ? val : [])}
|
||||
ListboxProps={{
|
||||
ref: listboxRef,
|
||||
onScroll: (e) => { scrollPosRef.current = (e.target as HTMLUListElement).scrollTop; },
|
||||
}}
|
||||
renderOption={(props, option, { selected }) => {
|
||||
const { key, ...rest } = props;
|
||||
return (
|
||||
<li key={key} {...rest}>
|
||||
{selected ? <DoneIcon sx={{ fontSize: 14, mr: 1, color: 'primary.main' }} /> : <Box sx={{ width: 22, mr: 1 }} />}
|
||||
{option}
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
renderTags={(tagValue, getTagProps) => {
|
||||
const maxChips = 1;
|
||||
return (
|
||||
<>
|
||||
{tagValue.slice(0, maxChips).map((tag, index) => {
|
||||
const { key, ...tagProps } = getTagProps({ index });
|
||||
return <Chip
|
||||
key={key}
|
||||
{...tagProps}
|
||||
label={tag.length > 10 ? `${tag.slice(0, 8)}..` : tag}
|
||||
size="small"
|
||||
onClick={toggleDropdown}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
/>;
|
||||
})}
|
||||
{tagValue.length > maxChips && (
|
||||
<Chip
|
||||
label={`+${tagValue.length - maxChips}`}
|
||||
size="small"
|
||||
onClick={toggleDropdown}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}}
|
||||
renderInput={(params) => <TextField {...params} placeholder={`Add ${label}...`} />}
|
||||
sx={{ '& .MuiOutlinedInput-root': { minHeight: '3rem', py: 0.5 } }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function extractOptions(
|
||||
fieldName: string,
|
||||
field: ResourceField,
|
||||
data: any[]
|
||||
): string[] {
|
||||
const values = new Set<string>();
|
||||
|
||||
if (field.options) return field.options;
|
||||
if (!data) return [];
|
||||
|
||||
const pull = (item: any): string | null => {
|
||||
if (item == null) return null;
|
||||
if (typeof item === "string") return item;
|
||||
if (typeof item !== "object") return String(item);
|
||||
|
||||
const df = field.displayField;
|
||||
if (!df) { debugger; return null; }
|
||||
|
||||
if (Array.isArray(df)) {
|
||||
const parts = df.map((k) => item[k]).filter((v) => v != null);
|
||||
if (parts.length > 0) return parts.join(" ");
|
||||
} else {
|
||||
const v = item[df];
|
||||
if (v != null) return String(v);
|
||||
}
|
||||
|
||||
debugger;
|
||||
return null;
|
||||
};
|
||||
|
||||
for (const row of data) {
|
||||
const v = row[fieldName];
|
||||
if (v == null) continue;
|
||||
|
||||
if (Array.isArray(v)) {
|
||||
for (const el of v) {
|
||||
const label = pull(el);
|
||||
if (label) values.add(label);
|
||||
}
|
||||
} else {
|
||||
const label = pull(v);
|
||||
if (label) values.add(label);
|
||||
}
|
||||
}
|
||||
|
||||
// console.log('extracted', fieldName, Array.from(values).sort())
|
||||
return Array.from(values).sort();
|
||||
}
|
||||
|
||||
function renderFilterInput(
|
||||
fieldName: string,
|
||||
field: ResourceField,
|
||||
options: string[],
|
||||
value: any,
|
||||
onChange: (key: string, val: any) => void
|
||||
) {
|
||||
const filterType = field.filterType;
|
||||
|
||||
if (filterType === "number-range") {
|
||||
const rangeVal = (value as { min?: string; max?: string }) || {};
|
||||
return (
|
||||
<Box sx={{ display: "flex", gap: 1 }}>
|
||||
<TextField type="number" placeholder="Min" size="small" value={rangeVal.min ?? ""}
|
||||
onChange={(e) => onChange("min", e.target.value || undefined)} sx={{ width: 100 }} />
|
||||
<TextField type="number" placeholder="Max" size="small" value={rangeVal.max ?? ""}
|
||||
onChange={(e) => onChange("max", e.target.value || undefined)} sx={{ width: 100 }} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (filterType === "date-range") {
|
||||
const rangeVal = (value as { start?: string; end?: string }) || {};
|
||||
return (
|
||||
<Box sx={{ display: "flex", gap: 1 }}>
|
||||
<TextField type="datetime-local" placeholder="From" size="small" value={rangeVal.start ?? ""}
|
||||
onChange={(e) => onChange("start", e.target.value || undefined)} InputLabelProps={{ shrink: true }} sx={{ width: 170 }} />
|
||||
<TextField type="datetime-local" placeholder="To" size="small" value={rangeVal.end ?? ""}
|
||||
onChange={(e) => onChange("end", e.target.value || undefined)} InputLabelProps={{ shrink: true }} sx={{ width: 170 }} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const selected = Array.isArray(value) ? value : [];
|
||||
|
||||
return (
|
||||
<FilterAutocomplete
|
||||
options={options}
|
||||
value={selected}
|
||||
label={field.label}
|
||||
onChange={(val) => onChange("value", val.length > 0 ? val : undefined)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export interface FilterBarProps {
|
||||
fields: Record<string, ResourceField>;
|
||||
filterableFields: string[];
|
||||
mode: ResourceMode;
|
||||
data?: any[];
|
||||
appliedValues: Record<string, any>;
|
||||
onApply: (values: Record<string, any>) => void;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
export default function FilterBar({
|
||||
fields,
|
||||
filterableFields,
|
||||
data,
|
||||
appliedValues,
|
||||
onApply,
|
||||
onClear,
|
||||
}: FilterBarProps) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [draft, setDraft] = React.useState<Record<string, any>>(() => ({ ...appliedValues }));
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) setDraft({ ...appliedValues });
|
||||
}, [appliedValues, open]);
|
||||
|
||||
if (!filterableFields || filterableFields.length === 0) return null;
|
||||
|
||||
const activeCount = Object.keys(appliedValues).filter((k) => {
|
||||
const v = appliedValues[k];
|
||||
if (v == null || v === "") return false;
|
||||
if (typeof v === "object" && Object.values(v).every((x) => x == null || x === "")) return false;
|
||||
return true;
|
||||
}).length;
|
||||
|
||||
const handleApply = () => onApply({ ...draft });
|
||||
const handleClear = () => {
|
||||
setDraft({});
|
||||
onClear();
|
||||
};
|
||||
|
||||
const updateDraft = (fieldName: string, key: string, val: any) => {
|
||||
setDraft((prev) => {
|
||||
if (key === "value") {
|
||||
return { ...prev, [fieldName]: val };
|
||||
}
|
||||
const existing = prev[fieldName] || {};
|
||||
return { ...prev, [fieldName]: { ...existing, [key]: val } };
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ mb: 2, borderRadius: 2, overflow: "hidden" }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
px: 2,
|
||||
py: 1,
|
||||
cursor: "pointer",
|
||||
"&:hover": { bgcolor: "action.hover" },
|
||||
}}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<FilterListIcon fontSize="small" color="action" />
|
||||
<Typography variant="subtitle2" fontWeight={600}>
|
||||
{open ? "Hide Filters" : "Show Filters"}
|
||||
</Typography>
|
||||
</Box>
|
||||
{activeCount > 0 && (
|
||||
<Typography variant="caption" color="primary" fontWeight={600}>
|
||||
{activeCount} active
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{open && (
|
||||
<Box sx={{ px: 2, pb: 2, borderTop: "1px solid", borderColor: "divider", pt: 2 }}>
|
||||
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 2, alignItems: "flex-end" }}>
|
||||
{filterableFields.map((fieldName) => {
|
||||
const field = fields[fieldName];
|
||||
if (!field) return null;
|
||||
|
||||
const needsOptions = !field.filterType || field.filterType === "autocomplete" || field.filterType === "multiselect";
|
||||
const options = needsOptions ? extractOptions(fieldName, field, data ?? []) : [];
|
||||
const raw = draft[fieldName];
|
||||
|
||||
return (
|
||||
<Box key={fieldName} sx={{ display: "flex", flexDirection: "column", flex: { xs: '0 0 100%', sm: 1 }, minWidth: { sm: 200 } }}>
|
||||
<Box sx={{ typography: "caption", mb: 0.5, color: "text.secondary" }}>
|
||||
{field.label}
|
||||
</Box>
|
||||
{renderFilterInput(fieldName, field, options, raw, (key, val) =>
|
||||
updateDraft(fieldName, key, val)
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mt: 2, display: "flex", gap: 1 }}>
|
||||
<Button variant="contained" onClick={handleApply}>
|
||||
Apply
|
||||
</Button>
|
||||
<Button variant="outlined" onClick={handleClear}>
|
||||
Clear
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import * as React from 'react';
|
||||
import { Box, Typography, Paper, CircularProgress } from '@mui/material';
|
||||
import { Box, Paper, CircularProgress } from '@mui/material';
|
||||
import { ResourceConfig } from '../types/config';
|
||||
import type { ResourceField } from '../types/config';
|
||||
import { useResource } from '../hooks/useResource';
|
||||
import GenericForm from './GenericForm';
|
||||
import EnhancedTable from './EnhancedTable';
|
||||
import { useParams, useLocation, useNavigate, Routes, Route } from 'react-router-dom';
|
||||
import FilterBar from './FilterBar';
|
||||
import { useParams, useLocation, useNavigate } from 'react-router-dom';
|
||||
|
||||
interface ResourceViewProps {
|
||||
config: ResourceConfig;
|
||||
@@ -13,36 +15,132 @@ interface ResourceViewProps {
|
||||
|
||||
import { GridPaginationModel } from '@mui/x-data-grid';
|
||||
|
||||
function getFilterDisplayFields(field: ResourceField): string[] {
|
||||
if (!field.displayField) return [];
|
||||
return (Array.isArray(field.displayField) ? field.displayField : [field.displayField]).filter(
|
||||
(df): df is string => !!df
|
||||
);
|
||||
}
|
||||
|
||||
function applyClientFilters(
|
||||
data: any[],
|
||||
filters: Record<string, any>,
|
||||
fields: Record<string, ResourceField>
|
||||
): any[] {
|
||||
const entries = Object.entries(filters).filter(([_, v]) => {
|
||||
if (v == null || v === "" || (Array.isArray(v) && v.length === 0)) return false;
|
||||
if (typeof v === "object" && !Array.isArray(v) && Object.values(v).every((x) => x == null || x === "")) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
if (entries.length === 0) return data;
|
||||
|
||||
return data.filter((item) =>
|
||||
entries.every(([fieldName, filterValue]) => {
|
||||
const field = fields[fieldName];
|
||||
if (!field) return true;
|
||||
|
||||
const itemValue = item[fieldName];
|
||||
|
||||
if (typeof filterValue === "object" && !Array.isArray(filterValue)) {
|
||||
if (field.type === "number") {
|
||||
if (filterValue.min != null && filterValue.min !== "" && Number(itemValue) < Number(filterValue.min)) return false;
|
||||
if (filterValue.max != null && filterValue.max !== "" && Number(itemValue) > Number(filterValue.max)) return false;
|
||||
return true;
|
||||
}
|
||||
if (field.type === "datetime" || field.type === "date") {
|
||||
const itemTime = new Date(itemValue).getTime();
|
||||
if (filterValue.start && new Date(filterValue.start).getTime() > itemTime) return false;
|
||||
if (filterValue.end && new Date(filterValue.end).getTime() < itemTime) return false;
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Array.isArray(filterValue)) {
|
||||
if (field.type === "array" && Array.isArray(itemValue)) {
|
||||
return itemValue.some((el: any) => {
|
||||
if (el != null && typeof el === "object") {
|
||||
const dispFields = getFilterDisplayFields(field);
|
||||
return dispFields.some((df) => filterValue.includes(String(el[df])));
|
||||
}
|
||||
return filterValue.includes(String(el));
|
||||
});
|
||||
}
|
||||
if (itemValue && typeof itemValue === "object") {
|
||||
const dispFields = getFilterDisplayFields(field);
|
||||
const itemDisplay = dispFields.map((df) => itemValue[df]).filter((v) => v != null).join(" ");
|
||||
return filterValue.includes(itemDisplay);
|
||||
}
|
||||
return filterValue.includes(String(itemValue));
|
||||
}
|
||||
|
||||
if (!filterValue) return true;
|
||||
|
||||
if (field.type === "boolean") {
|
||||
return String(itemValue) === filterValue;
|
||||
}
|
||||
|
||||
if (field.type === "array" && Array.isArray(itemValue)) {
|
||||
return itemValue.some((el: any) => {
|
||||
if (el != null && typeof el === "object") {
|
||||
const dispFields = getFilterDisplayFields(field);
|
||||
return dispFields.some((df) => String(el[df]) === String(filterValue));
|
||||
}
|
||||
return String(el) === String(filterValue);
|
||||
});
|
||||
}
|
||||
|
||||
if (itemValue && typeof itemValue === "object") {
|
||||
const dispFields = getFilterDisplayFields(field);
|
||||
return dispFields.some((df) => String(itemValue[df]) === String(filterValue));
|
||||
}
|
||||
|
||||
return String(itemValue) === String(filterValue);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export default function ResourceView({ config, onNavigateToResource }: ResourceViewProps) {
|
||||
const { id } = useParams();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
|
||||
const isCreate = location.pathname.endsWith('/create');
|
||||
const isEdit = location.pathname.includes('/edit/');
|
||||
const isView = !!id && !isEdit;
|
||||
const isList = !id && !isCreate;
|
||||
|
||||
const isServer = config.filterOptions?.mode !== "client";
|
||||
|
||||
const [paginationModel, setPaginationModel] = React.useState<GridPaginationModel>({
|
||||
page: 0,
|
||||
pageSize: 10,
|
||||
});
|
||||
|
||||
const [appliedFilters, setAppliedFilters] = React.useState<Record<string, any>>({});
|
||||
|
||||
const { useList, useRead, useCreate, useUpdate, useDelete } = useResource(config);
|
||||
|
||||
// Determine query parameters based on pagination config
|
||||
const queryParams = React.useMemo(() => {
|
||||
if (!config.pagination) return {};
|
||||
if (!isServer) return { limit: 10000 };
|
||||
return {
|
||||
skip: paginationModel.page * paginationModel.pageSize,
|
||||
limit: paginationModel.pageSize,
|
||||
};
|
||||
}, [config.pagination, paginationModel]);
|
||||
}, [isServer, paginationModel]);
|
||||
|
||||
const listQuery = useList(queryParams);
|
||||
const itemQuery = useRead(id || "");
|
||||
|
||||
const paginatedData = listQuery.data || { data: [], total: undefined };
|
||||
|
||||
const rawData = listQuery.data?.data || [];
|
||||
const totalCount = listQuery.data?.total;
|
||||
|
||||
const filteredData = React.useMemo(
|
||||
() => (isServer ? rawData : applyClientFilters(rawData, appliedFilters, config.fields)),
|
||||
[isServer, rawData, appliedFilters, config.fields]
|
||||
);
|
||||
|
||||
const createMutation = useCreate();
|
||||
const updateMutation = useUpdate();
|
||||
const deleteMutation = useDelete();
|
||||
@@ -80,18 +178,31 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
|
||||
return (
|
||||
<Box>
|
||||
{isList ? (
|
||||
<EnhancedTable
|
||||
config={config}
|
||||
data={paginatedData.data || []}
|
||||
total={paginatedData.total}
|
||||
paginationModel={paginationModel}
|
||||
onPaginationModelChange={setPaginationModel}
|
||||
loading={listQuery.isFetching}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onCreate={handleCreate}
|
||||
onNavigateToResource={(res, id) => navigate(`/admin/${res}/${id}`)}
|
||||
/>
|
||||
<Box>
|
||||
{!isServer && config.filterOptions?.fields && config.filterOptions.fields.length > 0 && (
|
||||
<FilterBar
|
||||
fields={config.fields}
|
||||
filterableFields={config.filterOptions.fields}
|
||||
mode={config.filterOptions?.mode || "server"}
|
||||
data={rawData}
|
||||
appliedValues={appliedFilters}
|
||||
onApply={setAppliedFilters}
|
||||
onClear={() => setAppliedFilters({})}
|
||||
/>
|
||||
)}
|
||||
<EnhancedTable
|
||||
config={config}
|
||||
data={filteredData}
|
||||
total={isServer ? totalCount : filteredData.length}
|
||||
paginationModel={isServer ? paginationModel : undefined}
|
||||
onPaginationModelChange={isServer ? setPaginationModel : undefined}
|
||||
loading={listQuery.isFetching}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onCreate={handleCreate}
|
||||
onNavigateToResource={(res, id) => navigate(`/admin/${res}/${id}`)}
|
||||
/>
|
||||
</Box>
|
||||
) : (
|
||||
<Paper sx={{ p: 4 }}>
|
||||
<GenericForm
|
||||
|
||||
@@ -30,13 +30,13 @@ export function useResource<T = any>(config: ResourceConfig | undefined) {
|
||||
});
|
||||
|
||||
// --- READ ONE ---
|
||||
const useRead = (id: string | null) =>
|
||||
const useRead = (id: string, params?: any | null) =>
|
||||
useQuery({
|
||||
queryKey: [name, "detail", id],
|
||||
queryKey: [name, "detail", id, params],
|
||||
queryFn: async () => {
|
||||
if (!id || !endpoint) return null;
|
||||
// @ts-ignore
|
||||
const res = await api.get<T>(`${endpoint}/${id}`);
|
||||
const res = await api.get<T>(`${endpoint}/${id}`, params ? { params } : undefined);
|
||||
return res.data;
|
||||
},
|
||||
enabled: !!id && !!endpoint,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
export { default as Admin } from "./Admin";
|
||||
export { api, auth, initializeApiClients } from "./api/client";
|
||||
export { getAppConfig } from "./config";
|
||||
export type { AppConfig, ResourceConfig, ResourceField } from "./types/config";
|
||||
export type { AppConfig, ResourceConfig, ResourceField, ResourceMode } from "./types/config";
|
||||
export { AppProvider } from "./providers/AppProvider";
|
||||
export { ConfigContext, useConfig } from "./providers/ConfigContext";
|
||||
export { useResource, useResourceByName } from "./hooks/useResource";
|
||||
export { default as FilterBar } from "./components/FilterBar";
|
||||
|
||||
@@ -20,8 +20,11 @@ export interface ResourceField {
|
||||
displayField?: string | string[];
|
||||
formatter?: (value: any) => string;
|
||||
relation?: string; // Name of the target resource
|
||||
filterType?: "autocomplete" | "multiselect" | "number-range" | "date-range";
|
||||
}
|
||||
|
||||
export type ResourceMode = "server" | "client";
|
||||
|
||||
export interface ResourceConfig {
|
||||
name: string;
|
||||
label: string;
|
||||
@@ -31,6 +34,10 @@ export interface ResourceConfig {
|
||||
fields: Record<string, ResourceField>;
|
||||
pagination?: boolean;
|
||||
hidden?: boolean;
|
||||
filterOptions?: {
|
||||
mode?: ResourceMode;
|
||||
fields?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
|
||||
@@ -7,10 +7,15 @@ export interface FieldOverride {
|
||||
displayField?: string | string[];
|
||||
display?: boolean;
|
||||
formatter?: (value: any) => string;
|
||||
filterType?: "autocomplete" | "multiselect" | "number-range" | "date-range";
|
||||
}
|
||||
|
||||
export interface ResourceOverride {
|
||||
fields?: Record<string, FieldOverride>;
|
||||
pagination?: boolean;
|
||||
hidden?: boolean;
|
||||
filterOptions?: {
|
||||
mode?: "server" | "client";
|
||||
fields?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -154,15 +154,21 @@ export async function loadConfigFromOpenApi(baseUrl: string, configuration: Reco
|
||||
|
||||
const resourceOverride = configuration[name] || {};
|
||||
|
||||
const fo = resourceOverride.filterOptions || {};
|
||||
|
||||
resources.push({
|
||||
name,
|
||||
label: schema.title || label,
|
||||
pluralLabel: pluralLabel,
|
||||
endpoint: listPath,
|
||||
primaryKey: "id", // Strict default, no heuristics
|
||||
primaryKey: "id",
|
||||
fields,
|
||||
pagination: resourceOverride.pagination,
|
||||
hidden: resourceOverride.hidden,
|
||||
filterOptions: {
|
||||
mode: fo.mode || "server",
|
||||
fields: fo.fields,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user