Compare commits
36 Commits
items-by-p
...
df5cf9fbb6
| Author | SHA1 | Date | |
|---|---|---|---|
| df5cf9fbb6 | |||
| 4b046c15a5 | |||
| 02eb55995e | |||
| 4e56d86cdb | |||
| 15f76eb5f0 | |||
| 7470da6d2d | |||
| 34594215f9 | |||
| 0a92126b92 | |||
| 30cf227050 | |||
| a0e62b1bc4 | |||
| ea3b451266 | |||
| 4b4875c3f5 | |||
| 25bd882b75 | |||
| f684083496 | |||
| 0e0928af95 | |||
| 7b0b3fb615 | |||
| 38f7416942 | |||
| e82cad4f21 | |||
| 1daa90d091 | |||
| 2d0b0bc470 | |||
| 5f85abdf86 | |||
| cc7e6509d2 | |||
| 8a3ebdb1be | |||
| a36d9119bb | |||
| 67d4c85146 | |||
| 89ad8e376e | |||
| 71afc157ff | |||
| 5acbb7ccdd | |||
| 3fd20f11ab | |||
| 922d05ae37 | |||
| 1fe44abfde | |||
| 49bdb85088 | |||
| b1509fd5ab | |||
| 175ca64d1f | |||
| c9e609fee6 | |||
| 82264a5c34 |
@@ -1,5 +1,4 @@
|
|||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
||||||
import { useAuth, AuthPage } from "../react-auth";
|
import { useAuth, AuthPage } from "../react-auth";
|
||||||
import { UploadProvider } from "./providers/UploadProvider";
|
import { UploadProvider } from "./providers/UploadProvider";
|
||||||
import AdminLayout from "./components/AdminLayout";
|
import AdminLayout from "./components/AdminLayout";
|
||||||
@@ -13,17 +12,17 @@ import {
|
|||||||
Route,
|
Route,
|
||||||
useNavigate,
|
useNavigate,
|
||||||
useParams,
|
useParams,
|
||||||
Navigate,
|
|
||||||
} from "react-router-dom";
|
} from "react-router-dom";
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
import { ConfigContext } from "./providers/ConfigContext";
|
||||||
|
|
||||||
// Create a context for the app config
|
|
||||||
export const ConfigContext = React.createContext<AppConfig | null>(null);
|
|
||||||
|
|
||||||
function Dashboard({ basePath }: { basePath: string }) {
|
function Dashboard({ basePath }: { basePath: string }) {
|
||||||
const config = React.useContext(ConfigContext);
|
const config = React.useContext(ConfigContext);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const resources = config?.resources || [];
|
||||||
|
const visibleResources = resources.filter((res) => !res.hidden);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box>
|
<Box>
|
||||||
<Typography variant="h4" gutterBottom>
|
<Typography variant="h4" gutterBottom>
|
||||||
@@ -41,7 +40,7 @@ function Dashboard({ basePath }: { basePath: string }) {
|
|||||||
mt: 4,
|
mt: 4,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{config?.resources.map((res) => (
|
{visibleResources.map((res) => (
|
||||||
<Paper
|
<Paper
|
||||||
key={res.name}
|
key={res.name}
|
||||||
sx={{
|
sx={{
|
||||||
@@ -69,6 +68,9 @@ function AdminApp({ basePath }: { basePath: string }) {
|
|||||||
const config = React.useContext(ConfigContext);
|
const config = React.useContext(ConfigContext);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const resources = config?.resources || [];
|
||||||
|
const visibleResources = resources.filter((res) => !res.hidden);
|
||||||
|
|
||||||
if (!currentUser) {
|
if (!currentUser) {
|
||||||
return (
|
return (
|
||||||
<AuthPage
|
<AuthPage
|
||||||
@@ -89,7 +91,7 @@ function AdminApp({ basePath }: { basePath: string }) {
|
|||||||
username={currentUser.username}
|
username={currentUser.username}
|
||||||
onLogout={logout}
|
onLogout={logout}
|
||||||
onSelectResource={(name) => navigate(`/admin/${name}`)}
|
onSelectResource={(name) => navigate(`/admin/${name}`)}
|
||||||
resources={config?.resources || []}
|
resources={visibleResources}
|
||||||
>
|
>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Dashboard basePath={basePath} />} />
|
<Route path="/" element={<Dashboard basePath={basePath} />} />
|
||||||
@@ -120,14 +122,17 @@ interface AdminProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function Admin({ basePath = "/admin", resourceOverrides = {}, profileConfig = {} }: 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(() => {
|
React.useEffect(() => {
|
||||||
|
if (!existingConfig) {
|
||||||
getAppConfig(resourceOverrides, profileConfig).then((cfg) => {
|
getAppConfig(resourceOverrides, profileConfig).then((cfg) => {
|
||||||
initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
|
initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
|
||||||
setConfig(cfg);
|
setConfig(cfg);
|
||||||
});
|
});
|
||||||
}, [resourceOverrides, profileConfig]);
|
}
|
||||||
|
}, [resourceOverrides, profileConfig, existingConfig]);
|
||||||
|
|
||||||
if (!config) {
|
if (!config) {
|
||||||
return (
|
return (
|
||||||
@@ -144,13 +149,21 @@ export default function Admin({ basePath = "/admin", resourceOverrides = {}, pro
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
const content = (
|
||||||
<QueryClientProvider client={queryClient}>
|
|
||||||
<ConfigContext.Provider value={config}>
|
|
||||||
<UploadProvider>
|
<UploadProvider>
|
||||||
<AdminApp basePath={basePath} />
|
<AdminApp basePath={basePath} />
|
||||||
</UploadProvider>
|
</UploadProvider>
|
||||||
|
);
|
||||||
|
|
||||||
|
// If we have an existing config, we are already inside a Provider and QueryClient
|
||||||
|
if (existingConfig) {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback for standalone usage
|
||||||
|
return (
|
||||||
|
<ConfigContext.Provider value={config}>
|
||||||
|
{content}
|
||||||
</ConfigContext.Provider>
|
</ConfigContext.Provider>
|
||||||
</QueryClientProvider>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,28 @@ import { createApiClient } from "../../react-auth";
|
|||||||
let _api: AxiosInstance | null = null;
|
let _api: AxiosInstance | null = null;
|
||||||
let _auth: 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 = {
|
export const api = {
|
||||||
get: (...args: Parameters<AxiosInstance["get"]>) => {
|
get: (...args: Parameters<AxiosInstance["get"]>) => {
|
||||||
if (!_api) throw new Error("API client not initialized");
|
if (!_api) throw new Error("API client not initialized");
|
||||||
@@ -38,6 +60,6 @@ export const auth = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
||||||
_api = createApiClient(baseUrl);
|
_api = withParamsSerializer(createApiClient(baseUrl));
|
||||||
_auth = createApiClient(authBaseUrl);
|
_auth = withParamsSerializer(createApiClient(authBaseUrl));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { useUpload } from '../providers/UploadProvider';
|
|||||||
import { useQueries } from '@tanstack/react-query';
|
import { useQueries } from '@tanstack/react-query';
|
||||||
import { useResource } from '../hooks/useResource';
|
import { useResource } from '../hooks/useResource';
|
||||||
import FormField from './fields/FormField';
|
import FormField from './fields/FormField';
|
||||||
import { ConfigContext } from '../Admin';
|
import { ConfigContext } from '../providers/ConfigContext';
|
||||||
|
|
||||||
interface GenericFormProps {
|
interface GenericFormProps {
|
||||||
config: ResourceConfig;
|
config: ResourceConfig;
|
||||||
@@ -67,6 +67,7 @@ export default function GenericForm({
|
|||||||
const relationDataMap = React.useMemo(() => {
|
const relationDataMap = React.useMemo(() => {
|
||||||
const map: Record<string, any[]> = {};
|
const map: Record<string, any[]> = {};
|
||||||
allRelations.forEach((relName, index) => {
|
allRelations.forEach((relName, index) => {
|
||||||
|
// @ts-ignore
|
||||||
map[relName] = queries[index].data || [];
|
map[relName] = queries[index].data || [];
|
||||||
});
|
});
|
||||||
return map;
|
return map;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import * as React from 'react';
|
|||||||
import { Box, Typography, Paper, CircularProgress, Alert } from '@mui/material';
|
import { Box, Typography, Paper, CircularProgress, Alert } from '@mui/material';
|
||||||
import { useResource } from '../hooks/useResource';
|
import { useResource } from '../hooks/useResource';
|
||||||
import GenericForm from './GenericForm';
|
import GenericForm from './GenericForm';
|
||||||
import { ConfigContext } from '../Admin';
|
import { ConfigContext } from '../providers/ConfigContext';
|
||||||
|
|
||||||
export default function ProfileView() {
|
export default function ProfileView() {
|
||||||
const appConfig = React.useContext(ConfigContext);
|
const appConfig = React.useContext(ConfigContext);
|
||||||
|
|||||||
@@ -1,16 +1,22 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { api } from "../api/client";
|
import { api } from "../api/client";
|
||||||
import { ResourceConfig } from "../types/config";
|
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 queryClient = useQueryClient();
|
||||||
const { name, endpoint, primaryKey } = config;
|
|
||||||
|
// Return empty/disabled hooks if config is missing
|
||||||
|
const { name = '', endpoint = '', primaryKey = 'id' } = config || {};
|
||||||
|
|
||||||
// --- READ ALL ---
|
// --- READ ALL ---
|
||||||
const useList = (params?: any) =>
|
const useList = (params?: any) =>
|
||||||
useQuery({
|
useQuery({
|
||||||
queryKey: [name, "list", params],
|
queryKey: [name, "list", params],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
|
if (!endpoint) return { data: [], total: 0 };
|
||||||
|
console.log('params:', params);
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const res = await api.get<T[]>(endpoint, { params });
|
const res = await api.get<T[]>(endpoint, { params });
|
||||||
const total = res.headers ? parseInt(res.headers['x-total-count'] || res.headers['X-Total-Count']) : undefined;
|
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,
|
data: res.data,
|
||||||
total: isNaN(total as any) ? undefined : total
|
total: isNaN(total as any) ? undefined : total
|
||||||
};
|
};
|
||||||
}
|
},
|
||||||
|
enabled: !!endpoint,
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- READ ONE ---
|
// --- READ ONE ---
|
||||||
@@ -26,18 +33,19 @@ export function useResource<T = any>(config: ResourceConfig) {
|
|||||||
useQuery({
|
useQuery({
|
||||||
queryKey: [name, "detail", id],
|
queryKey: [name, "detail", id],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
if (!id) return null;
|
if (!id || !endpoint) return null;
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const res = await api.get<T>(`${endpoint}/${id}`);
|
const res = await api.get<T>(`${endpoint}/${id}`);
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
enabled: !!id,
|
enabled: !!id && !!endpoint,
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- CREATE ---
|
// --- CREATE ---
|
||||||
const useCreate = () =>
|
const useCreate = () =>
|
||||||
useMutation({
|
useMutation({
|
||||||
mutationFn: async (data: Partial<T>) => {
|
mutationFn: async (data: Partial<T>) => {
|
||||||
|
if (!endpoint) throw new Error("Endpoint not defined");
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const res = await api.post<T>(endpoint, data);
|
const res = await api.post<T>(endpoint, data);
|
||||||
return res.data;
|
return res.data;
|
||||||
@@ -51,6 +59,7 @@ export function useResource<T = any>(config: ResourceConfig) {
|
|||||||
const useUpdate = () =>
|
const useUpdate = () =>
|
||||||
useMutation({
|
useMutation({
|
||||||
mutationFn: async ({ id, data }: { id: string; data: Partial<T> }) => {
|
mutationFn: async ({ id, data }: { id: string; data: Partial<T> }) => {
|
||||||
|
if (!endpoint) throw new Error("Endpoint not defined");
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const res = await api.put<T>(`${endpoint}/${id}`, data);
|
const res = await api.put<T>(`${endpoint}/${id}`, data);
|
||||||
return res.data;
|
return res.data;
|
||||||
@@ -67,6 +76,7 @@ export function useResource<T = any>(config: ResourceConfig) {
|
|||||||
const useDelete = () =>
|
const useDelete = () =>
|
||||||
useMutation({
|
useMutation({
|
||||||
mutationFn: async (id: string) => {
|
mutationFn: async (id: string) => {
|
||||||
|
if (!endpoint) throw new Error("Endpoint not defined");
|
||||||
await api.delete(`${endpoint}/${id}`);
|
await api.delete(`${endpoint}/${id}`);
|
||||||
return id;
|
return id;
|
||||||
},
|
},
|
||||||
@@ -79,6 +89,7 @@ export function useResource<T = any>(config: ResourceConfig) {
|
|||||||
const getListQueryOptions = (params?: any) => ({
|
const getListQueryOptions = (params?: any) => ({
|
||||||
queryKey: [name, "list", params],
|
queryKey: [name, "list", params],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
|
if (!endpoint) return { data: [], total: 0 };
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const res = await api.get<T[]>(endpoint, { params });
|
const res = await api.get<T[]>(endpoint, { params });
|
||||||
const total = res.headers ? parseInt(res.headers['x-total-count'] || res.headers['X-Total-Count']) : undefined;
|
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
|
total: isNaN(total as any) ? undefined : total
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
enabled: !!endpoint,
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- READ ME ---
|
// --- READ ME ---
|
||||||
@@ -94,16 +106,19 @@ export function useResource<T = any>(config: ResourceConfig) {
|
|||||||
useQuery({
|
useQuery({
|
||||||
queryKey: [name, "me"],
|
queryKey: [name, "me"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
|
if (!endpoint) return null;
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const res = await api.get<T>(`${endpoint}/me`);
|
const res = await api.get<T>(`${endpoint}/me`);
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
|
enabled: !!endpoint,
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- UPDATE ME ---
|
// --- UPDATE ME ---
|
||||||
const useUpdateMe = () =>
|
const useUpdateMe = () =>
|
||||||
useMutation({
|
useMutation({
|
||||||
mutationFn: async (data: Partial<T>) => {
|
mutationFn: async (data: Partial<T>) => {
|
||||||
|
if (!endpoint) throw new Error("Endpoint not defined");
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
const res = await api.put<T>(`${endpoint}/me`, data);
|
const res = await api.put<T>(`${endpoint}/me`, data);
|
||||||
return res.data;
|
return res.data;
|
||||||
@@ -125,3 +140,10 @@ export function useResource<T = any>(config: ResourceConfig) {
|
|||||||
getListQueryOptions,
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,3 +2,6 @@ export { default as Admin } from "./Admin";
|
|||||||
export { api, auth, initializeApiClients } from "./api/client";
|
export { api, auth, initializeApiClients } from "./api/client";
|
||||||
export { getAppConfig } from "./config";
|
export { getAppConfig } from "./config";
|
||||||
export type { AppConfig, ResourceConfig, ResourceField } from "./types/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";
|
||||||
|
|||||||
70
react-openapi/providers/AppProvider.tsx
Normal file
70
react-openapi/providers/AppProvider.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
12
react-openapi/providers/ConfigContext.tsx
Normal file
12
react-openapi/providers/ConfigContext.tsx
Normal 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;
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ export interface ResourceConfig {
|
|||||||
primaryKey: string;
|
primaryKey: string;
|
||||||
fields: Record<string, ResourceField>;
|
fields: Record<string, ResourceField>;
|
||||||
pagination?: boolean;
|
pagination?: boolean;
|
||||||
|
hidden?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AppConfig {
|
export interface AppConfig {
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ export interface FieldOverride {
|
|||||||
export interface ResourceOverride {
|
export interface ResourceOverride {
|
||||||
fields?: Record<string, FieldOverride>;
|
fields?: Record<string, FieldOverride>;
|
||||||
pagination?: boolean;
|
pagination?: boolean;
|
||||||
|
hidden?: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -162,6 +162,7 @@ export async function loadConfigFromOpenApi(baseUrl: string, configuration: Reco
|
|||||||
primaryKey: "id", // Strict default, no heuristics
|
primaryKey: "id", // Strict default, no heuristics
|
||||||
fields,
|
fields,
|
||||||
pagination: resourceOverride.pagination,
|
pagination: resourceOverride.pagination,
|
||||||
|
hidden: resourceOverride.hidden,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,100 +2,30 @@ import * as React from "react";
|
|||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
Container,
|
Container,
|
||||||
Grid,
|
|
||||||
CircularProgress,
|
CircularProgress,
|
||||||
Alert,
|
Alert
|
||||||
ToggleButton,
|
|
||||||
ToggleButtonGroup
|
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
|
|
||||||
import LatestItemsList, { LatestItem } from "./components/LatestItemsList";
|
import ConfigurableDashboard from "./components/Dashboard";
|
||||||
import HistoryChart from "./components/HistoryChart";
|
import { configuration } from "./dashboard-config";
|
||||||
import {
|
import {
|
||||||
AggregatedDashboardData
|
useReport,
|
||||||
} from "./types/historyChart";
|
prepareReport,
|
||||||
|
} from "./features/report";
|
||||||
import {
|
|
||||||
fetchLatestTransactions,
|
|
||||||
fetchAggregatedExpenses,
|
|
||||||
fetchAggregatedIncome,
|
|
||||||
} from "./utils/dashboardLoader";
|
|
||||||
|
|
||||||
export default function Dashboard() {
|
export default function Dashboard() {
|
||||||
const [latest, setLatest] = React.useState<{
|
const report = useReport({
|
||||||
expense: LatestItem[];
|
periods: ["weekly", "monthly", "full"],
|
||||||
income: LatestItem[];
|
rolling: true,
|
||||||
}>({
|
include_transactions: true,
|
||||||
expense: [],
|
group_by: ["tags"],
|
||||||
income: []
|
})
|
||||||
});
|
|
||||||
|
|
||||||
const [aggregated, setAggregated] = React.useState<{
|
const isLoading = report.isLoading;
|
||||||
expense: AggregatedDashboardData | null;
|
const error = report.error;
|
||||||
income: AggregatedDashboardData | null;
|
|
||||||
}>({
|
|
||||||
expense: null,
|
|
||||||
income: null
|
|
||||||
});
|
|
||||||
|
|
||||||
const [mode, setMode] = React.useState<"expense" | "income">("expense");
|
|
||||||
const [period, setPeriod] = React.useState<"rolling" | "calendar">("rolling");
|
|
||||||
const [comparison, setComparison] = React.useState(false);
|
|
||||||
|
|
||||||
const [loading, setLoading] = React.useState(true);
|
if (isLoading) {
|
||||||
const [error, setError] = React.useState<string | null>(null);
|
|
||||||
|
|
||||||
// -------- LOAD ONCE --------
|
|
||||||
React.useEffect(() => {
|
|
||||||
async function loadData() {
|
|
||||||
try {
|
|
||||||
setLoading(true);
|
|
||||||
|
|
||||||
const [
|
|
||||||
latestExpense,
|
|
||||||
latestIncome,
|
|
||||||
expenseData,
|
|
||||||
incomeData
|
|
||||||
] = await Promise.all([
|
|
||||||
fetchLatestTransactions("expense"),
|
|
||||||
fetchLatestTransactions("income"),
|
|
||||||
fetchAggregatedExpenses(),
|
|
||||||
fetchAggregatedIncome()
|
|
||||||
]);
|
|
||||||
|
|
||||||
setLatest({
|
|
||||||
expense: latestExpense,
|
|
||||||
income: latestIncome
|
|
||||||
});
|
|
||||||
|
|
||||||
setAggregated({
|
|
||||||
expense: expenseData,
|
|
||||||
income: incomeData
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (err: any) {
|
|
||||||
console.error(err);
|
|
||||||
setError(err.message || "Failed to load dashboard data");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
loadData();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const currentData = aggregated[mode];
|
|
||||||
if (!currentData) {
|
|
||||||
return (
|
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
|
|
||||||
<CircularProgress />
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const currentLatest = latest[mode];
|
|
||||||
|
|
||||||
// -------- UI STATES --------
|
|
||||||
if (loading) {
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
|
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
|
||||||
<CircularProgress />
|
<CircularProgress />
|
||||||
@@ -106,49 +36,20 @@ export default function Dashboard() {
|
|||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<Container sx={{ mt: 4 }}>
|
<Container sx={{ mt: 4 }}>
|
||||||
<Alert severity="error">{error}</Alert>
|
<Alert severity="error">{String(error)}</Alert>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = prepareReport(report.data?.data);
|
||||||
return (
|
return (
|
||||||
<Container sx={{ mt: 4, mb: 4 }}>
|
<ConfigurableDashboard
|
||||||
{/* -------- TOGGLE -------- */}
|
config={configuration}
|
||||||
<Box sx={{ display: "flex", justifyContent: "center", mb: 3 }}>
|
data={data}
|
||||||
<ToggleButtonGroup
|
|
||||||
value={mode}
|
|
||||||
exclusive
|
|
||||||
onChange={(_, val) => val && setMode(val)}
|
|
||||||
>
|
|
||||||
<ToggleButton value="expense">Expenses</ToggleButton>
|
|
||||||
<ToggleButton value="income">Income</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Grid container spacing={4} direction="row">
|
|
||||||
|
|
||||||
<Grid size={12}>
|
|
||||||
<HistoryChart
|
|
||||||
header={`${mode === "expense" ? "Expense" : "Income"} Breakdown`}
|
|
||||||
summary="Interactive chronological tracking"
|
|
||||||
tabs={["Daily", "Weekly", "Monthly"]}
|
|
||||||
data={currentData.chartData}
|
|
||||||
period={period}
|
|
||||||
onPeriodChange={setPeriod}
|
|
||||||
comparison={comparison}
|
|
||||||
setComparison={setComparison}
|
|
||||||
/>
|
/>
|
||||||
</Grid>
|
|
||||||
|
|
||||||
<Grid size={12}>
|
|
||||||
<LatestItemsList
|
|
||||||
title={`Recent ${mode === "expense" ? "Expenses" : "Income"}`}
|
|
||||||
items={currentLatest}
|
|
||||||
onViewAll={() => {}}
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
|
|
||||||
</Grid>
|
|
||||||
</Container>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -83,12 +83,14 @@ export default function Header({
|
|||||||
<Typography
|
<Typography
|
||||||
variant="h6"
|
variant="h6"
|
||||||
noWrap
|
noWrap
|
||||||
sx={{ flexGrow: 1, fontWeight: "bold", cursor: "pointer" }}
|
sx={{ fontWeight: "bold", cursor: "pointer" }}
|
||||||
onClick={() => navigate("/")}
|
onClick={() => navigate("/")}
|
||||||
>
|
>
|
||||||
{headerTitle}
|
{headerTitle}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
|
||||||
|
<span style={{ flexGrow: 1 }} />
|
||||||
|
|
||||||
{/* AUTH SECTION */}
|
{/* AUTH SECTION */}
|
||||||
{isAuthenticated ? (
|
{isAuthenticated ? (
|
||||||
<>
|
<>
|
||||||
|
|||||||
52
src/components/Dashboard/Dashboard.models.ts
Normal file
52
src/components/Dashboard/Dashboard.models.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import {
|
||||||
|
ReportData
|
||||||
|
} 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;
|
||||||
|
comparison: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardSection {
|
||||||
|
id: string;
|
||||||
|
title?: string;
|
||||||
|
summary?: string;
|
||||||
|
component: React.ComponentType<any>;
|
||||||
|
dataKey: string;
|
||||||
|
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;
|
||||||
|
}
|
||||||
49
src/components/Dashboard/Dashboard.tsx
Normal file
49
src/components/Dashboard/Dashboard.tsx
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
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,
|
||||||
|
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 }));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardView
|
||||||
|
{...props}
|
||||||
|
state={state}
|
||||||
|
setState={setState}
|
||||||
|
toggleMode={toggleMode}
|
||||||
|
togglePeriodType={togglePeriodType}
|
||||||
|
toggleComparison={toggleComparison}
|
||||||
|
setSelectedPeriodId={setSelectedPeriodId}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
134
src/components/Dashboard/Dashboard.view.tsx
Normal file
134
src/components/Dashboard/Dashboard.view.tsx
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Container,
|
||||||
|
Grid,
|
||||||
|
Typography,
|
||||||
|
ToggleButton,
|
||||||
|
ToggleButtonGroup
|
||||||
|
} from "@mui/material";
|
||||||
|
import { useTheme, alpha } from "@mui/material/styles";
|
||||||
|
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;
|
||||||
|
toggleComparison: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardView({
|
||||||
|
config,
|
||||||
|
data,
|
||||||
|
state,
|
||||||
|
setState,
|
||||||
|
toggleMode,
|
||||||
|
togglePeriodType,
|
||||||
|
toggleComparison,
|
||||||
|
setSelectedPeriodId,
|
||||||
|
}: ViewProps) {
|
||||||
|
const theme = useTheme();
|
||||||
|
const themeMode = theme.palette.mode;
|
||||||
|
const { mode, periodType, comparison, selectedPeriodId } = 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}
|
||||||
|
|
||||||
|
togglePeriodType={togglePeriodType}
|
||||||
|
toggleComparison={toggleComparison}
|
||||||
|
setSelectedPeriodId={setSelectedPeriodId}
|
||||||
|
/>
|
||||||
|
</Grid>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Grid>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
}
|
||||||
2
src/components/Dashboard/index.ts
Normal file
2
src/components/Dashboard/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default } from "./Dashboard";
|
||||||
|
export * from "./Dashboard.models";
|
||||||
@@ -1,387 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Typography,
|
|
||||||
ToggleButtonGroup,
|
|
||||||
ToggleButton,
|
|
||||||
Paper
|
|
||||||
} from "@mui/material";
|
|
||||||
import {
|
|
||||||
ChartDataPoint,
|
|
||||||
HistoryChartProps,
|
|
||||||
ChartData,
|
|
||||||
} from "../types/historyChart";
|
|
||||||
import IconButton from "@mui/material/IconButton";
|
|
||||||
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
|
|
||||||
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
|
|
||||||
|
|
||||||
const formatDisplay = (
|
|
||||||
point: ChartDataPoint,
|
|
||||||
tab: string,
|
|
||||||
comparison: boolean
|
|
||||||
) => {
|
|
||||||
const base = point.amount;
|
|
||||||
const cmp = point.compareAmount ?? 0;
|
|
||||||
|
|
||||||
const formatShort = (val: number) => {
|
|
||||||
if (tab === "monthly") {
|
|
||||||
if (val >= 100000) return `${(val / 100000).toFixed(2)}L`;
|
|
||||||
}
|
|
||||||
if (tab === "weekly") {
|
|
||||||
if (val >= 1000) return `${(val / 1000).toFixed(1)}K`;
|
|
||||||
}
|
|
||||||
return val.toLocaleString("en-IN");
|
|
||||||
};
|
|
||||||
|
|
||||||
// Only hide diff when comparison OFF or compare is undefined
|
|
||||||
if (!comparison) {
|
|
||||||
return `₹ ${formatShort(base)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const diff = base - cmp;
|
|
||||||
const sign = diff >= 0 ? "+" : "-";
|
|
||||||
const absDiff = Math.abs(diff);
|
|
||||||
|
|
||||||
return `₹ ${formatShort(base)} (${sign}${formatShort(absDiff)})`;
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatLabel = (label: string, type: string) => {
|
|
||||||
if (type === "monthly") return label;
|
|
||||||
|
|
||||||
if (type === "weekly") {
|
|
||||||
const parts = label.split(" - ");
|
|
||||||
if (parts.length === 2) {
|
|
||||||
const [start, end] = parts;
|
|
||||||
const startDay = start.split(" ")[0];
|
|
||||||
const endParts = end.split(" ");
|
|
||||||
const endDay = endParts[0];
|
|
||||||
const month = endParts[1];
|
|
||||||
return `${startDay}–${endDay} ${month}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return label;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function HistoryChart({
|
|
||||||
header,
|
|
||||||
summary,
|
|
||||||
tabs,
|
|
||||||
data,
|
|
||||||
period,
|
|
||||||
onPeriodChange,
|
|
||||||
comparison,
|
|
||||||
setComparison,
|
|
||||||
}: HistoryChartProps) {
|
|
||||||
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
|
|
||||||
|
|
||||||
const handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => {
|
|
||||||
if (newTab !== null) setActiveTab(newTab);
|
|
||||||
};
|
|
||||||
|
|
||||||
const activeDataKey = activeTab.toLowerCase() as keyof ChartData;
|
|
||||||
|
|
||||||
let rawData: ChartDataPoint[] = [];
|
|
||||||
|
|
||||||
if (activeDataKey === "daily") {
|
|
||||||
rawData = data.daily || [];
|
|
||||||
} else {
|
|
||||||
const section = data[activeDataKey];
|
|
||||||
rawData = section?.[period] || [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentData = rawData;
|
|
||||||
|
|
||||||
const maxAmount =
|
|
||||||
currentData.length > 0
|
|
||||||
? Math.max(
|
|
||||||
...currentData.flatMap((d) =>
|
|
||||||
comparison ? [d.amount, d.compareAmount || 0] : [d.amount]
|
|
||||||
),
|
|
||||||
1
|
|
||||||
)
|
|
||||||
: 1;
|
|
||||||
|
|
||||||
const [startIndex, setStartIndex] = React.useState(0);
|
|
||||||
const visibleCountDataTabMapping = {
|
|
||||||
daily: 7,
|
|
||||||
weekly: 6,
|
|
||||||
monthly: 4,
|
|
||||||
}
|
|
||||||
const visibleCount = visibleCountDataTabMapping[activeDataKey];
|
|
||||||
const total = currentData.length;
|
|
||||||
|
|
||||||
// clamp startIndex so we always show full 5 (when possible)
|
|
||||||
const clampedStartIndex = Math.min(
|
|
||||||
startIndex,
|
|
||||||
Math.max(total - visibleCount, 0)
|
|
||||||
);
|
|
||||||
|
|
||||||
const visibleData = currentData.slice(
|
|
||||||
clampedStartIndex,
|
|
||||||
clampedStartIndex + visibleCount
|
|
||||||
);
|
|
||||||
|
|
||||||
const canGoLeft = startIndex > 0;
|
|
||||||
const canGoRight = startIndex + visibleCount < currentData.length;
|
|
||||||
|
|
||||||
const handlePrev = () => {
|
|
||||||
if (canGoLeft) setStartIndex((prev) => prev - visibleCount);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleNext = () => {
|
|
||||||
if (canGoRight) setStartIndex((prev) => prev + visibleCount);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper
|
|
||||||
sx={{
|
|
||||||
p: { xs: 2, sm: 4 },
|
|
||||||
borderRadius: 4,
|
|
||||||
width: "100%",
|
|
||||||
boxShadow: "none",
|
|
||||||
border: "1px solid",
|
|
||||||
borderColor: "divider"
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<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",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
mb: 3
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* Rolling / Calendar */}
|
|
||||||
<ToggleButtonGroup
|
|
||||||
value={period}
|
|
||||||
exclusive
|
|
||||||
onChange={(_, v) => v && onPeriodChange(v)}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<ToggleButton value="rolling">Rolling</ToggleButton>
|
|
||||||
<ToggleButton
|
|
||||||
value="calendar"
|
|
||||||
disabled={activeDataKey === "daily"}
|
|
||||||
>
|
|
||||||
Calendar
|
|
||||||
</ToggleButton>
|
|
||||||
</ToggleButtonGroup>
|
|
||||||
|
|
||||||
{/* Compare toggle */}
|
|
||||||
<ToggleButton
|
|
||||||
value="compare"
|
|
||||||
selected={comparison}
|
|
||||||
onChange={() => setComparison(!comparison)}
|
|
||||||
size="small"
|
|
||||||
sx={{
|
|
||||||
textTransform: "none",
|
|
||||||
borderRadius: 2,
|
|
||||||
px: 2,
|
|
||||||
|
|
||||||
// OFF
|
|
||||||
color: "text.secondary",
|
|
||||||
border: "1px solid",
|
|
||||||
borderColor: "divider",
|
|
||||||
|
|
||||||
// ON
|
|
||||||
"&.Mui-selected": {
|
|
||||||
color: "white",
|
|
||||||
bgcolor: "success.main",
|
|
||||||
borderColor: "success.main"
|
|
||||||
},
|
|
||||||
"&.Mui-selected:hover": {
|
|
||||||
bgcolor: "success.dark"
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Compare
|
|
||||||
</ToggleButton>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{currentData.length > 0 ? (
|
|
||||||
<Box sx={{ position: "relative", mt: 4 }}>
|
|
||||||
|
|
||||||
{/* LEFT ARROW */}
|
|
||||||
{canGoLeft && (
|
|
||||||
<IconButton
|
|
||||||
onClick={handlePrev}
|
|
||||||
size="small"
|
|
||||||
sx={{
|
|
||||||
position: "absolute",
|
|
||||||
left: 0,
|
|
||||||
top: "50%",
|
|
||||||
transform: "translateY(-50%)",
|
|
||||||
zIndex: 2,
|
|
||||||
bgcolor: "background.paper",
|
|
||||||
boxShadow: 1
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ChevronLeftIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* CHART */}
|
|
||||||
<Box sx={{ display: "flex", alignItems: "flex-end", height: 220, mt: 4 }}>
|
|
||||||
{visibleData.map((point) => {
|
|
||||||
const currentHeight = (point.amount / maxAmount) * 100;
|
|
||||||
const compareHeight = comparison
|
|
||||||
? ((point.compareAmount || 0) / maxAmount) * 100
|
|
||||||
: 0;
|
|
||||||
const labelHeight = Math.max(currentHeight, compareHeight);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
key={point.id}
|
|
||||||
sx={{
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "flex-end",
|
|
||||||
height: "100%"
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "flex-end",
|
|
||||||
gap: comparison ? 0.5 : 0,
|
|
||||||
height: "100%",
|
|
||||||
position: "relative"
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{
|
|
||||||
position: "absolute",
|
|
||||||
bottom: `${labelHeight}%`,
|
|
||||||
left: "50%",
|
|
||||||
transform: "translate(-50%, -6px)",
|
|
||||||
fontSize: "0.65rem",
|
|
||||||
whiteSpace: "nowrap",
|
|
||||||
pointerEvents: "none"
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{formatDisplay(point, activeTab.toLowerCase(), comparison)}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
{/* Compare */}
|
|
||||||
{comparison && (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
width: 6,
|
|
||||||
height: `${compareHeight}%`,
|
|
||||||
bgcolor: "grey.400",
|
|
||||||
borderRadius: 2
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Spacer */}
|
|
||||||
<Box sx={{ width: 4 }} />
|
|
||||||
|
|
||||||
{/* Current */}
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
width: 10,
|
|
||||||
height: `${currentHeight}%`,
|
|
||||||
bgcolor: point.highlighted ? "error.main" : "primary.main",
|
|
||||||
borderRadius: 2
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
mt: 1,
|
|
||||||
textAlign: "center",
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: "center",
|
|
||||||
lineHeight: 1.1
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{
|
|
||||||
fontSize: "0.7rem",
|
|
||||||
opacity: 0.7,
|
|
||||||
color: "text.primary",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{formatLabel(point.id, activeDataKey)}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{
|
|
||||||
fontSize: "0.65rem",
|
|
||||||
color: "grey.400",
|
|
||||||
visibility:
|
|
||||||
comparison && point.compareLabel && activeDataKey !== "daily"
|
|
||||||
? "visible"
|
|
||||||
: "hidden"
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{point.compareLabel
|
|
||||||
? formatLabel(point.compareLabel, activeDataKey)
|
|
||||||
: "placeholder"}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{/* RIGHT ARROW */}
|
|
||||||
{canGoRight && (
|
|
||||||
<IconButton
|
|
||||||
onClick={handleNext}
|
|
||||||
size="small"
|
|
||||||
sx={{
|
|
||||||
position: "absolute",
|
|
||||||
right: 0,
|
|
||||||
top: "50%",
|
|
||||||
transform: "translateY(-50%)",
|
|
||||||
zIndex: 2,
|
|
||||||
bgcolor: "background.paper",
|
|
||||||
boxShadow: 1
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
40
src/components/HistoryChart/HistoryChart.models.ts
Normal file
40
src/components/HistoryChart/HistoryChart.models.ts
Normal 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;
|
||||||
|
}
|
||||||
191
src/components/HistoryChart/HistoryChart.tsx
Normal file
191
src/components/HistoryChart/HistoryChart.tsx
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { HistoryChartProps, ChartDataPoint } from "./HistoryChart.models";
|
||||||
|
import HistoryChartView from "./HistoryChart.view";
|
||||||
|
import { ReportPeriod } from "../../features/report";
|
||||||
|
|
||||||
|
type DecoratedPeriod = ReportPeriod & {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const TAB_TO_KEY: Record<string, "weekly" | "monthly" | "yearly" | "fyly"> = {
|
||||||
|
Weekly: "weekly",
|
||||||
|
Monthly: "monthly",
|
||||||
|
Yearly: "yearly",
|
||||||
|
FYLY: "fyly"
|
||||||
|
};
|
||||||
|
|
||||||
|
function getAmount(p: ReportPeriod, mode: "expense" | "income") {
|
||||||
|
return mode === "expense" ? p.expenses.sum : p.incomes.sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeMetric(a: any, b: any) {
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeBuckets(
|
||||||
|
buckets: any[],
|
||||||
|
key: "weekly" | "monthly" | "yearly" | "fyly"
|
||||||
|
): 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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildChartData(
|
||||||
|
reportData: HistoryChartProps["reportData"],
|
||||||
|
key: "weekly" | "monthly" | "yearly" | "fyly",
|
||||||
|
mode: "expense" | "income",
|
||||||
|
comparison: boolean
|
||||||
|
): ChartDataPoint[] {
|
||||||
|
const merged = mergeBuckets(reportData.buckets, key);
|
||||||
|
console.log("Merged periods:", merged);
|
||||||
|
|
||||||
|
let points: ChartDataPoint[] = merged.map((p) => ({
|
||||||
|
id: p.id,
|
||||||
|
label: p.label,
|
||||||
|
amount: getAmount(p, mode)
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (comparison) {
|
||||||
|
points = points.map((p, i) => ({
|
||||||
|
...p,
|
||||||
|
compare:
|
||||||
|
i > 0
|
||||||
|
? {
|
||||||
|
id: points[i - 1].id,
|
||||||
|
label: points[i - 1].label,
|
||||||
|
amount: points[i - 1].amount
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function HistoryChart(props: HistoryChartProps) {
|
||||||
|
const {
|
||||||
|
tabs,
|
||||||
|
reportData,
|
||||||
|
mode,
|
||||||
|
periodType,
|
||||||
|
comparison,
|
||||||
|
selectedPeriodId,
|
||||||
|
setSelectedPeriodId
|
||||||
|
} = props;
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
|
||||||
|
const [startIndex, setStartIndex] = React.useState(0);
|
||||||
|
|
||||||
|
const activeDataKey = TAB_TO_KEY[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
|
||||||
|
};
|
||||||
|
|
||||||
|
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, periodType]);
|
||||||
|
|
||||||
|
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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
27
src/components/HistoryChart/HistoryChart.utils.ts
Normal file
27
src/components/HistoryChart/HistoryChart.utils.ts
Normal 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))})`;
|
||||||
|
};
|
||||||
207
src/components/HistoryChart/HistoryChart.view.tsx
Normal file
207
src/components/HistoryChart/HistoryChart.view.tsx
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
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 handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => {
|
||||||
|
if (newTab !== null) setActiveTab(newTab);
|
||||||
|
};
|
||||||
|
|
||||||
|
const canGoLeft = startIndex > 0;
|
||||||
|
const canGoRight = startIndex + visibleCount < currentData.length;
|
||||||
|
|
||||||
|
const handlePrev = () => {
|
||||||
|
if (canGoLeft) setStartIndex((prev) => prev - visibleCount);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNext = () => {
|
||||||
|
if (canGoRight) setStartIndex((prev) => prev + visibleCount);
|
||||||
|
};
|
||||||
|
|
||||||
|
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"
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
2
src/components/HistoryChart/index.ts
Normal file
2
src/components/HistoryChart/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default } from "./HistoryChart";
|
||||||
|
export * from "./HistoryChart.models";
|
||||||
18
src/components/LatestItems/LatestItems.models.ts
Normal file
18
src/components/LatestItems/LatestItems.models.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
export interface LatestItem {
|
||||||
|
id: string | number;
|
||||||
|
icon: React.ReactNode;
|
||||||
|
iconBgColor?: string;
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
amount: string;
|
||||||
|
timeAgo: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LatestItemsListProps {
|
||||||
|
title?: string;
|
||||||
|
items: LatestItem[];
|
||||||
|
onViewAll?: () => void;
|
||||||
|
accentColor: string;
|
||||||
|
}
|
||||||
@@ -24,12 +24,14 @@ export interface LatestItemsListProps {
|
|||||||
title?: string;
|
title?: string;
|
||||||
items: LatestItem[];
|
items: LatestItem[];
|
||||||
onViewAll?: () => void;
|
onViewAll?: () => void;
|
||||||
|
accentColor: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function LatestItemsList({
|
export default function LatestItems({
|
||||||
title = "Recent Transactions",
|
title = "Recent Transactions",
|
||||||
items,
|
items,
|
||||||
onViewAll,
|
onViewAll,
|
||||||
|
accentColor,
|
||||||
}: LatestItemsListProps) {
|
}: LatestItemsListProps) {
|
||||||
return (
|
return (
|
||||||
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
|
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
|
||||||
@@ -69,7 +71,7 @@ export default function LatestItemsList({
|
|||||||
<Avatar
|
<Avatar
|
||||||
variant="rounded"
|
variant="rounded"
|
||||||
sx={{
|
sx={{
|
||||||
bgcolor: item.iconBgColor || "grey.200",
|
bgcolor: `${accentColor}22`,
|
||||||
color: "inherit",
|
color: "inherit",
|
||||||
width: 48,
|
width: 48,
|
||||||
height: 48,
|
height: 48,
|
||||||
6
src/components/LatestItems/LatestItems.view.tsx
Normal file
6
src/components/LatestItems/LatestItems.view.tsx
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import LatestItemsListView from "./LatestItems.view";
|
||||||
|
import { LatestItemsListProps } from "./LatestItems.models";
|
||||||
|
|
||||||
|
export default function LatestItemsList(props: LatestItemsListProps) {
|
||||||
|
return <LatestItemsListView {...props} />;
|
||||||
|
}
|
||||||
2
src/components/LatestItems/index.ts
Normal file
2
src/components/LatestItems/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default } from "./LatestItems";
|
||||||
|
export * from "./LatestItems.models";
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import * as React from "react";
|
|
||||||
import { Box, Typography, Paper, LinearProgress, linearProgressClasses } from "@mui/material";
|
|
||||||
|
|
||||||
export interface ProgressCardProps {
|
|
||||||
header: string;
|
|
||||||
summary?: string;
|
|
||||||
progressAmount: number;
|
|
||||||
totalAmount: number;
|
|
||||||
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ProgressCard({
|
|
||||||
header,
|
|
||||||
summary,
|
|
||||||
progressAmount,
|
|
||||||
totalAmount,
|
|
||||||
colorTheme = "info",
|
|
||||||
}: ProgressCardProps) {
|
|
||||||
const percentage = Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100)) || 0;
|
|
||||||
|
|
||||||
const displaySummary = summary ?? `Rs ${progressAmount} / Rs ${totalAmount}`;
|
|
||||||
|
|
||||||
const parts = displaySummary.split('/');
|
|
||||||
const prefixAmount = parts[0]?.trim() || '';
|
|
||||||
const suffixString = parts.length > 1 ? `/ ${parts.slice(1).join('/').trim()}` : '';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper
|
|
||||||
elevation={4}
|
|
||||||
sx={{
|
|
||||||
width: "100%",
|
|
||||||
p: { xs: 3, md: 4 },
|
|
||||||
borderRadius: 4,
|
|
||||||
background: (theme) =>
|
|
||||||
colorTheme === "info"
|
|
||||||
? "linear-gradient(135deg, #0284c7 0%, #06b6d4 100%)"
|
|
||||||
: `linear-gradient(135deg, ${theme.palette[colorTheme].main} 0%, ${theme.palette[colorTheme].light} 100%)`,
|
|
||||||
color: "#fff",
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
position: 'relative',
|
|
||||||
overflow: 'hidden',
|
|
||||||
boxShadow: (theme) => `0 12px 24px -10px ${theme.palette.mode === 'dark' ? '#000' : theme.palette[colorTheme].main}`,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography variant="subtitle1" fontWeight={600} sx={{ opacity: 0.9, mb: 1 }}>
|
|
||||||
{header}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Typography variant="h3" fontWeight={800} sx={{ mb: 3 }}>
|
|
||||||
{prefixAmount}{" "}
|
|
||||||
{suffixString && (
|
|
||||||
<Typography component="span" variant="subtitle1" sx={{ opacity: 0.7, fontWeight: 500 }}>
|
|
||||||
{suffixString}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Box sx={{ width: "85%" }}>
|
|
||||||
<LinearProgress
|
|
||||||
variant="determinate"
|
|
||||||
value={percentage}
|
|
||||||
sx={{
|
|
||||||
height: 10,
|
|
||||||
borderRadius: 5,
|
|
||||||
[`&.${linearProgressClasses.colorPrimary}`]: {
|
|
||||||
backgroundColor: "rgba(0, 0, 0, 0.2)",
|
|
||||||
},
|
|
||||||
[`& .${linearProgressClasses.bar}`]: {
|
|
||||||
borderRadius: 5,
|
|
||||||
backgroundColor: "#fff",
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
8
src/components/ProgressCard/ProgressCard.models.ts
Normal file
8
src/components/ProgressCard/ProgressCard.models.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
export interface ProgressCardProps {
|
||||||
|
header: string;
|
||||||
|
summary?: string;
|
||||||
|
progressAmount: number;
|
||||||
|
totalAmount: number;
|
||||||
|
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
23
src/components/ProgressCard/ProgressCard.tsx
Normal file
23
src/components/ProgressCard/ProgressCard.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import ProgressCardView from "./ProgressCard.view";
|
||||||
|
import { ProgressCardProps } from "./ProgressCard.models";
|
||||||
|
import { getPercentage, formatCurrency } from "./ProgressCard.utils";
|
||||||
|
|
||||||
|
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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
15
src/components/ProgressCard/ProgressCard.utils.ts
Normal file
15
src/components/ProgressCard/ProgressCard.utils.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
export const getPercentage = (progressAmount: number, totalAmount: number) => {
|
||||||
|
if (!totalAmount) return 0;
|
||||||
|
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
|
||||||
|
};
|
||||||
|
|
||||||
|
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)}`;
|
||||||
|
};
|
||||||
127
src/components/ProgressCard/ProgressCard.view.tsx
Normal file
127
src/components/ProgressCard/ProgressCard.view.tsx
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ProgressCardView({
|
||||||
|
header,
|
||||||
|
colorTheme = "info",
|
||||||
|
percentage,
|
||||||
|
formattedProgress,
|
||||||
|
formattedTotal,
|
||||||
|
compact = false,
|
||||||
|
}: ViewProps) {
|
||||||
|
const theme = useTheme();
|
||||||
|
const isDark = theme.palette.mode === "dark";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper
|
||||||
|
elevation={compact ? 2 : 4}
|
||||||
|
sx={{
|
||||||
|
width: "100%",
|
||||||
|
p: compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
|
||||||
|
borderRadius: compact ? 3 : 4,
|
||||||
|
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: isDark ? "1px solid rgba(255,255,255,0.1)" : "none",
|
||||||
|
boxShadow: (theme) =>
|
||||||
|
`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
|
||||||
|
}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
2
src/components/ProgressCard/index.ts
Normal file
2
src/components/ProgressCard/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { default } from "./ProgressCard";
|
||||||
|
export * from "./ProgressCard.models";
|
||||||
73
src/dashboard-config.ts
Normal file
73
src/dashboard-config.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import HistoryChart from "./components/HistoryChart";
|
||||||
|
import ProgressCard from "./components/ProgressCard";
|
||||||
|
import LatestItems from "./components/LatestItems";
|
||||||
|
import { DashboardConfig } from "./components/Dashboard";
|
||||||
|
|
||||||
|
export const configuration: DashboardConfig = {
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
id: "breakdown",
|
||||||
|
title: "Breakdown",
|
||||||
|
summary: "Interactive chronological tracking",
|
||||||
|
component: HistoryChart,
|
||||||
|
dataKey: "chartData",
|
||||||
|
settings: {
|
||||||
|
tabs: ["Weekly", "Monthly"],
|
||||||
|
// tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"],
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
size: 12,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "top-payees",
|
||||||
|
title: 'Top Payees',
|
||||||
|
component: ProgressCard,
|
||||||
|
dataKey: "topPayees",
|
||||||
|
isList: true,
|
||||||
|
settings: {
|
||||||
|
compact: true,
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
size: 12,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// {
|
||||||
|
// id: "latest",
|
||||||
|
// title: 'Recent Transactions',
|
||||||
|
// component: LatestItems,
|
||||||
|
// dataKey: "latest",
|
||||||
|
// 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
11
src/features/report/index.ts
Normal file
11
src/features/report/index.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
export {
|
||||||
|
useReport
|
||||||
|
} from './useReport'
|
||||||
|
export type {
|
||||||
|
Transaction,
|
||||||
|
ReportData,
|
||||||
|
ReportPeriod,
|
||||||
|
} from './report.models'
|
||||||
|
export {
|
||||||
|
prepareReport
|
||||||
|
} from './report.utils'
|
||||||
89
src/features/report/report.models.ts
Normal file
89
src/features/report/report.models.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
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[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------
|
||||||
|
// Final Report
|
||||||
|
// -----------------------------
|
||||||
|
|
||||||
|
export interface ReportData {
|
||||||
|
periods: ("weekly" | "monthly" | "yearly" | "fyly")[];
|
||||||
|
|
||||||
|
rolling: boolean;
|
||||||
|
report_date?: string;
|
||||||
|
|
||||||
|
group_by: ("payee" | "tags")[];
|
||||||
|
|
||||||
|
ignore_self: boolean;
|
||||||
|
include_transactions: boolean;
|
||||||
|
|
||||||
|
buckets: ReportBucket[];
|
||||||
|
}
|
||||||
137
src/features/report/report.utils.ts
Normal file
137
src/features/report/report.utils.ts
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
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":
|
||||||
|
if (sameMonth(start, end)) {
|
||||||
|
const sDay = start.getUTCDate();
|
||||||
|
const eDay = end.getUTCDate();
|
||||||
|
const m = monthFmt.format(start);
|
||||||
|
return `${sDay} ${m} - ${eDay} ${m}`;
|
||||||
|
}
|
||||||
|
return `${dayFmt.format(start)} - ${dayFmt.format(end)}`;
|
||||||
|
|
||||||
|
case "monthly":
|
||||||
|
if (sameMonth(start, end)) {
|
||||||
|
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
|
||||||
|
}
|
||||||
|
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
|
||||||
|
|
||||||
|
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), new Date(p.end)),
|
||||||
|
label: buildLabel(type, new Date(p.start), new Date(p.end)),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
20
src/features/report/useReport.ts
Normal file
20
src/features/report/useReport.ts
Normal 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,
|
||||||
|
});
|
||||||
|
}
|
||||||
13
src/main.jsx
13
src/main.jsx
@@ -12,7 +12,7 @@ import {
|
|||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import Home from './Home';
|
import Home from './Home';
|
||||||
import Dashboard from './Dashboard';
|
import Dashboard from './Dashboard';
|
||||||
import { Admin, initializeApiClients } from '../react-openapi';
|
import { Admin, AppProvider } from '../react-openapi';
|
||||||
import { configuration, profileConfiguration } from './openapi-config';
|
import { configuration, profileConfiguration } from './openapi-config';
|
||||||
import { Buffer } from 'buffer';
|
import { Buffer } from 'buffer';
|
||||||
import process from 'process';
|
import process from 'process';
|
||||||
@@ -21,17 +21,13 @@ import Header from './Header';
|
|||||||
import Footer from './Footer';
|
import Footer from './Footer';
|
||||||
import AppTheme from './AppTheme';
|
import AppTheme from './AppTheme';
|
||||||
|
|
||||||
// Polyfill Node.js globals for browser environment (needed by SwaggerParser)
|
|
||||||
window.Buffer = Buffer;
|
window.Buffer = Buffer;
|
||||||
window.process = process;
|
window.process = process;
|
||||||
|
|
||||||
const rootElement = document.getElementById('root');
|
const rootElement = document.getElementById('root');
|
||||||
const root = createRoot(rootElement);
|
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
|
const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;
|
||||||
initializeApiClients(API_BASE, AUTH_BASE);
|
|
||||||
|
|
||||||
const routerMapping = [
|
const routerMapping = [
|
||||||
{ path: "/", component: Home, headerTitle: "Home" },
|
{ path: "/", component: Home, headerTitle: "Home" },
|
||||||
@@ -41,6 +37,7 @@ const routerMapping = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
root.render(
|
root.render(
|
||||||
|
<AppProvider resourceOverrides={configuration} profileConfig={profileConfiguration}>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<AuthProvider authBaseUrl={AUTH_BASE}>
|
<AuthProvider authBaseUrl={AUTH_BASE}>
|
||||||
<AppTheme>
|
<AppTheme>
|
||||||
@@ -57,7 +54,7 @@ root.render(
|
|||||||
path={path}
|
path={path}
|
||||||
element={
|
element={
|
||||||
path.startsWith("/admin") ? (
|
path.startsWith("/admin") ? (
|
||||||
<Component basePath="/admin" resourceOverrides={configuration} profileConfig={profileConfiguration} />
|
<Component basePath="/admin" />
|
||||||
) : (
|
) : (
|
||||||
<Component />
|
<Component />
|
||||||
)
|
)
|
||||||
@@ -65,11 +62,11 @@ root.render(
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Footer />
|
<Footer />
|
||||||
</AppTheme>
|
</AppTheme>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
|
</AppProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -40,6 +40,9 @@ export const configuration: Record<string, ResourceOverride> = {
|
|||||||
},
|
},
|
||||||
pagination: true,
|
pagination: true,
|
||||||
},
|
},
|
||||||
|
reports: {
|
||||||
|
hidden: true
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const profileConfiguration = {
|
export const profileConfiguration = {
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
|
|
||||||
export interface ChartDataPoint {
|
|
||||||
id: string;
|
|
||||||
amount: number;
|
|
||||||
compareAmount?: number;
|
|
||||||
compareLabel?: string;
|
|
||||||
highlighted?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ChartSeries {
|
|
||||||
rolling: ChartDataPoint[];
|
|
||||||
calendar: ChartDataPoint[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ChartData {
|
|
||||||
daily: ChartDataPoint[];
|
|
||||||
weekly: ChartSeries;
|
|
||||||
monthly: ChartSeries;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AggregatedDashboardData {
|
|
||||||
chartData: ChartData;
|
|
||||||
totalAmount: number;
|
|
||||||
topPayees: Array<{ payeeName: string; amount: number }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HistoryChartProps {
|
|
||||||
header: string;
|
|
||||||
summary?: string;
|
|
||||||
tabs: string[];
|
|
||||||
data: ChartData;
|
|
||||||
period: "rolling" | "calendar";
|
|
||||||
onPeriodChange: (mode: "rolling" | "calendar") => void;
|
|
||||||
comparison: boolean;
|
|
||||||
setComparison: (mode: boolean) => void;
|
|
||||||
}
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
import { api } from "../../react-openapi";
|
|
||||||
import { LatestItem } from "../components/LatestItemsList";
|
|
||||||
import { ChartDataPoint } from "../types/historyChart";
|
|
||||||
import * as React from "react";
|
|
||||||
import { format } from "./dateUtils";
|
|
||||||
import MonetizationOnIcon from "@mui/icons-material/MonetizationOn";
|
|
||||||
|
|
||||||
import {
|
|
||||||
buildDailyBuckets,
|
|
||||||
buildWeeklyRolling,
|
|
||||||
buildWeeklyCalendar,
|
|
||||||
buildMonthlyRolling,
|
|
||||||
buildMonthlyCalendar
|
|
||||||
} from "./periodBuilders";
|
|
||||||
|
|
||||||
const DEFAULT_ICON = React.createElement(MonetizationOnIcon, {
|
|
||||||
sx: { color: "#388e3c" }
|
|
||||||
});
|
|
||||||
|
|
||||||
export async function fetchLatestTransactions(
|
|
||||||
type: "expense" | "income"
|
|
||||||
): Promise<LatestItem[]> {
|
|
||||||
const res = await api.get("/expenses", {
|
|
||||||
params: { limit: 100, sort: "-occurred_at" }
|
|
||||||
});
|
|
||||||
|
|
||||||
const items = res.data?.items || res.data || [];
|
|
||||||
|
|
||||||
const isValid = (amt: number) =>
|
|
||||||
type === "expense" ? amt < 0 : amt > 0;
|
|
||||||
|
|
||||||
return items
|
|
||||||
.filter((item: any) => isValid(Number(item.amount) || 0))
|
|
||||||
.slice(0, 5)
|
|
||||||
.map((exp: any, index: number) => {
|
|
||||||
const time = new Date(
|
|
||||||
exp.occurred_at || exp.created_at || Date.now()
|
|
||||||
).getTime();
|
|
||||||
|
|
||||||
const diffDays = Math.floor(
|
|
||||||
Math.abs(Date.now() - time) / (1000 * 60 * 60 * 24)
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: exp.id || index,
|
|
||||||
icon: DEFAULT_ICON,
|
|
||||||
iconBgColor:
|
|
||||||
type === "expense" ? "#ffebee" : "#e8f5e9",
|
|
||||||
title: exp.payee?.name || exp.payee || "Unknown Payee",
|
|
||||||
subtitle:
|
|
||||||
exp.category?.name || exp.account?.name || "Transaction",
|
|
||||||
amount: `Rs ${Math.abs(exp.amount || 0)}`,
|
|
||||||
timeAgo: diffDays === 0 ? "Today" : `${diffDays} days ago`
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchAggregatedData(
|
|
||||||
type: "expense" | "income"
|
|
||||||
) {
|
|
||||||
const res = await api.get("/expenses", { params: { limit: 0 } });
|
|
||||||
const all: any[] = res.data?.items || res.data || [];
|
|
||||||
|
|
||||||
const now = new Date();
|
|
||||||
|
|
||||||
let totalAmount = 0;
|
|
||||||
const payeeMap: Record<string, number> = {};
|
|
||||||
|
|
||||||
const isValid = (amt: number) =>
|
|
||||||
type === "expense" ? amt < 0 : amt > 0;
|
|
||||||
|
|
||||||
const normalize = (amt: number) => Math.abs(amt);
|
|
||||||
|
|
||||||
const {
|
|
||||||
buckets: dailyBuckets,
|
|
||||||
weekStart,
|
|
||||||
weekEnd,
|
|
||||||
prevWeekStart,
|
|
||||||
prevWeekEnd
|
|
||||||
} = buildDailyBuckets(now);
|
|
||||||
|
|
||||||
const weeklyRolling = buildWeeklyRolling(now);
|
|
||||||
const weeklyCalendar = buildWeeklyCalendar(now);
|
|
||||||
const monthlyRolling = buildMonthlyRolling(now);
|
|
||||||
const monthlyCalendar = buildMonthlyCalendar(now);
|
|
||||||
|
|
||||||
for (const item of all) {
|
|
||||||
const d = new Date(
|
|
||||||
item.occurred_at || item.created_at || Date.now()
|
|
||||||
);
|
|
||||||
|
|
||||||
const amtRaw = Number(item.amount) || 0;
|
|
||||||
if (!isValid(amtRaw)) continue;
|
|
||||||
|
|
||||||
const amt = normalize(amtRaw);
|
|
||||||
totalAmount += amt;
|
|
||||||
|
|
||||||
const payee = item.payee?.name || item.payee || "Unknown";
|
|
||||||
payeeMap[payee] = (payeeMap[payee] || 0) + amt;
|
|
||||||
|
|
||||||
const day = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()];
|
|
||||||
|
|
||||||
if (d >= weekStart && d <= weekEnd) {
|
|
||||||
if (dailyBuckets[day]) {
|
|
||||||
dailyBuckets[day].amount += amt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (d >= prevWeekStart && d <= prevWeekEnd) {
|
|
||||||
if (dailyBuckets[day]) {
|
|
||||||
dailyBuckets[day].compare += amt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const apply = (arr: any[]) => {
|
|
||||||
for (const b of arr) {
|
|
||||||
if (d >= b.start && d <= b.end) b.amount += amt;
|
|
||||||
if (d >= b.prevStart && d <= b.prevEnd)
|
|
||||||
b.compare += amt;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
apply(weeklyRolling);
|
|
||||||
apply(weeklyCalendar);
|
|
||||||
apply(monthlyRolling);
|
|
||||||
apply(monthlyCalendar);
|
|
||||||
}
|
|
||||||
|
|
||||||
const toPoints = (arr: any[], type: "weekly" | "monthly"): ChartDataPoint[] =>
|
|
||||||
arr.map((x) => {
|
|
||||||
let compareLabel: string | undefined;
|
|
||||||
|
|
||||||
if (x.prevStart && x.prevEnd) {
|
|
||||||
if (type === "monthly") {
|
|
||||||
const year = String(x.prevStart.getFullYear()).slice(2);
|
|
||||||
compareLabel = `${x.prevStart.toLocaleString("default", {
|
|
||||||
month: "short"
|
|
||||||
})}-${year}`;
|
|
||||||
} else {
|
|
||||||
const year = String(x.prevEnd.getFullYear()).slice(2);
|
|
||||||
compareLabel = `${format(x.prevStart)} - ${format(x.prevEnd)} ${year}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: x.label,
|
|
||||||
amount: x.amount,
|
|
||||||
compareAmount: x.compare,
|
|
||||||
compareLabel
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const chartData = {
|
|
||||||
daily: Object.entries(dailyBuckets).map(([k, v]: any) => ({
|
|
||||||
id: k,
|
|
||||||
amount: v.amount,
|
|
||||||
compareAmount: v.compare
|
|
||||||
})),
|
|
||||||
weekly: {
|
|
||||||
rolling: toPoints(weeklyRolling, "weekly"),
|
|
||||||
calendar: toPoints(weeklyCalendar, "weekly")
|
|
||||||
},
|
|
||||||
monthly: {
|
|
||||||
rolling: toPoints(monthlyRolling, "monthly"),
|
|
||||||
calendar: toPoints(monthlyCalendar, "monthly")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Object.values(chartData).forEach((group: any) => {
|
|
||||||
const arr = Array.isArray(group) ? group : group.rolling;
|
|
||||||
if (!arr?.length) return;
|
|
||||||
|
|
||||||
let max = arr[0];
|
|
||||||
for (const g of arr) {
|
|
||||||
if (g.amount > max.amount) max = g;
|
|
||||||
}
|
|
||||||
if (max.amount > 0) max.highlighted = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
const topPayees = Object.entries(payeeMap)
|
|
||||||
.map(([name, amt]) => ({ payeeName: name, amount: amt }))
|
|
||||||
.sort((a, b) => b.amount - a.amount)
|
|
||||||
.slice(0, 5);
|
|
||||||
|
|
||||||
return { chartData, totalAmount, topPayees };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const fetchAggregatedExpenses = () =>
|
|
||||||
fetchAggregatedData("expense");
|
|
||||||
|
|
||||||
export const fetchAggregatedIncome = () =>
|
|
||||||
fetchAggregatedData("income");
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
export const format = (d: Date) =>
|
|
||||||
`${d.getDate()} ${d.toLocaleString("default", { month: "short" })}`;
|
|
||||||
|
|
||||||
export const startOfDay = (d: Date) => {
|
|
||||||
const x = new Date(d);
|
|
||||||
x.setHours(0, 0, 0, 0);
|
|
||||||
return x;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const endOfDay = (d: Date) => {
|
|
||||||
const x = new Date(d);
|
|
||||||
x.setHours(23, 59, 59, 999);
|
|
||||||
return x;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getStartOfWeek = (d: Date) => {
|
|
||||||
const date = new Date(d);
|
|
||||||
const day = date.getDay() || 7;
|
|
||||||
if (day !== 1) date.setDate(date.getDate() - (day - 1));
|
|
||||||
return startOfDay(date);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const shiftDate = (d: Date, days: number) =>
|
|
||||||
new Date(d.getTime() + days * 86400000);
|
|
||||||
|
|
||||||
export const getWeekIndex = (date: Date) => {
|
|
||||||
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
|
|
||||||
const firstWeekStart = getStartOfWeek(firstDay);
|
|
||||||
return Math.floor(
|
|
||||||
(startOfDay(date).getTime() - firstWeekStart.getTime()) /
|
|
||||||
(7 * 86400000)
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
import {
|
|
||||||
format,
|
|
||||||
endOfDay,
|
|
||||||
getStartOfWeek,
|
|
||||||
shiftDate,
|
|
||||||
getWeekIndex
|
|
||||||
} from "./dateUtils";
|
|
||||||
|
|
||||||
export const buildDailyBuckets = (now: Date) => {
|
|
||||||
const buckets: Record<string, any> = {
|
|
||||||
Mon: { amount: 0, compare: 0 },
|
|
||||||
Tue: { amount: 0, compare: 0 },
|
|
||||||
Wed: { amount: 0, compare: 0 },
|
|
||||||
Thu: { amount: 0, compare: 0 },
|
|
||||||
Fri: { amount: 0, compare: 0 },
|
|
||||||
Sat: { amount: 0, compare: 0 },
|
|
||||||
Sun: { amount: 0, compare: 0 }
|
|
||||||
};
|
|
||||||
|
|
||||||
const weekStart = getStartOfWeek(now);
|
|
||||||
const weekEnd = endOfDay(new Date(weekStart.getTime() + 6 * 86400000));
|
|
||||||
const prevWeekStart = shiftDate(weekStart, -7);
|
|
||||||
const prevWeekEnd = shiftDate(weekEnd, -7);
|
|
||||||
|
|
||||||
return { buckets, weekStart, weekEnd, prevWeekStart, prevWeekEnd };
|
|
||||||
};
|
|
||||||
|
|
||||||
const getPrevMonthWeek = (start: Date) => {
|
|
||||||
const prevMonthDate = new Date(start);
|
|
||||||
prevMonthDate.setMonth(prevMonthDate.getMonth() - 1);
|
|
||||||
|
|
||||||
const prevMonthFirst = new Date(
|
|
||||||
prevMonthDate.getFullYear(),
|
|
||||||
prevMonthDate.getMonth(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
|
|
||||||
const prevFirstWeekStart = getStartOfWeek(prevMonthFirst);
|
|
||||||
const weekIndex = getWeekIndex(start);
|
|
||||||
|
|
||||||
const prevStart = new Date(
|
|
||||||
prevFirstWeekStart.getTime() + weekIndex * 7 * 86400000
|
|
||||||
);
|
|
||||||
const prevEnd = endOfDay(new Date(prevStart.getTime() + 6 * 86400000));
|
|
||||||
|
|
||||||
return { prevStart, prevEnd };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const buildWeeklyRolling = (now: Date) => {
|
|
||||||
const arr: any[] = [];
|
|
||||||
const currentWeekStart = getStartOfWeek(now);
|
|
||||||
|
|
||||||
for (let i = 4; i >= 0; i--) {
|
|
||||||
const start = new Date(
|
|
||||||
currentWeekStart.getTime() - i * 7 * 86400000
|
|
||||||
);
|
|
||||||
const end = endOfDay(new Date(start.getTime() + 6 * 86400000));
|
|
||||||
|
|
||||||
const { prevStart, prevEnd } = getPrevMonthWeek(start);
|
|
||||||
|
|
||||||
arr.push({
|
|
||||||
label: `${format(start)} - ${format(end)}`,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
amount: 0,
|
|
||||||
compare: 0,
|
|
||||||
prevStart,
|
|
||||||
prevEnd
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const buildWeeklyCalendar = (now: Date) => {
|
|
||||||
const arr: any[] = [];
|
|
||||||
|
|
||||||
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
||||||
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
|
|
||||||
const firstWeekStart = getStartOfWeek(startOfMonth);
|
|
||||||
|
|
||||||
const totalWeeks =
|
|
||||||
Math.ceil(
|
|
||||||
(endOfMonth.getTime() - firstWeekStart.getTime()) /
|
|
||||||
(7 * 86400000)
|
|
||||||
) + 1;
|
|
||||||
|
|
||||||
for (let i = 0; i < totalWeeks; i++) {
|
|
||||||
const start = new Date(
|
|
||||||
firstWeekStart.getTime() + i * 7 * 86400000
|
|
||||||
);
|
|
||||||
const end = endOfDay(new Date(start.getTime() + 6 * 86400000));
|
|
||||||
|
|
||||||
const { prevStart, prevEnd } = getPrevMonthWeek(start);
|
|
||||||
|
|
||||||
arr.push({
|
|
||||||
label: `${format(start)} - ${format(end)}`,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
amount: 0,
|
|
||||||
compare: 0,
|
|
||||||
prevStart,
|
|
||||||
prevEnd
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const buildMonthlyRolling = (now: Date) => {
|
|
||||||
const arr: any[] = [];
|
|
||||||
|
|
||||||
for (let i = 11; i >= 0; i--) {
|
|
||||||
const d = new Date(now);
|
|
||||||
d.setMonth(d.getMonth() - i);
|
|
||||||
|
|
||||||
const start = new Date(d.getFullYear(), d.getMonth(), 1);
|
|
||||||
const end =
|
|
||||||
i === 0
|
|
||||||
? endOfDay(now)
|
|
||||||
: endOfDay(new Date(d.getFullYear(), d.getMonth() + 1, 0));
|
|
||||||
|
|
||||||
const prevStart = new Date(start);
|
|
||||||
prevStart.setFullYear(prevStart.getFullYear() - 1);
|
|
||||||
|
|
||||||
let prevEnd = new Date(end);
|
|
||||||
prevEnd.setFullYear(prevEnd.getFullYear() - 1);
|
|
||||||
|
|
||||||
if (i === 0) {
|
|
||||||
prevEnd = new Date(prevStart);
|
|
||||||
prevEnd.setDate(now.getDate());
|
|
||||||
prevEnd = endOfDay(prevEnd);
|
|
||||||
}
|
|
||||||
|
|
||||||
arr.push({
|
|
||||||
label: `${d.toLocaleString("default", {
|
|
||||||
month: "short"
|
|
||||||
})}-${String(d.getFullYear()).slice(2)}`,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
amount: 0,
|
|
||||||
compare: 0,
|
|
||||||
prevStart,
|
|
||||||
prevEnd
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const buildMonthlyCalendar = (now: Date) => {
|
|
||||||
const arr: any[] = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < 12; i++) {
|
|
||||||
const start = new Date(now.getFullYear(), i, 1);
|
|
||||||
const end = endOfDay(new Date(now.getFullYear(), i + 1, 0));
|
|
||||||
|
|
||||||
const prevStart = new Date(start);
|
|
||||||
prevStart.setFullYear(prevStart.getFullYear() - 1);
|
|
||||||
|
|
||||||
const prevEnd = new Date(end);
|
|
||||||
prevEnd.setFullYear(prevEnd.getFullYear() - 1);
|
|
||||||
|
|
||||||
arr.push({
|
|
||||||
label: `${start.toLocaleString("default", {
|
|
||||||
month: "short"
|
|
||||||
})}-${String(start.getFullYear()).slice(2)}`,
|
|
||||||
start,
|
|
||||||
end,
|
|
||||||
amount: 0,
|
|
||||||
compare: 0,
|
|
||||||
prevStart,
|
|
||||||
prevEnd
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return arr;
|
|
||||||
};
|
|
||||||
Reference in New Issue
Block a user