Compare commits

...

32 Commits

Author SHA1 Message Date
77b60ba073 items-by-period (#2)
Reviewed-on: #2
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
2026-05-09 13:00:42 +00:00
f213a9455b Fix pagination bounds in HistoryChart and add responsive grid to TopTags 2026-05-07 16:42:52 +05:30
009ab50b47 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>
2026-05-07 11:00:54 +00:00
b1db439dda fixes for toggles 2026-04-07 13:32:16 +05:30
e4abe61781 fixes for correct labels 2026-04-07 12:48:42 +05:30
cef8f10990 added logic to only show 7 or 6 bars based on daily period or not 2026-04-07 12:16:13 +05:30
3f51d2f869 fixes 2026-04-07 12:01:22 +05:30
692d907ca5 fixes 2026-04-07 11:59:11 +05:30
15c2cce263 comparison amount text height refactor to avoid amount text clipping comparison bar 2026-04-07 11:59:01 +05:30
3704bd0c23 refactored types from HistoryChart.tsx 2026-04-07 11:32:32 +05:30
69c9fd6bef fixed urls (hardcoded /admin) to admin navigation 2026-04-07 11:26:56 +05:30
00c8da629c comparison with proper formatting for diff amount 2026-04-07 11:22:53 +05:30
ce0c34d014 labels with proper formatting 2026-04-07 11:14:04 +05:30
6c305e0cdd labels with proper formatting 2026-04-07 11:12:29 +05:30
b587f8aeb6 compare shows +/- instead of full amounts for easier consumption 2026-04-07 11:06:24 +05:30
6602d29299 fixed compare display 2026-04-07 10:54:57 +05:30
f4e5979c00 fixed compare 2026-04-07 10:49:10 +05:30
e6c7778c08 comparison 2026-04-06 18:39:19 +05:30
f320f6ff31 rolling and calender toggle 2026-04-06 18:31:03 +05:30
fc88703a38 rolling and calender toggle 2026-04-06 18:27:05 +05:30
787324260c rolling and calender toggle 2026-04-06 18:07:38 +05:30
8a866566ba aggre based time week, month, year renamed to daily, weekly, monthly 2026-04-06 17:37:45 +05:30
5f0fa91075 rolling calender 2026-04-06 17:15:00 +05:30
6f1547dde7 relationShip fixes 2026-04-06 17:14:52 +05:30
234f86d6b9 amount formatter 2026-04-06 16:10:09 +05:30
2979634033 5 instead of 10 transactions 2026-04-06 16:09:57 +05:30
b07de2b03c calcuation fixes 2026-04-04 22:42:34 +05:30
4eca3b7124 calcuation fixes 2026-04-04 22:35:17 +05:30
6abed4e72a grid fixes 2026-04-04 22:30:30 +05:30
214c0be44e dashboard fixes 2026-04-04 22:08:39 +05:30
68337ba312 dashboard loader 2026-04-04 20:14:39 +05:30
84059a84b5 rough dashboard components 2026-04-04 19:45:52 +05:30
46 changed files with 1996 additions and 82 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={{
@@ -51,7 +50,7 @@ function Dashboard({ basePath }: { basePath: string }) {
transition: 'transform 0.2s',
'&:hover': { transform: 'translateY(-4px)', boxShadow: 4 }
}}
onClick={() => navigate(`${basePath}/${res.name}`)}
onClick={() => navigate(`/admin/${res.name}`)}
>
<Typography variant="h6" color="primary">{res.pluralLabel}</Typography>
<Typography variant="body2" color="text.secondary">Manage {res.pluralLabel.toLowerCase()}</Typography>
@@ -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
@@ -88,8 +90,8 @@ function AdminApp({ basePath }: { basePath: string }) {
<AdminLayout
username={currentUser.username}
onLogout={logout}
onSelectResource={(name) => navigate(`${basePath}/${name}`)}
resources={config?.resources || []}
onSelectResource={(name) => navigate(`/admin/${name}`)}
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

@@ -104,12 +104,12 @@ export default function EnhancedTable({
<GridActionsCellItem
icon={<VisibilityIcon />}
label="View"
onClick={() => navigate(`/${config.name}/${params.id}`)}
onClick={() => navigate(`/admin/${config.name}/${params.id}`)}
/>,
<GridActionsCellItem
icon={<EditIcon />}
label="Edit"
onClick={() => navigate(`/${config.name}/edit/${params.id}`)}
onClick={() => navigate(`/admin/${config.name}/edit/${params.id}`)}
/>,
<GridActionsCellItem
icon={<DeleteIcon />}
@@ -222,8 +222,8 @@ function MobileCardRow({ row, config, onDelete, onNavigate, navigate }: any) {
<MoreVertIcon fontSize="small" />
</IconButton>
<Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
<MenuItem onClick={() => { handleClose(); navigate(`/${config.name}/${id}`); }}>View</MenuItem>
<MenuItem onClick={() => { handleClose(); navigate(`/${config.name}/edit/${id}`); }}>Edit</MenuItem>
<MenuItem onClick={() => { handleClose(); navigate(`/admin/${config.name}/${id}`); }}>View</MenuItem>
<MenuItem onClick={() => { handleClose(); navigate(`/admin/${config.name}/edit/${id}`); }}>Edit</MenuItem>
<MenuItem onClick={() => { handleClose(); onDelete(id); }} sx={{ color: 'error.main' }}>Delete</MenuItem>
</Menu>
</Box>
@@ -242,7 +242,7 @@ function MobileCardRow({ row, config, onDelete, onNavigate, navigate }: any) {
</Box>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end', px: 2, pb: 2 }}>
<Button size="small" onClick={() => navigate(`/${config.name}/${id}`)}>View Details</Button>
<Button size="small" onClick={() => navigate(`/admin/${config.name}/${id}`)}>View Details</Button>
</CardActions>
</Card>
);
@@ -359,7 +359,7 @@ function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate,
label={value}
size="small"
color="primary"
onClick={(e) => { e.stopPropagation(); navigate(`/${config.name}/${params.row[config.primaryKey]}`); }}
onClick={(e) => { e.stopPropagation(); navigate(`/admin/${config.name}/${params.row[config.primaryKey]}`); }}
sx={{ cursor: 'pointer', fontWeight: 'bold' }}
/>
);

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

@@ -48,11 +48,11 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
const deleteMutation = useDelete();
const handleEdit = (item: any) => {
navigate(`/${config.name}/edit/${item[config.primaryKey]}`);
navigate(`/admin/${config.name}/edit/${item[config.primaryKey]}`);
};
const handleCreate = () => {
navigate(`/${config.name}/create`);
navigate(`/admin/${config.name}/create`);
};
const handleSave = async (formData: any) => {
@@ -62,7 +62,7 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
} else {
await createMutation.mutateAsync(formData);
}
navigate(`/${config.name}`);
navigate(`/admin/${config.name}`);
} catch (err) {
console.error('Save failed:', err);
}
@@ -90,7 +90,7 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
onEdit={handleEdit}
onDelete={handleDelete}
onCreate={handleCreate}
onNavigateToResource={(res, id) => navigate(`/${res}/${id}`)}
onNavigateToResource={(res, id) => navigate(`/admin/${res}/${id}`)}
/>
) : (
<Paper sx={{ p: 4 }}>
@@ -98,10 +98,10 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
config={config}
initialData={isCreate ? null : itemQuery.data}
onSave={handleSave}
onCancel={() => navigate(`/${config.name}`)}
onCancel={() => navigate(`/admin/${config.name}`)}
loading={createMutation.isPending || updateMutation.isPending}
readOnly={isView}
onEditClick={() => navigate(`/${config.name}/edit/${id}`)}
onEditClick={() => navigate(`/admin/${config.name}/edit/${id}`)}
/>
</Paper>
)}

View File

@@ -71,7 +71,7 @@ export default function FormField({
// 2. Relation Handling (Select / Multi-Select)
if (field.relation && relationDataMap[field.relation]) {
const relationData = relationDataMap[field.relation];
const relationData = relationDataMap[field.relation].data;
const isArrayRelation = field.type === 'array';
// Determine how to display the related item

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);
}

7
react-openapi/index.ts Normal file
View File

@@ -0,0 +1,7 @@
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,
});
}

