Compare commits
11 Commits
38f7416942
...
0.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 5fb810bd5a | |||
| 2a12e33e22 | |||
| 7dd685ae49 | |||
| 86bb9ab222 | |||
| de59ef1f7d | |||
| 16d164b92a | |||
| 8bea3d06f6 | |||
| ad62d7dd9c | |||
| 77b60ba073 | |||
| f213a9455b | |||
| 009ab50b47 |
@@ -7,6 +7,28 @@ import { createApiClient } from "../../react-auth";
|
||||
let _api: AxiosInstance | null = null;
|
||||
let _auth: AxiosInstance | null = null;
|
||||
|
||||
function withParamsSerializer(instance: AxiosInstance): AxiosInstance {
|
||||
instance.defaults.paramsSerializer = {
|
||||
serialize: (params) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => {
|
||||
searchParams.append(key, String(v)); // NO []
|
||||
});
|
||||
} else if (value !== undefined && value !== null) {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
|
||||
return searchParams.toString();
|
||||
},
|
||||
};
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (...args: Parameters<AxiosInstance["get"]>) => {
|
||||
if (!_api) throw new Error("API client not initialized");
|
||||
@@ -38,6 +60,6 @@ export const auth = {
|
||||
};
|
||||
|
||||
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
||||
_api = createApiClient(baseUrl);
|
||||
_auth = createApiClient(authBaseUrl);
|
||||
_api = withParamsSerializer(createApiClient(baseUrl));
|
||||
_auth = withParamsSerializer(createApiClient(authBaseUrl));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQuery, useMutation, useQueryClient, keepPreviousData } from "@tanstack/react-query";
|
||||
import { api } from "../api/client";
|
||||
import { ResourceConfig } from "../types/config";
|
||||
import { ConfigContext } from "../providers/ConfigContext";
|
||||
@@ -26,6 +26,7 @@ export function useResource<T = any>(config: ResourceConfig | undefined) {
|
||||
};
|
||||
},
|
||||
enabled: !!endpoint,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
|
||||
// --- READ ONE ---
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import * as React from "react";
|
||||
import { ThemeProvider, createTheme } from "@mui/material/styles";
|
||||
import { getDesignTokens } from "./shared-theme/themePrimitives";
|
||||
import { inputsCustomizations } from "./shared-theme/customizations/inputs";
|
||||
import { dataDisplayCustomizations } from "./shared-theme/customizations/dataDisplay";
|
||||
import { feedbackCustomizations } from "./shared-theme/customizations/feedback";
|
||||
import { navigationCustomizations } from "./shared-theme/customizations/navigation";
|
||||
import { surfacesCustomizations } from "./shared-theme/customizations/surfaces";
|
||||
|
||||
export const ColorModeContext = React.createContext({
|
||||
toggleColorMode: () => {},
|
||||
mode: "light" as "light" | "dark",
|
||||
});
|
||||
|
||||
export default function AppTheme({ children }: { children: React.ReactNode }) {
|
||||
const [mode, setMode] = React.useState<"light" | "dark">("light");
|
||||
|
||||
const colorMode = React.useMemo(
|
||||
() => ({
|
||||
toggleColorMode: () => {
|
||||
setMode((prevMode) => (prevMode === "light" ? "dark" : "light"));
|
||||
},
|
||||
mode,
|
||||
}),
|
||||
[mode]
|
||||
);
|
||||
|
||||
const theme = React.useMemo(
|
||||
() =>
|
||||
createTheme({
|
||||
...getDesignTokens(mode),
|
||||
components: {
|
||||
...inputsCustomizations,
|
||||
...dataDisplayCustomizations,
|
||||
...feedbackCustomizations,
|
||||
...navigationCustomizations,
|
||||
...surfacesCustomizations,
|
||||
},
|
||||
}),
|
||||
[mode]
|
||||
);
|
||||
|
||||
return (
|
||||
<ColorModeContext.Provider value={colorMode}>
|
||||
<ThemeProvider theme={theme}>{children}</ThemeProvider>
|
||||
</ColorModeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -3,18 +3,203 @@ import {
|
||||
Box,
|
||||
Container,
|
||||
CircularProgress,
|
||||
Alert
|
||||
Alert,
|
||||
TextField,
|
||||
Paper,
|
||||
Autocomplete,
|
||||
Button
|
||||
} from "@mui/material";
|
||||
|
||||
import ConfigurableDashboard from "./components/Dashboard";
|
||||
import DashboardView from "./components/Dashboard";
|
||||
|
||||
import {
|
||||
DashboardState,
|
||||
DashboardStateSetters,
|
||||
DashboardFlow,
|
||||
} from "./components/Dashboard";
|
||||
|
||||
import { configuration } from "./dashboard-config";
|
||||
import { useDashboardData } from "./features/dashboard";
|
||||
import {
|
||||
useReport,
|
||||
prepareReport,
|
||||
} from "./features/report";
|
||||
|
||||
export default function Dashboard() {
|
||||
const [mode, setMode] = React.useState<"expense" | "income">("expense");
|
||||
const { data, latest, isLoading, error } = useDashboardData(mode);
|
||||
const [state, setState] = React.useState<DashboardState>({
|
||||
flow: "outflows",
|
||||
periodType: "rolling",
|
||||
selectedPeriodId: null,
|
||||
selectedGroupKey: null,
|
||||
comparison: false,
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
const [appliedPayees, setAppliedPayees] = React.useState<string[]>([]);
|
||||
const [appliedTags, setAppliedTags] = React.useState<string[]>([]);
|
||||
|
||||
const [payeeInput, setPayeeInput] = React.useState<string[]>([]);
|
||||
const [tagsInput, setTagsInput] = React.useState<string[]>([]);
|
||||
|
||||
const [loadedPayees, setLoadedPayees] = React.useState<string[]>([]);
|
||||
const [loadedTags, setLoadedTags] = React.useState<string[]>([]);
|
||||
|
||||
const report = useReport({
|
||||
periods: ["daily", "weekly", "monthly", "all"],
|
||||
flow: state.flow,
|
||||
payee: appliedPayees.length > 0 ? appliedPayees : undefined,
|
||||
tags: appliedTags.length > 0 ? appliedTags : undefined,
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (report.data?.data) {
|
||||
setLoadedPayees(prev => {
|
||||
const pSet = new Set<string>(prev);
|
||||
report.data.data.buckets.forEach((b: any) => {
|
||||
Object.values(b.periods).forEach((periodArray: any) => {
|
||||
periodArray?.forEach((p: any) => {
|
||||
p.metric?.transactions?.forEach((t: any) => {
|
||||
if (t.payee?.name) pSet.add(t.payee.name);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
return Array.from(pSet).sort();
|
||||
});
|
||||
|
||||
setLoadedTags(prev => {
|
||||
const tSet = new Set<string>(prev);
|
||||
report.data.data.buckets.forEach((b: any) => {
|
||||
Object.values(b.periods).forEach((periodArray: any) => {
|
||||
periodArray?.forEach((p: any) => {
|
||||
p.metric?.transactions?.forEach((t: any) => {
|
||||
t.tags?.forEach((tag: any) => tSet.add(tag.name || tag));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
return Array.from(tSet).sort();
|
||||
});
|
||||
}
|
||||
}, [report.data?.data]);
|
||||
|
||||
const toggleFlow =
|
||||
React.useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
|
||||
flow:
|
||||
prev.flow ===
|
||||
"outflows"
|
||||
? "inflows"
|
||||
: "outflows",
|
||||
|
||||
selectedGroupKey:
|
||||
null,
|
||||
|
||||
selectedPeriodId:
|
||||
null,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setFlow =
|
||||
React.useCallback(
|
||||
(
|
||||
flow: DashboardFlow
|
||||
) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
|
||||
flow,
|
||||
|
||||
selectedGroupKey:
|
||||
null,
|
||||
|
||||
selectedPeriodId:
|
||||
null,
|
||||
}));
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const togglePeriodType =
|
||||
React.useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
|
||||
periodType:
|
||||
prev.periodType ===
|
||||
"rolling"
|
||||
? "calendar"
|
||||
: "rolling",
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const toggleComparison =
|
||||
React.useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
|
||||
comparison:
|
||||
!prev.comparison,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setSelectedPeriodId =
|
||||
React.useCallback(
|
||||
(
|
||||
selectedPeriodId: DashboardState["selectedPeriodId"]
|
||||
) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
|
||||
selectedPeriodId,
|
||||
}));
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const setSelectedGroupKey =
|
||||
React.useCallback(
|
||||
(
|
||||
selectedGroupKey: DashboardState["selectedGroupKey"]
|
||||
) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
|
||||
selectedGroupKey,
|
||||
}));
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const stateSetters: DashboardStateSetters =
|
||||
React.useMemo(
|
||||
() => ({
|
||||
toggleFlow,
|
||||
|
||||
setFlow,
|
||||
|
||||
togglePeriodType,
|
||||
|
||||
toggleComparison,
|
||||
|
||||
setSelectedPeriodId,
|
||||
|
||||
setSelectedGroupKey,
|
||||
}),
|
||||
[
|
||||
toggleFlow,
|
||||
setFlow,
|
||||
togglePeriodType,
|
||||
toggleComparison,
|
||||
setSelectedPeriodId,
|
||||
setSelectedGroupKey,
|
||||
]
|
||||
);
|
||||
|
||||
const isLoading = report.isLoading;
|
||||
const error = report.error;
|
||||
|
||||
if (isLoading && !report.data) {
|
||||
return (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
|
||||
<CircularProgress />
|
||||
@@ -30,16 +215,77 @@ export default function Dashboard() {
|
||||
);
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
if (!report.data) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = prepareReport(report.data.data);
|
||||
return (
|
||||
<ConfigurableDashboard
|
||||
config={configuration}
|
||||
data={data}
|
||||
latest={latest}
|
||||
onModeChange={(newMode) => setMode(newMode)}
|
||||
/>
|
||||
<Box>
|
||||
<Container>
|
||||
<Paper
|
||||
sx={{
|
||||
mt: 4,
|
||||
p: 2,
|
||||
display: "flex",
|
||||
flexDirection: { xs: "column", sm: "row" },
|
||||
gap: 2,
|
||||
alignItems: { xs: "stretch", sm: "flex-end" },
|
||||
borderRadius: 4,
|
||||
mb: -2 // pull up to be closer to the dashboard container below
|
||||
}}
|
||||
elevation={0}
|
||||
variant="outlined"
|
||||
>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: { sm: 250 } }}>
|
||||
<Box sx={{ typography: 'caption', mb: 1, color: 'text.secondary' }}>
|
||||
Filter by Payee
|
||||
</Box>
|
||||
<Autocomplete
|
||||
multiple
|
||||
freeSolo
|
||||
options={loadedPayees}
|
||||
value={payeeInput}
|
||||
onChange={(_, val) => setPayeeInput(val as string[])}
|
||||
renderInput={(params) => <TextField {...params} placeholder="Add payees..." />}
|
||||
sx={{ '& .MuiOutlinedInput-root': { height: 'auto', minHeight: '2.5rem', py: 0.5 } }}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: { sm: 250 } }}>
|
||||
<Box sx={{ typography: 'caption', mb: 1, color: 'text.secondary' }}>
|
||||
Filter by Tags
|
||||
</Box>
|
||||
<Autocomplete
|
||||
multiple
|
||||
freeSolo
|
||||
options={loadedTags}
|
||||
value={tagsInput}
|
||||
onChange={(_, val) => setTagsInput(val as string[])}
|
||||
renderInput={(params) => <TextField {...params} placeholder="Add tags..." />}
|
||||
sx={{ '& .MuiOutlinedInput-root': { height: 'auto', minHeight: '2.5rem', py: 0.5 } }}
|
||||
/>
|
||||
</Box>
|
||||
<Button
|
||||
variant="contained"
|
||||
size="large"
|
||||
onClick={() => {
|
||||
setAppliedPayees(payeeInput);
|
||||
setAppliedTags(tagsInput);
|
||||
}}
|
||||
disabled={isLoading}
|
||||
sx={{ height: 40, borderRadius: 2 }}
|
||||
>
|
||||
Apply
|
||||
</Button>
|
||||
</Paper>
|
||||
</Container>
|
||||
<DashboardView
|
||||
config={configuration}
|
||||
data={data}
|
||||
state={state}
|
||||
stateSetters={stateSetters}
|
||||
isFetching={report.isFetching}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import DarkModeIcon from "@mui/icons-material/DarkMode";
|
||||
import LightModeIcon from "@mui/icons-material/LightMode";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuth } from "../react-auth";
|
||||
import { ColorModeContext } from "./AppTheme";
|
||||
import { ColorModeContext } from "./shared-theme/AppTheme";
|
||||
|
||||
interface HeaderProps {
|
||||
routerMapping: {
|
||||
|
||||
13
src/Home.tsx
13
src/Home.tsx
@@ -1,10 +1,12 @@
|
||||
import * as React from "react";
|
||||
import { Box, Typography, Button, Container, Stack } from "@mui/material";
|
||||
import { useTheme, alpha } from "@mui/material/styles";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
|
||||
|
||||
export default function Home() {
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<Box
|
||||
@@ -46,14 +48,13 @@ export default function Home() {
|
||||
sx={{
|
||||
p: { xs: 4, md: 8 },
|
||||
backdropFilter: "blur(20px)",
|
||||
backgroundColor: (theme) =>
|
||||
theme.palette.mode === "dark" ? "rgba(255, 255, 255, 0.03)" : "rgba(255, 255, 255, 0.6)",
|
||||
backgroundColor: (t) => alpha(t.palette.common.white, t.palette.mode === "dark" ? 0.04 : 0.6),
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 4,
|
||||
boxShadow: (theme) =>
|
||||
theme.palette.mode === "dark"
|
||||
? "0 8px 32px 0 rgba(0, 0, 0, 0.37)"
|
||||
boxShadow: (t) =>
|
||||
t.palette.mode === "dark"
|
||||
? "0 8px 32px 0 rgba(0, 0, 0, 0.5)"
|
||||
: "0 8px 32px 0 rgba(31, 38, 135, 0.07)",
|
||||
}}
|
||||
>
|
||||
@@ -94,7 +95,7 @@ export default function Home() {
|
||||
transition: "transform 0.2s ease-in-out, box-shadow 0.2s",
|
||||
"&:hover": {
|
||||
transform: "translateY(-3px)",
|
||||
boxShadow: "0 8px 20px rgba(236,72,153,0.4)",
|
||||
boxShadow: (t) => `0 8px 20px ${alpha(t.palette.primary.main, 0.4)}`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,49 +1,61 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
ReportData,
|
||||
GroupKey,
|
||||
} from "../../features/report";
|
||||
|
||||
export type DashboardMode = "expense" | "income";
|
||||
export type DashboardFlow = "outflows" | "inflows";
|
||||
export type DashboardPeriodType = "rolling" | "calendar";
|
||||
export type DashboardSelectedPeriodId = string | null;
|
||||
|
||||
export interface DashboardState {
|
||||
mode: DashboardMode;
|
||||
flow: DashboardFlow;
|
||||
periodType: DashboardPeriodType;
|
||||
selectedPeriodId: DashboardSelectedPeriodId;
|
||||
selectedGroupKey: GroupKey | null;
|
||||
comparison: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardStateSetters {
|
||||
setSelectedPeriodId: (id: DashboardSelectedPeriodId) => void;
|
||||
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
|
||||
toggleFlow: () => void;
|
||||
togglePeriodType: () => void;
|
||||
toggleComparison: () => void;
|
||||
}
|
||||
|
||||
export interface DashboardSection {
|
||||
id: string;
|
||||
title?: string;
|
||||
summary?: string;
|
||||
title: string;
|
||||
component: React.ComponentType<any>;
|
||||
dataKey?: string;
|
||||
summary?: 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 {
|
||||
export interface DashboardViewProps {
|
||||
config: DashboardConfig;
|
||||
data: any; // Aggregated data from features
|
||||
latest: any[]; // Latest items from features
|
||||
onModeChange?: (mode: DashboardMode) => void;
|
||||
data: ReportData;
|
||||
state: DashboardState;
|
||||
stateSetters: DashboardStateSetters;
|
||||
isFetching: boolean;
|
||||
}
|
||||
|
||||
export interface ColorScheme {
|
||||
primary: string;
|
||||
surface: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ComponentProps extends DashboardSection {
|
||||
reportData: ReportData;
|
||||
|
||||
state: DashboardState;
|
||||
stateSetters: DashboardStateSetters;
|
||||
isFetching: boolean;
|
||||
|
||||
colorScheme: ColorScheme;
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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",
|
||||
comparison: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<DashboardView
|
||||
{...props}
|
||||
state={state}
|
||||
setState={setState}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -3,93 +3,80 @@ import {
|
||||
Box,
|
||||
Container,
|
||||
Grid,
|
||||
Typography,
|
||||
ToggleButton,
|
||||
ToggleButtonGroup
|
||||
ToggleButtonGroup,
|
||||
Button
|
||||
} 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>>;
|
||||
}
|
||||
import { DashboardViewProps } from "./Dashboard.models";
|
||||
|
||||
export default function DashboardView({
|
||||
config,
|
||||
data,
|
||||
latest,
|
||||
state,
|
||||
setState,
|
||||
onModeChange
|
||||
}: ViewProps) {
|
||||
stateSetters,
|
||||
isFetching,
|
||||
}: DashboardViewProps) {
|
||||
const theme = useTheme();
|
||||
const themeMode = theme.palette.mode;
|
||||
const { mode, periodType, comparison } = state;
|
||||
|
||||
// Resolve colors with fallbacks
|
||||
const colors = React.useMemo(() => {
|
||||
const palette = config.style?.palette?.[mode];
|
||||
const modeColors = palette ? palette[themeMode] : null;
|
||||
const {
|
||||
flow,
|
||||
selectedGroupKey,
|
||||
} = state;
|
||||
|
||||
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]);
|
||||
|
||||
const handleModeChange = (_: any, newMode: any) => {
|
||||
if (newMode && onModeChange) {
|
||||
onModeChange(newMode);
|
||||
setState(prev => ({ ...prev, mode: newMode }));
|
||||
}
|
||||
};
|
||||
const colorScheme = flow === "outflows" ? theme.palette.flows.outflows : theme.palette.flows.inflows;
|
||||
|
||||
return (
|
||||
<Container
|
||||
sx={{
|
||||
mt: 4,
|
||||
mb: 4,
|
||||
background: `linear-gradient(180deg, ${colors.light} 0%, transparent 100%)`,
|
||||
background: `linear-gradient(180deg, ${alpha(colorScheme.primary, theme.palette.mode === "dark" ? 0.06 : 0.04)} 0%, transparent 100%)`,
|
||||
borderRadius: 4,
|
||||
p: 2,
|
||||
transition: 'background 0.3s ease'
|
||||
transition: "background 0.3s ease",
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", justifyContent: "center", mb: 3 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
mb: 3,
|
||||
}}
|
||||
>
|
||||
<ToggleButtonGroup
|
||||
value={mode}
|
||||
value={flow}
|
||||
exclusive
|
||||
onChange={handleModeChange}
|
||||
onChange={stateSetters.toggleFlow}
|
||||
sx={{
|
||||
borderRadius: 3,
|
||||
overflow: "hidden",
|
||||
"& .MuiToggleButton-root": {
|
||||
px: 3,
|
||||
textTransform: "none",
|
||||
color: "text.secondary"
|
||||
color: "text.secondary",
|
||||
},
|
||||
"&.Mui-selected": {
|
||||
bgcolor: colors.primary,
|
||||
bgcolor: colorScheme.primary,
|
||||
color: "white",
|
||||
borderColor: colors.primary
|
||||
borderColor: colorScheme.primary,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<ToggleButton value="expense">Expenses</ToggleButton>
|
||||
<ToggleButton value="income">Income</ToggleButton>
|
||||
<ToggleButton value="outflows">Outflows</ToggleButton>
|
||||
<ToggleButton value="inflows">Inflows</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
|
||||
{selectedGroupKey && Object.keys(selectedGroupKey).length > 0 && (
|
||||
<Button
|
||||
size="small"
|
||||
sx={{ mt: 1, textTransform: "none" }}
|
||||
onClick={() => stateSetters.setSelectedGroupKey(null)}
|
||||
>
|
||||
Clear Drill-down
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Grid container spacing={4}>
|
||||
@@ -97,54 +84,18 @@ export default function DashboardView({
|
||||
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>
|
||||
)}
|
||||
<Grid key={section.id} size={12}>
|
||||
<Component
|
||||
{...section}
|
||||
|
||||
{section.isList ? (
|
||||
<Box>
|
||||
{section.title && (
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Typography variant="h6" fontWeight={700}>
|
||||
{section.title}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
<Grid container spacing={2}>
|
||||
{(data[section.dataKey || ""] || []).map((item: any, idx: number) => (
|
||||
<Grid key={idx} size={{ xs: 12, sm: 6, md: 2.4 }}>
|
||||
<Component
|
||||
{...section.settings}
|
||||
header={item.payeeName || item.name}
|
||||
progressAmount={item.amount}
|
||||
totalAmount={data.totalAmount}
|
||||
colorTheme={mode === "expense" ? "error" : "success"}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
</Box>
|
||||
) : (
|
||||
<Component
|
||||
{...section.settings}
|
||||
header={section.title}
|
||||
summary={section.summary}
|
||||
data={section.dataKey ? data[section.dataKey] : data.chartData}
|
||||
items={section.dataKey === 'latest' ? latest : (data[section.dataKey || ''] || [])}
|
||||
title={section.title}
|
||||
accentColor={colors.primary}
|
||||
colorScheme={colors}
|
||||
periodType={periodType}
|
||||
onPeriodTypeChange={(p: any) => setState(prev => ({ ...prev, periodType: p }))}
|
||||
comparison={comparison}
|
||||
setComparison={(c: any) => setState(prev => ({ ...prev, comparison: c }))}
|
||||
/>
|
||||
)}
|
||||
reportData={data}
|
||||
|
||||
state={state}
|
||||
stateSetters={stateSetters}
|
||||
isFetching={isFetching}
|
||||
|
||||
colorScheme={colorScheme}
|
||||
/>
|
||||
</Grid>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export { default } from "./Dashboard";
|
||||
export { default } from "./Dashboard.view";
|
||||
export * from "./Dashboard.models";
|
||||
|
||||
73
src/components/HistoryChart/HistoryChart.adapter.ts
Normal file
73
src/components/HistoryChart/HistoryChart.adapter.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { ReportData } from "../../features/report";
|
||||
import {
|
||||
mergeBucketPeriods,
|
||||
getAmount,
|
||||
PeriodKey,
|
||||
} from "../report.helpers";
|
||||
import { ChartDataPoint } from "./HistoryChart.models";
|
||||
|
||||
// ─── Tab → PeriodKey ─────────────────────────────────────────
|
||||
|
||||
const TAB_TO_KEY: Record<string, PeriodKey> = {
|
||||
Daily: "daily",
|
||||
Weekly: "weekly",
|
||||
Monthly: "monthly",
|
||||
"All Time": "all",
|
||||
};
|
||||
|
||||
export function tabToKey(tab: string): PeriodKey {
|
||||
return TAB_TO_KEY[tab] ?? "all";
|
||||
}
|
||||
|
||||
// ─── Comparison ──────────────────────────────────────────────
|
||||
|
||||
function attachComparison(
|
||||
points: ChartDataPoint[],
|
||||
key: PeriodKey
|
||||
): ChartDataPoint[] {
|
||||
const getCompareIndex = (i: number) => {
|
||||
if (key === "daily") return i - 7;
|
||||
if (key === "weekly") return i - 4;
|
||||
if (key === "monthly") return i - 12;
|
||||
return -1;
|
||||
};
|
||||
|
||||
return points.map((p, i) => {
|
||||
const ci = getCompareIndex(i);
|
||||
|
||||
return {
|
||||
...p,
|
||||
compare:
|
||||
ci >= 0 && points[ci]
|
||||
? {
|
||||
id: points[ci].id,
|
||||
label: points[ci].label,
|
||||
amount: points[ci].amount,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Main adapter ────────────────────────────────────────────
|
||||
|
||||
export function buildChartData(
|
||||
reportData: ReportData,
|
||||
key: PeriodKey,
|
||||
flow: "outflows" | "inflows",
|
||||
comparison: boolean
|
||||
): ChartDataPoint[] {
|
||||
const merged = mergeBucketPeriods(reportData.buckets, key);
|
||||
|
||||
let points: ChartDataPoint[] = merged.map((p) => ({
|
||||
id: p.id,
|
||||
label: p.label,
|
||||
amount: getAmount(p),
|
||||
}));
|
||||
|
||||
if (comparison) {
|
||||
points = attachComparison(points, key);
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export interface _ChartDataPoint {
|
||||
id: string;
|
||||
label: string;
|
||||
amount: number;
|
||||
highlighted?: boolean;
|
||||
}
|
||||
@@ -7,31 +8,3 @@ export interface _ChartDataPoint {
|
||||
export interface ChartDataPoint extends _ChartDataPoint {
|
||||
compare?: _ChartDataPoint;
|
||||
}
|
||||
|
||||
export interface ChartData {
|
||||
daily?: ChartDataPoint[];
|
||||
weekly?: Record<string, ChartDataPoint[]>;
|
||||
monthly?: Record<string, ChartDataPoint[]>;
|
||||
}
|
||||
|
||||
export interface AggregatedDashboardData {
|
||||
chartData: ChartData;
|
||||
totalAmount: number;
|
||||
topPayees: Array<{ payeeName: string; amount: number }>;
|
||||
}
|
||||
|
||||
export interface HistoryChartProps {
|
||||
header: string;
|
||||
summary?: string;
|
||||
tabs: string[];
|
||||
data: ChartData;
|
||||
periodType: "rolling" | "calendar";
|
||||
onPeriodTypeChange: (p: "rolling" | "calendar") => void;
|
||||
comparison: boolean;
|
||||
setComparison: (v: boolean) => void;
|
||||
colorScheme: {
|
||||
primary: string;
|
||||
light: string;
|
||||
text: string;
|
||||
};
|
||||
}
|
||||
|
||||
21
src/components/HistoryChart/HistoryChart.props.ts
Normal file
21
src/components/HistoryChart/HistoryChart.props.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import * as React from "react";
|
||||
import { ComponentProps } from "../Dashboard";
|
||||
import { ChartDataPoint } from "./HistoryChart.models";
|
||||
|
||||
export interface HistoryChartProps extends ComponentProps {
|
||||
settings: {
|
||||
tabs: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface HistoryChartViewProps 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;
|
||||
}
|
||||
@@ -1,48 +1,84 @@
|
||||
import * as React from "react";
|
||||
import { ChartDataPoint, HistoryChartProps, ChartData } from "./HistoryChart.models";
|
||||
import HistoryChartView from "./HistoryChart.view";
|
||||
import { buildChartData, tabToKey } from "./HistoryChart.adapter";
|
||||
import { HistoryChartProps } from "./HistoryChart.props";
|
||||
|
||||
|
||||
export default function HistoryChart(props: HistoryChartProps) {
|
||||
const { tabs, data, periodType, comparison } = props;
|
||||
const {
|
||||
settings,
|
||||
reportData,
|
||||
state,
|
||||
stateSetters,
|
||||
|
||||
isFetching,
|
||||
} = props;
|
||||
|
||||
const { flow, comparison, selectedPeriodId } = state;
|
||||
const { setSelectedPeriodId } = stateSetters;
|
||||
const { tabs } = settings;
|
||||
|
||||
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
|
||||
const [startIndex, setStartIndex] = React.useState(0);
|
||||
|
||||
const activeDataKey = activeTab.toLowerCase() as keyof ChartData;
|
||||
const activeDataKey = tabToKey(activeTab);
|
||||
|
||||
let rawData: ChartDataPoint[] = [];
|
||||
|
||||
if (activeDataKey === "daily") {
|
||||
rawData = data.daily || [];
|
||||
} else {
|
||||
const section = data[activeDataKey];
|
||||
rawData = section?.[periodType] || [];
|
||||
}
|
||||
|
||||
const currentData = rawData;
|
||||
const currentData = React.useMemo(() => {
|
||||
return buildChartData(reportData, activeDataKey, flow, comparison);
|
||||
}, [reportData, activeDataKey, flow, comparison]);
|
||||
|
||||
const maxAmount =
|
||||
currentData.length > 0
|
||||
? Math.max(
|
||||
...currentData.flatMap((d) =>
|
||||
comparison ? [d.amount, d.compare?.amount ?? 0] : [d.amount]
|
||||
comparison
|
||||
? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
|
||||
: [d.amount]
|
||||
),
|
||||
1
|
||||
)
|
||||
: 1;
|
||||
|
||||
const visibleCountMap = { daily: 7, weekly: 6, monthly: 4 };
|
||||
const visibleCount = visibleCountMap[activeDataKey];
|
||||
const visibleCountMap = {
|
||||
daily: 7,
|
||||
weekly: 6,
|
||||
monthly: 4,
|
||||
all: 4,
|
||||
};
|
||||
|
||||
const visibleCount = visibleCountMap[activeDataKey] ?? 4;
|
||||
|
||||
const total = currentData.length;
|
||||
|
||||
const clampedStartIndex = Math.min(startIndex, Math.max(total - visibleCount, 0));
|
||||
const clampedStartIndex = Math.min(
|
||||
startIndex,
|
||||
Math.max(total - visibleCount, 0)
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (startIndex !== clampedStartIndex) {
|
||||
setStartIndex(clampedStartIndex);
|
||||
}
|
||||
}, [startIndex, clampedStartIndex]);
|
||||
|
||||
const visibleData = currentData.slice(
|
||||
clampedStartIndex,
|
||||
clampedStartIndex + visibleCount
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setSelectedPeriodId(null);
|
||||
}, [activeTab]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
selectedPeriodId &&
|
||||
!visibleData.some((p) => p.id === selectedPeriodId)
|
||||
) {
|
||||
setSelectedPeriodId(null);
|
||||
}
|
||||
}, [visibleData, selectedPeriodId]);
|
||||
|
||||
return (
|
||||
<HistoryChartView
|
||||
{...props}
|
||||
@@ -52,7 +88,7 @@ export default function HistoryChart(props: HistoryChartProps) {
|
||||
visibleData={visibleData}
|
||||
maxAmount={maxAmount}
|
||||
visibleCount={visibleCount}
|
||||
startIndex={startIndex}
|
||||
startIndex={clampedStartIndex}
|
||||
setStartIndex={setStartIndex}
|
||||
activeDataKey={activeDataKey}
|
||||
/>
|
||||
|
||||
@@ -25,19 +25,3 @@ export const formatDisplay = (
|
||||
|
||||
return `₹ ${formatShort(base)} (${sign}${formatShort(Math.abs(diff))})`;
|
||||
};
|
||||
|
||||
export 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 [endDay, month] = end.split(" ");
|
||||
return `${startDay}–${endDay} ${month}`;
|
||||
}
|
||||
}
|
||||
|
||||
return label;
|
||||
};
|
||||
|
||||
@@ -11,60 +11,60 @@ 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, formatLabel } from "./HistoryChart.utils";
|
||||
HistoryChartViewProps,
|
||||
} from "./HistoryChart.props";
|
||||
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({
|
||||
title,
|
||||
summary,
|
||||
settings,
|
||||
|
||||
export default function HistoryChartView(props: ViewProps) {
|
||||
const {
|
||||
header,
|
||||
summary,
|
||||
tabs,
|
||||
periodType,
|
||||
onPeriodTypeChange,
|
||||
comparison,
|
||||
setComparison,
|
||||
colorScheme,
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
currentData,
|
||||
visibleData,
|
||||
maxAmount,
|
||||
visibleCount,
|
||||
startIndex,
|
||||
setStartIndex,
|
||||
activeDataKey,
|
||||
} = props;
|
||||
state,
|
||||
stateSetters,
|
||||
isFetching,
|
||||
|
||||
colorScheme,
|
||||
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
currentData,
|
||||
visibleData,
|
||||
maxAmount,
|
||||
visibleCount,
|
||||
startIndex,
|
||||
setStartIndex,
|
||||
activeDataKey,
|
||||
}: HistoryChartViewProps) {
|
||||
|
||||
const { flow, periodType, selectedPeriodId, comparison } = state;
|
||||
const { togglePeriodType, setSelectedPeriodId, toggleComparison } = stateSetters;
|
||||
|
||||
const theme = useTheme();
|
||||
const isDark = theme.palette.mode === "dark";
|
||||
|
||||
const total = currentData.length;
|
||||
const maxStartIndex = Math.max(total - visibleCount, 0);
|
||||
const clampedStartIndex = Math.min(startIndex, maxStartIndex);
|
||||
|
||||
const handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => {
|
||||
if (newTab !== null) setActiveTab(newTab);
|
||||
};
|
||||
|
||||
const canGoLeft = startIndex > 0;
|
||||
const canGoRight = startIndex + visibleCount < currentData.length;
|
||||
const canGoLeft = clampedStartIndex > 0;
|
||||
const canGoRight = clampedStartIndex < maxStartIndex;
|
||||
|
||||
const handlePrev = () => {
|
||||
if (canGoLeft) setStartIndex((prev) => prev - visibleCount);
|
||||
if (!canGoLeft) return;
|
||||
setStartIndex((prev) => Math.max(prev - visibleCount, 0));
|
||||
};
|
||||
|
||||
const handleNext = () => {
|
||||
if (canGoRight) setStartIndex((prev) => prev + visibleCount);
|
||||
if (!canGoRight) return;
|
||||
setStartIndex((prev) => {
|
||||
const next = prev + visibleCount;
|
||||
return Math.min(next, maxStartIndex);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -76,12 +76,14 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
boxShadow: "none",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
bgcolor: isDark ? "background.paper" : colorScheme.light,
|
||||
transition: 'background-color 0.3s ease, border-color 0.3s ease'
|
||||
bgcolor: isDark ? "background.paper" : colorScheme.surface,
|
||||
opacity: isFetching ? 0.6 : 1,
|
||||
transition: "opacity 0.3s ease",
|
||||
pointerEvents: isFetching ? "none" : "auto",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} gutterBottom sx={{ color: isDark ? 'text.primary' : colorScheme.text }}>
|
||||
{header}
|
||||
<Typography variant="h6" fontWeight={700} gutterBottom>
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
{summary && (
|
||||
@@ -91,42 +93,24 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
)}
|
||||
|
||||
<ToggleButtonGroup value={activeTab} exclusive onChange={handleTabChange} fullWidth sx={{ mb: 4 }}>
|
||||
{tabs.map((tab) => (
|
||||
{settings.tabs.map((tab) => (
|
||||
<ToggleButton key={tab} value={tab}>
|
||||
{tab}
|
||||
</ToggleButton>
|
||||
))}
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", mb: 3 }}>
|
||||
<ToggleButtonGroup value={periodType} exclusive onChange={(_, v) => v && onPeriodTypeChange(v)} size="small">
|
||||
<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" disabled={activeDataKey === "daily"}>
|
||||
Calendar
|
||||
</ToggleButton>
|
||||
<ToggleButton value="calendar">Calendar</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<ToggleButton
|
||||
value="compare"
|
||||
selected={comparison}
|
||||
onChange={() => setComparison(!comparison)}
|
||||
onChange={toggleComparison}
|
||||
size="small"
|
||||
sx={{
|
||||
textTransform: "none",
|
||||
borderRadius: 2,
|
||||
px: 2,
|
||||
color: "text.secondary",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
"&.Mui-selected": {
|
||||
color: "white",
|
||||
bgcolor: "success.main",
|
||||
borderColor: "success.main"
|
||||
},
|
||||
"&.Mui-selected:hover": {
|
||||
bgcolor: "success.dark"
|
||||
}
|
||||
}}
|
||||
>
|
||||
Compare
|
||||
</ToggleButton>
|
||||
@@ -135,19 +119,7 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
{currentData.length > 0 ? (
|
||||
<Box sx={{ position: "relative", mt: 4 }}>
|
||||
{canGoLeft && (
|
||||
<IconButton
|
||||
onClick={handlePrev}
|
||||
size="small"
|
||||
sx={{
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
top: "50%",
|
||||
transform: "translateY(-50%)",
|
||||
zIndex: 2,
|
||||
bgcolor: "background.paper",
|
||||
boxShadow: 1
|
||||
}}
|
||||
>
|
||||
<IconButton onClick={handlePrev} size="small" sx={{ position: "absolute", left: 0, top: "50%" }}>
|
||||
<ChevronLeftIcon fontSize="small" />
|
||||
</IconButton>
|
||||
)}
|
||||
@@ -158,78 +130,67 @@ export default function HistoryChartView(props: ViewProps) {
|
||||
const compareHeight = comparison
|
||||
? ((point.compare?.amount ?? 0) / maxAmount) * 100
|
||||
: 0;
|
||||
const labelHeight = Math.max(currentHeight, compareHeight);
|
||||
|
||||
const isSelected = selectedPeriodId === point.id;
|
||||
const display = formatDisplay(point, activeDataKey, comparison);
|
||||
|
||||
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 ? 1 : 0.5, 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",
|
||||
color: 'text.secondary',
|
||||
fontWeight: 600
|
||||
}}
|
||||
>
|
||||
{formatDisplay(point, activeTab.toLowerCase(), comparison)}
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
key={point.id}
|
||||
onClick={() =>
|
||||
setSelectedPeriodId(isSelected ? null : point.id)
|
||||
}
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
cursor: "pointer",
|
||||
height: "100%"
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "flex-end", gap: 1, height: "100%" }}>
|
||||
{comparison && (
|
||||
<Box sx={{ width: 8, height: `${compareHeight}%`, bgcolor: isDark ? alpha(colorScheme.primary, 0.3) : alpha(colorScheme.primary, 0.4), borderRadius: '4px 4px 0 0' }} />
|
||||
<Box
|
||||
sx={{
|
||||
width: 8,
|
||||
height: `${compareHeight}%`,
|
||||
bgcolor: alpha(colorScheme.primary, 0.4),
|
||||
borderRadius: "4px 4px 0 0"
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
width: comparison ? 10 : 16,
|
||||
width: 12,
|
||||
height: `${currentHeight}%`,
|
||||
bgcolor: point.highlighted ? colorScheme.primary : isDark ? alpha(colorScheme.primary, 0.8) : alpha(colorScheme.primary, 0.9),
|
||||
borderRadius: '4px 4px 0 0',
|
||||
boxShadow: point.highlighted ? `0 0 10px ${alpha(colorScheme.primary, 0.5)}` : 'none'
|
||||
bgcolor: isSelected ? "warning.main" : colorScheme.primary,
|
||||
borderRadius: "4px 4px 0 0"
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mt: 1.5, textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", lineHeight: 1.1 }}>
|
||||
<Typography variant="caption" sx={{ fontSize: "0.7rem", opacity: 0.8, color: 'text.primary', fontWeight: 500 }}>
|
||||
{formatLabel(point.id, activeDataKey)}
|
||||
</Typography>
|
||||
<Typography variant="caption">
|
||||
{point.label}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
fontSize: "0.65rem",
|
||||
color: "text.disabled",
|
||||
visibility: comparison && point.compare && activeDataKey !== "daily" ? "visible" : "hidden"
|
||||
}}
|
||||
>
|
||||
{point.compare ? formatLabel(point.compare.id, activeDataKey) : "placeholder"}
|
||||
{comparison && point.compare && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{point.compare.label}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Typography variant="caption">
|
||||
{display}
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
||||
{canGoRight && (
|
||||
<IconButton
|
||||
onClick={handleNext}
|
||||
size="small"
|
||||
sx={{
|
||||
position: "absolute",
|
||||
right: 0,
|
||||
top: "50%",
|
||||
transform: "translateY(-50%)",
|
||||
zIndex: 2,
|
||||
bgcolor: "background.paper",
|
||||
boxShadow: 1
|
||||
}}
|
||||
>
|
||||
<IconButton onClick={handleNext} size="small" sx={{ position: "absolute", right: 0, top: "50%" }}>
|
||||
<ChevronRightIcon fontSize="small" />
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
31
src/components/LatestItems/LatestItems.adapter.ts
Normal file
31
src/components/LatestItems/LatestItems.adapter.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { ReportData, GroupKey } from "../../features/report";
|
||||
import {
|
||||
formatCurrency,
|
||||
extractFilteredTransactions,
|
||||
} from "../report.helpers";
|
||||
import { LatestItem } from "./LatestItems.models";
|
||||
|
||||
// ─── Main adapter ────────────────────────────────────────────
|
||||
|
||||
export function buildLatestItems(
|
||||
reportData: ReportData,
|
||||
selectedPeriodId: string | null | undefined,
|
||||
selectedGroupKey: GroupKey | null | undefined,
|
||||
flow: "outflows" | "inflows"
|
||||
): LatestItem[] {
|
||||
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
|
||||
|
||||
return txns
|
||||
.sort(
|
||||
(a, b) =>
|
||||
new Date(b.occurred_at).getTime() -
|
||||
new Date(a.occurred_at).getTime()
|
||||
)
|
||||
.map((t, index) => ({
|
||||
id: index + 1,
|
||||
title: t.payee.name,
|
||||
subtitle: t.tags.map((tag) => tag.name).join(", "),
|
||||
amount: formatCurrency(t.amount),
|
||||
timeAgo: new Date(t.occurred_at).toLocaleDateString("en-IN"),
|
||||
}));
|
||||
}
|
||||
@@ -1,18 +1,7 @@
|
||||
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;
|
||||
}
|
||||
|
||||
10
src/components/LatestItems/LatestItems.props.ts
Normal file
10
src/components/LatestItems/LatestItems.props.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ComponentProps } from "../Dashboard";
|
||||
import { LatestItem } from "./LatestItems.models";
|
||||
|
||||
export interface LatestItemsProps extends ComponentProps {}
|
||||
|
||||
export interface LatestItemsViewProps extends LatestItemsProps {
|
||||
items: LatestItem[];
|
||||
canExpand: boolean;
|
||||
onExpand: () => void;
|
||||
}
|
||||
@@ -1,112 +1,40 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
List,
|
||||
ListItem,
|
||||
ListItemAvatar,
|
||||
ListItemText,
|
||||
Avatar,
|
||||
Typography,
|
||||
Box,
|
||||
Button,
|
||||
} from "@mui/material";
|
||||
import { buildLatestItems } from "./LatestItems.adapter";
|
||||
import LatestItemsView from "./LatestItems.view";
|
||||
import { LatestItemsProps } from "./LatestItems.props";
|
||||
|
||||
export interface LatestItem {
|
||||
id: string | number;
|
||||
icon: React.ReactNode;
|
||||
iconBgColor?: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
amount: string;
|
||||
timeAgo: string;
|
||||
}
|
||||
export default function LatestItems(props: LatestItemsProps) {
|
||||
const {
|
||||
reportData,
|
||||
state,
|
||||
stateSetters,
|
||||
isFetching,
|
||||
} = props;
|
||||
|
||||
export interface LatestItemsListProps {
|
||||
title?: string;
|
||||
items: LatestItem[];
|
||||
onViewAll?: () => void;
|
||||
accentColor: any;
|
||||
}
|
||||
const { flow, selectedPeriodId, selectedGroupKey } = state;
|
||||
const [visibleCount, setVisibleCount] = React.useState(5);
|
||||
|
||||
// Reset count when flow changes to start clean
|
||||
React.useEffect(() => {
|
||||
setVisibleCount(5);
|
||||
}, [flow]);
|
||||
|
||||
const allItems = React.useMemo(() => {
|
||||
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, flow);
|
||||
}, [reportData, selectedPeriodId, selectedGroupKey, flow]);
|
||||
|
||||
const visibleItems = React.useMemo(() => {
|
||||
return allItems.slice(0, visibleCount);
|
||||
}, [allItems, visibleCount]);
|
||||
|
||||
const canExpand = visibleCount < allItems.length;
|
||||
|
||||
export default function LatestItems({
|
||||
title = "Recent Transactions",
|
||||
items,
|
||||
onViewAll,
|
||||
accentColor,
|
||||
}: LatestItemsListProps) {
|
||||
return (
|
||||
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
|
||||
{/* Header */}
|
||||
<Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", mb: 2, px: 2 }}>
|
||||
<Typography variant="h6" fontWeight="bold">
|
||||
{title}
|
||||
</Typography>
|
||||
{onViewAll && (
|
||||
<Button
|
||||
variant="text"
|
||||
color="inherit"
|
||||
size="small"
|
||||
sx={{ textTransform: "none", color: "text.secondary", fontWeight: "medium" }}
|
||||
onClick={onViewAll}
|
||||
>
|
||||
view all
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* List */}
|
||||
<List disablePadding>
|
||||
{items.map((item, index) => (
|
||||
<ListItem
|
||||
key={item.id}
|
||||
sx={{
|
||||
px: { xs: 1, sm: 2 },
|
||||
py: 2,
|
||||
mb: index !== items.length - 1 ? 1 : 0,
|
||||
borderRadius: 3,
|
||||
"&:hover": { bgcolor: "action.hover" },
|
||||
transition: "background-color 0.2s ease",
|
||||
}}
|
||||
>
|
||||
<ListItemAvatar>
|
||||
<Avatar
|
||||
variant="rounded"
|
||||
sx={{
|
||||
bgcolor: `${accentColor}22`,
|
||||
color: "inherit",
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 3,
|
||||
mr: 2,
|
||||
}}
|
||||
>
|
||||
{item.icon}
|
||||
</Avatar>
|
||||
</ListItemAvatar>
|
||||
|
||||
<ListItemText
|
||||
primary={
|
||||
<Typography variant="subtitle1" fontWeight={600} color="text.primary">
|
||||
{item.title}
|
||||
</Typography>
|
||||
}
|
||||
secondary={
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{item.subtitle}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
|
||||
<Box sx={{ textAlign: "right" }}>
|
||||
<Typography variant="subtitle1" fontWeight={700} color="text.primary">
|
||||
{item.amount}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
|
||||
{item.timeAgo}
|
||||
</Typography>
|
||||
</Box>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</Box>
|
||||
<LatestItemsView
|
||||
{...props}
|
||||
items={visibleItems}
|
||||
canExpand={canExpand}
|
||||
onExpand={() => setVisibleCount((prev) => prev + 5)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,93 @@
|
||||
import LatestItemsListView from "./LatestItems.view";
|
||||
import { LatestItemsListProps } from "./LatestItems.models";
|
||||
import * as React from "react";
|
||||
import {
|
||||
List,
|
||||
ListItem,
|
||||
ListItemAvatar,
|
||||
ListItemText,
|
||||
Avatar,
|
||||
Typography,
|
||||
Box,
|
||||
IconButton,
|
||||
} from "@mui/material";
|
||||
import { alpha } from "@mui/material/styles";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import { LatestItemsViewProps } from "./LatestItems.props";
|
||||
|
||||
export default function LatestItemsList(props: LatestItemsListProps) {
|
||||
return <LatestItemsListView {...props} />;
|
||||
export default function LatestItemsView({
|
||||
items,
|
||||
title,
|
||||
canExpand,
|
||||
onExpand,
|
||||
isFetching,
|
||||
colorScheme,
|
||||
}: LatestItemsViewProps) {
|
||||
const accentColor = colorScheme?.primary || "";
|
||||
|
||||
return (
|
||||
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2, opacity: isFetching ? 0.6 : 1, transition: "opacity 0.3s ease", pointerEvents: isFetching ? "none" : "auto" }}>
|
||||
<Box sx={{ mb: 2, px: 2 }}>
|
||||
<Typography variant="h6" fontWeight="bold">
|
||||
{title}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<List disablePadding>
|
||||
{items.map((item, index) => (
|
||||
<ListItem
|
||||
key={item.id}
|
||||
sx={{
|
||||
px: { xs: 1, sm: 2 },
|
||||
py: 2,
|
||||
mb: index !== items.length - 1 ? 1 : 0,
|
||||
borderRadius: 3,
|
||||
"&:hover": { bgcolor: "action.hover" },
|
||||
}}
|
||||
>
|
||||
<ListItemAvatar>
|
||||
<Avatar
|
||||
variant="rounded"
|
||||
sx={{
|
||||
bgcolor: alpha(accentColor, 0.13),
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 3,
|
||||
mr: 2,
|
||||
}}
|
||||
/>
|
||||
</ListItemAvatar>
|
||||
|
||||
<ListItemText
|
||||
primary={
|
||||
<Typography variant="subtitle1" fontWeight={600}>
|
||||
{item.title}
|
||||
</Typography>
|
||||
}
|
||||
secondary={
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{item.subtitle}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
|
||||
<Box sx={{ textAlign: "right" }}>
|
||||
<Typography variant="subtitle1" fontWeight={700}>
|
||||
{item.amount}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{item.timeAgo}
|
||||
</Typography>
|
||||
</Box>
|
||||
</ListItem>
|
||||
))}
|
||||
|
||||
{canExpand && (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", mt: 2 }}>
|
||||
<IconButton size="small" onClick={onExpand}>
|
||||
<ExpandMoreIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</List>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
export interface ProgressCardProps {
|
||||
header: string;
|
||||
summary?: string;
|
||||
progressAmount: number;
|
||||
totalAmount: number;
|
||||
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
|
||||
compact?: boolean;
|
||||
}
|
||||
14
src/components/ProgressCard/ProgressCard.props.ts
Normal file
14
src/components/ProgressCard/ProgressCard.props.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ComponentProps } from "../Dashboard";
|
||||
|
||||
export interface ProgressCardProps extends ComponentProps {
|
||||
settings: {
|
||||
compact: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ProgressCardViewProps extends ProgressCardProps {
|
||||
progressAmount: number;
|
||||
totalAmount: number;
|
||||
selected: boolean;
|
||||
onClick: () => void;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
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)}`;
|
||||
};
|
||||
@@ -8,77 +8,79 @@ import {
|
||||
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;
|
||||
}
|
||||
import { getPercentage, formatCurrency } from "../report.helpers";
|
||||
import { ProgressCardViewProps } from "./ProgressCard.props";
|
||||
|
||||
export default function ProgressCardView({
|
||||
header,
|
||||
colorTheme = "info",
|
||||
percentage,
|
||||
formattedProgress,
|
||||
formattedTotal,
|
||||
compact = false,
|
||||
}: ViewProps) {
|
||||
title,
|
||||
settings,
|
||||
|
||||
isFetching,
|
||||
|
||||
colorScheme,
|
||||
|
||||
progressAmount,
|
||||
totalAmount,
|
||||
selected,
|
||||
onClick,
|
||||
}: ProgressCardViewProps) {
|
||||
const theme = useTheme();
|
||||
const isDark = theme.palette.mode === "dark";
|
||||
|
||||
const percentage = getPercentage(progressAmount, totalAmount);
|
||||
const formattedProgress = formatCurrency(progressAmount);
|
||||
const formattedTotal = formatCurrency(totalAmount);
|
||||
|
||||
return (
|
||||
<Paper
|
||||
elevation={compact ? 2 : 4}
|
||||
elevation={settings.compact ? 2 : 4}
|
||||
onClick={onClick}
|
||||
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",
|
||||
p: settings.compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
|
||||
borderRadius: settings.compact ? 3 : 4,
|
||||
transform: selected ? "scale(1.02)" : "scale(1)",
|
||||
transition: "transform 0.2s ease, box-shadow 0.2s ease",
|
||||
bgcolor: colorScheme.surface,
|
||||
color: colorScheme.text,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: compact ? "flex-start" : "center",
|
||||
alignItems: settings.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
|
||||
}`,
|
||||
border: selected
|
||||
? `2px solid ${colorScheme.primary}`
|
||||
: "1px solid",
|
||||
borderColor: selected ? colorScheme.primary : "divider",
|
||||
boxShadow: "none",
|
||||
opacity: isFetching ? 0.6 : 1,
|
||||
pointerEvents: isFetching ? "none" : "auto",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant={compact ? "body2" : "subtitle1"}
|
||||
variant={settings.compact ? "body2" : "subtitle1"}
|
||||
fontWeight={700}
|
||||
sx={{
|
||||
opacity: 0.95,
|
||||
mb: compact ? 1.5 : 2,
|
||||
width: '100%',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
mb: settings.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}
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
<Box sx={{ mb: compact ? 2 : 3, width: '100%' }}>
|
||||
<Box sx={{ mb: settings.compact ? 2 : 3, width: "100%" }}>
|
||||
<Typography
|
||||
variant={compact ? "h5" : "h3"}
|
||||
variant={settings.compact ? "h5" : "h3"}
|
||||
fontWeight={900}
|
||||
sx={{ mb: 0.5, lineHeight: 1.2, textShadow: isDark ? '0 2px 4px rgba(0,0,0,0.3)' : 'none' }}
|
||||
sx={{
|
||||
mb: 0.5,
|
||||
lineHeight: 1.2,
|
||||
}}
|
||||
>
|
||||
{formattedProgress}
|
||||
</Typography>
|
||||
@@ -86,38 +88,38 @@ export default function ProgressCardView({
|
||||
<Divider
|
||||
sx={{
|
||||
my: 1,
|
||||
borderColor: "rgba(255,255,255,0.25)",
|
||||
borderColor: "divider",
|
||||
width: "100%",
|
||||
}}
|
||||
/>
|
||||
|
||||
<Typography
|
||||
variant={compact ? "caption" : "body2"}
|
||||
variant={settings.compact ? "caption" : "body2"}
|
||||
sx={{
|
||||
opacity: 0.85,
|
||||
fontWeight: 500,
|
||||
display: "block",
|
||||
color: "rgba(255,255,255,0.9)"
|
||||
color: alpha(colorScheme.text, 0.85),
|
||||
}}
|
||||
>
|
||||
of {formattedTotal}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ width: "100%", mt: 'auto' }}>
|
||||
<Box sx={{ width: "100%", mt: "auto" }}>
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
value={percentage}
|
||||
sx={{
|
||||
height: compact ? 6 : 10,
|
||||
height: settings.compact ? 6 : 10,
|
||||
borderRadius: 5,
|
||||
[`&.${linearProgressClasses.colorPrimary}`]: {
|
||||
backgroundColor: "rgba(0, 0, 0, 0.25)",
|
||||
backgroundColor: alpha(theme.palette.divider, 0.5),
|
||||
},
|
||||
[`& .${linearProgressClasses.bar}`]: {
|
||||
borderRadius: 5,
|
||||
backgroundColor: "#fff",
|
||||
boxShadow: '0 0 8px rgba(255,255,255,0.4)'
|
||||
backgroundColor: colorScheme.primary,
|
||||
boxShadow: `0 0 8px ${alpha(colorScheme.primary, 0.4)}`,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
|
||||
31
src/components/ProgressCard/TopPayees.adapter.ts
Normal file
31
src/components/ProgressCard/TopPayees.adapter.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { GroupKey, ReportData } from "../../features/report";
|
||||
import {
|
||||
extractFilteredTransactions,
|
||||
aggregateTransactions,
|
||||
} from "../report.helpers";
|
||||
|
||||
export interface PayeeItem {
|
||||
name: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export function extractTopPayees(
|
||||
reportData: ReportData,
|
||||
flow: "outflows" | "inflows",
|
||||
selectedPeriodId?: string | null,
|
||||
selectedGroupKey?: GroupKey | null
|
||||
): { items: PayeeItem[]; total: number } {
|
||||
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
|
||||
|
||||
const { items, total } = aggregateTransactions(txns, (txn) => {
|
||||
if (txn.payee && txn.payee.name) {
|
||||
return [txn.payee.name];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
};
|
||||
}
|
||||
83
src/components/ProgressCard/TopPayees.tsx
Normal file
83
src/components/ProgressCard/TopPayees.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import * as React from "react";
|
||||
import { Box, Paper, Typography } from "@mui/material";
|
||||
import ProgressCardView from "./ProgressCard.view";
|
||||
import { extractTopPayees } from "./TopPayees.adapter";
|
||||
import { ProgressCardProps } from "./ProgressCard.props";
|
||||
|
||||
export default function TopPayees(props: ProgressCardProps) {
|
||||
const {
|
||||
title,
|
||||
|
||||
reportData,
|
||||
state,
|
||||
stateSetters,
|
||||
|
||||
isFetching,
|
||||
} = props
|
||||
const { flow, selectedPeriodId, selectedGroupKey } = state;
|
||||
const { setSelectedGroupKey } = stateSetters;
|
||||
|
||||
const { items, total } = React.useMemo(() => {
|
||||
return extractTopPayees(reportData, flow, selectedPeriodId, selectedGroupKey);
|
||||
}, [reportData, flow, selectedPeriodId, selectedGroupKey]);
|
||||
|
||||
return (
|
||||
<Paper
|
||||
sx={{
|
||||
p: { xs: 2.5, sm: 4 },
|
||||
borderRadius: 4,
|
||||
width: "100%",
|
||||
boxShadow: "none",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
bgcolor: "background.paper",
|
||||
opacity: isFetching ? 0.6 : 1,
|
||||
transition: "opacity 0.3s ease",
|
||||
pointerEvents: isFetching ? "none" : "auto",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} gutterBottom>
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: {
|
||||
xs: "1fr",
|
||||
sm: "repeat(2, 1fr)",
|
||||
md: "repeat(4, 1fr)",
|
||||
},
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
{items.map((item) => {
|
||||
const isSelected = !!selectedGroupKey?.payee?.includes(item.name);
|
||||
return (
|
||||
<ProgressCardView
|
||||
{...props}
|
||||
key={item.name}
|
||||
title={item.name}
|
||||
progressAmount={item.amount}
|
||||
totalAmount={total}
|
||||
selected={isSelected}
|
||||
onClick={() => {
|
||||
if (setSelectedGroupKey) {
|
||||
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};
|
||||
|
||||
if (isSelected) {
|
||||
delete newKey.payee;
|
||||
} else {
|
||||
newKey.payee = [item.name];
|
||||
}
|
||||
|
||||
setSelectedGroupKey(Object.keys(newKey).length ? newKey : null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
31
src/components/ProgressCard/TopTags.adapter.ts
Normal file
31
src/components/ProgressCard/TopTags.adapter.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { ReportData, GroupKey } from "../../features/report";
|
||||
import {
|
||||
extractFilteredTransactions,
|
||||
aggregateTransactions,
|
||||
} from "../report.helpers";
|
||||
|
||||
export interface TagItem {
|
||||
tag: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export function extractTopTags(
|
||||
reportData: ReportData,
|
||||
flow: "outflows" | "inflows",
|
||||
selectedPeriodId?: string | null,
|
||||
selectedGroupKey?: GroupKey | null
|
||||
): { items: TagItem[]; total: number } {
|
||||
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
|
||||
|
||||
const { items, total } = aggregateTransactions(txns, (txn) => {
|
||||
if (txn.tags && txn.tags.length > 0) {
|
||||
return txn.tags.map((t) => (typeof t === "string" ? t : t.name));
|
||||
}
|
||||
return ["Untagged"];
|
||||
});
|
||||
|
||||
return {
|
||||
items: items.map((item) => ({ tag: item.name, amount: item.amount })),
|
||||
total,
|
||||
};
|
||||
}
|
||||
83
src/components/ProgressCard/TopTags.tsx
Normal file
83
src/components/ProgressCard/TopTags.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import * as React from "react";
|
||||
import { Box, Paper, Typography } from "@mui/material";
|
||||
import ProgressCardView from "./ProgressCard.view";
|
||||
import { extractTopTags } from "./TopTags.adapter";
|
||||
import { ProgressCardProps } from "./ProgressCard.props";
|
||||
|
||||
export default function TopTags(props: ProgressCardProps) {
|
||||
const {
|
||||
title,
|
||||
|
||||
reportData,
|
||||
state,
|
||||
stateSetters,
|
||||
|
||||
isFetching,
|
||||
} = props
|
||||
const { flow, selectedPeriodId, selectedGroupKey } = state;
|
||||
const { setSelectedGroupKey } = stateSetters;
|
||||
|
||||
const { items, total } = React.useMemo(() => {
|
||||
return extractTopTags(reportData, flow, selectedPeriodId, selectedGroupKey);
|
||||
}, [reportData, flow, selectedPeriodId, selectedGroupKey]);
|
||||
|
||||
return (
|
||||
<Paper
|
||||
sx={{
|
||||
p: { xs: 2.5, sm: 4 },
|
||||
borderRadius: 4,
|
||||
width: "100%",
|
||||
boxShadow: "none",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
bgcolor: "background.paper",
|
||||
opacity: isFetching ? 0.6 : 1,
|
||||
transition: "opacity 0.3s ease",
|
||||
pointerEvents: isFetching ? "none" : "auto",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} gutterBottom>
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: {
|
||||
xs: "1fr",
|
||||
sm: "repeat(2, 1fr)",
|
||||
md: "repeat(4, 1fr)",
|
||||
},
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
{items.map((item) => {
|
||||
const isSelected = !!selectedGroupKey?.tags?.includes(item.tag);
|
||||
return (
|
||||
<ProgressCardView
|
||||
{...props}
|
||||
key={item.tag}
|
||||
title={item.tag}
|
||||
progressAmount={item.amount}
|
||||
totalAmount={total}
|
||||
selected={isSelected}
|
||||
onClick={() => {
|
||||
if (setSelectedGroupKey) {
|
||||
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};
|
||||
|
||||
if (isSelected) {
|
||||
delete newKey.tags;
|
||||
} else {
|
||||
newKey.tags = [item.tag];
|
||||
}
|
||||
|
||||
setSelectedGroupKey(Object.keys(newKey).length ? newKey : null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
export { default } from "./ProgressCard";
|
||||
export * from "./ProgressCard.models";
|
||||
export { default } from "./ProgressCard.view";
|
||||
export * from "./ProgressCard.props";
|
||||
|
||||
230
src/components/report.helpers.ts
Normal file
230
src/components/report.helpers.ts
Normal file
@@ -0,0 +1,230 @@
|
||||
import {
|
||||
ReportPeriod,
|
||||
ReportBucket,
|
||||
GroupKey,
|
||||
PeriodType,
|
||||
ReportData,
|
||||
Transaction,
|
||||
} from "../features/report";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────
|
||||
|
||||
export type PeriodKey = PeriodType;
|
||||
|
||||
export type DecoratedPeriod = ReportPeriod & {
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
// ─── Period helpers ───────────────────────────────────────────
|
||||
|
||||
const PREFIX_TO_KEY: Record<string, PeriodKey> = {
|
||||
D: "daily",
|
||||
W: "weekly",
|
||||
M: "monthly",
|
||||
ALL: "all",
|
||||
};
|
||||
|
||||
/**
|
||||
* Derive the period key from a decorated-period id.
|
||||
* E.g. `"W:2026-04-28_2026-05-04"` → `"weekly"`
|
||||
*/
|
||||
export function periodIdToKey(periodId: string): PeriodKey {
|
||||
const prefix = periodId.split(":")[0];
|
||||
return PREFIX_TO_KEY[prefix] ?? "all";
|
||||
}
|
||||
|
||||
// ─── Metric helpers ───────────────────────────────────────────
|
||||
|
||||
export function getAmount(period: ReportPeriod): number {
|
||||
return period.metric.sum;
|
||||
}
|
||||
|
||||
function mergeMetric(a: ReportPeriod["metric"], b: ReportPeriod["metric"]) {
|
||||
const sum = a.sum + b.sum;
|
||||
const count = a.count + b.count;
|
||||
|
||||
return {
|
||||
...a,
|
||||
sum,
|
||||
count,
|
||||
average: count > 0 ? sum / count : 0,
|
||||
transactions:
|
||||
a.transactions || b.transactions
|
||||
? [...(a.transactions || []), ...(b.transactions || [])]
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge periods with the same id across all buckets, summing
|
||||
* their metrics and concatenating transactions.
|
||||
*
|
||||
* Returns sorted by start date ascending.
|
||||
*/
|
||||
export function mergeBucketPeriods(
|
||||
buckets: ReportBucket[],
|
||||
key: PeriodKey
|
||||
): DecoratedPeriod[] {
|
||||
const map = new Map<string, DecoratedPeriod>();
|
||||
|
||||
for (const bucket of buckets) {
|
||||
const periods = (bucket.periods[key] || []) as DecoratedPeriod[];
|
||||
|
||||
for (const p of periods) {
|
||||
const existing = map.get(p.id);
|
||||
|
||||
if (!existing) {
|
||||
map.set(p.id, {
|
||||
...p,
|
||||
metric: { ...p.metric },
|
||||
});
|
||||
} else {
|
||||
map.set(p.id, {
|
||||
...existing,
|
||||
metric: mergeMetric(existing.metric, p.metric),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(map.values()).sort(
|
||||
(a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Formatting ───────────────────────────────────────────────
|
||||
|
||||
export const formatCurrency = (val: number) => {
|
||||
const absVal = Math.abs(val);
|
||||
if (absVal >= 100000) {
|
||||
return `₹ ${(val / 100000).toFixed(2)}L`;
|
||||
}
|
||||
if (absVal >= 1000) {
|
||||
return `₹ ${(val / 1000).toFixed(2)}k`;
|
||||
}
|
||||
return `₹ ${val.toFixed(2)}`;
|
||||
};
|
||||
|
||||
export const getPercentage = (progressAmount: number, totalAmount: number) => {
|
||||
if (!totalAmount) return 0;
|
||||
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
|
||||
};
|
||||
|
||||
// ─── Group filtering ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if a bucket's group_key matches the selected GroupKey.
|
||||
* Every dimension present in `selected` must exist in the bucket
|
||||
* and contain all the selected values.
|
||||
*/
|
||||
export function matchesGroupKey(
|
||||
bucket: ReportBucket,
|
||||
selected: GroupKey
|
||||
): boolean {
|
||||
for (const [dim, values] of Object.entries(selected)) {
|
||||
const bucketValues = bucket.group_key[dim];
|
||||
if (!bucketValues) return false;
|
||||
if (!(values as string[]).every((v) => bucketValues.includes(v)))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return only buckets matching the selected group key,
|
||||
* or all buckets if no selection.
|
||||
*/
|
||||
export function filterBuckets(
|
||||
buckets: ReportBucket[],
|
||||
selectedGroupKey: GroupKey | null
|
||||
): ReportBucket[] {
|
||||
if (!selectedGroupKey) return buckets;
|
||||
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
|
||||
}
|
||||
|
||||
export function extractFilteredTransactions(
|
||||
reportData: ReportData,
|
||||
selectedPeriodId: string | null | undefined,
|
||||
selectedGroupKey: GroupKey | null | undefined
|
||||
): Transaction[] {
|
||||
let txns: Transaction[] = [];
|
||||
|
||||
if (selectedPeriodId) {
|
||||
const key = periodIdToKey(selectedPeriodId);
|
||||
const periods = mergeBucketPeriods(reportData.buckets, key);
|
||||
const selected = periods.find((p) => p.id === selectedPeriodId);
|
||||
txns = selected?.metric.transactions || [];
|
||||
} else {
|
||||
const periods = mergeBucketPeriods(reportData.buckets, "all");
|
||||
if (periods.length > 0) {
|
||||
const period = periods.reduce((latest, p) =>
|
||||
new Date(p.start).getTime() > new Date(latest.start).getTime()
|
||||
? p
|
||||
: latest
|
||||
, periods[0]);
|
||||
txns = period?.metric.transactions || [];
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedGroupKey) {
|
||||
txns = txns.filter((txn) => {
|
||||
let match = true;
|
||||
if (selectedGroupKey.tags && selectedGroupKey.tags.length > 0) {
|
||||
if (!txn.tags) {
|
||||
match = false;
|
||||
} else {
|
||||
const txnTags = txn.tags.map((t: any) =>
|
||||
typeof t === "string" ? t : t.name
|
||||
);
|
||||
if (
|
||||
!selectedGroupKey.tags.every((selectedTag) =>
|
||||
txnTags.includes(selectedTag)
|
||||
)
|
||||
) {
|
||||
match = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (match && selectedGroupKey.payee && selectedGroupKey.payee.length > 0) {
|
||||
if (!txn.payee || !txn.payee.name) {
|
||||
match = false;
|
||||
} else {
|
||||
if (!selectedGroupKey.payee.includes(txn.payee.name)) {
|
||||
match = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return match;
|
||||
});
|
||||
}
|
||||
|
||||
return txns;
|
||||
}
|
||||
|
||||
export function aggregateTransactions(
|
||||
transactions: Transaction[],
|
||||
keyExtractor: (txn: Transaction) => string[],
|
||||
limit = 4
|
||||
): { items: { name: string; amount: number }[]; total: number } {
|
||||
const map = new Map<string, number>();
|
||||
|
||||
for (const txn of transactions) {
|
||||
const keys = keyExtractor(txn);
|
||||
for (const key of keys) {
|
||||
map.set(key, (map.get(key) || 0) + txn.amount);
|
||||
}
|
||||
}
|
||||
|
||||
const items = Array.from(map.entries()).map(([name, amount]) => ({
|
||||
name,
|
||||
amount,
|
||||
}));
|
||||
|
||||
items.sort((a, b) => b.amount - a.amount);
|
||||
|
||||
const top = items.slice(0, limit);
|
||||
const total = top.reduce((sum, item) => sum + item.amount, 0);
|
||||
|
||||
return { items: top, total };
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import HistoryChart from "./components/HistoryChart";
|
||||
import ProgressCard from "./components/ProgressCard";
|
||||
import LatestItems from "./components/LatestItems";
|
||||
import { DashboardConfig } from "./components/Dashboard";
|
||||
import TopTags from "./components/ProgressCard/TopTags";
|
||||
import TopPayees from "./components/ProgressCard/TopPayees";
|
||||
|
||||
export const configuration: DashboardConfig = {
|
||||
sections: [
|
||||
@@ -10,63 +11,30 @@ export const configuration: DashboardConfig = {
|
||||
title: "Breakdown",
|
||||
summary: "Interactive chronological tracking",
|
||||
component: HistoryChart,
|
||||
dataKey: "chartData",
|
||||
settings: {
|
||||
tabs: ["Daily", "Weekly", "Monthly"],
|
||||
tabs: ["Weekly", "Monthly"],
|
||||
},
|
||||
style: {
|
||||
size: 12,
|
||||
},
|
||||
{
|
||||
id: "top-categories",
|
||||
title: 'Top Categories',
|
||||
component: TopTags,
|
||||
settings: {
|
||||
compact: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "top-payees",
|
||||
title: 'Top Payees',
|
||||
component: ProgressCard,
|
||||
dataKey: "topPayees",
|
||||
isList: true,
|
||||
component: TopPayees,
|
||||
settings: {
|
||||
compact: true,
|
||||
},
|
||||
style: {
|
||||
size: 12,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "latest",
|
||||
id: "items",
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import * as React from "react";
|
||||
import MonetizationOnIcon from "@mui/icons-material/MonetizationOn";
|
||||
import { LatestItem } from "../../components/LatestItems";
|
||||
|
||||
const DEFAULT_ICON = React.createElement(MonetizationOnIcon, {
|
||||
sx: { color: "#388e3c" }
|
||||
});
|
||||
|
||||
export function mapToLatestItems(
|
||||
items: any[],
|
||||
type: "expense" | "income"
|
||||
): LatestItem[] {
|
||||
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`
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export {
|
||||
useDashboardData
|
||||
} from './useDashboardData'
|
||||
@@ -1,52 +0,0 @@
|
||||
import { useResourceByName } from "../../../react-openapi";
|
||||
import { mapToLatestItems } from "./dashboard.mapper";
|
||||
import { mapReportToDashboard } from "../report/report.mapper";
|
||||
|
||||
export function useDashboardData(type: "expense" | "income") {
|
||||
const { useList: useExpenseList } = useResourceByName("expenses");
|
||||
const { useList: useReportList } = useResourceByName("reports");
|
||||
|
||||
// Fetch latest transactions
|
||||
const latestQuery = useExpenseList({
|
||||
limit: 100,
|
||||
sort: "-occurred_at"
|
||||
});
|
||||
|
||||
// Fetch reports for aggregation
|
||||
const weeklyReport = useReportList({ period: "weekly", rolling: true });
|
||||
const monthlyReport = useReportList({ period: "monthly", rolling: true });
|
||||
const payeeReport = useReportList({ period: "full", rolling: true, group_by: "payee" });
|
||||
|
||||
const isLoading =
|
||||
latestQuery.isLoading ||
|
||||
weeklyReport.isLoading ||
|
||||
monthlyReport.isLoading ||
|
||||
payeeReport.isLoading;
|
||||
|
||||
const error =
|
||||
latestQuery.error ||
|
||||
weeklyReport.error ||
|
||||
monthlyReport.error ||
|
||||
payeeReport.error;
|
||||
|
||||
const latest = latestQuery.data?.data
|
||||
? mapToLatestItems(latestQuery.data.data, type)
|
||||
: [];
|
||||
|
||||
const aggregatedData =
|
||||
weeklyReport.data?.data && monthlyReport.data?.data && payeeReport.data?.data
|
||||
? mapReportToDashboard(
|
||||
(weeklyReport.data.data as any).buckets,
|
||||
(monthlyReport.data.data as any).buckets,
|
||||
(payeeReport.data.data as any).buckets,
|
||||
type
|
||||
)
|
||||
: null;
|
||||
|
||||
return {
|
||||
data: aggregatedData,
|
||||
latest: latest,
|
||||
isLoading,
|
||||
error,
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,15 @@
|
||||
export {
|
||||
useReport
|
||||
} from './useReport'
|
||||
export type {
|
||||
Transaction,
|
||||
ReportData,
|
||||
ReportBucket,
|
||||
ReportPeriod,
|
||||
ReportQuery,
|
||||
GroupKey,
|
||||
PeriodType,
|
||||
} from './report.models'
|
||||
export {
|
||||
prepareReport
|
||||
} from './report.utils'
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
import {
|
||||
AggregatedDashboardData,
|
||||
ChartData,
|
||||
ChartDataPoint,
|
||||
} from "../../components/HistoryChart";
|
||||
|
||||
type ReportBucket = any;
|
||||
|
||||
const sumBucket = (bucket: ReportBucket, flow: "expenses" | "incomes") =>
|
||||
bucket.groups.reduce(
|
||||
(acc: number, g: any) => acc + (g?.[flow]?.sum || 0),
|
||||
0
|
||||
);
|
||||
|
||||
const toLabel = (start: string, end: string, type: "weekly" | "monthly") => {
|
||||
const s = new Date(start);
|
||||
const e = new Date(end);
|
||||
|
||||
if (type === "monthly") {
|
||||
return s.toLocaleString("default", { month: "short" });
|
||||
}
|
||||
|
||||
return `${s.getDate()}–${e.getDate()} ${e.toLocaleString("default", {
|
||||
month: "short",
|
||||
})}`;
|
||||
};
|
||||
|
||||
const getWeekOfMonth = (date: Date) => {
|
||||
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
|
||||
return Math.ceil((date.getDate() + firstDay.getDay()) / 7);
|
||||
};
|
||||
|
||||
const findCompareBucket = (
|
||||
current: ReportBucket,
|
||||
buckets: ReportBucket[],
|
||||
type: "weekly" | "monthly"
|
||||
): ReportBucket | undefined => {
|
||||
const start = new Date(current.start);
|
||||
|
||||
if (type === "monthly") {
|
||||
const targetYear = start.getFullYear() - 1;
|
||||
const targetMonth = start.getMonth();
|
||||
|
||||
return buckets.find(b => {
|
||||
const d = new Date(b.start);
|
||||
return (
|
||||
d.getFullYear() === targetYear &&
|
||||
d.getMonth() === targetMonth
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (type === "weekly") {
|
||||
const weekIndex = getWeekOfMonth(start); // you must define this
|
||||
const target = new Date(start);
|
||||
target.setMonth(target.getMonth() - 1);
|
||||
|
||||
return buckets.find(b => {
|
||||
const d = new Date(b.start);
|
||||
return (
|
||||
d.getFullYear() === target.getFullYear() &&
|
||||
d.getMonth() === target.getMonth() &&
|
||||
getWeekOfMonth(d) === weekIndex
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const toPoints = (
|
||||
buckets: ReportBucket[],
|
||||
type: "weekly" | "monthly",
|
||||
flow: "expenses" | "incomes"
|
||||
): ChartDataPoint[] => {
|
||||
return buckets.map((b) => {
|
||||
const amount = sumBucket(b, flow);
|
||||
const prev = findCompareBucket(b, buckets, type);
|
||||
|
||||
return {
|
||||
id: toLabel(b.start, b.end, type),
|
||||
amount,
|
||||
compare: prev
|
||||
? {
|
||||
id: toLabel(prev.start, prev.end, type),
|
||||
amount: sumBucket(prev, flow),
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export function mapReportToDashboard(
|
||||
weekly: ReportBucket[],
|
||||
monthly: ReportBucket[],
|
||||
payeeBuckets: ReportBucket[],
|
||||
type: "expense" | "income"
|
||||
): AggregatedDashboardData {
|
||||
const flow = type === "expense" ? "expenses" : "incomes";
|
||||
|
||||
const chartData: ChartData = {
|
||||
daily: [],
|
||||
|
||||
weekly: {
|
||||
rolling: toPoints(weekly, "weekly", flow),
|
||||
calendar: toPoints(weekly, "weekly", flow),
|
||||
},
|
||||
|
||||
monthly: {
|
||||
rolling: toPoints(monthly, "monthly", flow),
|
||||
calendar: toPoints(monthly, "monthly", flow),
|
||||
},
|
||||
};
|
||||
|
||||
const totalAmount = weekly.reduce(
|
||||
(acc, b) => acc + sumBucket(b, flow),
|
||||
0
|
||||
);
|
||||
|
||||
const payeeMap: Record<string, number> = {};
|
||||
|
||||
const sourceForPayees = (payeeBuckets && payeeBuckets.length > 0) ? payeeBuckets : weekly;
|
||||
|
||||
for (const b of sourceForPayees) {
|
||||
for (const g of b.groups) {
|
||||
const key = g.group_key || "Unknown";
|
||||
const amt = g?.[flow]?.sum || 0;
|
||||
payeeMap[key] = (payeeMap[key] || 0) + amt;
|
||||
}
|
||||
}
|
||||
|
||||
const topPayees = Object.entries(payeeMap)
|
||||
// .filter(([name]) => name !== "Unknown")
|
||||
.map(([payeeName, amount]) => ({ payeeName, amount }))
|
||||
.sort((a, b) => b.amount - a.amount)
|
||||
.slice(0, 5);
|
||||
|
||||
return {
|
||||
chartData,
|
||||
totalAmount,
|
||||
topPayees,
|
||||
};
|
||||
}
|
||||
112
src/features/report/report.models.ts
Normal file
112
src/features/report/report.models.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
export interface Payor {
|
||||
id?: string;
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface Payee {
|
||||
type: "merchant" | "person" | "transfer" | "other";
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
id: string;
|
||||
name: string;
|
||||
number: string;
|
||||
type: "cash" | "bank" | "credit_card" | "wallet" | "other";
|
||||
currency: string;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
id: string;
|
||||
name: string;
|
||||
icon: string;
|
||||
parent_id?: string | null;
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
id: string;
|
||||
payor: Payor;
|
||||
payee: Payee;
|
||||
amount: number;
|
||||
account: Account;
|
||||
tags: Tag[];
|
||||
occurred_at: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Metrics
|
||||
// -----------------------------
|
||||
|
||||
export interface ReportMetric {
|
||||
sum: number;
|
||||
count: number;
|
||||
average: number;
|
||||
transactions?: Transaction[];
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Period
|
||||
// -----------------------------
|
||||
|
||||
export type PeriodType = "daily" | "weekly" | "monthly" | "all";
|
||||
|
||||
export interface ReportPeriod {
|
||||
start: string;
|
||||
end: string;
|
||||
metric: ReportMetric;
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Group (bucket)
|
||||
// -----------------------------
|
||||
|
||||
export type GroupKey = {
|
||||
[dimension: string]: string[];
|
||||
};
|
||||
|
||||
export interface ReportBucket {
|
||||
group_key: GroupKey;
|
||||
|
||||
periods: {
|
||||
daily?: ReportPeriod[];
|
||||
weekly?: ReportPeriod[];
|
||||
monthly?: ReportPeriod[];
|
||||
all?: ReportPeriod[];
|
||||
};
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Report Query
|
||||
// -----------------------------
|
||||
|
||||
export interface ReportQuery {
|
||||
accounts?: string[] | null;
|
||||
ignore_self?: boolean | null;
|
||||
start_date?: string | null;
|
||||
end_date?: string | null;
|
||||
min_amount?: number | null;
|
||||
max_amount?: number | null;
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Final Report
|
||||
// -----------------------------
|
||||
|
||||
export interface ReportData {
|
||||
snapshot_id?: string | null;
|
||||
|
||||
flow?: "inflows" | "outflows" | null;
|
||||
|
||||
periods: PeriodType[];
|
||||
|
||||
tags?: string[] | null;
|
||||
payee?: string[] | null;
|
||||
|
||||
buckets: ReportBucket[];
|
||||
|
||||
query: ReportQuery;
|
||||
}
|
||||
117
src/features/report/report.utils.ts
Normal file
117
src/features/report/report.utils.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import {
|
||||
ReportData,
|
||||
ReportPeriod,
|
||||
PeriodType,
|
||||
} 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: PeriodType,
|
||||
start: Date,
|
||||
end: Date
|
||||
): string {
|
||||
const s = formatDate(start);
|
||||
const e = formatDate(end);
|
||||
|
||||
switch (type) {
|
||||
case "daily":
|
||||
return `D:${s}_${e}`;
|
||||
case "weekly":
|
||||
return `W:${s}_${e}`;
|
||||
case "monthly":
|
||||
return `M:${s}_${e}`;
|
||||
case "all":
|
||||
return `ALL:${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 buildLabel(
|
||||
type: PeriodType,
|
||||
start: Date,
|
||||
end: Date
|
||||
): string {
|
||||
switch (type) {
|
||||
case "daily":
|
||||
return dayFmt.format(start);
|
||||
|
||||
case "weekly": {
|
||||
const sDay = start.getUTCDate();
|
||||
const m = monthFmt.format(start);
|
||||
return `${sDay} ${m}`;
|
||||
}
|
||||
|
||||
case "monthly":
|
||||
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
|
||||
|
||||
default:
|
||||
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- MAIN ---------- */
|
||||
|
||||
function decoratePeriods(
|
||||
type: PeriodType,
|
||||
periods: ReportPeriod[]
|
||||
): (ReportPeriod & { id: string; label: string })[] {
|
||||
return periods.map((p) => ({
|
||||
...p,
|
||||
id: buildPeriodId(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
|
||||
label: buildLabel(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
|
||||
}));
|
||||
}
|
||||
|
||||
export function prepareReport(reportData: ReportData): ReportData {
|
||||
return {
|
||||
...reportData,
|
||||
buckets: reportData.buckets.map((bucket) => {
|
||||
const newPeriods: typeof bucket.periods = {};
|
||||
|
||||
for (const type of reportData.periods) {
|
||||
const arr = bucket.periods[type];
|
||||
if (arr) {
|
||||
newPeriods[type] = decoratePeriods(type, arr);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...bucket,
|
||||
periods: newPeriods,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
import { useResourceByName } from "../../../react-openapi";
|
||||
|
||||
export interface ReportParams {
|
||||
period: "weekly" | "monthly" | "yearly" | "fyly";
|
||||
rolling?: boolean;
|
||||
report_date?: string;
|
||||
group_by?: ("flow" | "payee" | "tags")[];
|
||||
ignore_self?: boolean;
|
||||
snapshot_id?: string;
|
||||
periods?: ("daily" | "weekly" | "monthly" | "all")[];
|
||||
flow?: "inflows" | "outflows";
|
||||
payee?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export function useReport(params: ReportParams) {
|
||||
const { useList } = useResourceByName("reports");
|
||||
return useList(params);
|
||||
|
||||
return useList({
|
||||
...params,
|
||||
periods: params.periods,
|
||||
});
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import process from 'process';
|
||||
import { AuthProvider } from "../react-auth";
|
||||
import Header from './Header';
|
||||
import Footer from './Footer';
|
||||
import AppTheme from './AppTheme';
|
||||
import AppTheme from './shared-theme/AppTheme';
|
||||
|
||||
window.Buffer = Buffer;
|
||||
window.process = process;
|
||||
|
||||
@@ -1,53 +1,103 @@
|
||||
import * as React from 'react';
|
||||
import { ThemeProvider, createTheme } from '@mui/material/styles';
|
||||
import type { ThemeOptions } from '@mui/material/styles';
|
||||
import { inputsCustomizations } from './customizations/inputs';
|
||||
import { dataDisplayCustomizations } from './customizations/dataDisplay';
|
||||
import { feedbackCustomizations } from './customizations/feedback';
|
||||
import { navigationCustomizations } from './customizations/navigation';
|
||||
import { surfacesCustomizations } from './customizations/surfaces';
|
||||
import { colorSchemes, typography, shadows, shape } from './themePrimitives';
|
||||
import * as React from "react";
|
||||
import {
|
||||
ThemeProvider,
|
||||
createTheme,
|
||||
CssBaseline,
|
||||
Box,
|
||||
} from "@mui/material";
|
||||
|
||||
interface AppThemeProps {
|
||||
import { getDesignTokens } from "./themePrimitives";
|
||||
import { getSemanticColors } from "./themeConfig";
|
||||
|
||||
import { inputsCustomizations } from "./customizations/inputs";
|
||||
import { dataDisplayCustomizations } from "./customizations/dataDisplay";
|
||||
import { feedbackCustomizations } from "./customizations/feedback";
|
||||
import { navigationCustomizations } from "./customizations/navigation";
|
||||
import { surfacesCustomizations } from "./customizations/surfaces";
|
||||
|
||||
export type ColorMode = "light" | "dark";
|
||||
|
||||
type ColorModeContextValue = {
|
||||
mode: ColorMode;
|
||||
setMode: (mode: ColorMode) => void;
|
||||
toggleColorMode: () => void;
|
||||
};
|
||||
|
||||
export const ColorModeContext =
|
||||
React.createContext<ColorModeContextValue>({
|
||||
mode: "light",
|
||||
setMode: () => {},
|
||||
toggleColorMode: () => {},
|
||||
});
|
||||
|
||||
type AppThemeProps = {
|
||||
children: React.ReactNode;
|
||||
/**
|
||||
* This is for the docs site. You can ignore it or remove it.
|
||||
*/
|
||||
disableCustomTheme?: boolean;
|
||||
themeComponents?: ThemeOptions['components'];
|
||||
}
|
||||
defaultMode?: ColorMode;
|
||||
};
|
||||
|
||||
export default function AppTheme({
|
||||
children,
|
||||
defaultMode = "light",
|
||||
}: AppThemeProps) {
|
||||
const [mode, setMode] =
|
||||
React.useState<ColorMode>(defaultMode);
|
||||
|
||||
const toggleColorMode = React.useCallback(() => {
|
||||
setMode((prev) =>
|
||||
prev === "light" ? "dark" : "light"
|
||||
);
|
||||
}, []);
|
||||
|
||||
const contextValue = React.useMemo(
|
||||
() => ({
|
||||
mode,
|
||||
setMode,
|
||||
toggleColorMode,
|
||||
}),
|
||||
[mode, toggleColorMode]
|
||||
);
|
||||
|
||||
const semantic = React.useMemo(
|
||||
() => getSemanticColors(mode),
|
||||
[mode]
|
||||
);
|
||||
|
||||
const theme = React.useMemo(
|
||||
() =>
|
||||
createTheme({
|
||||
...getDesignTokens(mode),
|
||||
semantic,
|
||||
|
||||
components: {
|
||||
...inputsCustomizations,
|
||||
...dataDisplayCustomizations,
|
||||
...feedbackCustomizations,
|
||||
...navigationCustomizations,
|
||||
...surfacesCustomizations,
|
||||
},
|
||||
}),
|
||||
[mode, semantic]
|
||||
);
|
||||
|
||||
export default function AppTheme(props: AppThemeProps) {
|
||||
const { children, disableCustomTheme, themeComponents } = props;
|
||||
const theme = React.useMemo(() => {
|
||||
return disableCustomTheme
|
||||
? {}
|
||||
: createTheme({
|
||||
// For more details about CSS variables configuration, see https://mui.com/material-ui/customization/css-theme-variables/configuration/
|
||||
cssVariables: {
|
||||
colorSchemeSelector: 'data-mui-color-scheme',
|
||||
cssVarPrefix: 'template',
|
||||
},
|
||||
colorSchemes, // Recently added in v6 for building light & dark mode app, see https://mui.com/material-ui/customization/palette/#color-schemes
|
||||
typography,
|
||||
shadows,
|
||||
shape,
|
||||
components: {
|
||||
...inputsCustomizations,
|
||||
...dataDisplayCustomizations,
|
||||
...feedbackCustomizations,
|
||||
...navigationCustomizations,
|
||||
...surfacesCustomizations,
|
||||
...themeComponents,
|
||||
},
|
||||
});
|
||||
}, [disableCustomTheme, themeComponents]);
|
||||
if (disableCustomTheme) {
|
||||
return <React.Fragment>{children}</React.Fragment>;
|
||||
}
|
||||
return (
|
||||
<ThemeProvider theme={theme} disableTransitionOnChange>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
<ColorModeContext.Provider value={contextValue}>
|
||||
<ThemeProvider theme={theme}>
|
||||
<CssBaseline />
|
||||
<Box
|
||||
sx={{
|
||||
"--bg-page": semantic.surface.page,
|
||||
"--bg-card": semantic.surface.card,
|
||||
"--bg-elevated": semantic.surface.elevated,
|
||||
"--border-default": semantic.border.default,
|
||||
"--border-subtle": semantic.border.subtle,
|
||||
"--text-primary": semantic.text.primary,
|
||||
"--text-secondary": semantic.text.secondary,
|
||||
"--text-muted": semantic.text.muted,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
</ThemeProvider>
|
||||
</ColorModeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import DarkModeIcon from '@mui/icons-material/DarkModeRounded';
|
||||
import LightModeIcon from '@mui/icons-material/LightModeRounded';
|
||||
import Box from '@mui/material/Box';
|
||||
import IconButton, { IconButtonOwnProps } from '@mui/material/IconButton';
|
||||
import Menu from '@mui/material/Menu';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import { useColorScheme } from '@mui/material/styles';
|
||||
|
||||
export default function ColorModeIconDropdown(props: IconButtonOwnProps) {
|
||||
const { mode, systemMode, setMode } = useColorScheme();
|
||||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||
const open = Boolean(anchorEl);
|
||||
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
};
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null);
|
||||
};
|
||||
const handleMode = (targetMode: 'system' | 'light' | 'dark') => () => {
|
||||
setMode(targetMode);
|
||||
handleClose();
|
||||
};
|
||||
if (!mode) {
|
||||
return (
|
||||
<Box
|
||||
data-screenshot="toggle-mode"
|
||||
sx={(theme) => ({
|
||||
verticalAlign: 'bottom',
|
||||
display: 'inline-flex',
|
||||
width: '2.25rem',
|
||||
height: '2.25rem',
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: '1px solid',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const resolvedMode = (systemMode || mode) as 'light' | 'dark';
|
||||
const icon = {
|
||||
light: <LightModeIcon />,
|
||||
dark: <DarkModeIcon />,
|
||||
}[resolvedMode];
|
||||
return (
|
||||
<React.Fragment>
|
||||
<IconButton
|
||||
data-screenshot="toggle-mode"
|
||||
onClick={handleClick}
|
||||
disableRipple
|
||||
size="small"
|
||||
aria-controls={open ? 'color-scheme-menu' : undefined}
|
||||
aria-haspopup="true"
|
||||
aria-expanded={open ? 'true' : undefined}
|
||||
{...props}
|
||||
>
|
||||
{icon}
|
||||
</IconButton>
|
||||
<Menu
|
||||
anchorEl={anchorEl}
|
||||
id="account-menu"
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
onClick={handleClose}
|
||||
slotProps={{
|
||||
paper: {
|
||||
variant: 'outlined',
|
||||
elevation: 0,
|
||||
sx: {
|
||||
my: '4px',
|
||||
},
|
||||
},
|
||||
}}
|
||||
transformOrigin={{ horizontal: 'right', vertical: 'top' }}
|
||||
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
|
||||
>
|
||||
<MenuItem selected={mode === 'system'} onClick={handleMode('system')}>
|
||||
System
|
||||
</MenuItem>
|
||||
<MenuItem selected={mode === 'light'} onClick={handleMode('light')}>
|
||||
Light
|
||||
</MenuItem>
|
||||
<MenuItem selected={mode === 'dark'} onClick={handleMode('dark')}>
|
||||
Dark
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</React.Fragment>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import { useColorScheme } from '@mui/material/styles';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import Select, { SelectProps } from '@mui/material/Select';
|
||||
|
||||
export default function ColorModeSelect(props: SelectProps) {
|
||||
const { mode, setMode } = useColorScheme();
|
||||
if (!mode) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Select
|
||||
value={mode}
|
||||
onChange={(event) =>
|
||||
setMode(event.target.value as 'system' | 'light' | 'dark')
|
||||
}
|
||||
SelectDisplayProps={{
|
||||
// @ts-ignore
|
||||
'data-screenshot': 'toggle-mode',
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<MenuItem value="system">System</MenuItem>
|
||||
<MenuItem value="light">Light</MenuItem>
|
||||
<MenuItem value="dark">Dark</MenuItem>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
@@ -14,8 +14,8 @@ export const feedbackCustomizations: Components<Theme> = {
|
||||
color: orange[500],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: `${alpha(orange[900], 0.5)}`,
|
||||
border: `1px solid ${alpha(orange[800], 0.5)}`,
|
||||
backgroundColor: alpha(orange[900], 0.35),
|
||||
border: `1px solid ${alpha(orange[800], 0.3)}`,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -125,15 +125,15 @@ export const inputsCustomizations: Components<Theme> = {
|
||||
backgroundColor: gray[200],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: gray[800],
|
||||
borderColor: gray[700],
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.06)',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
|
||||
'&:hover': {
|
||||
backgroundColor: gray[900],
|
||||
borderColor: gray[600],
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
|
||||
borderColor: 'hsla(0, 0%, 100%, 0.15)',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[900],
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
|
||||
},
|
||||
}),
|
||||
},
|
||||
@@ -183,12 +183,12 @@ export const inputsCustomizations: Components<Theme> = {
|
||||
backgroundColor: gray[200],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
color: gray[50],
|
||||
color: 'hsl(0, 0%, 92%)',
|
||||
'&:hover': {
|
||||
backgroundColor: gray[700],
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.08)',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: alpha(gray[700], 0.7),
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.12)',
|
||||
},
|
||||
}),
|
||||
},
|
||||
@@ -241,14 +241,14 @@ export const inputsCustomizations: Components<Theme> = {
|
||||
backgroundColor: gray[200],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: gray[800],
|
||||
borderColor: gray[700],
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.06)',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
'&:hover': {
|
||||
backgroundColor: gray[900],
|
||||
borderColor: gray[600],
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
|
||||
borderColor: 'hsla(0, 0%, 100%, 0.15)',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[900],
|
||||
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
|
||||
},
|
||||
}),
|
||||
variants: [
|
||||
@@ -288,7 +288,7 @@ export const inputsCustomizations: Components<Theme> = {
|
||||
[`& .${toggleButtonGroupClasses.selected}`]: {
|
||||
color: '#fff',
|
||||
},
|
||||
boxShadow: `0 4px 16px ${alpha(brand[700], 0.5)}`,
|
||||
boxShadow: `0 2px 8px ${alpha(brand[700], 0.3)}`,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
@@ -302,7 +302,7 @@ export const inputsCustomizations: Components<Theme> = {
|
||||
fontWeight: 500,
|
||||
...theme.applyStyles('dark', {
|
||||
color: gray[400],
|
||||
boxShadow: '0 4px 16px rgba(0, 0, 0, 0.5)',
|
||||
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.25)',
|
||||
[`&.${toggleButtonClasses.selected}`]: {
|
||||
color: brand[300],
|
||||
},
|
||||
|
||||
@@ -49,9 +49,8 @@ export const navigationCustomizations: Components<Theme> = {
|
||||
},
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
background: gray[900],
|
||||
boxShadow:
|
||||
'hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px',
|
||||
background: (theme.vars || theme).palette.background.paper,
|
||||
boxShadow: '0 4px 16px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.3)',
|
||||
}),
|
||||
}),
|
||||
},
|
||||
@@ -84,17 +83,17 @@ export const navigationCustomizations: Components<Theme> = {
|
||||
|
||||
...theme.applyStyles('dark', {
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
borderColor: gray[700],
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||
boxShadow: `inset 0 1px 0 1px ${alpha(gray[700], 0.15)}, inset 0 -1px 0 1px hsla(220, 0%, 0%, 0.7)`,
|
||||
boxShadow: 'inset 0 1px 0 hsla(0, 0%, 100%, 0.05)',
|
||||
'&:hover': {
|
||||
borderColor: alpha(gray[700], 0.7),
|
||||
borderColor: 'hsla(0, 0%, 100%, 0.15)',
|
||||
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||
boxShadow: 'none',
|
||||
},
|
||||
[`&.${selectClasses.focused}`]: {
|
||||
outlineOffset: 0,
|
||||
borderColor: gray[900],
|
||||
borderColor: 'hsl(210, 55%, 55%)',
|
||||
},
|
||||
'&:before, &:after': {
|
||||
display: 'none',
|
||||
@@ -108,7 +107,7 @@ export const navigationCustomizations: Components<Theme> = {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
'&:focus-visible': {
|
||||
backgroundColor: gray[900],
|
||||
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
@@ -151,6 +150,7 @@ export const navigationCustomizations: Components<Theme> = {
|
||||
styleOverrides: {
|
||||
paper: ({ theme }) => ({
|
||||
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||
borderRight: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -204,8 +204,8 @@ export const navigationCustomizations: Components<Theme> = {
|
||||
...theme.applyStyles('dark', {
|
||||
':hover': {
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
backgroundColor: gray[800],
|
||||
borderColor: gray[700],
|
||||
backgroundColor: alpha((theme.vars || theme).palette.common.white, 0.08),
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
},
|
||||
[`&.${tabClasses.selected}`]: {
|
||||
color: '#fff',
|
||||
|
||||
@@ -40,7 +40,7 @@ export const surfacesCustomizations: Components<Theme> = {
|
||||
'&:hover': { backgroundColor: gray[50] },
|
||||
'&:focus-visible': { backgroundColor: 'transparent' },
|
||||
...theme.applyStyles('dark', {
|
||||
'&:hover': { backgroundColor: gray[800] },
|
||||
'&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.06) },
|
||||
}),
|
||||
}),
|
||||
},
|
||||
@@ -67,7 +67,7 @@ export const surfacesCustomizations: Components<Theme> = {
|
||||
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||
boxShadow: 'none',
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: gray[800],
|
||||
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||
}),
|
||||
variants: [
|
||||
{
|
||||
@@ -79,7 +79,7 @@ export const surfacesCustomizations: Components<Theme> = {
|
||||
boxShadow: 'none',
|
||||
background: 'hsl(0, 0%, 100%)',
|
||||
...theme.applyStyles('dark', {
|
||||
background: alpha(gray[900], 0.4),
|
||||
background: alpha((theme.vars || theme).palette.background.paper, 0.6),
|
||||
}),
|
||||
},
|
||||
},
|
||||
|
||||
72
src/shared-theme/themeConfig.ts
Normal file
72
src/shared-theme/themeConfig.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { gray } from "./themePrimitives";
|
||||
import { alpha } from "@mui/material/styles";
|
||||
|
||||
declare module "@mui/material/styles" {
|
||||
interface Theme {
|
||||
semantic: SemanticColors;
|
||||
}
|
||||
interface ThemeOptions {
|
||||
semantic?: SemanticColors;
|
||||
}
|
||||
}
|
||||
|
||||
export type SemanticColorMode = "light" | "dark";
|
||||
|
||||
export interface SemanticColors {
|
||||
surface: {
|
||||
page: string;
|
||||
card: string;
|
||||
elevated: string;
|
||||
};
|
||||
border: {
|
||||
default: string;
|
||||
subtle: string;
|
||||
};
|
||||
text: {
|
||||
primary: string;
|
||||
secondary: string;
|
||||
muted: string;
|
||||
};
|
||||
}
|
||||
|
||||
const darkBg = 'hsl(0, 0%, 9%)';
|
||||
const darkPaper = 'hsl(0, 0%, 14%)';
|
||||
const darkElevated = 'hsl(0, 0%, 19%)';
|
||||
|
||||
export function getSemanticColors(mode: SemanticColorMode): SemanticColors {
|
||||
if (mode === "dark") {
|
||||
return {
|
||||
surface: {
|
||||
page: darkBg,
|
||||
card: darkPaper,
|
||||
elevated: darkElevated,
|
||||
},
|
||||
border: {
|
||||
default: 'hsla(0, 0%, 100%, 0.08)',
|
||||
subtle: 'hsla(0, 0%, 100%, 0.04)',
|
||||
},
|
||||
text: {
|
||||
primary: 'hsl(0, 0%, 92%)',
|
||||
secondary: 'hsl(0, 0%, 60%)',
|
||||
muted: 'hsl(0, 0%, 45%)',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
surface: {
|
||||
page: "hsl(0, 0%, 99%)",
|
||||
card: "hsl(220, 35%, 97%)",
|
||||
elevated: gray[100],
|
||||
},
|
||||
border: {
|
||||
default: alpha(gray[300], 0.4),
|
||||
subtle: alpha(gray[200], 0.3),
|
||||
},
|
||||
text: {
|
||||
primary: gray[800],
|
||||
secondary: gray[600],
|
||||
muted: gray[500],
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -23,6 +23,10 @@ declare module '@mui/material/styles' {
|
||||
|
||||
interface Palette {
|
||||
baseShadow: string;
|
||||
flows: {
|
||||
outflows: { primary: string; surface: string; text: string };
|
||||
inflows: { primary: string; surface: string; text: string };
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +56,9 @@ export const gray = {
|
||||
500: 'hsl(220, 20%, 42%)',
|
||||
600: 'hsl(220, 20%, 35%)',
|
||||
700: 'hsl(220, 20%, 25%)',
|
||||
750: 'hsl(220, 20%, 18%)',
|
||||
800: 'hsl(220, 30%, 6%)',
|
||||
850: 'hsl(220, 22%, 11%)',
|
||||
900: 'hsl(220, 35%, 3%)',
|
||||
};
|
||||
|
||||
@@ -95,10 +101,14 @@ export const red = {
|
||||
900: 'hsl(0, 93%, 6%)',
|
||||
};
|
||||
|
||||
const darkBg = 'hsl(0, 0%, 9%)';
|
||||
const darkPaper = 'hsl(0, 0%, 14%)';
|
||||
const darkElevated = 'hsl(0, 0%, 19%)';
|
||||
|
||||
export const getDesignTokens = (mode: PaletteMode) => {
|
||||
customShadows[1] =
|
||||
mode === 'dark'
|
||||
? 'hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px'
|
||||
? '0 4px 16px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.3)'
|
||||
: 'hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px';
|
||||
|
||||
return {
|
||||
@@ -111,9 +121,9 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
contrastText: brand[50],
|
||||
...(mode === 'dark' && {
|
||||
contrastText: brand[50],
|
||||
light: brand[300],
|
||||
main: brand[400],
|
||||
dark: brand[700],
|
||||
light: 'hsl(210, 50%, 65%)',
|
||||
main: 'hsl(210, 55%, 55%)',
|
||||
dark: 'hsl(210, 50%, 35%)',
|
||||
}),
|
||||
},
|
||||
info: {
|
||||
@@ -122,10 +132,10 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
dark: brand[600],
|
||||
contrastText: gray[50],
|
||||
...(mode === 'dark' && {
|
||||
contrastText: brand[300],
|
||||
light: brand[500],
|
||||
main: brand[700],
|
||||
dark: brand[900],
|
||||
contrastText: 'hsl(210, 30%, 80%)',
|
||||
light: 'hsl(210, 40%, 50%)',
|
||||
main: 'hsl(210, 35%, 40%)',
|
||||
dark: 'hsl(210, 30%, 25%)',
|
||||
}),
|
||||
},
|
||||
warning: {
|
||||
@@ -133,9 +143,9 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
main: orange[400],
|
||||
dark: orange[800],
|
||||
...(mode === 'dark' && {
|
||||
light: orange[400],
|
||||
main: orange[500],
|
||||
dark: orange[700],
|
||||
light: 'hsl(45, 60%, 55%)',
|
||||
main: 'hsl(45, 55%, 45%)',
|
||||
dark: 'hsl(45, 50%, 30%)',
|
||||
}),
|
||||
},
|
||||
error: {
|
||||
@@ -143,9 +153,9 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
main: red[400],
|
||||
dark: red[800],
|
||||
...(mode === 'dark' && {
|
||||
light: red[400],
|
||||
main: red[500],
|
||||
dark: red[700],
|
||||
light: 'hsl(0, 55%, 60%)',
|
||||
main: 'hsl(0, 55%, 50%)',
|
||||
dark: 'hsl(0, 50%, 35%)',
|
||||
}),
|
||||
},
|
||||
success: {
|
||||
@@ -153,34 +163,46 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
main: green[400],
|
||||
dark: green[800],
|
||||
...(mode === 'dark' && {
|
||||
light: green[400],
|
||||
main: green[500],
|
||||
dark: green[700],
|
||||
light: 'hsl(120, 40%, 55%)',
|
||||
main: 'hsl(120, 40%, 45%)',
|
||||
dark: 'hsl(120, 35%, 30%)',
|
||||
}),
|
||||
},
|
||||
grey: {
|
||||
...gray,
|
||||
},
|
||||
divider: mode === 'dark' ? alpha(gray[700], 0.6) : alpha(gray[300], 0.4),
|
||||
divider: mode === 'dark' ? 'hsla(0, 0%, 100%, 0.08)' : alpha(gray[300], 0.4),
|
||||
background: {
|
||||
default: 'hsl(0, 0%, 99%)',
|
||||
paper: 'hsl(220, 35%, 97%)',
|
||||
...(mode === 'dark' && { default: gray[900], paper: 'hsl(220, 30%, 7%)' }),
|
||||
...(mode === 'dark' && { default: darkBg, paper: darkPaper }),
|
||||
},
|
||||
text: {
|
||||
primary: gray[800],
|
||||
secondary: gray[600],
|
||||
warning: orange[400],
|
||||
...(mode === 'dark' && { primary: 'hsl(0, 0%, 100%)', secondary: gray[400] }),
|
||||
...(mode === 'dark' && { primary: 'hsl(0, 0%, 92%)', secondary: 'hsl(0, 0%, 60%)' }),
|
||||
},
|
||||
action: {
|
||||
hover: alpha(gray[200], 0.2),
|
||||
selected: `${alpha(gray[200], 0.3)}`,
|
||||
...(mode === 'dark' && {
|
||||
hover: alpha(gray[600], 0.2),
|
||||
selected: alpha(gray[600], 0.3),
|
||||
hover: 'hsla(0, 0%, 100%, 0.06)',
|
||||
selected: 'hsla(0, 0%, 100%, 0.1)',
|
||||
}),
|
||||
},
|
||||
flows: {
|
||||
outflows: {
|
||||
primary: mode === 'dark' ? 'hsl(0, 55%, 60%)' : '#d32f2f',
|
||||
surface: mode === 'dark' ? 'hsla(0, 35%, 25%, 0.6)' : '#fdecea',
|
||||
text: mode === 'dark' ? 'hsl(0, 60%, 80%)' : '#b71c1c',
|
||||
},
|
||||
inflows: {
|
||||
primary: mode === 'dark' ? 'hsl(120, 40%, 55%)' : '#2e7d32',
|
||||
surface: mode === 'dark' ? 'hsla(120, 25%, 22%, 0.6)' : '#e8f5e9',
|
||||
text: mode === 'dark' ? 'hsl(120, 40%, 78%)' : '#1b5e20',
|
||||
},
|
||||
},
|
||||
},
|
||||
typography: {
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
@@ -285,6 +307,18 @@ export const colorSchemes = {
|
||||
hover: alpha(gray[200], 0.2),
|
||||
selected: `${alpha(gray[200], 0.3)}`,
|
||||
},
|
||||
flows: {
|
||||
outflows: {
|
||||
primary: '#d32f2f',
|
||||
surface: '#fdecea',
|
||||
text: '#b71c1c',
|
||||
},
|
||||
inflows: {
|
||||
primary: '#2e7d32',
|
||||
surface: '#e8f5e9',
|
||||
text: '#1b5e20',
|
||||
},
|
||||
},
|
||||
baseShadow:
|
||||
'hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px',
|
||||
},
|
||||
@@ -293,49 +327,60 @@ export const colorSchemes = {
|
||||
palette: {
|
||||
primary: {
|
||||
contrastText: brand[50],
|
||||
light: brand[300],
|
||||
main: brand[400],
|
||||
dark: brand[700],
|
||||
light: 'hsl(210, 50%, 65%)',
|
||||
main: 'hsl(210, 55%, 55%)',
|
||||
dark: 'hsl(210, 50%, 35%)',
|
||||
},
|
||||
info: {
|
||||
contrastText: brand[300],
|
||||
light: brand[500],
|
||||
main: brand[700],
|
||||
dark: brand[900],
|
||||
contrastText: 'hsl(210, 30%, 80%)',
|
||||
light: 'hsl(210, 40%, 50%)',
|
||||
main: 'hsl(210, 35%, 40%)',
|
||||
dark: 'hsl(210, 30%, 25%)',
|
||||
},
|
||||
warning: {
|
||||
light: orange[400],
|
||||
main: orange[500],
|
||||
dark: orange[700],
|
||||
light: 'hsl(45, 60%, 55%)',
|
||||
main: 'hsl(45, 55%, 45%)',
|
||||
dark: 'hsl(45, 50%, 30%)',
|
||||
},
|
||||
error: {
|
||||
light: red[400],
|
||||
main: red[500],
|
||||
dark: red[700],
|
||||
light: 'hsl(0, 55%, 60%)',
|
||||
main: 'hsl(0, 55%, 50%)',
|
||||
dark: 'hsl(0, 50%, 35%)',
|
||||
},
|
||||
success: {
|
||||
light: green[400],
|
||||
main: green[500],
|
||||
dark: green[700],
|
||||
light: 'hsl(120, 40%, 55%)',
|
||||
main: 'hsl(120, 40%, 45%)',
|
||||
dark: 'hsl(120, 35%, 30%)',
|
||||
},
|
||||
grey: {
|
||||
...gray,
|
||||
},
|
||||
divider: alpha(gray[700], 0.6),
|
||||
divider: 'hsla(0, 0%, 100%, 0.08)',
|
||||
background: {
|
||||
default: gray[900],
|
||||
paper: 'hsl(220, 30%, 7%)',
|
||||
default: darkBg,
|
||||
paper: darkPaper,
|
||||
},
|
||||
text: {
|
||||
primary: 'hsl(0, 0%, 100%)',
|
||||
secondary: gray[400],
|
||||
primary: 'hsl(0, 0%, 92%)',
|
||||
secondary: 'hsl(0, 0%, 60%)',
|
||||
},
|
||||
action: {
|
||||
hover: alpha(gray[600], 0.2),
|
||||
selected: alpha(gray[600], 0.3),
|
||||
hover: 'hsla(0, 0%, 100%, 0.06)',
|
||||
selected: 'hsla(0, 0%, 100%, 0.1)',
|
||||
},
|
||||
baseShadow:
|
||||
'hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px',
|
||||
flows: {
|
||||
outflows: {
|
||||
primary: 'hsl(0, 55%, 60%)',
|
||||
surface: 'hsla(0, 35%, 25%, 0.6)',
|
||||
text: 'hsl(0, 60%, 80%)',
|
||||
},
|
||||
inflows: {
|
||||
primary: 'hsl(120, 40%, 55%)',
|
||||
surface: 'hsla(120, 25%, 22%, 0.6)',
|
||||
text: 'hsl(120, 40%, 78%)',
|
||||
},
|
||||
},
|
||||
baseShadow: '0 4px 16px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.3)',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user