major refactor of the dashboard and react-openapi integration (#1)

## Summary

This MR introduces a major refactor of the dashboard and react-openapi integration, focusing on configurability, separation of concerns, and improved extensibility.

---

## Key Changes

### 1. OpenAPI / Admin Refactor

* Extracted `ConfigContext` into a dedicated provider.
* Introduced `AppProvider` to encapsulate:

  * Config loading
  * API client initialization
  * React Query setup
* Removed internal `QueryClientProvider` from `Admin` for better composability.
* `Admin` now supports both:

  * Standalone usage
  * Nested usage inside an existing provider

### 2. Resource System Improvements

* Added `hidden` flag to `ResourceConfig` and overrides.
* Admin UI now filters out hidden resources.
* Added `useResourceByName` helper for dynamic resource access.
* Improved `useResource`:

  * Handles undefined config safely
  * Adds guards for missing endpoints
  * Disables queries when endpoint is absent

### 3. API Client Enhancements

* Added custom `paramsSerializer`:

  * Serializes arrays without `[]`
  * Ensures backend-compatible query formats

### 4. Dashboard Architecture Overhaul

* Replaced hardcoded dashboard with **config-driven system**:

  * Introduced `ConfigurableDashboard`
  * Dashboard sections defined via config
* New state model:

  * `mode` (expense/income)
  * `periodType` (rolling/calendar)
  * `comparison`
  * `selectedPeriodId`

### 5. Component Refactor (View / Logic Split)

* Split major components into:

  * `.tsx` (logic/controller)
  * `.view.tsx` (presentation)
  * `.models.ts` (types)
* Applied to:

  * Dashboard
  * HistoryChart
  * ProgressCard
  * LatestItems

### 6. HistoryChart Redesign

* Fully rebuilt using report-driven data
* Supports:

  * Weekly / Monthly / Yearly / FY / Full views
  * Rolling vs Calendar periods
  * Comparison mode (auto-aligned offsets)
* Introduced:

  * Bucket merging logic
  * Dynamic comparison attachment

### 7. Reporting Integration

* Dashboard now powered by:

  * `useReport`
  * `prepareReport`
* Removes need for multiple manual API calls

### 8. UI / UX Improvements

* Theme-aware color system
* Dynamic accent colors per mode
* Cleaner layout using section-based rendering
* Improved selection and interaction in charts

### 9. Cleanup & Removals

* Removed legacy components:

  * Old `HistoryChart`
  * Old `ProgressCard`
* Simplified Header layout spacing

---

## Behavior Changes

* Hidden resources are no longer visible in Admin UI.
* Dashboard is now entirely configuration-driven.
* API query params for arrays no longer use `[]`.
* Resource hooks no longer crash on missing config.

---

## Risks / Considerations

* Dashboard depends on correct configuration structure.
* Hidden flag may unintentionally hide resources if misconfigured.
* Query param serialization change must align with backend expectations.

---

## Follow-ups

* Add typing improvements to remove `@ts-ignore` in `GenericForm`.
* Extend dashboard config with more reusable section presets.
* Add tests for report aggregation and comparison logic.

---

Reviewed-on: #1
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
This commit is contained in:
2026-05-07 11:00:54 +00:00
committed by aetos
parent b1db439dda
commit 009ab50b47
45 changed files with 1600 additions and 1099 deletions

View File

@@ -1,5 +1,4 @@
import * as React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useAuth, AuthPage } from "../react-auth";
import { UploadProvider } from "./providers/UploadProvider";
import AdminLayout from "./components/AdminLayout";
@@ -13,17 +12,17 @@ import {
Route,
useNavigate,
useParams,
Navigate,
} from "react-router-dom";
const queryClient = new QueryClient();
// Create a context for the app config
export const ConfigContext = React.createContext<AppConfig | null>(null);
import { ConfigContext } from "./providers/ConfigContext";
function Dashboard({ basePath }: { basePath: string }) {
const config = React.useContext(ConfigContext);
const navigate = useNavigate();
const resources = config?.resources || [];
const visibleResources = resources.filter((res) => !res.hidden);
return (
<Box>
<Typography variant="h4" gutterBottom>
@@ -41,7 +40,7 @@ function Dashboard({ basePath }: { basePath: string }) {
mt: 4,
}}
>
{config?.resources.map((res) => (
{visibleResources.map((res) => (
<Paper
key={res.name}
sx={{
@@ -69,6 +68,9 @@ function AdminApp({ basePath }: { basePath: string }) {
const config = React.useContext(ConfigContext);
const navigate = useNavigate();
const resources = config?.resources || [];
const visibleResources = resources.filter((res) => !res.hidden);
if (!currentUser) {
return (
<AuthPage
@@ -89,7 +91,7 @@ function AdminApp({ basePath }: { basePath: string }) {
username={currentUser.username}
onLogout={logout}
onSelectResource={(name) => navigate(`/admin/${name}`)}
resources={config?.resources || []}
resources={visibleResources}
>
<Routes>
<Route path="/" element={<Dashboard basePath={basePath} />} />
@@ -120,14 +122,17 @@ interface AdminProps {
}
export default function Admin({ basePath = "/admin", resourceOverrides = {}, profileConfig = {} }: AdminProps) {
const [config, setConfig] = React.useState<AppConfig | null>(null);
const existingConfig = React.useContext(ConfigContext);
const [config, setConfig] = React.useState<AppConfig | null>(existingConfig);
React.useEffect(() => {
getAppConfig(resourceOverrides, profileConfig).then((cfg) => {
initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
setConfig(cfg);
});
}, [resourceOverrides, profileConfig]);
if (!existingConfig) {
getAppConfig(resourceOverrides, profileConfig).then((cfg) => {
initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
setConfig(cfg);
});
}
}, [resourceOverrides, profileConfig, existingConfig]);
if (!config) {
return (
@@ -144,13 +149,21 @@ export default function Admin({ basePath = "/admin", resourceOverrides = {}, pro
);
}
const content = (
<UploadProvider>
<AdminApp basePath={basePath} />
</UploadProvider>
);
// If we have an existing config, we are already inside a Provider and QueryClient
if (existingConfig) {
return content;
}
// Fallback for standalone usage
return (
<QueryClientProvider client={queryClient}>
<ConfigContext.Provider value={config}>
<UploadProvider>
<AdminApp basePath={basePath} />
</UploadProvider>
</ConfigContext.Provider>
</QueryClientProvider>
<ConfigContext.Provider value={config}>
{content}
</ConfigContext.Provider>
);
}

View File

@@ -7,6 +7,28 @@ import { createApiClient } from "../../react-auth";
let _api: AxiosInstance | null = null;
let _auth: AxiosInstance | null = null;
function withParamsSerializer(instance: AxiosInstance): AxiosInstance {
instance.defaults.paramsSerializer = {
serialize: (params) => {
const searchParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((v) => {
searchParams.append(key, String(v)); // NO []
});
} else if (value !== undefined && value !== null) {
searchParams.append(key, String(value));
}
});
return searchParams.toString();
},
};
return instance;
}
export const api = {
get: (...args: Parameters<AxiosInstance["get"]>) => {
if (!_api) throw new Error("API client not initialized");
@@ -38,6 +60,6 @@ export const auth = {
};
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
_api = createApiClient(baseUrl);
_auth = createApiClient(authBaseUrl);
_api = withParamsSerializer(createApiClient(baseUrl));
_auth = withParamsSerializer(createApiClient(authBaseUrl));
}

View File

@@ -11,7 +11,7 @@ import { useUpload } from '../providers/UploadProvider';
import { useQueries } from '@tanstack/react-query';
import { useResource } from '../hooks/useResource';
import FormField from './fields/FormField';
import { ConfigContext } from '../Admin';
import { ConfigContext } from '../providers/ConfigContext';
interface GenericFormProps {
config: ResourceConfig;
@@ -67,7 +67,8 @@ export default function GenericForm({
const relationDataMap = React.useMemo(() => {
const map: Record<string, any[]> = {};
allRelations.forEach((relName, index) => {
map[relName] = queries[index].data || [];
// @ts-ignore
map[relName] = queries[index].data || [];
});
return map;
}, [allRelations, queries]);

View File

@@ -2,7 +2,7 @@ import * as React from 'react';
import { Box, Typography, Paper, CircularProgress, Alert } from '@mui/material';
import { useResource } from '../hooks/useResource';
import GenericForm from './GenericForm';
import { ConfigContext } from '../Admin';
import { ConfigContext } from '../providers/ConfigContext';
export default function ProfileView() {
const appConfig = React.useContext(ConfigContext);

View File

@@ -1,16 +1,22 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../api/client";
import { ResourceConfig } from "../types/config";
import { ConfigContext } from "../providers/ConfigContext";
import * as React from "react";
export function useResource<T = any>(config: ResourceConfig) {
export function useResource<T = any>(config: ResourceConfig | undefined) {
const queryClient = useQueryClient();
const { name, endpoint, primaryKey } = config;
// Return empty/disabled hooks if config is missing
const { name = '', endpoint = '', primaryKey = 'id' } = config || {};
// --- READ ALL ---
const useList = (params?: any) =>
useQuery({
queryKey: [name, "list", params],
queryFn: async () => {
if (!endpoint) return { data: [], total: 0 };
console.log('params:', params);
// @ts-ignore
const res = await api.get<T[]>(endpoint, { params });
const total = res.headers ? parseInt(res.headers['x-total-count'] || res.headers['X-Total-Count']) : undefined;
@@ -18,7 +24,8 @@ export function useResource<T = any>(config: ResourceConfig) {
data: res.data,
total: isNaN(total as any) ? undefined : total
};
}
},
enabled: !!endpoint,
});
// --- READ ONE ---
@@ -26,18 +33,19 @@ export function useResource<T = any>(config: ResourceConfig) {
useQuery({
queryKey: [name, "detail", id],
queryFn: async () => {
if (!id) return null;
if (!id || !endpoint) return null;
// @ts-ignore
const res = await api.get<T>(`${endpoint}/${id}`);
return res.data;
},
enabled: !!id,
enabled: !!id && !!endpoint,
});
// --- CREATE ---
const useCreate = () =>
useMutation({
mutationFn: async (data: Partial<T>) => {
if (!endpoint) throw new Error("Endpoint not defined");
// @ts-ignore
const res = await api.post<T>(endpoint, data);
return res.data;
@@ -51,6 +59,7 @@ export function useResource<T = any>(config: ResourceConfig) {
const useUpdate = () =>
useMutation({
mutationFn: async ({ id, data }: { id: string; data: Partial<T> }) => {
if (!endpoint) throw new Error("Endpoint not defined");
// @ts-ignore
const res = await api.put<T>(`${endpoint}/${id}`, data);
return res.data;
@@ -67,6 +76,7 @@ export function useResource<T = any>(config: ResourceConfig) {
const useDelete = () =>
useMutation({
mutationFn: async (id: string) => {
if (!endpoint) throw new Error("Endpoint not defined");
await api.delete(`${endpoint}/${id}`);
return id;
},
@@ -79,6 +89,7 @@ export function useResource<T = any>(config: ResourceConfig) {
const getListQueryOptions = (params?: any) => ({
queryKey: [name, "list", params],
queryFn: async () => {
if (!endpoint) return { data: [], total: 0 };
// @ts-ignore
const res = await api.get<T[]>(endpoint, { params });
const total = res.headers ? parseInt(res.headers['x-total-count'] || res.headers['X-Total-Count']) : undefined;
@@ -87,6 +98,7 @@ export function useResource<T = any>(config: ResourceConfig) {
total: isNaN(total as any) ? undefined : total
};
},
enabled: !!endpoint,
});
// --- READ ME ---
@@ -94,16 +106,19 @@ export function useResource<T = any>(config: ResourceConfig) {
useQuery({
queryKey: [name, "me"],
queryFn: async () => {
if (!endpoint) return null;
// @ts-ignore
const res = await api.get<T>(`${endpoint}/me`);
return res.data;
},
enabled: !!endpoint,
});
// --- UPDATE ME ---
const useUpdateMe = () =>
useMutation({
mutationFn: async (data: Partial<T>) => {
if (!endpoint) throw new Error("Endpoint not defined");
// @ts-ignore
const res = await api.put<T>(`${endpoint}/me`, data);
return res.data;
@@ -125,3 +140,10 @@ export function useResource<T = any>(config: ResourceConfig) {
getListQueryOptions,
};
}
export function useResourceByName<T = any>(name: string) {
const config = React.useContext(ConfigContext);
const resourceConfig = config?.resources.find((r) => r.name === name);
return useResource<T>(resourceConfig);
}

View File

@@ -2,3 +2,6 @@ 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 { AppProvider } from "./providers/AppProvider";
export { ConfigContext, useConfig } from "./providers/ConfigContext";
export { useResource, useResourceByName } from "./hooks/useResource";

View File

@@ -0,0 +1,70 @@
import * as React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ConfigContext } from "./ConfigContext";
import { getAppConfig } from "../config";
import { initializeApiClients } from "../api/client";
import { AppConfig } from "../types/config";
import { Box, CircularProgress } from "@mui/material";
const defaultQueryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 5 * 60 * 1000,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
interface AppProviderProps {
children: React.ReactNode;
resourceOverrides?: Record<string, any>;
profileConfig?: any;
queryClient?: QueryClient;
}
export function AppProvider({
children,
resourceOverrides = {},
profileConfig = {},
queryClient = defaultQueryClient,
}: AppProviderProps) {
const [config, setConfig] = React.useState<AppConfig | null>(null);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
getAppConfig(resourceOverrides, profileConfig)
.then((cfg) => {
initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
setConfig(cfg);
setLoading(false);
})
.catch((err) => {
console.error("Failed to load OpenAPI configuration:", err);
setLoading(false);
});
}, [resourceOverrides, profileConfig]);
if (loading) {
return (
<Box
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
}}
>
<CircularProgress />
</Box>
);
}
return (
<QueryClientProvider client={queryClient}>
<ConfigContext.Provider value={config}>
{children}
</ConfigContext.Provider>
</QueryClientProvider>
);
}

View File

@@ -0,0 +1,12 @@
import * as React from "react";
import { AppConfig } from "../types/config";
export const ConfigContext = React.createContext<AppConfig | null>(null);
export function useConfig() {
const context = React.useContext(ConfigContext);
if (context === undefined) {
throw new Error("useConfig must be used within a ConfigProvider");
}
return context;
}

View File

@@ -30,6 +30,7 @@ export interface ResourceConfig {
primaryKey: string;
fields: Record<string, ResourceField>;
pagination?: boolean;
hidden?: boolean;
}
export interface AppConfig {

View File

@@ -12,4 +12,5 @@ export interface FieldOverride {
export interface ResourceOverride {
fields?: Record<string, FieldOverride>;
pagination?: boolean;
hidden?: boolean;
}

View File

@@ -162,6 +162,7 @@ export async function loadConfigFromOpenApi(baseUrl: string, configuration: Reco
primaryKey: "id", // Strict default, no heuristics
fields,
pagination: resourceOverride.pagination,
hidden: resourceOverride.hidden,
});
}