55
src/Dashboard.tsx Normal file
View File

@@ -0,0 +1,55 @@
import * as React from "react";
import {
Box,
Container,
CircularProgress,
Alert
} from "@mui/material";
import ConfigurableDashboard from "./components/Dashboard";
import { configuration } from "./dashboard-config";
import {
useReport,
prepareReport,
} from "./features/report";
export default function Dashboard() {
const report = useReport({
periods: ["weekly", "monthly", "full"],
rolling: true,
include_transactions: true,
group_by: ["tags"],
})
const isLoading = report.isLoading;
const error = report.error;
if (isLoading) {
return (
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
<CircularProgress />
</Box>
);
}
if (error) {
return (
<Container sx={{ mt: 4 }}>
<Alert severity="error">{String(error)}</Alert>
</Container>
);
}
if (!report) {
return null;
}
const data = prepareReport(report.data?.data);
return (
<ConfigurableDashboard
config={configuration}
data={data}
/>
);
}

View File

@@ -83,12 +83,14 @@ export default function Header({
<Typography
variant="h6"
noWrap
sx={{ flexGrow: 1, fontWeight: "bold", cursor: "pointer" }}
sx={{ fontWeight: "bold", cursor: "pointer" }}
onClick={() => navigate("/")}
>
{headerTitle}
</Typography>
<span style={{ flexGrow: 1 }} />
{/* AUTH SECTION */}
{isAuthenticated ? (
<>
@@ -99,6 +101,13 @@ export default function Header({
mr: 2,
}}
>
<Button
color="inherit"
onClick={() => navigate("/admin")}
sx={{ textTransform: "none", fontWeight: 500 }}
>
Admin
</Button>
<Button
color="inherit"
onClick={() => navigate("/admin/profile")}

View File

@@ -84,7 +84,7 @@ export default function Home() {
variant="contained"
size="large"
endIcon={<ArrowForwardIcon />}
onClick={() => navigate("/admin")}
onClick={() => navigate("/dashboard")}
sx={{
px: 4,
py: 1.5,

View File

@@ -0,0 +1,53 @@
import * as React from "react";
import {
ReportData,
GroupKey,
} from "../../features/report";
export type DashboardMode = "expense" | "income";
export type DashboardPeriodType = "rolling" | "calendar";
export type DashboardSelectedPeriodId = string | null;
export interface DashboardState {
mode: DashboardMode;
periodType: DashboardPeriodType;
selectedPeriodId: DashboardSelectedPeriodId;
selectedGroupKey: GroupKey | null;
comparison: boolean;
}
export interface DashboardSection {
id: string;
title?: string;
summary?: string;
component: React.ComponentType<any>;
settings?: Record<string, any>;
isList?: boolean;
style?: {
size?: number;
[key: string]: any;
};
}
export interface ColorDefinition {
primary: string;
background?: string;
text?: string;
}
export interface ThemeAwarePalette {
light: ColorDefinition;
dark: ColorDefinition;
}
export interface DashboardConfig {
sections: DashboardSection[];
style?: {
palette?: Record<DashboardMode, ThemeAwarePalette>;
};
}
export interface DashboardProps {
config: DashboardConfig;
data: ReportData;
}

View File

@@ -0,0 +1,55 @@
import * as React from "react";
import DashboardView from "./Dashboard.view";
import { DashboardProps, DashboardState } from "./Dashboard.models";
export default function Dashboard(props: DashboardProps) {
const [state, setState] = React.useState<DashboardState>({
mode: "expense",
periodType: "rolling",
selectedPeriodId: null,
selectedGroupKey: null,
comparison: false,
});
const toggleMode = () => {
setState(prev => ({
...prev,
mode: prev.mode === "expense" ? "income" : "expense",
}));
};
const togglePeriodType = () => {
setState(prev => ({
...prev,
periodType: prev.periodType === "rolling" ? "calendar" : "rolling",
}));
};
const toggleComparison = () => {
setState(prev => ({
...prev,
comparison: !prev.comparison,
}));
};
const setSelectedPeriodId = (selectedPeriodId: typeof state.selectedPeriodId) => {
setState(prev => ({ ...prev, selectedPeriodId }));
};
const setSelectedGroupKey = (groupKey: typeof state.selectedGroupKey) => {
setState(prev => ({ ...prev, selectedGroupKey: groupKey }));
};
return (
<DashboardView
{...props}
state={state}
setState={setState}
toggleMode={toggleMode}
togglePeriodType={togglePeriodType}
toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId}
setSelectedGroupKey={setSelectedGroupKey}
/>
);
}

View File

@@ -0,0 +1,139 @@
import * as React from "react";
import {
Box,
Container,
Grid,
Typography,
ToggleButton,
ToggleButtonGroup
} from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles";
import { GroupKey } from "../../features/report";
import { DashboardProps, DashboardState } from "./Dashboard.models";
interface ViewProps extends DashboardProps {
state: DashboardState;
setState: React.Dispatch<React.SetStateAction<DashboardState>>;
toggleMode: () => void;
togglePeriodType: () => void;
setSelectedPeriodId: (id: string | null) => void;
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
toggleComparison: () => void;
}
export default function DashboardView({
config,
data,
state,
setState,
toggleMode,
togglePeriodType,
toggleComparison,
setSelectedPeriodId,
setSelectedGroupKey,
}: ViewProps) {
const theme = useTheme();
const themeMode = theme.palette.mode;
const { mode, periodType, comparison, selectedPeriodId, selectedGroupKey } = state;
// Resolve colors with fallbacks
const colors = React.useMemo(() => {
const palette = config.style?.palette?.[mode];
const modeColors = palette ? palette[themeMode] : null;
if (modeColors) {
return {
primary: modeColors.primary,
light: modeColors.background || alpha(modeColors.primary, 0.1),
text: modeColors.text || (themeMode === 'light' ? theme.palette.text.primary : '#fff')
};
}
// Fallback to standard theme colors
const themeColor = mode === 'expense' ? theme.palette.error : theme.palette.success;
return {
primary: themeColor.main,
light: alpha(themeColor.main, themeMode === 'light' ? 0.08 : 0.15),
text: themeColor.main
};
}, [config.style?.palette, mode, themeMode, theme.palette]);
return (
<Container
sx={{
mt: 4,
mb: 4,
background: `linear-gradient(180deg, ${colors.light} 0%, transparent 100%)`,
borderRadius: 4,
p: 2,
transition: 'background 0.3s ease'
}}
>
<Box sx={{ display: "flex", justifyContent: "center", mb: 3 }}>
<ToggleButtonGroup
value={mode}
exclusive
onChange={toggleMode}
sx={{
borderRadius: 3,
overflow: "hidden",
"& .MuiToggleButton-root": {
px: 3,
textTransform: "none",
color: "text.secondary"
},
"&.Mui-selected": {
bgcolor: colors.primary,
color: "white",
borderColor: colors.primary
},
}}
>
<ToggleButton value="expense">Expenses</ToggleButton>
<ToggleButton value="income">Income</ToggleButton>
</ToggleButtonGroup>
</Box>
<Grid container spacing={4}>
{config.sections.map((section) => {
const Component = section.component;
return (
<Grid key={section.id} size={section.style?.size || 12 as any}>
{section.title && !section.isList && (
<Box sx={{ mb: 2 }}>
<Typography variant="h6" fontWeight={700}>
{section.title}
</Typography>
</Box>
)}
<Component
{...section.settings}
header={section.title}
summary={section.summary}
reportData={data}
title={section.title}
accentColor={colors.primary}
colorScheme={colors}
// State management
mode={mode}
periodType={periodType}
comparison={comparison}
selectedPeriodId={selectedPeriodId}
selectedGroupKey={selectedGroupKey}
togglePeriodType={togglePeriodType}
toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId}
setSelectedGroupKey={setSelectedGroupKey}
/>
</Grid>
);
})}
</Grid>
</Container>
);
}

View File

@@ -0,0 +1,2 @@
export { default } from "./Dashboard";
export * from "./Dashboard.models";

View File

@@ -0,0 +1,75 @@
import { ReportData } from "../../features/report";
import {
mergeBucketPeriods,
getAmount,
PeriodKey,
} from "../report.helpers";
import { ChartDataPoint } from "./HistoryChart.models";
// ─── Tab → PeriodKey ─────────────────────────────────────────
const TAB_TO_KEY: Record<string, PeriodKey> = {
Weekly: "weekly",
Monthly: "monthly",
Yearly: "yearly",
"Financial Year": "fyly",
"All Time": "full",
};
export function tabToKey(tab: string): PeriodKey {
return TAB_TO_KEY[tab] ?? "full";
}
// ─── Comparison ──────────────────────────────────────────────
function attachComparison(
points: ChartDataPoint[],
key: PeriodKey
): ChartDataPoint[] {
const getCompareIndex = (i: number) => {
if (key === "weekly") return i - 4;
if (key === "monthly") return i - 12;
if (key === "yearly") return i - 1;
if (key === "fyly") return i - 1;
return -1;
};
return points.map((p, i) => {
const ci = getCompareIndex(i);
return {
...p,
compare:
ci >= 0 && points[ci]
? {
id: points[ci].id,
label: points[ci].label,
amount: points[ci].amount,
}
: undefined,
};
});
}
// ─── Main adapter ────────────────────────────────────────────
export function buildChartData(
reportData: ReportData,
key: PeriodKey,
mode: "expense" | "income",
comparison: boolean
): ChartDataPoint[] {
const merged = mergeBucketPeriods(reportData.buckets, key);
let points: ChartDataPoint[] = merged.map((p) => ({
id: p.id,
label: p.label,
amount: getAmount(p, mode),
}));
if (comparison) {
points = attachComparison(points, key);
}
return points;
}

View File

@@ -0,0 +1,40 @@
import {
DashboardMode,
DashboardPeriodType,
DashboardSelectedPeriodId
} from "../Dashboard";
import { ReportData } from "../../features/report";
export interface _ChartDataPoint {
id: string;
label: string;
amount: number;
highlighted?: boolean;
}
export interface ChartDataPoint extends _ChartDataPoint {
compare?: _ChartDataPoint;
}
export interface HistoryChartProps {
header: string;
summary?: string;
tabs: string[];
reportData: ReportData;
colorScheme: {
primary: string;
light: string;
text: string;
};
mode: DashboardMode;
periodType: DashboardPeriodType;
selectedPeriodId: DashboardSelectedPeriodId;
comparison: boolean;
togglePeriodType: () => void;
setSelectedPeriodId: (id: string | null) => void;
toggleComparison: () => void;
}

View File

@@ -0,0 +1,92 @@
import * as React from "react";
import { HistoryChartProps } from "./HistoryChart.models";
import HistoryChartView from "./HistoryChart.view";
import { buildChartData, tabToKey } from "./HistoryChart.adapter";
export default function HistoryChart(props: HistoryChartProps) {
const {
tabs,
reportData,
mode,
comparison,
selectedPeriodId,
setSelectedPeriodId
} = props;
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
const [startIndex, setStartIndex] = React.useState(0);
const activeDataKey = tabToKey(activeTab);
const currentData = React.useMemo(() => {
return buildChartData(reportData, activeDataKey, mode, comparison);
}, [reportData, activeDataKey, mode, comparison]);
const maxAmount =
currentData.length > 0
? Math.max(
...currentData.flatMap((d) =>
comparison
? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
: [d.amount]
),
1
)
: 1;
const visibleCountMap = {
weekly: 6,
monthly: 4,
yearly: 4,
fyly: 4,
full: 4,
};
const visibleCount = visibleCountMap[activeDataKey] ?? 4;
const total = currentData.length;
const clampedStartIndex = Math.min(
startIndex,
Math.max(total - visibleCount, 0)
);
React.useEffect(() => {
if (startIndex !== clampedStartIndex) {
setStartIndex(clampedStartIndex);
}
}, [startIndex, clampedStartIndex]);
const visibleData = currentData.slice(
clampedStartIndex,
clampedStartIndex + visibleCount
);
React.useEffect(() => {
setSelectedPeriodId(null);
}, [activeTab]);
React.useEffect(() => {
if (
selectedPeriodId &&
!visibleData.some((p) => p.id === selectedPeriodId)
) {
setSelectedPeriodId(null);
}
}, [visibleData, selectedPeriodId]);
return (
<HistoryChartView
{...props}
activeTab={activeTab}
setActiveTab={setActiveTab}
currentData={currentData}
visibleData={visibleData}
maxAmount={maxAmount}
visibleCount={visibleCount}
startIndex={clampedStartIndex}
setStartIndex={setStartIndex}
activeDataKey={activeDataKey}
/>
);
}

View File

@@ -0,0 +1,27 @@
import { ChartDataPoint } from "./HistoryChart.models";
export const formatDisplay = (
point: ChartDataPoint,
tab: string,
comparison: boolean
) => {
const base = point.amount;
const cmp = point.compare?.amount ?? 0;
const formatShort = (val: number) => {
if (tab === "monthly" && val >= 100000) {
return `${(val / 100000).toFixed(2)}L`;
}
if (tab === "weekly" && val >= 1000) {
return `${(val / 1000).toFixed(1)}K`;
}
return val.toLocaleString("en-IN");
};
if (!comparison) return `${formatShort(base)}`;
const diff = base - cmp;
const sign = diff >= 0 ? "+" : "-";
return `${formatShort(base)} (${sign}${formatShort(Math.abs(diff))})`;
};

View File

@@ -0,0 +1,217 @@
import * as React from "react";
import {
Box,
Typography,
ToggleButtonGroup,
ToggleButton,
Paper
} from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles";
import IconButton from "@mui/material/IconButton";
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
import {
ChartDataPoint,
HistoryChartProps,
} from "./HistoryChart.models";
import { formatDisplay } from "./HistoryChart.utils";
interface ViewProps extends HistoryChartProps {
activeTab: string;
setActiveTab: (v: string) => void;
currentData: ChartDataPoint[];
visibleData: ChartDataPoint[];
maxAmount: number;
visibleCount: number;
startIndex: number;
setStartIndex: React.Dispatch<React.SetStateAction<number>>;
activeDataKey: string;
}
export default function HistoryChartView(props: ViewProps) {
const {
header,
summary,
tabs,
colorScheme,
mode,
periodType,
selectedPeriodId,
comparison,
togglePeriodType,
setSelectedPeriodId,
toggleComparison,
activeTab,
setActiveTab,
currentData,
visibleData,
maxAmount,
visibleCount,
startIndex,
setStartIndex,
activeDataKey,
} = props;
const theme = useTheme();
const isDark = theme.palette.mode === "dark";
const total = currentData.length;
const maxStartIndex = Math.max(total - visibleCount, 0);
const clampedStartIndex = Math.min(startIndex, maxStartIndex);
const handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => {
if (newTab !== null) setActiveTab(newTab);
};
const canGoLeft = clampedStartIndex > 0;
const canGoRight = clampedStartIndex < maxStartIndex;
const handlePrev = () => {
if (!canGoLeft) return;
setStartIndex((prev) => Math.max(prev - visibleCount, 0));
};
const handleNext = () => {
if (!canGoRight) return;
setStartIndex((prev) => {
const next = prev + visibleCount;
return Math.min(next, maxStartIndex);
});
};
return (
<Paper
sx={{
p: { xs: 2.5, sm: 4 },
borderRadius: 4,
width: "100%",
boxShadow: "none",
border: "1px solid",
borderColor: "divider",
bgcolor: isDark ? "background.paper" : colorScheme.light,
}}
>
<Typography variant="h6" fontWeight={700} gutterBottom>
{header}
</Typography>
{summary && (
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
{summary}
</Typography>
)}
<ToggleButtonGroup value={activeTab} exclusive onChange={handleTabChange} fullWidth sx={{ mb: 4 }}>
{tabs.map((tab) => (
<ToggleButton key={tab} value={tab}>
{tab}
</ToggleButton>
))}
</ToggleButtonGroup>
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}>
<ToggleButtonGroup value={periodType} exclusive onChange={togglePeriodType} size="small">
<ToggleButton value="rolling">Rolling</ToggleButton>
<ToggleButton value="calendar">Calendar</ToggleButton>
</ToggleButtonGroup>
<ToggleButton
value="compare"
selected={comparison}
onChange={toggleComparison}
size="small"
>
Compare
</ToggleButton>
</Box>
{currentData.length > 0 ? (
<Box sx={{ position: "relative", mt: 4 }}>
{canGoLeft && (
<IconButton onClick={handlePrev} size="small" sx={{ position: "absolute", left: 0, top: "50%" }}>
<ChevronLeftIcon fontSize="small" />
</IconButton>
)}
<Box sx={{ display: "flex", alignItems: "flex-end", height: 220, mt: 4 }}>
{visibleData.map((point) => {
const currentHeight = (point.amount / maxAmount) * 100;
const compareHeight = comparison
? ((point.compare?.amount ?? 0) / maxAmount) * 100
: 0;
const isSelected = selectedPeriodId === point.id;
const display = formatDisplay(point, activeDataKey, comparison);
return (
<Box
key={point.id}
onClick={() =>
setSelectedPeriodId(isSelected ? null : point.id)
}
sx={{
flex: 1,
display: "flex",
flexDirection: "column",
alignItems: "center",
cursor: "pointer",
height: "100%"
}}
>
<Box sx={{ display: "flex", alignItems: "flex-end", gap: 1, height: "100%" }}>
{comparison && (
<Box
sx={{
width: 8,
height: `${compareHeight}%`,
bgcolor: alpha(colorScheme.primary, 0.4),
borderRadius: "4px 4px 0 0"
}}
/>
)}
<Box
sx={{
width: 12,
height: `${currentHeight}%`,
bgcolor: isSelected ? "warning.main" : colorScheme.primary,
borderRadius: "4px 4px 0 0"
}}
/>
</Box>
<Typography variant="caption">
{point.label}
</Typography>
{comparison && point.compare && (
<Typography variant="caption" color="text.secondary">
{point.compare.label}
</Typography>
)}
<Typography variant="caption">
{display}
</Typography>
</Box>
);
})}
</Box>
{canGoRight && (
<IconButton onClick={handleNext} size="small" sx={{ position: "absolute", right: 0, top: "50%" }}>
<ChevronRightIcon fontSize="small" />
</IconButton>
)}
</Box>
) : (
<Box sx={{ height: 200, display: "flex", alignItems: "center", justifyContent: "center" }}>
<Typography color="text.secondary">No Data Available</Typography>
</Box>
)}
</Paper>
);
}

View File

@@ -0,0 +1,2 @@
export { default } from "./HistoryChart";
export * from "./HistoryChart.models";

View File

@@ -0,0 +1,66 @@
import { ReportData, Transaction, GroupKey } from "../../features/report";
import {
mergeBucketPeriods,
periodIdToKey,
formatCurrency,
filterBuckets,
} from "../report.helpers";
import { LatestItem } from "./LatestItems.models";
// ─── Transaction extraction ─────────────────────────────────
function extractTransactions(
reportData: ReportData,
selectedPeriodId: string | null,
selectedGroupKey: GroupKey | null,
mode: "expense" | "income"
): Transaction[] {
const buckets = filterBuckets(reportData.buckets, selectedGroupKey);
if (selectedPeriodId) {
const key = periodIdToKey(selectedPeriodId);
const periods = mergeBucketPeriods(buckets, key);
const selected = periods.find((p) => p.id === selectedPeriodId);
if (!selected) return [];
return mode === "expense"
? (selected.expenses.transactions || [])
: (selected.incomes.transactions || []);
}
const periods = mergeBucketPeriods(buckets, "full");
if (!periods.length) return [];
const full = periods[0];
return mode === "expense"
? (full.expenses.transactions || [])
: (full.incomes.transactions || []);
}
// ─── Main adapter ────────────────────────────────────────────
export function buildLatestItems(
reportData: ReportData,
selectedPeriodId: string | null,
selectedGroupKey: GroupKey | null,
mode: "expense" | "income"
): LatestItem[] {
const txns = extractTransactions(reportData, selectedPeriodId, selectedGroupKey, mode);
return txns
.filter((t) => (mode === "expense" ? t.amount < 0 : t.amount >= 0))
.sort(
(a, b) =>
new Date(b.occurred_at).getTime() -
new Date(a.occurred_at).getTime()
)
.map((t, index) => ({
id: index + 1,
title: t.payee.name,
subtitle: t.tags.map((tag) => tag.name).join(", "),
amount: formatCurrency(t.amount),
timeAgo: new Date(t.occurred_at).toLocaleDateString("en-IN"),
}));
}

View File

@@ -0,0 +1,14 @@
export interface LatestItem {
id: string | number;
title: string;
subtitle: string;
amount: string;
timeAgo: string;
}
export interface LatestItemsViewProps {
items: LatestItem[];
accentColor: string;
canExpand: boolean;
onExpand: () => void;
}

View File

@@ -0,0 +1,44 @@
import * as React from "react";
import { ReportData, GroupKey } from "../../features/report";
import { buildLatestItems } from "./LatestItems.adapter";
import LatestItemsView from "./LatestItems.view";
type Props = {
reportData: ReportData;
mode: "expense" | "income";
selectedPeriodId: string | null;
selectedGroupKey?: GroupKey | null;
accentColor: string;
};
export default function LatestItems({
reportData,
mode,
selectedPeriodId,
selectedGroupKey = null,
accentColor,
}: Props) {
const [visibleCount, setVisibleCount] = React.useState(5);
const allItems = React.useMemo(() => {
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, mode);
}, [reportData, selectedPeriodId, selectedGroupKey, mode]);
const hasSelection = Boolean(selectedPeriodId) || Boolean(selectedGroupKey);
const visibleItems = React.useMemo(() => {
if (!hasSelection) return allItems.slice(0, 5);
return allItems.slice(0, visibleCount);
}, [allItems, hasSelection, visibleCount]);
const canExpand = hasSelection && visibleCount < allItems.length;
return (
<LatestItemsView
items={visibleItems}
accentColor={accentColor}
canExpand={canExpand}
onExpand={() => setVisibleCount((prev) => prev + 5)}
/>
);
}

View File

@@ -0,0 +1,88 @@
import * as React from "react";
import {
List,
ListItem,
ListItemAvatar,
ListItemText,
Avatar,
Typography,
Box,
IconButton,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { LatestItemsViewProps } from "./LatestItems.models";
export default function LatestItemsView({
items,
accentColor,
canExpand,
onExpand,
}: LatestItemsViewProps) {
return (
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
<Box sx={{ mb: 2, px: 2 }}>
<Typography variant="h6" fontWeight="bold">
Recent Transactions
</Typography>
</Box>
<List disablePadding>
{items.map((item, index) => (
<ListItem
key={item.id}
sx={{
px: { xs: 1, sm: 2 },
py: 2,
mb: index !== items.length - 1 ? 1 : 0,
borderRadius: 3,
"&:hover": { bgcolor: "action.hover" },
}}
>
<ListItemAvatar>
<Avatar
variant="rounded"
sx={{
bgcolor: `${accentColor}22`,
width: 48,
height: 48,
borderRadius: 3,
mr: 2,
}}
/>
</ListItemAvatar>
<ListItemText
primary={
<Typography variant="subtitle1" fontWeight={600}>
{item.title}
</Typography>
}
secondary={
<Typography variant="body2" color="text.secondary">
{item.subtitle}
</Typography>
}
/>
<Box sx={{ textAlign: "right" }}>
<Typography variant="subtitle1" fontWeight={700}>
{item.amount}
</Typography>
<Typography variant="caption" color="text.secondary">
{item.timeAgo}
</Typography>
</Box>
</ListItem>
))}
{canExpand && (
<Box sx={{ display: "flex", justifyContent: "center", mt: 2 }}>
<IconButton size="small" onClick={onExpand}>
<ExpandMoreIcon />
</IconButton>
</Box>
)}
</List>
</Box>
);
}

View File

@@ -0,0 +1,2 @@
export { default } from "./LatestItems";
export * from "./LatestItems.models";

View File

@@ -0,0 +1,10 @@
export interface ProgressCardProps {
header: string;
summary?: string;
progressAmount: number;
totalAmount: number;
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
compact?: boolean;
selected?: boolean;
onClick?: () => void;
}

View File

@@ -0,0 +1,25 @@
import * as React from "react";
import ProgressCardView from "./ProgressCard.view";
import { ProgressCardProps } from "./ProgressCard.models";
import { getPercentage, formatCurrency } from "../report.helpers";
export default function ProgressCard(props: ProgressCardProps) {
const { progressAmount, totalAmount, compact = false } = props;
const percentage = getPercentage(progressAmount, totalAmount);
const formattedProgress = formatCurrency(progressAmount);
const formattedTotal = formatCurrency(totalAmount);
return (
<ProgressCardView
{...props}
percentage={percentage}
formattedProgress={formattedProgress}
formattedTotal={formattedTotal}
compact={compact}
selected={props.selected}
onClick={props.onClick}
/>
);
}

View File

@@ -0,0 +1,141 @@
import * as React from "react";
import {
Box,
Typography,
Paper,
LinearProgress,
Divider,
linearProgressClasses
} from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles";
import { ProgressCardProps } from "./ProgressCard.models";
interface ViewProps extends ProgressCardProps {
percentage: number;
formattedProgress: string;
formattedTotal: string;
selected?: boolean;
onClick?: () => void;
}
export default function ProgressCardView({
header,
colorTheme = "info",
percentage,
formattedProgress,
formattedTotal,
compact = false,
selected,
onClick,
}: ViewProps) {
const theme = useTheme();
const isDark = theme.palette.mode === "dark";
return (
<Paper
elevation={compact ? 2 : 4}
onClick={onClick}
sx={{
width: "100%",
p: compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
borderRadius: compact ? 3 : 4,
cursor: onClick ? "pointer" : "default",
transform: selected ? "scale(1.02)" : "scale(1)",
transition: "transform 0.2s ease, box-shadow 0.2s ease",
background: (theme) => {
const baseColor = theme.palette[colorTheme]?.main || theme.palette.primary.main;
const lightColor = theme.palette[colorTheme]?.light || theme.palette.primary.light;
return isDark
? `linear-gradient(135deg, ${alpha(baseColor, 0.9)} 0%, ${alpha(baseColor, 0.3)} 100%)`
: `linear-gradient(135deg, ${baseColor} 0%, ${lightColor} 100%)`;
},
color: "#fff",
display: "flex",
flexDirection: "column",
alignItems: compact ? "flex-start" : "center",
justifyContent: "center",
position: "relative",
overflow: "hidden",
border: selected
? `2px solid #fff`
: isDark ? "1px solid rgba(255,255,255,0.1)" : "none",
boxShadow: (theme) => {
const baseShadow = `0 ${compact ? 6 : 12}px ${compact ? 12 : 24}px -10px ${
isDark
? "rgba(0,0,0,0.5)"
: theme.palette[colorTheme]?.main || theme.palette.primary.main
}`;
return selected
? `${baseShadow}, 0 0 0 2px ${theme.palette.background.paper}, 0 0 0 4px ${theme.palette[colorTheme]?.main || theme.palette.primary.main}`
: baseShadow;
},
}}
>
<Typography
variant={compact ? "body2" : "subtitle1"}
fontWeight={700}
sx={{
opacity: 0.95,
mb: compact ? 1.5 : 2,
width: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
letterSpacing: 0.5,
textShadow: isDark ? '0 1px 2px rgba(0,0,0,0.3)' : 'none'
}}
>
{header}
</Typography>
<Box sx={{ mb: compact ? 2 : 3, width: '100%' }}>
<Typography
variant={compact ? "h5" : "h3"}
fontWeight={900}
sx={{ mb: 0.5, lineHeight: 1.2, textShadow: isDark ? '0 2px 4px rgba(0,0,0,0.3)' : 'none' }}
>
{formattedProgress}
</Typography>
<Divider
sx={{
my: 1,
borderColor: "rgba(255,255,255,0.25)",
width: "100%",
}}
/>
<Typography
variant={compact ? "caption" : "body2"}
sx={{
opacity: 0.85,
fontWeight: 500,
display: "block",
color: "rgba(255,255,255,0.9)"
}}
>
of {formattedTotal}
</Typography>
</Box>
<Box sx={{ width: "100%", mt: 'auto' }}>
<LinearProgress
variant="determinate"
value={percentage}
sx={{
height: compact ? 6 : 10,
borderRadius: 5,
[`&.${linearProgressClasses.colorPrimary}`]: {
backgroundColor: "rgba(0, 0, 0, 0.25)",
},
[`& .${linearProgressClasses.bar}`]: {
borderRadius: 5,
backgroundColor: "#fff",
boxShadow: '0 0 8px rgba(255,255,255,0.4)'
},
}}
/>
</Box>
</Paper>
);
}

View File

@@ -0,0 +1,74 @@
import { ReportData } from "../../features/report";
import {
getAmount,
DecoratedPeriod,
} from "../report.helpers";
// ─── Helpers ─────────────────────────────────────────────────
function findPeriod(
periods: DecoratedPeriod[],
selectedPeriodId?: string | null
) {
if (!periods.length) return null;
if (selectedPeriodId) {
const match = periods.find((p) => p.id === selectedPeriodId);
if (match) return match;
}
// fallback → latest
return periods.reduce((latest, p) =>
new Date(p.start).getTime() > new Date(latest.start).getTime()
? p
: latest
);
}
// ─── Main adapter ────────────────────────────────────────────
export interface TagItem {
tag: string;
amount: number;
}
export function extractTopTags(
reportData: ReportData,
mode: "expense" | "income",
selectedPeriodId?: string | null
): { items: TagItem[]; total: number } {
const tagMap = new Map<string, number>();
for (const bucket of reportData.buckets) {
const tags = bucket.group_key.tags;
if (!tags || tags.length === 0) continue;
// Prefer FULL if available
const fullPeriods = (bucket.periods.full || []) as DecoratedPeriod[];
const periodsToUse = selectedPeriodId
? (Object.values(bucket.periods).flat() as DecoratedPeriod[])
: fullPeriods;
const period = findPeriod(periodsToUse, selectedPeriodId);
if (!period) continue;
const amount = getAmount(period, mode);
for (const tag of tags) {
tagMap.set(tag, (tagMap.get(tag) || 0) + amount);
}
}
const arr = Array.from(tagMap.entries()).map(([tag, amount]) => ({
tag,
amount,
}));
arr.sort((a, b) => b.amount - a.amount);
const top = arr.slice(0, 4);
const total = top.reduce((sum, t) => sum + t.amount, 0);
return { items: top, total };
}

View File

@@ -0,0 +1,61 @@
import * as React from "react";
import { Box } from "@mui/material";
import { ReportData, GroupKey } from "../../features/report";
import ProgressCard from "./ProgressCard";
import { extractTopTags } from "./TopTags.adapter";
type Props = {
reportData: ReportData;
mode: "expense" | "income";
selectedPeriodId?: string | null;
selectedGroupKey?: GroupKey | null;
setSelectedGroupKey?: (key: GroupKey | null) => void;
compact?: boolean;
};
export default function TopTags({
reportData,
mode,
selectedPeriodId,
selectedGroupKey,
setSelectedGroupKey,
compact = true,
}: Props) {
const { items, total } = React.useMemo(() => {
return extractTopTags(reportData, mode, selectedPeriodId);
}, [reportData, mode, selectedPeriodId]);
return (
<Box
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "repeat(2, 1fr)",
md: "repeat(4, 1fr)",
},
gap: 2,
}}
>
{items.map((item) => {
const isSelected = selectedGroupKey?.tags?.includes(item.tag);
return (
<ProgressCard
key={item.tag}
header={item.tag}
progressAmount={item.amount}
totalAmount={total}
compact={compact}
colorTheme={mode === "expense" ? "error" : "success"}
selected={isSelected}
onClick={() => {
if (setSelectedGroupKey) {
setSelectedGroupKey(isSelected ? null : { tags: [item.tag] });
}
}}
/>
);
})}
</Box>
);
}

View File

@@ -0,0 +1,2 @@
export { default } from "./ProgressCard";
export * from "./ProgressCard.models";

View File

@@ -0,0 +1,147 @@
import {
ReportPeriod,
ReportBucket,
GroupKey,
} from "../features/report";
// ─── Types ────────────────────────────────────────────────────
export type PeriodKey = "weekly" | "monthly" | "yearly" | "fyly" | "full";
export type DecoratedPeriod = ReportPeriod & {
id: string;
label: string;
};
// ─── Period helpers ───────────────────────────────────────────
const PREFIX_TO_KEY: Record<string, PeriodKey> = {
W: "weekly",
M: "monthly",
Y: "yearly",
FY: "fyly",
FULL: "full",
};
/**
* Derive the period key from a decorated-period id.
* E.g. `"W:2026-04-28_2026-05-04"` → `"weekly"`
*/
export function periodIdToKey(periodId: string): PeriodKey {
const prefix = periodId.split(":")[0];
return PREFIX_TO_KEY[prefix] ?? "full";
}
// ─── Metric helpers ───────────────────────────────────────────
export function getAmount(
period: ReportPeriod,
mode: "expense" | "income"
): number {
return mode === "expense" ? period.expenses.sum : period.incomes.sum;
}
function mergeMetric(a: ReportPeriod["expenses"], b: ReportPeriod["expenses"]) {
const sum = a.sum + b.sum;
const count = a.count + b.count;
return {
...a,
sum,
count,
average: count > 0 ? sum / count : 0,
transactions:
a.transactions || b.transactions
? [...(a.transactions || []), ...(b.transactions || [])]
: undefined,
};
}
/**
* Merge periods with the same id across all buckets, summing
* their metrics and concatenating transactions.
*
* Returns sorted by start date ascending.
*/
export function mergeBucketPeriods(
buckets: ReportBucket[],
key: PeriodKey
): DecoratedPeriod[] {
const map = new Map<string, DecoratedPeriod>();
for (const bucket of buckets) {
const periods = (bucket.periods[key] || []) as DecoratedPeriod[];
for (const p of periods) {
const existing = map.get(p.id);
if (!existing) {
map.set(p.id, {
...p,
expenses: { ...p.expenses },
incomes: { ...p.incomes },
});
} else {
map.set(p.id, {
...existing,
expenses: mergeMetric(existing.expenses, p.expenses),
incomes: mergeMetric(existing.incomes, p.incomes),
});
}
}
}
return Array.from(map.values()).sort(
(a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()
);
}
// ─── Formatting ───────────────────────────────────────────────
export const formatCurrency = (val: number) => {
const absVal = Math.abs(val);
if (absVal >= 100000) {
return `${(val / 100000).toFixed(2)}L`;
}
if (absVal >= 1000) {
return `${(val / 1000).toFixed(2)}k`;
}
return `${val.toFixed(2)}`;
};
export const getPercentage = (progressAmount: number, totalAmount: number) => {
if (!totalAmount) return 0;
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
};
// ─── Group filtering ──────────────────────────────────────────
/**
* Check if a bucket's group_key matches the selected GroupKey.
* Every dimension present in `selected` must exist in the bucket
* and contain all the selected values.
*/
export function matchesGroupKey(
bucket: ReportBucket,
selected: GroupKey
): boolean {
for (const [dim, values] of Object.entries(selected)) {
const bucketValues = bucket.group_key[dim as keyof GroupKey];
if (!bucketValues) return false;
if (!(values as string[]).every((v) => bucketValues.includes(v)))
return false;
}
return true;
}
/**
* Return only buckets matching the selected group key,
* or all buckets if no selection.
*/
export function filterBuckets(
buckets: ReportBucket[],
selectedGroupKey: GroupKey | null
): ReportBucket[] {
if (!selectedGroupKey) return buckets;
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
}

68
src/dashboard-config.ts Normal file
View File

@@ -0,0 +1,68 @@
import HistoryChart from "./components/HistoryChart";
import LatestItems from "./components/LatestItems";
import { DashboardConfig } from "./components/Dashboard";
import TopTags from "./components/ProgressCard/TopTags";
export const configuration: DashboardConfig = {
sections: [
{
id: "breakdown",
title: "Breakdown",
summary: "Interactive chronological tracking",
component: HistoryChart,
settings: {
tabs: ["Weekly", "Monthly"],
// tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"],
},
style: {
size: 12,
},
},
{
id: "top-categories",
title: 'Top Categories',
component: TopTags,
settings: {
compact: true,
},
style: {
size: 12,
},
},
{
id: "items",
component: LatestItems,
style: {
size: 12,
},
},
],
style: {
palette: {
expense: {
light: {
primary: "#d32f2f",
background: "#fdecea",
text: "#b71c1c"
},
dark: {
primary: "#f44336",
background: "rgba(244, 67, 54, 0.15)",
text: "#ffcdd2"
}
},
income: {
light: {
primary: "#2e7d32",
background: "#e8f5e9",
text: "#1b5e20"
},
dark: {
primary: "#4caf50",
background: "rgba(76, 175, 80, 0.15)",
text: "#c8e6c9"
}
}
}
}
};

View File

@@ -0,0 +1,13 @@
export {
useReport
} from './useReport'
export type {
Transaction,
ReportData,
ReportBucket,
ReportPeriod,
GroupKey,
} from './report.models'
export {
prepareReport
} from './report.utils'

View File

@@ -0,0 +1,90 @@
export interface Payor {
name: string;
}
export interface Payee {
name: string;
}
export interface Account {
name: string;
number: string;
}
export interface Tag {
name: string;
icon: string;
description: string;
}
export interface Transaction {
payor: Payor;
payee: Payee;
amount: number;
account: Account;
tags: Tag[];
occurred_at: Date;
}
// -----------------------------
// Metrics
// -----------------------------
export interface ReportMetric {
sum: number;
count: number;
average: number;
transactions?: Transaction[];
}
// -----------------------------
// Period
// -----------------------------
export interface ReportPeriod {
start: Date;
end: Date;
expenses: ReportMetric;
incomes: ReportMetric;
}
// -----------------------------
// Group (bucket)
// -----------------------------
export type GroupKey = {
payee?: string[];
tags?: string[];
flow?: string[];
};
export interface ReportBucket {
group_key: GroupKey;
periods: {
weekly?: ReportPeriod[];
monthly?: ReportPeriod[];
yearly?: ReportPeriod[];
fyly?: ReportPeriod[];
full?: ReportPeriod[];
};
}
// -----------------------------
// Final Report
// -----------------------------
export interface ReportData {
periods: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
rolling: boolean;
report_date?: string;
group_by: ("payee" | "tags")[];
ignore_self: boolean;
include_transactions: boolean;
buckets: ReportBucket[];
}

View File

@@ -0,0 +1,131 @@
import {
ReportData,
ReportPeriod
} from "./report.models";
/* ---------- ID BUILDING ---------- */
function formatDate(d: Date): string {
const y = d.getUTCFullYear();
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
const day = String(d.getUTCDate()).padStart(2, "0");
return `${y}-${m}-${day}`;
}
function buildPeriodId(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
start: Date,
end: Date
): string {
const s = formatDate(start);
const e = formatDate(end);
switch (type) {
case "weekly":
return `W:${s}_${e}`;
case "monthly":
return `M:${s}_${e}`;
case "yearly":
return `Y:${s}_${e}`;
case "fyly":
return `FY:${s}_${e}`;
case "full":
return `FULL:${s}_${e}`;
default:
return `${s}_${e}`;
}
}
/* ---------- LABEL BUILDING ---------- */
const dayFmt = new Intl.DateTimeFormat("en-GB", {
day: "numeric",
month: "short",
timeZone: "UTC",
});
const monthDayFmt = new Intl.DateTimeFormat("en-GB", {
month: "short",
day: "numeric",
timeZone: "UTC",
});
const monthFmt = new Intl.DateTimeFormat("en-GB", {
month: "short",
timeZone: "UTC",
});
const yearFmt = new Intl.DateTimeFormat("en-GB", {
year: "numeric",
timeZone: "UTC",
});
function sameMonth(a: Date, b: Date) {
return (
a.getUTCFullYear() === b.getUTCFullYear() &&
a.getUTCMonth() === b.getUTCMonth()
);
}
function buildLabel(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
start: Date,
end: Date
): string {
switch (type) {
case "weekly": {
const sDay = start.getUTCDate();
const m = monthFmt.format(start);
return `${sDay} ${m}`;
}
case "monthly":
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
case "yearly":
return yearFmt.format(start);
case "fyly": {
const startY = start.getUTCFullYear();
const endY = end.getUTCFullYear();
return `FY ${startY}${String(endY).slice(-2)}`;
}
default:
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
}
}
/* ---------- MAIN ---------- */
function decoratePeriods(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
periods: ReportPeriod[]
): (ReportPeriod & { id: string; label: string })[] {
return periods.map((p) => ({
...p,
id: buildPeriodId(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
label: buildLabel(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
}));
}
export function prepareReport(reportData: ReportData): ReportData {
return {
...reportData,
buckets: reportData.buckets.map((bucket) => {
const newPeriods: typeof bucket.periods = {};
for (const type of reportData.periods) {
const arr = bucket.periods[type];
if (arr) {
newPeriods[type] = decoratePeriods(type, arr);
}
}
return {
...bucket,
periods: newPeriods,
};
}),
};
}

View File

@@ -0,0 +1,20 @@
import { useResourceByName } from "../../../react-openapi";
export interface ReportParams {
periods?: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
rolling?: boolean;
report_date?: string;
group_by?: ("payee" | "tags")[];
ignore_self?: boolean;
include_transactions?: boolean;
}
export function useReport(params: ReportParams) {
const { useList } = useResourceByName("reports");
return useList({
...params,
periods: params.periods,
group_by: params.group_by,
});
}

View File

@@ -11,7 +11,8 @@ import {
Toolbar
} from "@mui/material";
import Home from './Home';
import { Admin, initializeApiClients } from '../react-openapi';
import Dashboard from './Dashboard';
import { Admin, AppProvider } from '../react-openapi';
import { configuration, profileConfiguration } from './openapi-config';
import { Buffer } from 'buffer';
import process from 'process';
@@ -20,54 +21,52 @@ import Header from './Header';
import Footer from './Footer';
import AppTheme from './AppTheme';
// Polyfill Node.js globals for browser environment (needed by SwaggerParser)
window.Buffer = Buffer;
window.process = process;
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
const API_BASE = import.meta.env.VITE_API_BASE_URL;
const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;
// Initialize global API clients so all components across khata-ui have generic API access
initializeApiClients(API_BASE, AUTH_BASE);
const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;
const routerMapping = [
{ path: "/", component: Home, headerTitle: "Home" },
{ path: "/home", component: Home, headerTitle: "Home" },
{ path: "/dashboard", component: Dashboard, headerTitle: "Dashboard" },
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
];
root.render(
<BrowserRouter>
<AuthProvider authBaseUrl={AUTH_BASE}>
<AppTheme>
<CssBaseline enableColorScheme />
<Header routerMapping={routerMapping} />
<AppProvider resourceOverrides={configuration} profileConfig={profileConfiguration}>
<BrowserRouter>
<AuthProvider authBaseUrl={AUTH_BASE}>
<AppTheme>
<CssBaseline enableColorScheme />
<Header routerMapping={routerMapping} />
<Box sx={{ pb: 8 }}>
<Toolbar />
<Box sx={{ pb: 8 }}>
<Toolbar />
<Routes>
{routerMapping.map(({ path, component: Component }) => (
<Route
key={path}
path={path}
element={
path.startsWith("/admin") ? (
<Component basePath="/admin" resourceOverrides={configuration} profileConfig={profileConfiguration} />
) : (
<Component />
)
}
/>
))}
</Routes>
<Routes>
{routerMapping.map(({ path, component: Component }) => (
<Route
key={path}
path={path}
element={
path.startsWith("/admin") ? (
<Component basePath="/admin" />
) : (
<Component />
)
}
/>
))}
</Routes>
</Box>
</Box>
<Footer />
</AppTheme>
</AuthProvider>
</BrowserRouter>
<Footer />
</AppTheme>
</AuthProvider>
</BrowserRouter>
</AppProvider>
);

View File

@@ -40,6 +40,9 @@ export const configuration: Record<string, ResourceOverride> = {
},
pagination: true,
},
reports: {
hidden: true
}
};
export const profileConfiguration = {