Compare commits
5 Commits
3c8a17f336
...
1.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 2add23efe7 | |||
| 25ec534597 | |||
| 51762f8d18 | |||
| 002b22ff0e | |||
| 885ccdcfa7 |
@@ -3,17 +3,19 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="initial-scale=1, width=device-width" />
|
||||
<meta name="description" content="Khata — your intelligent, extensible financial ledger. Import transactions, generate reports, and stay on top of your cashflow." />
|
||||
<meta name="theme-color" content="#635BFF" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
|
||||
/>
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
<title>khata - Aetoskia</title>
|
||||
<title>Khata — Financial Ledger</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
265
package-lock.json
generated
265
package-lock.json
generated
@@ -13,7 +13,6 @@
|
||||
"@emotion/styled": "^11.13.0",
|
||||
"@mui/icons-material": "^5.16.7",
|
||||
"@mui/material": "^5.16.7",
|
||||
"@mui/x-data-grid": "^7.22.0",
|
||||
"@tanstack/react-query": "^5.96.1",
|
||||
"axios": "^1.7.7",
|
||||
"buffer": "^6.0.3",
|
||||
@@ -1097,201 +1096,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/private-theming": {
|
||||
"version": "7.3.11",
|
||||
"resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-7.3.11.tgz",
|
||||
"integrity": "sha512-9B+YKms0fRHbNrqp9tOT/DNbNnU5gyvJ1o3qAGXfq8GmZcbJnE3At9x07Zr/o0pkhzg4aDdwXVqe4+AcgtOCPA==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6",
|
||||
"@mui/utils": "^7.3.11",
|
||||
"prop-types": "^15.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mui-org"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/private-theming/node_modules/@mui/types": {
|
||||
"version": "7.4.12",
|
||||
"resolved": "https://registry.npmjs.org/@mui/types/-/types-7.4.12.tgz",
|
||||
"integrity": "sha512-iKNAF2u9PzSIj40CjvKJWxFXJo122jXVdrmdh0hMYd+FR+NuJMkr/L88XwWLCRiJ5P1j+uyac25+Kp6YC4hu6w==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/private-theming/node_modules/@mui/utils": {
|
||||
"version": "7.3.11",
|
||||
"resolved": "https://registry.npmjs.org/@mui/utils/-/utils-7.3.11.tgz",
|
||||
"integrity": "sha512-XTjGnifwteg71/ij+0e7Y7d+hwyntMYP5wPoA/g2drdGH+Flkvjwy0OfrVpKBbaOvofq4zU/LIyUZyKgmWu18g==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6",
|
||||
"@mui/types": "^7.4.12",
|
||||
"@types/prop-types": "^15.7.15",
|
||||
"clsx": "^2.1.1",
|
||||
"prop-types": "^15.8.1",
|
||||
"react-is": "^19.2.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mui-org"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/styled-engine": {
|
||||
"version": "7.3.10",
|
||||
"resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-7.3.10.tgz",
|
||||
"integrity": "sha512-WxE9SiF8xskAQqGjsp0poXCkCqsoXFEsSr0HBXfApmGHR+DBnXRp+z46Vsltg4gpPM4Z96DeAQRpeAOnhNg7Ng==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6",
|
||||
"@emotion/cache": "^11.14.0",
|
||||
"@emotion/serialize": "^1.3.3",
|
||||
"@emotion/sheet": "^1.4.0",
|
||||
"csstype": "^3.2.3",
|
||||
"prop-types": "^15.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mui-org"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@emotion/react": "^11.4.1",
|
||||
"@emotion/styled": "^11.3.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@emotion/react": {
|
||||
"optional": true
|
||||
},
|
||||
"@emotion/styled": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/system": {
|
||||
"version": "7.3.11",
|
||||
"resolved": "https://registry.npmjs.org/@mui/system/-/system-7.3.11.tgz",
|
||||
"integrity": "sha512-7izwGWdNawAKpBKcRlx7f2gFnAAjmASBWvMcyX4YYEeLOFsbfGRbUYGInvnAcUeql3rPxI7F9Ft4oY2OLRz44g==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6",
|
||||
"@mui/private-theming": "^7.3.11",
|
||||
"@mui/styled-engine": "^7.3.10",
|
||||
"@mui/types": "^7.4.12",
|
||||
"@mui/utils": "^7.3.11",
|
||||
"clsx": "^2.1.1",
|
||||
"csstype": "^3.2.3",
|
||||
"prop-types": "^15.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mui-org"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@emotion/react": "^11.5.0",
|
||||
"@emotion/styled": "^11.3.0",
|
||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@emotion/react": {
|
||||
"optional": true
|
||||
},
|
||||
"@emotion/styled": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/system/node_modules/@mui/types": {
|
||||
"version": "7.4.12",
|
||||
"resolved": "https://registry.npmjs.org/@mui/types/-/types-7.4.12.tgz",
|
||||
"integrity": "sha512-iKNAF2u9PzSIj40CjvKJWxFXJo122jXVdrmdh0hMYd+FR+NuJMkr/L88XwWLCRiJ5P1j+uyac25+Kp6YC4hu6w==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/system/node_modules/@mui/utils": {
|
||||
"version": "7.3.11",
|
||||
"resolved": "https://registry.npmjs.org/@mui/utils/-/utils-7.3.11.tgz",
|
||||
"integrity": "sha512-XTjGnifwteg71/ij+0e7Y7d+hwyntMYP5wPoA/g2drdGH+Flkvjwy0OfrVpKBbaOvofq4zU/LIyUZyKgmWu18g==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.6",
|
||||
"@mui/types": "^7.4.12",
|
||||
"@types/prop-types": "^15.7.15",
|
||||
"clsx": "^2.1.1",
|
||||
"prop-types": "^15.8.1",
|
||||
"react-is": "^19.2.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mui-org"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/types": {
|
||||
"version": "7.2.24",
|
||||
"resolved": "https://registry.npmjs.org/@mui/types/-/types-7.2.24.tgz",
|
||||
@@ -1334,62 +1138,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/x-data-grid": {
|
||||
"version": "7.29.13",
|
||||
"resolved": "https://registry.npmjs.org/@mui/x-data-grid/-/x-data-grid-7.29.13.tgz",
|
||||
"integrity": "sha512-XHrZTvpa61eqSgUIevDzXYfYCbI7cbN/aRxSCaw2cZzQZ/USdpECYbnTEhgw5XgUlvkAK0mItKZmgKM4X7zT+Q==",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.25.7",
|
||||
"@mui/utils": "^5.16.6 || ^6.0.0 || ^7.0.0",
|
||||
"@mui/x-internals": "7.29.0",
|
||||
"clsx": "^2.1.1",
|
||||
"prop-types": "^15.8.1",
|
||||
"reselect": "^5.1.1",
|
||||
"use-sync-external-store": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mui-org"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@emotion/react": "^11.9.0",
|
||||
"@emotion/styled": "^11.8.1",
|
||||
"@mui/material": "^5.15.14 || ^6.0.0 || ^7.0.0",
|
||||
"@mui/system": "^5.15.14 || ^6.0.0 || ^7.0.0",
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@emotion/react": {
|
||||
"optional": true
|
||||
},
|
||||
"@emotion/styled": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@mui/x-internals": {
|
||||
"version": "7.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@mui/x-internals/-/x-internals-7.29.0.tgz",
|
||||
"integrity": "sha512-+Gk6VTZIFD70XreWvdXBwKd8GZ2FlSCuecQFzm6znwqXg1ZsndavrhG9tkxpxo2fM1Zf7Tk8+HcOO0hCbhTQFA==",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.25.7",
|
||||
"@mui/utils": "^5.16.6 || ^6.0.0 || ^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mui-org"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@popperjs/core": {
|
||||
"version": "2.11.8",
|
||||
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
|
||||
@@ -4174,11 +3922,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/reselect": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz",
|
||||
"integrity": "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw=="
|
||||
},
|
||||
"node_modules/resolve": {
|
||||
"version": "1.22.12",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz",
|
||||
@@ -4516,14 +4259,6 @@
|
||||
"browserslist": ">= 4.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/use-sync-external-store": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
|
||||
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vfile": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
"@emotion/styled": "^11.13.0",
|
||||
"@mui/icons-material": "^5.16.7",
|
||||
"@mui/material": "^5.16.7",
|
||||
"@mui/x-data-grid": "^7.22.0",
|
||||
"@tanstack/react-query": "^5.96.1",
|
||||
"axios": "^1.7.7",
|
||||
"buffer": "^6.0.3",
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
import * as React from 'react';
|
||||
import { Box, TextField, Button, Typography, IconButton, CircularProgress, Link } from '@mui/material';
|
||||
import {
|
||||
Box,
|
||||
TextField,
|
||||
Button,
|
||||
Typography,
|
||||
IconButton,
|
||||
CircularProgress,
|
||||
Link,
|
||||
InputAdornment,
|
||||
alpha,
|
||||
} from '@mui/material';
|
||||
import VisibilityIcon from '@mui/icons-material/Visibility';
|
||||
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
|
||||
import CheckRoundedIcon from '@mui/icons-material/CheckRounded';
|
||||
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
|
||||
import { useTheme } from '@mui/material/styles';
|
||||
|
||||
export type AuthMode = "login" | "register";
|
||||
|
||||
@@ -15,6 +29,12 @@ export interface AuthPageProps {
|
||||
currentUser: any;
|
||||
}
|
||||
|
||||
const FEATURES = [
|
||||
"OpenAPI-driven admin for accounts, expenses, tags & payors",
|
||||
"Import bank statements with live pipeline progress",
|
||||
"Entity & tag enrichment for clean, comparable data",
|
||||
];
|
||||
|
||||
export function AuthPage({
|
||||
mode,
|
||||
onBack,
|
||||
@@ -25,114 +45,200 @@ export function AuthPage({
|
||||
error,
|
||||
currentUser,
|
||||
}: AuthPageProps) {
|
||||
|
||||
const theme = useTheme();
|
||||
const [username, setUsername] = React.useState('');
|
||||
const [password, setPassword] = React.useState('');
|
||||
const [showPassword, setShowPassword] = React.useState(false);
|
||||
const [fieldErrors, setFieldErrors] = React.useState<{ username?: string; password?: string }>({});
|
||||
|
||||
const isLogin = mode === "login";
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (isLogin) {
|
||||
await login(username, password);
|
||||
} else {
|
||||
await register(username, password);
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ Auto-return if already logged in
|
||||
React.useEffect(() => {
|
||||
if (currentUser) onBack();
|
||||
}, [currentUser, onBack]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
maxWidth: 400,
|
||||
mx: 'auto',
|
||||
mt: 8,
|
||||
p: 4,
|
||||
borderRadius: 3,
|
||||
boxShadow: 3,
|
||||
bgcolor: 'background.paper',
|
||||
}}
|
||||
>
|
||||
<IconButton onClick={onBack} sx={{ mb: 2 }}>
|
||||
<ArrowBackRoundedIcon />
|
||||
const validate = (): boolean => {
|
||||
const next: { username?: string; password?: string } = {};
|
||||
if (!username.trim()) next.username = "Username is required";
|
||||
else if (username.trim().length < 3) next.username = "Username must be at least 3 characters";
|
||||
if (!password) next.password = "Password is required";
|
||||
else if (password.length < 6) next.password = "Password must be at least 6 characters";
|
||||
setFieldErrors(next);
|
||||
return Object.keys(next).length === 0;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!validate()) return;
|
||||
if (isLogin) {
|
||||
await login(username.trim(), password);
|
||||
} else {
|
||||
await register(username.trim(), password);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSwitch = () => {
|
||||
setFieldErrors({});
|
||||
onSwitchMode();
|
||||
};
|
||||
|
||||
const form = (
|
||||
<Box sx={{ width: '100%', maxWidth: 400 }}>
|
||||
<IconButton onClick={onBack} sx={{ mb: 2, border: '1px solid', borderColor: 'divider' }} aria-label="Go back">
|
||||
<ArrowBackRoundedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
|
||||
<Typography variant="h4" fontWeight="bold" gutterBottom>
|
||||
{isLogin ? "Sign In" : "Create Account"}
|
||||
<Typography variant="h4" fontWeight={700} gutterBottom sx={{ letterSpacing: '-0.02em' }}>
|
||||
{isLogin ? "Sign in to Khata" : "Create your account"}
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body2" color="text.secondary" gutterBottom>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
|
||||
{isLogin
|
||||
? "Please log in to continue"
|
||||
: "Create an account to get started"}
|
||||
? "Welcome back. Enter your credentials to continue."
|
||||
: "Start managing your ledger in a few seconds."}
|
||||
</Typography>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Username"
|
||||
type="username"
|
||||
margin="normal"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Password"
|
||||
type="password"
|
||||
margin="normal"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => {
|
||||
setUsername(e.target.value);
|
||||
if (fieldErrors.username) setFieldErrors((p) => ({ ...p, username: undefined }));
|
||||
}}
|
||||
error={!!fieldErrors.username}
|
||||
helperText={fieldErrors.username}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => {
|
||||
setPassword(e.target.value);
|
||||
if (fieldErrors.password) setFieldErrors((p) => ({ ...p, password: undefined }));
|
||||
}}
|
||||
error={!!fieldErrors.password}
|
||||
helperText={fieldErrors.password}
|
||||
autoComplete={isLogin ? 'current-password' : 'new-password'}
|
||||
InputProps={{
|
||||
endAdornment: (
|
||||
<InputAdornment position="end">
|
||||
<IconButton
|
||||
aria-label={showPassword ? 'Hide password' : 'Show password'}
|
||||
onClick={() => setShowPassword((s) => !s)}
|
||||
edge="end"
|
||||
size="small"
|
||||
sx={{ border: 'none' }}
|
||||
>
|
||||
{showPassword ? <VisibilityOffIcon fontSize="small" /> : <VisibilityIcon fontSize="small" />}
|
||||
</IconButton>
|
||||
</InputAdornment>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<Typography color="error" variant="body2" sx={{ mt: 1 }}>
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Button
|
||||
fullWidth
|
||||
type="submit"
|
||||
variant="contained"
|
||||
color="primary"
|
||||
sx={{ mt: 3 }}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<CircularProgress size={24} color="inherit" />
|
||||
) : isLogin ? (
|
||||
"Login"
|
||||
) : (
|
||||
"Register"
|
||||
{error && (
|
||||
<Typography color="error" variant="body2" sx={{ mt: 0.5 }}>
|
||||
{error}
|
||||
</Typography>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
fullWidth
|
||||
type="submit"
|
||||
variant="contained"
|
||||
size="large"
|
||||
sx={{ mt: 1, fontWeight: 600 }}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<CircularProgress size={20} color="inherit" />
|
||||
) : isLogin ? (
|
||||
"Sign In"
|
||||
) : (
|
||||
"Create Account"
|
||||
)}
|
||||
</Button>
|
||||
</Box>
|
||||
</form>
|
||||
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
align="center"
|
||||
sx={{ mt: 3 }}
|
||||
>
|
||||
{isLogin ? "Don’t have an account?" : "Already have an account?"}{' '}
|
||||
<Link
|
||||
component="button"
|
||||
underline="hover"
|
||||
color="primary"
|
||||
onClick={onSwitchMode}
|
||||
sx={{ fontWeight: 500 }}
|
||||
>
|
||||
{isLogin ? "Register" : "Login"}
|
||||
<Typography variant="body2" color="text.secondary" align="center" sx={{ mt: 3 }}>
|
||||
{isLogin ? "Don't have an account?" : "Already have an account?"}{' '}
|
||||
<Link component="button" underline="hover" color="primary" onClick={handleSwitch} sx={{ fontWeight: 600 }}>
|
||||
{isLogin ? "Register" : "Sign In"}
|
||||
</Link>
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
minHeight: 'calc(100vh - 64px)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
p: { xs: 2, md: 4 },
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: '100%',
|
||||
maxWidth: 960,
|
||||
display: 'grid',
|
||||
gridTemplateColumns: { xs: '1fr', md: '5fr 6fr' },
|
||||
borderRadius: 3,
|
||||
overflow: 'hidden',
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
backgroundColor: 'background.paper',
|
||||
boxShadow: (t) =>
|
||||
`0 12px 40px ${alpha(t.palette.common.black, t.palette.mode === 'dark' ? 0.4 : 0.08)}`,
|
||||
}}
|
||||
>
|
||||
{/* LEFT BRAND PANEL */}
|
||||
<Box
|
||||
sx={{
|
||||
display: { xs: 'none', md: 'flex' },
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'space-between',
|
||||
p: 4,
|
||||
background: 'linear-gradient(150deg, #635BFF 0%, #4F46E5 55%, #3B82F6 100%)',
|
||||
color: '#fff',
|
||||
}}
|
||||
>
|
||||
<Box>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: '-0.02em' }}>
|
||||
Khata
|
||||
</Typography>
|
||||
<Typography sx={{ mt: 3, fontSize: '1.25rem', fontWeight: 600, lineHeight: 1.4, maxWidth: 320 }}>
|
||||
The intelligent, extensible financial ledger for your cashflow.
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
|
||||
{FEATURES.map((f) => (
|
||||
<Box key={f} sx={{ display: 'flex', gap: 1.5, alignItems: 'flex-start' }}>
|
||||
<CheckRoundedIcon sx={{ fontSize: 18, mt: 0.25, color: alpha('#fff', 0.9) }} />
|
||||
<Typography variant="body2" sx={{ color: alpha('#fff', 0.92), lineHeight: 1.5 }}>
|
||||
{f}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* RIGHT FORM PANEL */}
|
||||
<Box sx={{ p: { xs: 3, md: 5 }, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
|
||||
{form}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ Auto-generates an admin panel (CRUD, datatable, relationship management) from an
|
||||
```bash
|
||||
npm install react-openapi
|
||||
# peer dependencies (install these in your app):
|
||||
npm install react react-dom react-router-dom @mui/material @mui/icons-material @mui/x-data-grid @emotion/react @emotion/styled axios js-yaml
|
||||
npm install react react-dom react-router-dom @mui/material @mui/icons-material @emotion/react @emotion/styled axios js-yaml
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -5,6 +5,12 @@ export { useAppContext } from "./src/context/AppContext";
|
||||
export { useResource } from "./src/context/useResource";
|
||||
export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields";
|
||||
export { FormFieldRenderer } from "./src/components/fields/FormFieldRenderer";
|
||||
export { MultiEnumField } from "./src/components/fields/renderers/MultiEnumField";
|
||||
export { extractFields } from "./src/transformers/field-config";
|
||||
export { useFkFieldOptions } from "./src/hooks/useFkFieldOptions";
|
||||
export type { FkOption } from "./src/hooks/useFkFieldOptions";
|
||||
export { CurrencyField, formatCurrency } from "./src/components/fields/renderers/CurrencyField";
|
||||
export { FkMultiSelectField } from "./src/components/fields/renderers/FkMultiSelectField";
|
||||
export { SseStreamView } from "./src/components/SseStreamView";
|
||||
export { SseConnectionStatus } from "./src/components/SseConnectionStatus";
|
||||
export { getApi } from "./src/hooks/useApi";
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
"react-router-dom": "^6.28.0",
|
||||
"@mui/material": "^5.16.7",
|
||||
"@mui/icons-material": "^5.16.7",
|
||||
"@mui/x-data-grid": "^7.22.0",
|
||||
"@emotion/react": "^11.13.3",
|
||||
"@emotion/styled": "^11.13.0",
|
||||
"axios": "^1.7.7",
|
||||
|
||||
@@ -58,9 +58,14 @@ export function ResourceDetail({ resource, basePath }: ResourceDetailProps) {
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<Typography variant="body1" color="text.secondary" sx={{ py: 4 }}>
|
||||
Record not found
|
||||
</Typography>
|
||||
<Box sx={{ py: 6, textAlign: "center" }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Record not found
|
||||
</Typography>
|
||||
<Button sx={{ mt: 1.5 }} onClick={() => navigate(`${basePath}/${resource.name}`)}>
|
||||
Back to list
|
||||
</Button>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -82,7 +87,7 @@ export function ResourceDetail({ resource, basePath }: ResourceDetailProps) {
|
||||
<Button startIcon={<ArrowBackIcon />} onClick={() => navigate(`${basePath}/${resource.name}`)}>
|
||||
Back
|
||||
</Button>
|
||||
<Typography variant="h5" fontWeight={700} sx={{ flex: 1 }}>
|
||||
<Typography variant="h5" fontWeight={700} sx={{ flex: 1, letterSpacing: "-0.02em" }}>
|
||||
{applyDisplayFormat(
|
||||
Object.fromEntries(
|
||||
resource.orderedFields.map((field) => {
|
||||
|
||||
@@ -20,11 +20,13 @@ import {
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Grid,
|
||||
Skeleton,
|
||||
} from "@mui/material";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import EditIcon from "@mui/icons-material/Edit";
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||
import StorageIcon from "@mui/icons-material/Storage";
|
||||
import type { ResourceConfig, FieldConfig } from "../types";
|
||||
import { useResource } from "../context/useResource";
|
||||
import { useAppContext } from "../context/AppContext";
|
||||
@@ -38,6 +40,10 @@ interface ResourceListProps {
|
||||
basePath: string;
|
||||
}
|
||||
|
||||
function isNumericColumn(col: FieldConfig): boolean {
|
||||
return col.type === "integer" || col.type === "number";
|
||||
}
|
||||
|
||||
function matchRow(row: any, filters: Record<string, string>, fields: FieldConfig[], allResources: ResourceConfig[]): boolean {
|
||||
for (const field of fields) {
|
||||
if (!field.filterable) continue;
|
||||
@@ -265,12 +271,16 @@ export function ResourceList({ resource, basePath }: ResourceListProps) {
|
||||
/>
|
||||
)}
|
||||
|
||||
<TableContainer component={Paper} variant="outlined">
|
||||
<TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 3 }}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{visibleColumns.map((col) => (
|
||||
<TableCell key={col.name} sx={{ fontWeight: 700 }}>
|
||||
<TableCell
|
||||
key={col.name}
|
||||
align={isNumericColumn(col) ? "right" : "left"}
|
||||
sx={{ fontWeight: 700, fontSize: "0.75rem", py: 1, whiteSpace: "nowrap" }}
|
||||
>
|
||||
{col.sortable ? (
|
||||
<TableSortLabel
|
||||
active={sortField === col.name}
|
||||
@@ -284,16 +294,45 @@ export function ResourceList({ resource, basePath }: ResourceListProps) {
|
||||
)}
|
||||
</TableCell>
|
||||
))}
|
||||
{hasActions && <TableCell align="right" sx={{ fontWeight: 700 }}>Actions</TableCell>}
|
||||
{hasActions && <TableCell align="right" sx={{ fontWeight: 700, fontSize: "0.75rem", py: 1 }}>Actions</TableCell>}
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{displayData.length === 0 ? (
|
||||
{crud.loading && displayData.length === 0 ? (
|
||||
Array.from({ length: 6 }).map((_, i) => (
|
||||
<TableRow key={`skeleton-${i}`}>
|
||||
{visibleColumns.map((col) => (
|
||||
<TableCell key={col.name} align={isNumericColumn(col) ? "right" : "left"} sx={{ py: 1 }}>
|
||||
<Skeleton variant="text" width={col.type === "integer" || col.type === "number" ? 56 : "80%"} />
|
||||
</TableCell>
|
||||
))}
|
||||
{hasActions && (
|
||||
<TableCell align="right" sx={{ py: 1 }}>
|
||||
<Skeleton variant="rectangular" width={72} height={24} sx={{ ml: "auto", borderRadius: 1 }} />
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
))
|
||||
) : displayData.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={visibleColumns.length + (hasActions ? 1 : 0)} align="center">
|
||||
<Typography variant="body2" color="text.secondary" sx={{ py: 4 }}>
|
||||
{isStreaming ? "Waiting for events\u2026" : "No records found"}
|
||||
</Typography>
|
||||
<Box sx={{ py: 5, display: "flex", flexDirection: "column", alignItems: "center", gap: 1 }}>
|
||||
<StorageIcon sx={{ fontSize: 32, color: "text.disabled" }} />
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{isStreaming ? "Waiting for events…" : "No records found"}
|
||||
</Typography>
|
||||
{!isStreaming && resource.operations.create && (
|
||||
<Button
|
||||
variant="contained"
|
||||
size="small"
|
||||
startIcon={<AddIcon />}
|
||||
onClick={() => navigate(`${basePath}/${resource.name}/new`)}
|
||||
sx={{ mt: 1 }}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
@@ -303,7 +342,7 @@ export function ResourceList({ resource, basePath }: ResourceListProps) {
|
||||
<TableRow
|
||||
key={rowId}
|
||||
hover
|
||||
sx={{ cursor: "pointer" }}
|
||||
sx={{ cursor: "pointer", "&:hover .row-actions": { opacity: 1 } }}
|
||||
onClick={() => {
|
||||
if (isStreaming) {
|
||||
setDetailRow(row);
|
||||
@@ -322,34 +361,56 @@ export function ResourceList({ resource, basePath }: ResourceListProps) {
|
||||
fmt = col.inlineDisplayFormat;
|
||||
}
|
||||
return (
|
||||
<TableCell key={col.name}>
|
||||
<TableCell
|
||||
key={col.name}
|
||||
align={isNumericColumn(col) ? "right" : "left"}
|
||||
sx={{
|
||||
py: 1,
|
||||
fontSize: "0.8125rem",
|
||||
...(isNumericColumn(col) && { fontVariantNumeric: "tabular-nums" }),
|
||||
}}
|
||||
>
|
||||
<ListCellRenderer field={col} value={value} displayFormat={fmt} basePath={basePath} />
|
||||
</TableCell>
|
||||
);
|
||||
})}
|
||||
{hasActions && (
|
||||
<TableCell align="right" onClick={(e) => e.stopPropagation()}>
|
||||
{resource.operations.get && !isStreaming && (
|
||||
<Tooltip title="View">
|
||||
<IconButton size="small" onClick={() => navigate(`${basePath}/${resource.name}/${rowId}`)}>
|
||||
<VisibilityIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{resource.operations.update && (
|
||||
<Tooltip title="Edit">
|
||||
<IconButton size="small" onClick={() => navigate(`${basePath}/${resource.name}/${rowId}/edit`)}>
|
||||
<EditIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{resource.operations.delete && (
|
||||
<Tooltip title="Delete">
|
||||
<IconButton size="small" onClick={() => handleDelete(rowId)} color="error">
|
||||
<DeleteIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
<TableCell
|
||||
align="right"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Box
|
||||
className="row-actions"
|
||||
sx={{
|
||||
opacity: { xs: 1, md: 0 },
|
||||
display: "flex",
|
||||
justifyContent: "flex-end",
|
||||
gap: 0.5,
|
||||
transition: "opacity 160ms ease",
|
||||
}}
|
||||
>
|
||||
{resource.operations.get && !isStreaming && (
|
||||
<Tooltip title="View">
|
||||
<IconButton size="small" onClick={() => navigate(`${basePath}/${resource.name}/${rowId}`)}>
|
||||
<VisibilityIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{resource.operations.update && (
|
||||
<Tooltip title="Edit">
|
||||
<IconButton size="small" onClick={() => navigate(`${basePath}/${resource.name}/${rowId}/edit`)}>
|
||||
<EditIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{resource.operations.delete && (
|
||||
<Tooltip title="Delete">
|
||||
<IconButton size="small" onClick={() => handleDelete(rowId)} color="error">
|
||||
<DeleteIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Box>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
|
||||
@@ -30,11 +30,6 @@ export function SideMenu({ resources, basePath, mobileOpen, onClose }: SideMenuP
|
||||
const theme = useTheme();
|
||||
const isMobile = useMediaQuery(theme.breakpoints.down("md"));
|
||||
|
||||
const colors = [
|
||||
"#6366f1", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6",
|
||||
"#ec4899", "#14b8a6", "#f97316", "#06b6d4", "#84cc16",
|
||||
];
|
||||
|
||||
const content = (
|
||||
<Box>
|
||||
<Toolbar>
|
||||
@@ -43,7 +38,7 @@ export function SideMenu({ resources, basePath, mobileOpen, onClose }: SideMenuP
|
||||
</Typography>
|
||||
</Toolbar>
|
||||
<List sx={{ px: 1 }}>
|
||||
{resources.map((r, i) => {
|
||||
{resources.map((r) => {
|
||||
const listPath = `${basePath}/${r.name}`;
|
||||
const active = location.pathname.startsWith(listPath);
|
||||
return (
|
||||
@@ -58,13 +53,15 @@ export function SideMenu({ resources, basePath, mobileOpen, onClose }: SideMenuP
|
||||
borderRadius: 2,
|
||||
mb: 0.5,
|
||||
"&.Mui-selected": {
|
||||
bgcolor: `${colors[i % colors.length]}15`,
|
||||
"&:hover": { bgcolor: `${colors[i % colors.length]}20` },
|
||||
bgcolor: "primary.main",
|
||||
color: "primary.contrastText",
|
||||
"&:hover": { bgcolor: "primary.main" },
|
||||
"& .MuiListItemIcon-root": { color: "primary.contrastText" },
|
||||
},
|
||||
}}
|
||||
>
|
||||
<ListItemIcon sx={{ minWidth: 36 }}>
|
||||
<CircleIcon sx={{ color: colors[i % colors.length], fontSize: 12 }} />
|
||||
<CircleIcon sx={{ fontSize: 12 }} />
|
||||
</ListItemIcon>
|
||||
<ListItemText
|
||||
primary={r.displayName}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import React from "react";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { Box, Typography, Avatar } from "@mui/material";
|
||||
import type { FieldConfig } from "../../types";
|
||||
import { ListCellRenderer } from "./ListCellRenderer";
|
||||
import { CurrencyField } from "./renderers/CurrencyField";
|
||||
import { resolveMediaUrl } from "./utils";
|
||||
import { useAppContext } from "../../context/AppContext";
|
||||
|
||||
interface DetailFieldProps {
|
||||
field: FieldConfig;
|
||||
@@ -11,6 +14,7 @@ interface DetailFieldProps {
|
||||
}
|
||||
|
||||
export function DetailFieldRenderer({ field, value, displayFormat, basePath }: DetailFieldProps) {
|
||||
const { config } = useAppContext();
|
||||
if (field.hidden?.detail) return null;
|
||||
|
||||
return (
|
||||
@@ -18,7 +22,13 @@ export function DetailFieldRenderer({ field, value, displayFormat, basePath }: D
|
||||
<Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ mb: 0.25, display: "block" }}>
|
||||
{field.label}
|
||||
</Typography>
|
||||
<ListCellRenderer field={field} value={value} displayFormat={displayFormat} basePath={basePath} />
|
||||
{field.uiType === "currency" ? (
|
||||
<CurrencyField value={Number(value)} large />
|
||||
) : field.uiType === "image" ? (
|
||||
<Avatar src={resolveMediaUrl(value, config.baseApiUrl)} variant="rounded" sx={{ width: 120, height: 120 }} />
|
||||
) : (
|
||||
<ListCellRenderer field={field} value={value} displayFormat={displayFormat} basePath={basePath} />
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { NumberField } from "./renderers/NumberField";
|
||||
import { DateField } from "./renderers/DateField";
|
||||
import { BooleanField } from "./renderers/BooleanField";
|
||||
import { EnumField } from "./renderers/EnumField";
|
||||
import { MultiEnumField } from "./renderers/MultiEnumField";
|
||||
import { FkSelectField } from "./renderers/FkSelectField";
|
||||
import { FkMultiSelectField } from "./renderers/FkMultiSelectField";
|
||||
import { FileUploadField } from "./renderers/FileUploadField";
|
||||
@@ -81,6 +82,17 @@ export function FormFieldRenderer({ field, value, onChange, error, fkOptions, fk
|
||||
);
|
||||
}
|
||||
|
||||
if (field.isArray && field.enumValues) {
|
||||
return (
|
||||
<MultiEnumField
|
||||
field={field}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
error={error}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (field.enumValues) {
|
||||
return (
|
||||
<EnumField
|
||||
@@ -96,6 +108,17 @@ export function FormFieldRenderer({ field, value, onChange, error, fkOptions, fk
|
||||
return <BooleanField field={field} value={value} onChange={onChange} />;
|
||||
}
|
||||
|
||||
if (field.uiType === "currency") {
|
||||
return (
|
||||
<NumberField
|
||||
field={field}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
error={error}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (field.type === "integer" || field.type === "number") {
|
||||
return (
|
||||
<NumberField
|
||||
|
||||
@@ -2,8 +2,9 @@ import React, { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Box, Typography, Chip, Avatar, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
|
||||
import type { FieldConfig } from "../../types";
|
||||
import { applyDisplayFormat } from "./utils";
|
||||
import { applyDisplayFormat, resolveMediaUrl } from "./utils";
|
||||
import { InlineRefField } from "./renderers/InlineRefField";
|
||||
import { CurrencyField } from "./renderers/CurrencyField";
|
||||
import { extractFields } from "../../transformers/field-config";
|
||||
import { useAppContext } from "../../context/AppContext";
|
||||
|
||||
@@ -16,7 +17,7 @@ interface ListCellProps {
|
||||
|
||||
export function ListCellRenderer({ field, value, displayFormat, basePath }: ListCellProps) {
|
||||
const navigate = useNavigate();
|
||||
const { schemas } = useAppContext();
|
||||
const { schemas, config } = useAppContext();
|
||||
const [inlineItem, setInlineItem] = useState<any>(null);
|
||||
|
||||
if (value === null || value === undefined) {
|
||||
@@ -137,7 +138,11 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
|
||||
}
|
||||
|
||||
if (field.uiType === "image" && value) {
|
||||
return <Avatar src={value} variant="rounded" sx={{ width: 40, height: 40 }} />;
|
||||
return <Avatar src={resolveMediaUrl(value, config.baseApiUrl)} variant="rounded" sx={{ width: 40, height: 40 }} />;
|
||||
}
|
||||
|
||||
if (field.uiType === "currency" && value != null && !Number.isNaN(Number(value))) {
|
||||
return <CurrencyField value={Number(value)} />;
|
||||
}
|
||||
|
||||
if (field.type === "boolean") {
|
||||
|
||||
@@ -3,3 +3,5 @@ export { ListCellRenderer } from "./ListCellRenderer";
|
||||
export { DetailFieldRenderer } from "./DetailFieldRenderer";
|
||||
export { applyDisplayFormat } from "./utils";
|
||||
export { JsonField } from "./renderers/JsonField";
|
||||
export { MultiEnumField } from "./renderers/MultiEnumField";
|
||||
export { CurrencyField, formatCurrency } from "./renderers/CurrencyField";
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import React from "react";
|
||||
import { Typography } from "@mui/material";
|
||||
|
||||
const CURRENCIES = ["INR", "USD", "EUR", "GBP", "AED", "SGD"];
|
||||
const _currencyFormatters = new Map<string, Intl.NumberFormat>();
|
||||
|
||||
export function formatCurrency(amount: number, currency?: string): string {
|
||||
const code = currency && CURRENCIES.includes(currency) ? currency : "INR";
|
||||
let formatter = _currencyFormatters.get(code);
|
||||
if (!formatter) {
|
||||
formatter = new Intl.NumberFormat("en-IN", {
|
||||
style: "currency",
|
||||
currency: code,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
_currencyFormatters.set(code, formatter);
|
||||
}
|
||||
return formatter.format(Math.abs(amount));
|
||||
}
|
||||
|
||||
interface CurrencyFieldProps {
|
||||
value: number;
|
||||
currency?: string;
|
||||
large?: boolean;
|
||||
}
|
||||
|
||||
export function CurrencyField({ value, currency, large }: CurrencyFieldProps) {
|
||||
const negative = value < 0;
|
||||
return (
|
||||
<Typography
|
||||
component="span"
|
||||
sx={{
|
||||
fontWeight: 700,
|
||||
fontSize: large ? "0.9375rem" : "0.8125rem",
|
||||
fontVariantNumeric: "tabular-nums",
|
||||
color: negative ? "error.main" : "success.main",
|
||||
}}
|
||||
>
|
||||
{formatCurrency(value, currency)}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import React from "react";
|
||||
import { Box, Typography, Avatar, Chip, Button, FormHelperText } from "@mui/material";
|
||||
import type { FieldConfig } from "../../../types";
|
||||
import { getApi } from "../../../hooks/useApi";
|
||||
import { useAppContext } from "../../../context/AppContext";
|
||||
import { resolveMediaUrl } from "../utils";
|
||||
|
||||
interface Props {
|
||||
field: FieldConfig;
|
||||
@@ -19,6 +21,7 @@ const acceptMap: Record<string, string> = {
|
||||
export function FileUploadField({ field, value, onChange }: Props) {
|
||||
const uploadConfig = field.upload!;
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
const { config } = useAppContext();
|
||||
|
||||
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
@@ -51,12 +54,12 @@ export function FileUploadField({ field, value, onChange }: Props) {
|
||||
</Typography>
|
||||
{value ? (
|
||||
uploadConfig.type === "image" ? (
|
||||
<Avatar src={`/uploads/${value}`} variant="rounded" sx={{ width: 120, height: 120 }} />
|
||||
<Avatar src={resolveMediaUrl(`/uploads/${value}`, config.baseApiUrl)} variant="rounded" sx={{ width: 120, height: 120 }} />
|
||||
) : (
|
||||
<Chip
|
||||
label={value}
|
||||
component="a"
|
||||
href={`/uploads/${value}`}
|
||||
href={resolveMediaUrl(`/uploads/${value}`, config.baseApiUrl)}
|
||||
clickable
|
||||
onDelete={handleReplace}
|
||||
/>
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Box, Typography, Avatar, FormHelperText } from "@mui/material";
|
||||
import Button from "@mui/material/Button";
|
||||
import type { FieldConfig } from "../../../types";
|
||||
import { getApi } from "../../../hooks/useApi";
|
||||
import { useAppContext } from "../../../context/AppContext";
|
||||
import { resolveMediaUrl } from "../utils";
|
||||
|
||||
interface Props {
|
||||
field: FieldConfig;
|
||||
@@ -13,6 +15,7 @@ interface Props {
|
||||
}
|
||||
|
||||
export function ImageField({ field, value, onChange, id, uploadUrl }: Props) {
|
||||
const { config } = useAppContext();
|
||||
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
@@ -47,7 +50,7 @@ export function ImageField({ field, value, onChange, id, uploadUrl }: Props) {
|
||||
{field.label}
|
||||
</Typography>
|
||||
{value ? (
|
||||
<Avatar src={value} variant="rounded" sx={{ width: 120, height: 120 }} />
|
||||
<Avatar src={resolveMediaUrl(value, config.baseApiUrl)} variant="rounded" sx={{ width: 120, height: 120 }} />
|
||||
) : (
|
||||
<Button variant="outlined" component="label" size="small">
|
||||
Upload {field.label}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import React from "react";
|
||||
import { Autocomplete, TextField, Chip, Box } from "@mui/material";
|
||||
import DoneIcon from "@mui/icons-material/Done";
|
||||
import type { FieldConfig } from "../../../types";
|
||||
|
||||
interface Props {
|
||||
field: FieldConfig;
|
||||
value: any;
|
||||
onChange: (value: any[]) => void;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function MultiEnumField({ field, value, onChange, error }: Props) {
|
||||
const selected: string[] = Array.isArray(value) ? value : [];
|
||||
|
||||
return (
|
||||
<Autocomplete
|
||||
multiple
|
||||
disableCloseOnSelect
|
||||
size="small"
|
||||
options={field.enumValues ?? []}
|
||||
value={selected}
|
||||
onChange={(_, newVal) => onChange(newVal)}
|
||||
renderOption={(props, option, { selected: isSelected }) => {
|
||||
const { key, ...rest } = props as any;
|
||||
return (
|
||||
<li key={key} {...rest}>
|
||||
{isSelected ? (
|
||||
<DoneIcon sx={{ fontSize: 14, mr: 1, color: "primary.main" }} />
|
||||
) : (
|
||||
<Box sx={{ width: 22, mr: 1 }} />
|
||||
)}
|
||||
{option}
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
renderTags={(tagValue, getTagProps) =>
|
||||
tagValue.map((tag, index) => {
|
||||
const { key, ...tagProps } = getTagProps({ index });
|
||||
return <Chip key={key} {...tagProps} label={tag} size="small" />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
label={field.label}
|
||||
placeholder={field.description || undefined}
|
||||
error={!!error}
|
||||
helperText={error || field.description || undefined}
|
||||
size="small"
|
||||
/>
|
||||
)}
|
||||
sx={{
|
||||
"& .MuiAutocomplete-popupIndicator, & .MuiAutocomplete-clearIndicator": { width: 20, height: 20, fontSize: 16 },
|
||||
}}
|
||||
disabled={field.readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -9,3 +9,15 @@ export function applyDisplayFormat(item: any, format: string): string {
|
||||
return val != null ? String(val) : "";
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a media/image URL against the API base so relative paths
|
||||
* like `/uploads/entity_logos/x.svg` point at the backend origin.
|
||||
* Absolute (http/data/blob) URLs are returned untouched.
|
||||
*/
|
||||
export function resolveMediaUrl(value: string | null | undefined, baseUrl?: string): string | undefined {
|
||||
if (value == null || value === "") return undefined;
|
||||
if (value.startsWith("http") || value.startsWith("data:") || value.startsWith("blob:")) return value;
|
||||
if (value.startsWith("/") && baseUrl) return `${baseUrl.replace(/\/+$/, "")}${value}`;
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -43,6 +43,20 @@ function extractProfileOperations(spec: any): ProfileOperation[] {
|
||||
return ops;
|
||||
}
|
||||
|
||||
function applyResourceOverrides(configs: ResourceConfig[], specConfiguration: SpecConfiguration): ResourceConfig[] {
|
||||
for (const resource of configs) {
|
||||
const fieldTypes = specConfiguration.resourceConfig?.[resource.name]?.fieldTypes;
|
||||
if (!fieldTypes) continue;
|
||||
// fields and orderedFields share the same FieldConfig object references,
|
||||
// so an in-place mutation updates both.
|
||||
for (const field of resource.fields) {
|
||||
const override = fieldTypes[field.name];
|
||||
if (override) field.uiType = override;
|
||||
}
|
||||
}
|
||||
return configs;
|
||||
}
|
||||
|
||||
const DEFAULT_AUTH_CONFIG: AuthConfig = {
|
||||
serverUrl: "",
|
||||
loginPath: "/login",
|
||||
@@ -88,7 +102,7 @@ export function AppProvider({ specConfiguration, children }: AppProviderProps) {
|
||||
if (errs.length === 0) {
|
||||
const configs = buildResourceConfigs(spec);
|
||||
if (!cancelled) {
|
||||
setResources(configs);
|
||||
setResources(applyResourceOverrides(configs, specConfiguration));
|
||||
}
|
||||
|
||||
const baseUrl = specConfiguration.baseApiUrl ?? spec.servers?.[0]?.url ?? "";
|
||||
|
||||
@@ -56,6 +56,7 @@ interface UseResourceReturn {
|
||||
get: (id: string | number, params?: Record<string, any>) => Promise<any>;
|
||||
create: (data: any) => Promise<any>;
|
||||
update: (id: string | number, data: any) => Promise<any>;
|
||||
patch?: (id: string | number, data: any) => Promise<any>;
|
||||
remove: (id: string | number) => Promise<void>;
|
||||
stream?: (handlers: StreamHandlers, pathParams?: Record<string, string | number>) => StreamSubscription;
|
||||
loading: boolean;
|
||||
@@ -596,7 +597,7 @@ export function useResource(resourceName: string): UseResourceReturn {
|
||||
|
||||
const rPath = resource?.path;
|
||||
const rPagination = resource?.pagination;
|
||||
const rUpdateMethod = resource?.updateMethod;
|
||||
const rPatch = resource ? (resource.operations.patch || undefined) : false;
|
||||
const rStreaming = resource?.streaming;
|
||||
const rFields = resource?.fields;
|
||||
|
||||
@@ -706,8 +707,7 @@ export function useResource(resourceName: string): UseResourceReturn {
|
||||
const sanitized = rFields && schemas
|
||||
? await sanitizePayload(data, rFields, schemas, resolveFk)
|
||||
: data;
|
||||
const method = rUpdateMethod ?? "put";
|
||||
const res = await (method === "patch" ? api.patch : api.put)(`${rPath}/${id}`, sanitized);
|
||||
const res = await api.put(`${rPath}/${id}`, sanitized);
|
||||
return res.data;
|
||||
} catch (e: any) {
|
||||
setError(parseError(e));
|
||||
@@ -716,7 +716,29 @@ export function useResource(resourceName: string): UseResourceReturn {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[rPath, rFields, schemas, resolveFk, rUpdateMethod, setLoading, setError]
|
||||
[rPath, rFields, schemas, resolveFk, setLoading, setError]
|
||||
);
|
||||
|
||||
const _patch = useCallback(
|
||||
async (id: string | number, data: any): Promise<any> => {
|
||||
if (!rPath) throw new Error(`Resource "${resourceName}" not found yet`);
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const api = getApi();
|
||||
const sanitized = rFields && schemas
|
||||
? await sanitizePayload(data, rFields, schemas, resolveFk)
|
||||
: data;
|
||||
const res = await api.patch(`${rPath}/${id}`, sanitized);
|
||||
return res.data;
|
||||
} catch (e: any) {
|
||||
setError(parseError(e));
|
||||
throw e;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[rPath, rFields, schemas, resolveFk, setLoading, setError]
|
||||
);
|
||||
|
||||
const remove = useCallback(
|
||||
@@ -791,6 +813,7 @@ export function useResource(resourceName: string): UseResourceReturn {
|
||||
get,
|
||||
create,
|
||||
update,
|
||||
patch: undefined,
|
||||
remove,
|
||||
stream: undefined,
|
||||
loading: false,
|
||||
@@ -798,5 +821,5 @@ export function useResource(resourceName: string): UseResourceReturn {
|
||||
};
|
||||
}
|
||||
|
||||
return { resource, components, list, get, create, update, remove, stream: rStreaming ? stream : undefined, loading: state.loading, error: state.error };
|
||||
return { resource, components, list, get, create, update, patch: rPatch ? _patch : undefined, remove, stream: rStreaming ? stream : undefined, loading: state.loading, error: state.error };
|
||||
}
|
||||
@@ -3,6 +3,24 @@ import axios, { AxiosInstance } from "axios";
|
||||
let apiClient: AxiosInstance | null = null;
|
||||
let _onUnauthorized: (() => void) | undefined;
|
||||
|
||||
function serializeParams(params: Record<string, any>): string {
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params ?? {})) {
|
||||
if (value === undefined || value === null) continue;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) searchParams.append(key, String(item));
|
||||
} else if (typeof value === "object") {
|
||||
for (const [nestedKey, nestedValue] of Object.entries(value)) {
|
||||
if (nestedValue === undefined || nestedValue === null) continue;
|
||||
searchParams.append(`${key}[${nestedKey}]`, String(nestedValue));
|
||||
}
|
||||
} else {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
}
|
||||
return searchParams.toString();
|
||||
}
|
||||
|
||||
export function initApi(baseUrl: string, getToken?: () => string | null, onUnauthorized?: () => void): AxiosInstance {
|
||||
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
||||
_onUnauthorized = onUnauthorized;
|
||||
@@ -14,6 +32,7 @@ export function initApi(baseUrl: string, getToken?: () => string | null, onUnaut
|
||||
apiClient = axios.create({
|
||||
baseURL: baseUrl,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
paramsSerializer: serializeParams,
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
|
||||
82
react-openapi/src/hooks/useFkFieldOptions.ts
Normal file
82
react-openapi/src/hooks/useFkFieldOptions.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { FieldConfig, FKFieldConfig } from "../types";
|
||||
import { useAppContext } from "../context/AppContext";
|
||||
import { getApi } from "./useApi";
|
||||
|
||||
export interface FkOption {
|
||||
value: any;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function applyFormat(obj: any, format: string): string {
|
||||
if (!obj || typeof obj !== "object") return String(obj ?? "");
|
||||
return format.replace(/\{(\w+)\}/g, (_, key) => String(obj[key] ?? ""));
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads select options for FK-annotated fields of a field set.
|
||||
* Option values bind to `fk.value` when set (e.g. account names),
|
||||
* otherwise to the target resource's primary key.
|
||||
*/
|
||||
export function useFkFieldOptions(fields: FieldConfig[]) {
|
||||
const { resources } = useAppContext();
|
||||
const [fkOptions, setFkOptions] = useState<Record<string, FkOption[]>>({});
|
||||
const [fkLoading, setFkLoading] = useState<Record<string, boolean>>({});
|
||||
|
||||
const loadFkOptions = useCallback(
|
||||
async (fieldName: string, fk: FKFieldConfig) => {
|
||||
setFkLoading((prev) => ({ ...prev, [fieldName]: true }));
|
||||
try {
|
||||
const targetRes = resources.find((r) => r.name === fk.resource);
|
||||
if (!targetRes) return;
|
||||
|
||||
const api = getApi();
|
||||
const params: Record<string, any> = {};
|
||||
if (targetRes.pagination) params.limit = 0;
|
||||
const res = await api.get(targetRes.path, { params });
|
||||
|
||||
let items: any[];
|
||||
if (targetRes.pagination) {
|
||||
if (!res.data || typeof res.data !== "object" || !Array.isArray(res.data.items)) {
|
||||
throw new Error(`Expected paginated response from ${targetRes.path}`);
|
||||
}
|
||||
items = res.data.items;
|
||||
} else {
|
||||
if (!Array.isArray(res.data)) {
|
||||
throw new Error(`Expected array response from ${targetRes.path}`);
|
||||
}
|
||||
items = res.data;
|
||||
}
|
||||
|
||||
const opts: FkOption[] = items.map((item: any) => ({
|
||||
value: item[fk.value ?? targetRes.primaryKey],
|
||||
label: applyFormat(item, targetRes.displayFormat),
|
||||
}));
|
||||
setFkOptions((prev) => ({ ...prev, [fieldName]: opts }));
|
||||
} catch {
|
||||
// leave options empty; the field renders without suggestions
|
||||
} finally {
|
||||
setFkLoading((prev) => ({ ...prev, [fieldName]: false }));
|
||||
}
|
||||
},
|
||||
[resources]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fields.forEach((f) => {
|
||||
if (f.fk?.prefetch) loadFkOptions(f.name, f.fk);
|
||||
});
|
||||
}, [fields, loadFkOptions]);
|
||||
|
||||
const loadFkOnOpen = useCallback(
|
||||
(fieldName: string) => {
|
||||
const field = fields.find((f) => f.name === fieldName);
|
||||
if (field?.fk && !field.fk.prefetch && !fkOptions[fieldName]) {
|
||||
loadFkOptions(fieldName, field.fk);
|
||||
}
|
||||
},
|
||||
[fields, fkOptions, loadFkOptions]
|
||||
);
|
||||
|
||||
return { fkOptions, fkLoading, loadFkOnOpen };
|
||||
}
|
||||
@@ -136,7 +136,10 @@ export function extractFields(schemaName: string, schema: any, schemas: Record<s
|
||||
sortable: prop["x-sortable"] ?? false,
|
||||
readOnly: prop.readOnly ?? false,
|
||||
required: requiredFields.includes(name),
|
||||
enumValues: prop.enum,
|
||||
// Lift enum constraints from array items so arrays-of-enum can render
|
||||
// as multi-selects (e.g. ReportQuery.granularities).
|
||||
enumValues: prop.enum ?? (prop.type === "array" ? prop.items?.enum : undefined),
|
||||
defaultValue: prop.default,
|
||||
fk: prop["x-fk"],
|
||||
uiType: prop["x-ui-type"],
|
||||
uploadUrl: prop["x-upload-url"],
|
||||
|
||||
@@ -98,9 +98,9 @@ export function buildResourceConfigs(spec: OpenApiSpec): ResourceConfig[] {
|
||||
const parent = nameMap.get(parentName);
|
||||
if (!parent) continue;
|
||||
if (hasOperation(pathObj, "get")) parent.operations.get = true;
|
||||
if (hasOperation(pathObj, "put") || hasOperation(pathObj, "patch")) parent.operations.update = true;
|
||||
if (hasOperation(pathObj, "put")) parent.operations.update = true;
|
||||
if (hasOperation(pathObj, "patch")) parent.operations.patch = true;
|
||||
if (hasOperation(pathObj, "delete")) parent.operations.delete = true;
|
||||
if (hasOperation(pathObj, "patch") && !hasOperation(pathObj, "put")) parent.updateMethod = "patch";
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -127,8 +127,8 @@ export function buildResourceConfigs(spec: OpenApiSpec): ResourceConfig[] {
|
||||
fields: hasSSE ? [SSE_RECEIVED_FIELD, ...fields.map((f) => ({ ...f, readOnly: true }))] : fields,
|
||||
orderedFields: [],
|
||||
operations: hasSSE
|
||||
? { list: true, get: false, create: false, update: false, delete: false }
|
||||
: { list: hasOperation(pathObj, "get"), get: false, create: false, update: false, delete: false },
|
||||
? { list: true, get: false, create: false, update: false, patch: false, delete: false }
|
||||
: { list: hasOperation(pathObj, "get"), get: false, create: false, update: false, patch: false, delete: false },
|
||||
updateMethod: "put",
|
||||
pagination: hasSSE ? null : detectPagination(pathObj),
|
||||
relationships: [],
|
||||
@@ -172,9 +172,9 @@ export function buildResourceConfigs(spec: OpenApiSpec): ResourceConfig[] {
|
||||
listColumns: schema?.["x-list-columns"] ?? [],
|
||||
fields: hasSSE ? [SSE_RECEIVED_FIELD, ...fields.map((f) => ({ ...f, readOnly: true }))] : fields,
|
||||
orderedFields: [],
|
||||
operations: hasSSE
|
||||
? { list: true, get: false, create: false, update: false, delete: false }
|
||||
: { list: hasOperation(pathObj, "get"), get: false, create: hasOperation(pathObj, "post"), update: false, delete: false },
|
||||
operations: hasSSE
|
||||
? { list: true, get: false, create: false, update: false, patch: false, delete: false }
|
||||
: { list: hasOperation(pathObj, "get"), get: false, create: hasOperation(pathObj, "post"), update: false, patch: false, delete: false },
|
||||
updateMethod: "put",
|
||||
pagination: hasSSE ? null : detectPagination(pathObj),
|
||||
relationships,
|
||||
|
||||
@@ -4,6 +4,8 @@ export interface ResourceConfiguration {
|
||||
filterOptions?: {
|
||||
mode?: FilterMode;
|
||||
};
|
||||
/** Map of field name → uiType override (e.g. { amount: "currency" }). */
|
||||
fieldTypes?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface ProfileComponents {
|
||||
@@ -65,6 +67,7 @@ export interface ResourceConfig {
|
||||
get: boolean;
|
||||
create: boolean;
|
||||
update: boolean;
|
||||
patch: boolean;
|
||||
delete: boolean;
|
||||
};
|
||||
updateMethod: "put" | "patch";
|
||||
@@ -82,6 +85,8 @@ export interface ResourceConfig {
|
||||
export interface FKFieldConfig {
|
||||
resource: string;
|
||||
prefetch: boolean;
|
||||
/** Target property used as the wire value (defaults to the target's primary key). */
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export interface OneOfOption {
|
||||
@@ -103,6 +108,8 @@ export interface FieldConfig {
|
||||
readOnly: boolean;
|
||||
required: boolean;
|
||||
enumValues?: string[];
|
||||
/** Schema-level `default` used to seed create-form state. */
|
||||
defaultValue?: any;
|
||||
fk?: FKFieldConfig;
|
||||
uiType?: string;
|
||||
uploadUrl?: string;
|
||||
|
||||
@@ -29,7 +29,9 @@ export async function sanitizePayload(
|
||||
|
||||
const val = result[key];
|
||||
|
||||
if (field.fk) {
|
||||
// FK fields whose wire value is a plain target property (fk.value, e.g.
|
||||
// account names) are already in wire format — no id→object resolution.
|
||||
if (field.fk && !field.fk.value) {
|
||||
if (val == null || val === "") {
|
||||
result[key] = null;
|
||||
} else if (resolveFk) {
|
||||
|
||||
126
src/Expense.tsx
Normal file
126
src/Expense.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Container,
|
||||
Box,
|
||||
Paper,
|
||||
Typography,
|
||||
Alert,
|
||||
Skeleton,
|
||||
Button,
|
||||
} from "@mui/material";
|
||||
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useResource, useAppContext, formatCurrency } from "../react-openapi";
|
||||
import { PageHeader } from "./ui/PageHeader";
|
||||
import { EmptyState } from "./ui/EmptyState";
|
||||
import { StatCard } from "./common/components/StatCard";
|
||||
import { TransactionList } from "./common/components/TransactionList";
|
||||
import { buildTxnFieldConfigs } from "./common/utils/fieldConfigs";
|
||||
import { isExpense } from "./common/utils/transactions";
|
||||
import { currentMonthKey, monthKey, monthLabel, parseOccurredAt } from "./common/utils/dates";
|
||||
import type { ExpenseItem } from "./common/types";
|
||||
|
||||
export default function Expense() {
|
||||
const navigate = useNavigate();
|
||||
const { list, loading, error, resource } = useResource("expenses");
|
||||
const { resources } = useAppContext();
|
||||
const [items, setItems] = useState<ExpenseItem[] | null>(null);
|
||||
|
||||
const fieldConfigs = useMemo(() => buildTxnFieldConfigs(resources), [resources]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
list({ limit: 0 }).then((res) => {
|
||||
if (!mounted) return;
|
||||
setItems((res.items ?? []) as ExpenseItem[]);
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [list]);
|
||||
|
||||
const sorted = useMemo(
|
||||
() =>
|
||||
[...(items ?? [])].sort(
|
||||
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
||||
),
|
||||
[items],
|
||||
);
|
||||
|
||||
const summary = useMemo(() => {
|
||||
const currency = sorted.find((it) => it.account?.currency)?.account?.currency ?? "INR";
|
||||
const totalSpent = sorted.filter(isExpense).reduce((s, it) => s + (it.amount ?? 0), 0);
|
||||
const totalIncome = sorted.filter((it) => !isExpense(it)).reduce((s, it) => s + (it.amount ?? 0), 0);
|
||||
const thisMonth = currentMonthKey();
|
||||
const monthItems = sorted.filter((it) => monthKey(it.occurred_at) === thisMonth);
|
||||
const monthTotal = monthItems.filter(isExpense).reduce((s, it) => s + (it.amount ?? 0), 0);
|
||||
return { currency, totalSpent, totalIncome, thisMonth: monthLabel(thisMonth), monthItems, monthTotal };
|
||||
}, [sorted]);
|
||||
|
||||
const loadingUI = (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 4 }}>
|
||||
{[0, 1, 2].map((i) => (
|
||||
<Box key={i}>
|
||||
<Skeleton variant="text" width={160} height={32} sx={{ mb: 1.5 }} />
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
{[0, 1, 2].map((j) => (
|
||||
<Skeleton key={j} variant="rounded" height={64} sx={{ borderRadius: 2 }} />
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<Container maxWidth="lg" sx={{ py: 4 }}>
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Home", path: "/" }, { label: "Expenses" }]}
|
||||
title="Expenses"
|
||||
subtitle="Every transaction imported from your accounts, grouped by month."
|
||||
actions={
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => navigate("/admin/expenses/new")}
|
||||
>
|
||||
New Expense
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
Failed to load expenses: {error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{items === null && !error ? (
|
||||
loadingUI
|
||||
) : items && items.length === 0 ? (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 3, mt: 2 }}>
|
||||
<EmptyState
|
||||
icon={<ReceiptLongIcon />}
|
||||
title="No expenses yet"
|
||||
description="Once you run a fetch request, imported transactions will show up here grouped by month."
|
||||
actionLabel="Go to Fetch Requests"
|
||||
onAction={() => navigate("/fetch-requests")}
|
||||
/>
|
||||
</Paper>
|
||||
) : (
|
||||
<>
|
||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
||||
<StatCard
|
||||
label="Outflows"
|
||||
value={formatCurrency(summary.totalSpent, summary.currency)}
|
||||
hint={`${summary.monthItems.length} transaction${summary.monthItems.length === 1 ? "" : "s"} this month`}
|
||||
/>
|
||||
<StatCard label="This month" value={formatCurrency(summary.monthTotal, summary.currency)} hint={summary.thisMonth} />
|
||||
<StatCard label="Inflows" value={formatCurrency(summary.totalIncome, summary.currency)} />
|
||||
</Box>
|
||||
|
||||
{fieldConfigs && <TransactionList items={sorted} fields={fieldConfigs} />}
|
||||
</>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -4,10 +4,13 @@ import {
|
||||
CircularProgress,
|
||||
} from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
||||
import { useAppContext, useResource, ListCellRenderer, FormFieldRenderer, getApi, applyDisplayFormat } from "../../react-openapi";
|
||||
import type { FieldConfig } from "../../react-openapi";
|
||||
import { PageHeader } from "../ui/PageHeader";
|
||||
import { EmptyState } from "../ui/EmptyState";
|
||||
|
||||
const CREATE_FIELDS = ["account", "format", "start_date", "end_date", "source"];
|
||||
const CREATE_FIELDS = ["account", "bank", "pipeline", "start_date", "end_date", "source"];
|
||||
|
||||
function FetchRequestList() {
|
||||
const navigate = useNavigate();
|
||||
@@ -29,25 +32,39 @@ function FetchRequestList() {
|
||||
|
||||
if (!rows) {
|
||||
return (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
|
||||
<CircularProgress size={24} />
|
||||
<Box sx={{ display: "flex", justifyContent: "center", py: 6 }}>
|
||||
<CircularProgress size={28} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
return <Typography variant="body2" color="text.secondary">No fetch requests found.</Typography>;
|
||||
return (
|
||||
<EmptyState
|
||||
icon={<ReceiptLongIcon />}
|
||||
title="No fetch requests yet"
|
||||
description="Upload a bank statement or configure email ingestion to import your first transactions."
|
||||
actionLabel="New Fetch Request"
|
||||
onAction={() => document.getElementById("new-fetch-request")?.scrollIntoView({ behavior: "smooth", block: "center" })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||
{rows.map((row, i) => {
|
||||
const displayFormat = resource?.displayFormat ?? "";
|
||||
return (
|
||||
<Paper
|
||||
key={row.id ?? i}
|
||||
variant="outlined"
|
||||
sx={{ p: 2, cursor: "pointer", "&:hover": { borderColor: "primary.main" } }}
|
||||
sx={{
|
||||
p: 2,
|
||||
cursor: "pointer",
|
||||
borderRadius: 2,
|
||||
transition: "border-color 160ms ease, box-shadow 160ms ease",
|
||||
"&:hover": { borderColor: "primary.main", boxShadow: 1 },
|
||||
}}
|
||||
onClick={() => navigate(`/fetch-requests/${row.id}`)}
|
||||
>
|
||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", alignItems: "center" }}>
|
||||
@@ -145,18 +162,25 @@ export default function FetchRequestCreate() {
|
||||
|
||||
return (
|
||||
<Container maxWidth="lg" sx={{ py: 4 }}>
|
||||
<Typography variant="h5" fontWeight={800} gutterBottom>
|
||||
Fetch Requests
|
||||
</Typography>
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests" }]}
|
||||
title="Fetch Requests"
|
||||
subtitle="Import transactions from bank statements or email and track pipeline progress."
|
||||
/>
|
||||
|
||||
<Paper variant="outlined" sx={{ p: 3, mb: 4, borderRadius: 2, position: "relative", overflow: "hidden", "&::before": { content: '""', position: "absolute", left: 0, top: 0, bottom: 0, width: 4, bgcolor: "primary.main" } }}>
|
||||
<Box sx={{ ml: 0.5, mb: 2.5 }}>
|
||||
<Typography variant="subtitle1" fontWeight={700}>
|
||||
New Fetch Request
|
||||
</Typography>
|
||||
</Box>
|
||||
<Paper
|
||||
id="new-fetch-request"
|
||||
variant="outlined"
|
||||
sx={{ p: 3, mb: 4, borderRadius: 3 }}
|
||||
>
|
||||
<Typography variant="subtitle1" fontWeight={700} gutterBottom>
|
||||
New Fetch Request
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3, maxWidth: 520, lineHeight: 1.6 }}>
|
||||
Choose an account, pipeline, and a file or email source to kick off an import.
|
||||
</Typography>
|
||||
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, maxWidth: 480 }}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2, maxWidth: 520 }}>
|
||||
{formFields.map((field) => (
|
||||
<FormFieldRenderer
|
||||
key={field.name}
|
||||
@@ -168,18 +192,18 @@ export default function FetchRequestCreate() {
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 2, gap: 1 }}>
|
||||
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, gap: 1.5 }}>
|
||||
<Button variant="outlined" onClick={() => { setFormData({}); setResult(null); }}>
|
||||
Reset
|
||||
</Button>
|
||||
<Button variant="contained" onClick={handleSubmit} disabled={loading}>
|
||||
<Button variant="contained" onClick={handleSubmit} disabled={loading} sx={{ minWidth: 180 }}>
|
||||
{loading ? <CircularProgress size={20} sx={{ mr: 0.5 }} /> : null}
|
||||
Create Fetch Request
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
{result && (
|
||||
<Alert severity={result.severity} sx={{ mt: 1 }} onClose={() => setResult(null)}>
|
||||
<Alert severity={result.severity} sx={{ mt: 2 }} onClose={() => setResult(null)}>
|
||||
{result.message}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -9,10 +9,8 @@ import {
|
||||
Chip,
|
||||
CircularProgress,
|
||||
Alert,
|
||||
IconButton,
|
||||
Snackbar,
|
||||
Divider,
|
||||
} from "@mui/material";
|
||||
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
||||
import ReplayIcon from "@mui/icons-material/Replay";
|
||||
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
|
||||
import ErrorIcon from "@mui/icons-material/Error";
|
||||
@@ -20,12 +18,14 @@ import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
|
||||
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
|
||||
import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord";
|
||||
import { useResource, useItemSse, DetailFieldRenderer, applyDisplayFormat } from "../../react-openapi";
|
||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||
import { useResource, useItemSse, useAppContext, DetailFieldRenderer, applyDisplayFormat } from "../../react-openapi";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { RETRY_MAX, formatApiError } from "../features/fetch-requests";
|
||||
import type { FetchRequestStatus, SSEEvent, ProgressMessage } from "../features/fetch-requests";
|
||||
import { PipelineStepper } from "./components/PipelineStepper";
|
||||
import { AmbiguityResolver } from "./components/AmbiguityResolver";
|
||||
import { PageHeader } from "../ui/PageHeader";
|
||||
import { useToast } from "../ui/Toast";
|
||||
|
||||
const statusColors: Record<FetchRequestStatus, "default" | "primary" | "warning" | "info" | "success" | "error"> = {
|
||||
pending: "default",
|
||||
@@ -68,13 +68,29 @@ function sseIcon(status: SSEEvent["status"]) {
|
||||
}
|
||||
}
|
||||
|
||||
function Section({ title, children, action }: { title: string; children: React.ReactNode; action?: React.ReactNode }) {
|
||||
return (
|
||||
<Paper sx={{ p: 3, borderRadius: 3, mb: 3 }} variant="outlined">
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, mb: 2 }}>
|
||||
<Typography variant="subtitle1" fontWeight={700} sx={{ flex: 1 }}>
|
||||
{title}
|
||||
</Typography>
|
||||
{action}
|
||||
</Box>
|
||||
{children}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
export default function FetchRequestDetail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { get, update, resource } = useResource("fetch-requests");
|
||||
const { get, patch, resource } = useResource("fetch-requests");
|
||||
const { resources: allResources } = useAppContext();
|
||||
const [stepStats, setStepStats] = useState<Record<string, number>>({});
|
||||
const [liveParsedCount, setLiveParsedCount] = useState<number | undefined>(undefined);
|
||||
const [failNotif, setFailNotif] = useState<string | null>(null);
|
||||
const [retrying, setRetrying] = useState(false);
|
||||
const { showToast } = useToast();
|
||||
const feedRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data: fetchRequest, isLoading, error: fetchError, refetch: refetchRequest } = useQuery({
|
||||
@@ -83,10 +99,6 @@ export default function FetchRequestDetail() {
|
||||
enabled: !!id,
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id: rid, data }: { id: string; data: any }) => update(rid, data),
|
||||
});
|
||||
|
||||
const sseUrl = id ? `/fetch-requests/${id}/events` : null;
|
||||
const { connected: sseConnected, events: sseEvents } = useItemSse(sseUrl, {
|
||||
onEvent: (parsed: SSEEvent) => {
|
||||
@@ -112,7 +124,7 @@ export default function FetchRequestDetail() {
|
||||
refetchRequest();
|
||||
}
|
||||
if (parsed.status === "failed") {
|
||||
setFailNotif(parsed.message.error || "Fetch request failed");
|
||||
showToast(parsed.message.error || "Fetch request failed", "error");
|
||||
refetchRequest();
|
||||
}
|
||||
if (parsed.status === "completed" || parsed.step === "resume_extract") {
|
||||
@@ -150,15 +162,41 @@ export default function FetchRequestDetail() {
|
||||
}, [sseEvents]);
|
||||
|
||||
const handleRetry = async () => {
|
||||
if (!id) return;
|
||||
if (!id || !patch || retrying) return;
|
||||
setRetrying(true);
|
||||
try {
|
||||
await updateMutation.mutateAsync({ id, data: { status: "pending" } });
|
||||
await patch(id, { status: "pending" });
|
||||
refetchRequest();
|
||||
} catch (err: any) {
|
||||
setFailNotif(formatApiError(err));
|
||||
showToast(formatApiError(err), "error");
|
||||
} finally {
|
||||
setRetrying(false);
|
||||
}
|
||||
};
|
||||
|
||||
const req = fetchRequest as any;
|
||||
const retryCount = req?.retry_count ?? 0;
|
||||
const isRetryExhausted = retryCount >= RETRY_MAX;
|
||||
const status = (req?.status ?? "pending") as FetchRequestStatus;
|
||||
const detailFields = (resource?.orderedFields ?? []).filter(
|
||||
(f) => f.name !== "source",
|
||||
);
|
||||
|
||||
const displayTitle = useMemo(() => {
|
||||
if (!resource || !req) return "";
|
||||
const resolved = Object.fromEntries(
|
||||
resource.orderedFields.map((field) => {
|
||||
const value = req[field.name];
|
||||
if (field.fk && typeof value === "object" && value != null) {
|
||||
const target = allResources.find((r) => r.name === field.fk!.resource);
|
||||
if (target) return [field.name, applyDisplayFormat(value, target.displayFormat)];
|
||||
}
|
||||
return [field.name, value];
|
||||
}),
|
||||
);
|
||||
return applyDisplayFormat(resolved, resource.displayFormat);
|
||||
}, [resource, req, allResources]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", p: 8 }}>
|
||||
@@ -170,56 +208,67 @@ export default function FetchRequestDetail() {
|
||||
if (fetchError || !fetchRequest) {
|
||||
return (
|
||||
<Container sx={{ mt: 4 }}>
|
||||
<Button startIcon={<ArrowBackIcon />} onClick={() => navigate("/fetch-requests")} sx={{ mb: 2 }}>
|
||||
Back
|
||||
</Button>
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests", path: "/fetch-requests" }, { label: "Details" }]}
|
||||
title="Fetch Request"
|
||||
/>
|
||||
<Alert severity="error">Failed to load fetch request</Alert>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
const req = fetchRequest as any;
|
||||
const retryCount = req.retry_count ?? 0;
|
||||
const isRetryExhausted = retryCount >= RETRY_MAX;
|
||||
const status = req.status as FetchRequestStatus;
|
||||
|
||||
const detailFields = (resource?.orderedFields ?? []).filter(
|
||||
(f) => f.name !== "source",
|
||||
);
|
||||
|
||||
return (
|
||||
<Container sx={{ mt: 4, mb: 4 }}>
|
||||
<Button startIcon={<ArrowBackIcon />} onClick={() => navigate("/fetch-requests")} sx={{ mb: 2 }}>
|
||||
Back to Fetch Requests
|
||||
</Button>
|
||||
<Container maxWidth="lg" sx={{ py: 4 }}>
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Home", path: "/" }, { label: "Fetch Requests", path: "/fetch-requests" }, { label: displayTitle }]}
|
||||
title={displayTitle}
|
||||
subtitle="Live pipeline status, progress events, and ambiguity resolution for this import."
|
||||
/>
|
||||
|
||||
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2, flexWrap: "wrap" }}>
|
||||
<Section
|
||||
title="Overview"
|
||||
action={
|
||||
<Chip
|
||||
icon={statusIcons[status] as any}
|
||||
label={status.replace(/_/g, " ")}
|
||||
color={statusColors[status]}
|
||||
sx={{ textTransform: "capitalize" }}
|
||||
/>
|
||||
<Typography variant="h6" fontWeight={600}>{req.account_name}</Typography>
|
||||
}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2, flexWrap: "wrap" }}>
|
||||
<Chip
|
||||
label={"path" in (req.source ?? {}) ? "File" : "Email"}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
color={"path" in (req.source ?? {}) ? "primary" : "secondary"}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
ID: {req.id}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 4, flexWrap: "wrap", mb: 2 }}>
|
||||
{detailFields.map((field) => (
|
||||
<DetailFieldRenderer
|
||||
key={field.name}
|
||||
field={field}
|
||||
value={req[field.name]}
|
||||
displayFormat={resource?.displayFormat}
|
||||
/>
|
||||
))}
|
||||
{detailFields.map((field) => {
|
||||
const value = req[field.name];
|
||||
let fmt = resource?.displayFormat;
|
||||
if (field.fk && typeof value === "object" && value != null) {
|
||||
const target = allResources.find((r) => r.name === field.fk!.resource);
|
||||
if (target) fmt = target.displayFormat;
|
||||
}
|
||||
return (
|
||||
<DetailFieldRenderer
|
||||
key={field.name}
|
||||
field={field}
|
||||
value={value}
|
||||
displayFormat={fmt}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
||||
<Divider sx={{ my: 2 }} />
|
||||
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
||||
<Box sx={{ flex: 1, maxWidth: 300 }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
@@ -232,13 +281,13 @@ export default function FetchRequestDetail() {
|
||||
size="small"
|
||||
startIcon={<ReplayIcon />}
|
||||
onClick={handleRetry}
|
||||
disabled={updateMutation.isPending}
|
||||
disabled={retrying}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
</Section>
|
||||
|
||||
{status === "failed" && req.error_message && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
@@ -258,33 +307,33 @@ export default function FetchRequestDetail() {
|
||||
liveParsedCount={liveParsedCount ?? 0}
|
||||
/>
|
||||
|
||||
<Paper sx={{ borderRadius: 4, mb: 3 }} variant="outlined">
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, p: 2, pb: 0 }}>
|
||||
<Typography variant="subtitle1" fontWeight={600} sx={{ flex: 1 }}>
|
||||
Progress Events
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: "50%",
|
||||
bgcolor: sseConnected ? "success.main" : "error.main",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{sseConnected ? "Connected" : "Disconnected"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Section
|
||||
title="Progress Events"
|
||||
action={
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 8,
|
||||
height: 8,
|
||||
borderRadius: "50%",
|
||||
bgcolor: sseConnected ? "success.main" : "error.main",
|
||||
}}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{sseConnected ? "Connected" : "Disconnected"}
|
||||
</Typography>
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
<Box
|
||||
ref={feedRef}
|
||||
sx={{
|
||||
maxHeight: 300,
|
||||
overflowY: "auto",
|
||||
p: 2,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 1,
|
||||
pr: 0.5,
|
||||
}}
|
||||
>
|
||||
{displayEvents.length === 0 ? (
|
||||
@@ -299,7 +348,7 @@ export default function FetchRequestDetail() {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1.5,
|
||||
p: 1,
|
||||
p: 1.25,
|
||||
borderRadius: 2,
|
||||
bgcolor: "action.hover",
|
||||
}}
|
||||
@@ -319,20 +368,9 @@ export default function FetchRequestDetail() {
|
||||
))
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
</Section>
|
||||
|
||||
<AmbiguityResolver fetchRequestId={id!} />
|
||||
|
||||
<Snackbar
|
||||
open={!!failNotif}
|
||||
autoHideDuration={6000}
|
||||
onClose={() => setFailNotif(null)}
|
||||
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
|
||||
>
|
||||
<Alert severity="error" onClose={() => setFailNotif(null)} sx={{ borderRadius: 2 }}>
|
||||
{failNotif}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,642 +0,0 @@
|
||||
import * as React from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import {
|
||||
Box,
|
||||
Container,
|
||||
Paper,
|
||||
Typography,
|
||||
Button,
|
||||
Chip,
|
||||
CircularProgress,
|
||||
Alert,
|
||||
Stepper,
|
||||
Step,
|
||||
StepLabel,
|
||||
LinearProgress,
|
||||
IconButton,
|
||||
Snackbar,
|
||||
} from "@mui/material";
|
||||
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
||||
import ReplayIcon from "@mui/icons-material/Replay";
|
||||
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
|
||||
import ErrorIcon from "@mui/icons-material/Error";
|
||||
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
|
||||
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
|
||||
import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord";
|
||||
import {
|
||||
useFetchRequestAmbiguities,
|
||||
useResolveAmbiguity,
|
||||
} from "./features/fetch-requests";
|
||||
import type {
|
||||
FetchRequestStatus,
|
||||
SSEEvent,
|
||||
ProgressMessage,
|
||||
} from "./features/fetch-requests";
|
||||
import { RETRY_MAX, formatApiError } from "./features/fetch-requests";
|
||||
import { useAppContext, useResource, useItemSse } from "../react-openapi";
|
||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||
|
||||
const statusColors: Record<FetchRequestStatus, "default" | "primary" | "warning" | "info" | "success" | "error"> = {
|
||||
pending: "default",
|
||||
processing: "info",
|
||||
paused: "warning",
|
||||
raw_expenses_done: "primary",
|
||||
enriched_done: "warning",
|
||||
completed: "success",
|
||||
failed: "error",
|
||||
};
|
||||
|
||||
const statusIcons: Record<FetchRequestStatus, React.ReactNode> = {
|
||||
pending: <PlayArrowIcon sx={{ fontSize: 16 }} />,
|
||||
processing: <CircularProgress size={14} />,
|
||||
paused: <WarningAmberIcon sx={{ fontSize: 16 }} />,
|
||||
raw_expenses_done: <CheckCircleIcon sx={{ fontSize: 16 }} />,
|
||||
enriched_done: <CheckCircleIcon sx={{ fontSize: 16 }} />,
|
||||
completed: <CheckCircleIcon sx={{ fontSize: 16 }} />,
|
||||
failed: <ErrorIcon sx={{ fontSize: 16 }} />,
|
||||
};
|
||||
|
||||
const stepLabels = ["Extract", "Raw Expense", "Enrich", "Save"];
|
||||
|
||||
function computeProgressPercent(
|
||||
status: FetchRequestStatus,
|
||||
liveCount: number,
|
||||
seenSteps: Set<string>,
|
||||
stepStats: Record<string, number>,
|
||||
txnBlockCount: number,
|
||||
txnDictCount: number,
|
||||
): number {
|
||||
if (status === "pending") return 0;
|
||||
if (status === "completed") return 100;
|
||||
|
||||
let pct = 0;
|
||||
|
||||
if (seenSteps.has("raw_lines") || seenSteps.has("txn_blocks")) pct += 10;
|
||||
|
||||
if (txnBlockCount > 0) {
|
||||
const current = Math.max(liveCount, stepStats.txn_dicts ?? 0);
|
||||
pct += Math.min(1, current / txnBlockCount) * 20;
|
||||
}
|
||||
|
||||
if (txnDictCount > 0) {
|
||||
pct += Math.min(1, (stepStats.enrich_count ?? 0) / txnDictCount) * 50;
|
||||
pct += Math.min(1, (stepStats.save_count ?? 0) / txnDictCount) * 20;
|
||||
}
|
||||
|
||||
return Math.round(Math.min(100, pct));
|
||||
}
|
||||
|
||||
function computeActiveStep(status: FetchRequestStatus, seenSteps: Set<string>): number {
|
||||
if (status === "completed") return stepLabels.length;
|
||||
|
||||
if (seenSteps.has("save_expenses/completed") || seenSteps.has("complete/completed")) return stepLabels.length;
|
||||
if (seenSteps.has("save_expenses") || seenSteps.has("complete")) return 3;
|
||||
|
||||
if (seenSteps.has("enrich/completed")) return 3;
|
||||
if (seenSteps.has("enrich")) return 2;
|
||||
|
||||
if (seenSteps.has("txn_dicts/completed") || status === "raw_expenses_done") return 2;
|
||||
if (seenSteps.has("txn_dicts")) return 1;
|
||||
|
||||
if (seenSteps.has("txn_blocks/completed")) return 1;
|
||||
if (seenSteps.has("raw_lines") || seenSteps.has("txn_blocks")) return 0;
|
||||
|
||||
if (status === "processing" || status === "paused") return 0;
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
function formatProgressMessage(msg: ProgressMessage): string {
|
||||
if (msg.lines !== undefined) return `${msg.lines} lines`;
|
||||
if (msg.blocks !== undefined) return `${msg.blocks} blocks`;
|
||||
if (msg.count !== undefined && msg.unit) return `${msg.count} ${msg.unit}`;
|
||||
if (msg.count !== undefined) return `${msg.count} items`;
|
||||
if (msg.raw_ocr_line) return `"${msg.raw_ocr_line.slice(0, 60)}${msg.raw_ocr_line.length > 60 ? "…" : ""}"`;
|
||||
if (msg.error) return msg.error.slice(0, 80);
|
||||
return "";
|
||||
}
|
||||
|
||||
function sseIcon(status: SSEEvent["status"]) {
|
||||
switch (status) {
|
||||
case "started": return <CircularProgress size={14} />;
|
||||
case "completed": return <CheckCircleIcon sx={{ fontSize: 16, color: "success.main" }} />;
|
||||
case "failed": return <ErrorIcon sx={{ fontSize: 16, color: "error.main" }} />;
|
||||
case "skipped": return <RemoveCircleOutlineIcon sx={{ fontSize: 16, color: "text.disabled" }} />;
|
||||
case "paused": return <WarningAmberIcon sx={{ fontSize: 16, color: "warning.main" }} />;
|
||||
case "progress": return <FiberManualRecordIcon sx={{ fontSize: 14, color: "info.main" }} />;
|
||||
}
|
||||
}
|
||||
|
||||
export default function FetchRequestDetail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { get, update } = useResource("fetch-requests");
|
||||
|
||||
const { data: fetchRequest, isLoading, error: fetchError, refetch: refetchRequest } = useQuery({
|
||||
queryKey: ["fetch-requests", "detail", id],
|
||||
queryFn: () => get(id!),
|
||||
enabled: !!id,
|
||||
});
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id: rid, data }: { id: string; data: any }) => update(rid, data),
|
||||
});
|
||||
const resolveMutation = useResolveAmbiguity();
|
||||
const { data: ambiguities, refetch: refetchAmbiguities } = useFetchRequestAmbiguities(id!);
|
||||
|
||||
const [stepStats, setStepStats] = React.useState<Record<string, number>>({});
|
||||
const [liveParsedCount, setLiveParsedCount] = React.useState<number | undefined>(undefined);
|
||||
const [failNotif, setFailNotif] = React.useState<string | null>(null);
|
||||
const feedRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
const sseUrl = id ? `/fetch-requests/${id}/events` : null;
|
||||
const { connected: sseConnected, events: sseEvents } = useItemSse(sseUrl, {
|
||||
onEvent: (parsed: SSEEvent) => {
|
||||
if (parsed.status === "progress" && parsed.message.count !== undefined) {
|
||||
if (parsed.step === "txn_dicts") setLiveParsedCount(parsed.message.count);
|
||||
if (parsed.step === "enrich") setStepStats((prev) => ({ ...prev, enrich_count: parsed.message.count! }));
|
||||
if (parsed.step === "save_expenses") setStepStats((prev) => ({ ...prev, save_count: parsed.message.count! }));
|
||||
}
|
||||
|
||||
if (parsed.status === "completed" && parsed.message.count !== undefined) {
|
||||
const stats: Record<string, number> = {};
|
||||
if (parsed.step === "raw_lines" && parsed.message.lines !== undefined) stats.raw_lines = parsed.message.lines;
|
||||
if (parsed.step === "txn_blocks" && parsed.message.blocks !== undefined) stats.txn_blocks = parsed.message.blocks;
|
||||
if (parsed.step === "txn_dicts") stats.txn_dicts = parsed.message.count;
|
||||
if (parsed.step === "enrich") stats.enrich_count = parsed.message.count;
|
||||
if (parsed.step === "save_expenses") stats.save_count = parsed.message.count;
|
||||
if (Object.keys(stats).length) {
|
||||
setStepStats((prev) => ({ ...prev, ...stats }));
|
||||
}
|
||||
}
|
||||
|
||||
if (parsed.status === "paused") {
|
||||
refetchRequest();
|
||||
refetchAmbiguities();
|
||||
}
|
||||
if (parsed.status === "failed") {
|
||||
setFailNotif(parsed.message.error || "Fetch request failed");
|
||||
refetchRequest();
|
||||
}
|
||||
if (parsed.status === "completed" || parsed.step === "resume_extract") {
|
||||
refetchRequest();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (feedRef.current) {
|
||||
feedRef.current.scrollTop = feedRef.current.scrollHeight;
|
||||
}
|
||||
}, [sseEvents]);
|
||||
|
||||
const txnBlockCount = React.useMemo(() => {
|
||||
const blocks = (fetchRequest as any)?.source?.txn_blocks;
|
||||
if (!blocks) return 0;
|
||||
return Object.values(blocks).reduce(
|
||||
(sum: number, list: any) => sum + (Array.isArray(list) ? list.length : 0),
|
||||
0,
|
||||
);
|
||||
}, [fetchRequest]);
|
||||
|
||||
const seenSteps = React.useMemo(() => {
|
||||
const steps = new Set<string>();
|
||||
for (const evt of sseEvents) {
|
||||
steps.add(evt.step);
|
||||
if (evt.status === "completed") steps.add(`${evt.step}/completed`);
|
||||
if (evt.status === "failed") steps.add(`${evt.step}/failed`);
|
||||
if (evt.status === "started") steps.add(`${evt.step}/started`);
|
||||
if (evt.status === "progress") steps.add(`${evt.step}/progress`);
|
||||
}
|
||||
return steps;
|
||||
}, [sseEvents]);
|
||||
|
||||
const displayParsedCount = React.useMemo(() => {
|
||||
if (liveParsedCount && liveParsedCount > 0) return liveParsedCount;
|
||||
const source = (fetchRequest as any)?.source;
|
||||
const persistedCount = source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||
if (persistedCount > 0) return persistedCount;
|
||||
const dicts = source?.txn_dicts;
|
||||
if (Array.isArray(dicts) && dicts.length > 0) return dicts.length;
|
||||
return 0;
|
||||
}, [liveParsedCount, fetchRequest]);
|
||||
|
||||
const txnDictCount = React.useMemo(() => {
|
||||
const source = (fetchRequest as any)?.source;
|
||||
if (stepStats.txn_dicts && stepStats.txn_dicts > 0) return stepStats.txn_dicts;
|
||||
return source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||
}, [fetchRequest, stepStats]);
|
||||
|
||||
const stepMessages = React.useMemo(() => {
|
||||
const msgs: Record<number, string> = {};
|
||||
const source = (fetchRequest as any)?.source;
|
||||
|
||||
const rawLineCount = stepStats.raw_lines ?? (source?.raw_lines?.length ?? 0);
|
||||
if (rawLineCount) msgs[0] = `${rawLineCount}`;
|
||||
|
||||
const sourceDictCount = source?.txn_dict_count ?? source?.txn_dicts_count ?? 0;
|
||||
const dictLive = liveParsedCount ?? stepStats.txn_dicts ?? 0;
|
||||
const dictCurrent = Math.max(dictLive, sourceDictCount);
|
||||
if (dictCurrent && txnBlockCount) msgs[1] = `${dictCurrent}/${txnBlockCount}`;
|
||||
else if (dictCurrent) msgs[1] = `${dictCurrent}`;
|
||||
|
||||
const txnDictDenom = stepStats.txn_dicts ?? sourceDictCount;
|
||||
if (stepStats.enrich_count && txnDictDenom) msgs[2] = `${stepStats.enrich_count}/${txnDictDenom}`;
|
||||
else if (stepStats.enrich_count) msgs[2] = `${stepStats.enrich_count}`;
|
||||
|
||||
if (stepStats.save_count && txnDictDenom) msgs[3] = `${stepStats.save_count}/${txnDictDenom}`;
|
||||
else if (stepStats.save_count) msgs[3] = `${stepStats.save_count}`;
|
||||
|
||||
return msgs;
|
||||
}, [fetchRequest, stepStats, liveParsedCount, txnBlockCount]);
|
||||
|
||||
const progressPercent = React.useMemo(
|
||||
() => computeProgressPercent(
|
||||
(fetchRequest as any)?.status as FetchRequestStatus ?? "pending",
|
||||
displayParsedCount,
|
||||
seenSteps,
|
||||
stepStats,
|
||||
txnBlockCount,
|
||||
txnDictCount,
|
||||
),
|
||||
[fetchRequest, displayParsedCount, seenSteps, stepStats, txnBlockCount, txnDictCount],
|
||||
);
|
||||
|
||||
const displayEvents = React.useMemo(() => {
|
||||
const progressSteps = new Set(["txn_dicts", "enrich", "save_expenses"]);
|
||||
const lastProgressIdx: Record<string, number> = {};
|
||||
for (let i = sseEvents.length - 1; i >= 0; i--) {
|
||||
const e = sseEvents[i];
|
||||
if (progressSteps.has(e.step) && e.status === "progress" && lastProgressIdx[e.step] === undefined) {
|
||||
lastProgressIdx[e.step] = i;
|
||||
}
|
||||
}
|
||||
|
||||
const terminalStatuses = new Set(["completed", "skipped", "paused", "failed"]);
|
||||
return sseEvents.filter((e, i) => {
|
||||
if (progressSteps.has(e.step) && e.status === "progress") return i === lastProgressIdx[e.step];
|
||||
if (e.status === "started") {
|
||||
return !sseEvents.slice(i + 1).some(
|
||||
(later) => later.step === e.step && terminalStatuses.has(later.status),
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [sseEvents]);
|
||||
|
||||
const handleRetry = async () => {
|
||||
if (!id) return;
|
||||
try {
|
||||
await updateMutation.mutateAsync({ id, data: { status: "pending" } });
|
||||
} catch (err: any) {
|
||||
setFailNotif(formatApiError(err));
|
||||
}
|
||||
};
|
||||
|
||||
const handleResolve = async (ambiguity: any, candidate: { amount: number; balance: number }) => {
|
||||
await resolveMutation.mutateAsync({
|
||||
ambiguityId: ambiguity.id,
|
||||
payload: { chosen: { amount: candidate.amount, balance: candidate.balance } },
|
||||
});
|
||||
refetchAmbiguities();
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", p: 8 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (fetchError || !fetchRequest) {
|
||||
return (
|
||||
<Container sx={{ mt: 4 }}>
|
||||
<Button startIcon={<ArrowBackIcon />} onClick={() => navigate("/fetch-requests")} sx={{ mb: 2 }}>
|
||||
Back
|
||||
</Button>
|
||||
<Alert severity="error">Failed to load fetch request</Alert>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
const req = fetchRequest as any;
|
||||
const activeStep = computeActiveStep(req.status as FetchRequestStatus, seenSteps);
|
||||
const retryCount = req.retry_count ?? 0;
|
||||
const isRetryExhausted = retryCount >= RETRY_MAX;
|
||||
const hasAmbiguities = ambiguities && ambiguities.length > 0;
|
||||
const allResolved = hasAmbiguities && ambiguities.every((a: any) => a.status === "resolved");
|
||||
|
||||
return (
|
||||
<Container sx={{ mt: 4, mb: 4 }}>
|
||||
<Button startIcon={<ArrowBackIcon />} onClick={() => navigate("/fetch-requests")} sx={{ mb: 2 }}>
|
||||
Back to Fetch Requests
|
||||
</Button>
|
||||
|
||||
{/* Header Card */}
|
||||
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 2, flexWrap: "wrap" }}>
|
||||
<Chip
|
||||
icon={statusIcons[req.status as FetchRequestStatus] as any}
|
||||
label={req.status.replace(/_/g, " ")}
|
||||
color={statusColors[req.status as FetchRequestStatus]}
|
||||
/>
|
||||
<Typography variant="h6" fontWeight={600}>{req.account_name}</Typography>
|
||||
<Chip
|
||||
label={"path" in req.source ? "File" : "Email"}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
color={"path" in req.source ? "primary" : "secondary"}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 4, flexWrap: "wrap", mb: 2 }}>
|
||||
<Box>
|
||||
<Typography variant="caption" color="text.secondary">Date Range</Typography>
|
||||
<Typography variant="body2">
|
||||
{req.start_date ? new Date(req.start_date).toLocaleDateString() : "?"} → {req.end_date ? new Date(req.end_date).toLocaleDateString() : "?"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography variant="caption" color="text.secondary">Created</Typography>
|
||||
<Typography variant="body2">{new Date(req.created_at).toLocaleString()}</Typography>
|
||||
</Box>
|
||||
{req.completed_at && (
|
||||
<Box>
|
||||
<Typography variant="caption" color="text.secondary">Completed</Typography>
|
||||
<Typography variant="body2">{new Date(req.completed_at).toLocaleString()}</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Progress Bar */}
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 0.5 }}>
|
||||
<Typography variant="caption" color="text.secondary">Overall Progress</Typography>
|
||||
{["processing", "paused"].includes(req.status) && displayParsedCount > 0 && (
|
||||
<Typography variant="caption" fontWeight={600} color="info.main">
|
||||
Validated: {displayParsedCount} transactions
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
value={progressPercent}
|
||||
color={req.status === "failed" ? "error" : req.status === "completed" ? "success" : "primary"}
|
||||
sx={{ borderRadius: 1, height: 8, transition: "width 0.3s ease" }}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ mt: 0.25, display: "block" }}>
|
||||
{progressPercent}%
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Retry Counter */}
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
|
||||
<Box sx={{ flex: 1, maxWidth: 300 }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
Retries: {retryCount}/{RETRY_MAX}
|
||||
</Typography>
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
value={(retryCount / RETRY_MAX) * 100}
|
||||
color={isRetryExhausted ? "error" : "primary"}
|
||||
sx={{ mt: 0.5, borderRadius: 1, height: 6 }}
|
||||
/>
|
||||
</Box>
|
||||
{req.status === "failed" && !isRetryExhausted && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<ReplayIcon />}
|
||||
onClick={handleRetry}
|
||||
disabled={updateMutation.isPending}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
{/* Error Alerts */}
|
||||
{req.status === "failed" && req.error_message && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
{req.error_message}
|
||||
</Alert>
|
||||
)}
|
||||
{isRetryExhausted && req.status === "failed" && (
|
||||
<Alert severity="info" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
Max retries reached — no further retry attempts will be made.
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Pipeline Stepper */}
|
||||
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||
Pipeline Progress
|
||||
</Typography>
|
||||
<Stepper activeStep={activeStep} alternativeLabel>
|
||||
{stepLabels.map((label, index) => {
|
||||
const isCompleted = index < activeStep;
|
||||
const isActive = index === activeStep;
|
||||
const isPaused = req.status === "paused" && isActive;
|
||||
const isFailed = req.status === "failed" && isActive;
|
||||
|
||||
let icon: React.ReactNode;
|
||||
if (isCompleted) {
|
||||
icon = <CheckCircleIcon sx={{ color: "success.main" }} />;
|
||||
} else if (isFailed) {
|
||||
icon = <ErrorIcon sx={{ color: "error.main" }} />;
|
||||
} else if (isPaused) {
|
||||
icon = <WarningAmberIcon sx={{ color: "warning.main" }} />;
|
||||
} else if (isActive) {
|
||||
icon = <CircularProgress size={20} />;
|
||||
} else {
|
||||
icon = <Typography variant="caption" color="text.disabled">{index + 1}</Typography>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Step key={label}>
|
||||
<StepLabel
|
||||
StepIconComponent={() => <Box sx={{ display: "flex", alignItems: "center" }}>{icon}</Box>}
|
||||
>
|
||||
<Typography variant="body2" fontWeight={600}>{label}</Typography>
|
||||
{stepMessages[index] && (
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: "block", lineHeight: 1.2 }}>
|
||||
{stepMessages[index]}
|
||||
</Typography>
|
||||
)}
|
||||
</StepLabel>
|
||||
</Step>
|
||||
);
|
||||
})}
|
||||
</Stepper>
|
||||
</Paper>
|
||||
|
||||
{/* SSE Event Feed */}
|
||||
<Paper sx={{ borderRadius: 4, mb: 3 }} variant="outlined">
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, p: 2, pb: 0 }}>
|
||||
<Typography variant="subtitle1" fontWeight={600} sx={{ flex: 1 }}>
|
||||
Progress Events
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
borderRadius: "50%",
|
||||
bgcolor: sseConnected ? "success.main" : "error.main",
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{sseConnected ? "Connected" : "Disconnected"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
ref={feedRef}
|
||||
sx={{
|
||||
maxHeight: 300,
|
||||
overflowY: "auto",
|
||||
p: 2,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: 1,
|
||||
}}
|
||||
>
|
||||
{displayEvents.length === 0 ? (
|
||||
<Typography variant="body2" color="text.disabled" sx={{ textAlign: "center", py: 2 }}>
|
||||
Waiting for events...
|
||||
</Typography>
|
||||
) : (
|
||||
displayEvents.map((evt, i) => (
|
||||
<Box
|
||||
key={i}
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1.5,
|
||||
p: 1,
|
||||
borderRadius: 2,
|
||||
bgcolor: "action.hover",
|
||||
}}
|
||||
>
|
||||
{sseIcon(evt.status)}
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography variant="body2" fontWeight={600}>
|
||||
{evt.step.replace(/_/g, " ")}
|
||||
</Typography>
|
||||
{evt.message && formatProgressMessage(evt.message) && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{formatProgressMessage(evt.message)}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
))
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
{/* Ambiguity Resolution */}
|
||||
{hasAmbiguities && (
|
||||
<Paper sx={{ p: 3, borderRadius: 4, mb: 3 }} variant="outlined">
|
||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||
Ambiguity Resolution
|
||||
</Typography>
|
||||
|
||||
{allResolved ? (
|
||||
<Alert severity="success" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
All ambiguities resolved — pipeline will resume on next poll cycle
|
||||
</Alert>
|
||||
) : (
|
||||
<Alert severity="warning" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
Pipeline paused — resolve ambiguities to continue
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
{ambiguities.map((ambiguity: any) => {
|
||||
const isResolved = ambiguity.status === "resolved";
|
||||
return (
|
||||
<Paper
|
||||
key={ambiguity.id}
|
||||
sx={{
|
||||
p: 2,
|
||||
borderRadius: 3,
|
||||
border: 1,
|
||||
borderColor: isResolved ? "success.main" : "divider",
|
||||
opacity: isResolved ? 0.8 : 1,
|
||||
}}
|
||||
variant="outlined"
|
||||
>
|
||||
<Box sx={{ fontFamily: "monospace", fontSize: "0.85rem", mb: 1.5, p: 1, bgcolor: "grey.900", borderRadius: 1, color: "grey.100" }}>
|
||||
{ambiguity.line}
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 3, mb: 1.5, flexWrap: "wrap" }}>
|
||||
<Box>
|
||||
<Typography variant="caption" color="text.secondary">OCR Amount</Typography>
|
||||
<Typography variant="body2" sx={{ textDecoration: "line-through", color: "text.secondary" }}>
|
||||
₹{ambiguity.ocr_amount}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography variant="caption" color="text.secondary">OCR Balance</Typography>
|
||||
<Typography variant="body2" sx={{ textDecoration: "line-through", color: "text.secondary" }}>
|
||||
₹{ambiguity.ocr_balance}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography variant="caption" color="text.secondary">Previous Balance</Typography>
|
||||
<Typography variant="body2">₹{ambiguity.prev_balance}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{isResolved ? (
|
||||
<Alert severity="success" sx={{ py: 0.5, borderRadius: 2 }} icon={<CheckCircleIcon />}>
|
||||
Resolved: ₹{ambiguity.chosen?.amount} / ₹{ambiguity.chosen?.balance}
|
||||
</Alert>
|
||||
) : (
|
||||
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||
{ambiguity.candidates.map((candidate: any, ci: number) => {
|
||||
const isCredit = candidate.amount > 0;
|
||||
const isDebit = candidate.amount < 0;
|
||||
const cColor = isCredit ? "success.main" : isDebit ? "error.main" : undefined;
|
||||
return (
|
||||
<Button
|
||||
key={ci}
|
||||
variant="outlined"
|
||||
size="small"
|
||||
onClick={() => handleResolve(ambiguity, candidate)}
|
||||
disabled={resolveMutation.isPending}
|
||||
sx={{
|
||||
borderColor: cColor,
|
||||
color: cColor,
|
||||
"&:hover": cColor ? { borderColor: cColor } : undefined,
|
||||
}}
|
||||
>
|
||||
₹{candidate.amount} / ₹{candidate.balance}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
<Snackbar
|
||||
open={!!failNotif}
|
||||
autoHideDuration={6000}
|
||||
onClose={() => setFailNotif(null)}
|
||||
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
|
||||
>
|
||||
<Alert severity="error" onClose={() => setFailNotif(null)} sx={{ borderRadius: 2 }}>
|
||||
{failNotif}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -1,509 +0,0 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
Container,
|
||||
Paper,
|
||||
Typography,
|
||||
Button,
|
||||
ToggleButtonGroup,
|
||||
ToggleButton,
|
||||
Chip,
|
||||
IconButton,
|
||||
CircularProgress,
|
||||
Alert,
|
||||
Snackbar,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogActions,
|
||||
Tooltip,
|
||||
TextField,
|
||||
Select,
|
||||
MenuItem,
|
||||
InputLabel,
|
||||
FormControl,
|
||||
OutlinedInput,
|
||||
Autocomplete,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableRow,
|
||||
} from "@mui/material";
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
||||
import RefreshIcon from "@mui/icons-material/Refresh";
|
||||
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
|
||||
import ReplayIcon from "@mui/icons-material/Replay";
|
||||
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
|
||||
import ErrorIcon from "@mui/icons-material/Error";
|
||||
import ScheduleIcon from "@mui/icons-material/Schedule";
|
||||
import HourglassEmptyIcon from "@mui/icons-material/HourglassEmpty";
|
||||
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||
import { useUploadFile } from "./features/fetch-requests";
|
||||
import type {
|
||||
FetchRequest,
|
||||
FetchRequestStatus,
|
||||
FileSource,
|
||||
EmailSource,
|
||||
} from "./features/fetch-requests";
|
||||
import { RETRY_MAX, formatApiError } from "./features/fetch-requests";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useResource, FormFieldRenderer, applyDisplayFormat } from "../react-openapi";
|
||||
import type { FieldConfig } from "../react-openapi";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
|
||||
const statusColors: Record<FetchRequestStatus, "default" | "primary" | "warning" | "info" | "success" | "error"> = {
|
||||
pending: "default",
|
||||
processing: "info",
|
||||
paused: "warning",
|
||||
raw_expenses_done: "primary",
|
||||
enriched_done: "warning",
|
||||
completed: "success",
|
||||
failed: "error",
|
||||
};
|
||||
|
||||
const statusIcons: Record<FetchRequestStatus, React.ReactNode> = {
|
||||
pending: <ScheduleIcon sx={{ fontSize: 16 }} />,
|
||||
processing: <CircularProgress size={14} sx={{ mr: 0.5 }} />,
|
||||
paused: <WarningAmberIcon sx={{ fontSize: 16, color: "warning.main" }} />,
|
||||
raw_expenses_done: <HourglassEmptyIcon sx={{ fontSize: 16 }} />,
|
||||
enriched_done: <HourglassEmptyIcon sx={{ fontSize: 16 }} />,
|
||||
completed: <CheckCircleIcon sx={{ fontSize: 16, color: "success.main" }} />,
|
||||
failed: <ErrorIcon sx={{ fontSize: 16, color: "error.main" }} />,
|
||||
};
|
||||
|
||||
const STATUS_OPTIONS: FetchRequestStatus[] = [
|
||||
"pending",
|
||||
"processing",
|
||||
"paused",
|
||||
"raw_expenses_done",
|
||||
"enriched_done",
|
||||
"completed",
|
||||
"failed",
|
||||
];
|
||||
|
||||
function shortId(fp: string) {
|
||||
return fp.length > 8 ? fp.slice(0, 8) + "\u2026" : fp;
|
||||
}
|
||||
|
||||
export default function FetchRequests() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [sourceType, setSourceType] = React.useState<"file" | "email">("file");
|
||||
const [accountName, setAccountName] = React.useState("");
|
||||
const [payorUsername, setPayorUsername] = React.useState("aetos");
|
||||
const [format, setFormat] = React.useState("");
|
||||
const [file, setFile] = React.useState<File | null>(null);
|
||||
const [uploadedPath, setUploadedPath] = React.useState<string | null>(null);
|
||||
const [fromEmail, setFromEmail] = React.useState("");
|
||||
const [subject, setSubject] = React.useState("");
|
||||
const [rawTerms, setRawTerms] = React.useState("");
|
||||
const [startDate, setStartDate] = React.useState("");
|
||||
const [endDate, setEndDate] = React.useState("");
|
||||
const [snackbar, setSnackbar] = React.useState<{ message: string; severity: "success" | "error" } | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = React.useState<FetchRequest | null>(null);
|
||||
|
||||
const [statusFilter, setStatusFilter] = React.useState<string[]>([]);
|
||||
const [accountFilter, setAccountFilter] = React.useState("");
|
||||
const [sourceFilter, setSourceFilter] = React.useState<"all" | "file" | "email">("all");
|
||||
|
||||
const { list, create, update, remove, resource: fetchRes } = useResource("fetch-requests");
|
||||
|
||||
const { data: listData, isLoading, isFetching, refetch } = useQuery({
|
||||
queryKey: ["fetch-requests", "list", { statusFilter, accountFilter, sourceFilter }],
|
||||
queryFn: () => list({
|
||||
...(statusFilter.length > 0 ? { status: statusFilter.join(",") } : {}),
|
||||
...(accountFilter ? { account_name: accountFilter } : {}),
|
||||
...(sourceFilter !== "all" ? { source_type: sourceFilter } : {}),
|
||||
}),
|
||||
});
|
||||
|
||||
const { list: listAccounts } = useResource("accounts");
|
||||
const { data: accountsData } = useQuery({
|
||||
queryKey: ["accounts", "list"],
|
||||
queryFn: () => listAccounts(),
|
||||
});
|
||||
const accountOptions: string[] = React.useMemo(() => {
|
||||
return (accountsData?.items ?? []).map((a: any) => a.name).filter(Boolean);
|
||||
}, [accountsData]);
|
||||
|
||||
const fields = fetchRes?.orderedFields ?? [];
|
||||
const formatField: FieldConfig | undefined = fields.find(f => f.name === "format");
|
||||
const startDateField: FieldConfig | undefined = fields.find(f => f.name === "start_date");
|
||||
const endDateField: FieldConfig | undefined = fields.find(f => f.name === "end_date");
|
||||
const payorUsernameField: FieldConfig | undefined = fields.find(f => f.name === "payor_username");
|
||||
|
||||
const createMutation = useMutation({ mutationFn: (data: any) => create(data) });
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: ({ id, data }: { id: string; data: any }) => update(id, data),
|
||||
});
|
||||
const deleteMutation = useMutation({ mutationFn: (id: string) => remove(id) });
|
||||
const uploadMutation = useUploadFile();
|
||||
|
||||
const requests = listData?.items ?? [];
|
||||
|
||||
const handleUpload = async () => {
|
||||
if (!file) return;
|
||||
const result = await uploadMutation.mutateAsync(file);
|
||||
if (result?.saved_as) {
|
||||
setUploadedPath(result.saved_as);
|
||||
if (!format) setFormat(file.name.split(".").pop() || "");
|
||||
setSnackbar({ message: `File uploaded: ${result.saved_as}`, severity: "success" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!accountName) return;
|
||||
|
||||
let source: FileSource | EmailSource;
|
||||
|
||||
if (sourceType === "file") {
|
||||
if (!uploadedPath || !format) return;
|
||||
source = { path: uploadedPath, format } as FileSource;
|
||||
} else {
|
||||
if (!format) return;
|
||||
const emailSource: EmailSource = { format };
|
||||
if (fromEmail) emailSource.from_email = fromEmail;
|
||||
if (subject) emailSource.subject = subject;
|
||||
if (rawTerms.trim()) emailSource.raw_terms = rawTerms.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
source = emailSource;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await createMutation.mutateAsync({
|
||||
source,
|
||||
account_name: accountName,
|
||||
payor_username: payorUsername,
|
||||
...(startDate ? { start_date: new Date(startDate).toISOString() } : {}),
|
||||
...(endDate ? { end_date: new Date(endDate).toISOString() } : {}),
|
||||
});
|
||||
setSnackbar({ message: "Fetch request created", severity: "success" });
|
||||
resetForm();
|
||||
navigate(`/fetch-requests/${result.id}`);
|
||||
} catch (err: any) {
|
||||
if (err?.response?.status === 409) {
|
||||
setSnackbar({ message: "Duplicate — same fingerprint already exists", severity: "error" });
|
||||
} else {
|
||||
setSnackbar({ message: formatApiError(err) || "Failed to create fetch request", severity: "error" });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setAccountName("");
|
||||
setFormat("");
|
||||
setFile(null);
|
||||
setUploadedPath(null);
|
||||
setFromEmail("");
|
||||
setSubject("");
|
||||
setRawTerms("");
|
||||
setStartDate("");
|
||||
setEndDate("");
|
||||
};
|
||||
|
||||
const handleRetry = async (req: FetchRequest) => {
|
||||
try {
|
||||
await updateMutation.mutateAsync({ id: req.id, data: { status: "pending" } });
|
||||
setSnackbar({ message: "Retrying fetch request", severity: "success" });
|
||||
} catch {
|
||||
setSnackbar({ message: "Failed to retry", severity: "error" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteTarget) return;
|
||||
try {
|
||||
await deleteMutation.mutateAsync(deleteTarget.id);
|
||||
setSnackbar({ message: "Fetch request deleted", severity: "success" });
|
||||
} catch {
|
||||
setSnackbar({ message: "Failed to delete", severity: "error" });
|
||||
}
|
||||
setDeleteTarget(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<Container sx={{ mt: 4, mb: 4 }}>
|
||||
<Typography variant="h5" fontWeight="bold" gutterBottom>
|
||||
Fetch Request Pipeline
|
||||
</Typography>
|
||||
|
||||
{/* Create Form */}
|
||||
<Paper sx={{ p: 3, mb: 4, borderRadius: 4 }} variant="outlined">
|
||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||
New Fetch Request
|
||||
</Typography>
|
||||
|
||||
<ToggleButtonGroup
|
||||
value={sourceType}
|
||||
exclusive
|
||||
onChange={(_, val) => val && setSourceType(val)}
|
||||
sx={{ mb: 3 }}
|
||||
size="small"
|
||||
>
|
||||
<ToggleButton value="file">File Upload</ToggleButton>
|
||||
<ToggleButton value="email">Email Fetch</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
{sourceType === "file" ? (
|
||||
<>
|
||||
<Box sx={{ display: "flex", gap: 2, alignItems: "flex-end" }}>
|
||||
<Button variant="outlined" component="label" startIcon={<CloudUploadIcon />}>
|
||||
Choose File
|
||||
<input type="file" hidden onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
|
||||
</Button>
|
||||
<Typography variant="body2" sx={{ flex: 1, color: "text.secondary" }}>
|
||||
{file ? file.name : "No file selected"}
|
||||
</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={handleUpload}
|
||||
disabled={!file || uploadMutation.isPending}
|
||||
>
|
||||
{uploadMutation.isPending ? "Uploading..." : "Upload"}
|
||||
</Button>
|
||||
</Box>
|
||||
{uploadedPath && (
|
||||
<Alert severity="success" sx={{ py: 0 }}>
|
||||
Uploaded as: {uploadedPath}
|
||||
</Alert>
|
||||
)}
|
||||
{formatField && (
|
||||
<FormFieldRenderer field={formatField} value={format} onChange={setFormat} />
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{formatField && (
|
||||
<FormFieldRenderer field={formatField} value={format} onChange={setFormat} />
|
||||
)}
|
||||
<TextField label="From Email" value={fromEmail} onChange={(e) => setFromEmail(e.target.value)} size="small" />
|
||||
<TextField label="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} size="small" />
|
||||
<TextField label="Raw Terms" value={rawTerms} onChange={(e) => setRawTerms(e.target.value)} size="small" helperText="Comma-separated search terms" />
|
||||
</>
|
||||
)}
|
||||
|
||||
<Autocomplete
|
||||
options={accountOptions}
|
||||
value={accountName || null}
|
||||
onChange={(_, val) => setAccountName(val ?? "")}
|
||||
renderInput={(params) => (
|
||||
<TextField {...params} label="Account Name" size="small" required />
|
||||
)}
|
||||
/>
|
||||
|
||||
{payorUsernameField && (
|
||||
<FormFieldRenderer field={payorUsernameField} value={payorUsername} onChange={setPayorUsername} />
|
||||
)}
|
||||
|
||||
<Box sx={{ display: "flex", gap: 2 }}>
|
||||
{startDateField && (
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<FormFieldRenderer field={startDateField} value={startDate} onChange={setStartDate} />
|
||||
</Box>
|
||||
)}
|
||||
{endDateField && (
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<FormFieldRenderer field={endDateField} value={endDate} onChange={setEndDate} />
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={handleCreate}
|
||||
disabled={createMutation.isPending || !accountName || (sourceType === "file" && (!uploadedPath || !format)) || (sourceType === "email" && !format)}
|
||||
>
|
||||
{createMutation.isPending ? "Creating..." : "Create Fetch Request"}
|
||||
</Button>
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
{/* Filters */}
|
||||
<Paper sx={{ borderRadius: 4, mb: 2, p: 2 }} variant="outlined">
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
||||
<FormControl size="small" sx={{ minWidth: 200 }}>
|
||||
<InputLabel>Status</InputLabel>
|
||||
<Select
|
||||
multiple
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value as string[])}
|
||||
input={<OutlinedInput label="Status" />}
|
||||
renderValue={(selected) => (selected as string[]).join(", ")}
|
||||
>
|
||||
{STATUS_OPTIONS.map((s) => (
|
||||
<MenuItem key={s} value={s}>{s.replace(/_/g, " ")}</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Autocomplete
|
||||
options={accountOptions}
|
||||
value={accountFilter || null}
|
||||
onChange={(_, val) => setAccountFilter(val ?? "")}
|
||||
renderInput={(params) => (
|
||||
<TextField {...params} label="Account" size="small" sx={{ minWidth: 160 }} />
|
||||
)}
|
||||
sx={{ minWidth: 160 }}
|
||||
/>
|
||||
<ToggleButtonGroup
|
||||
value={sourceFilter}
|
||||
exclusive
|
||||
onChange={(_, val) => val && setSourceFilter(val)}
|
||||
size="small"
|
||||
>
|
||||
<ToggleButton value="all">All</ToggleButton>
|
||||
<ToggleButton value="file">File</ToggleButton>
|
||||
<ToggleButton value="email">Email</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<IconButton onClick={() => refetch()} disabled={isFetching}>
|
||||
<RefreshIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Paper>
|
||||
|
||||
{/* List Table */}
|
||||
{isLoading ? (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : requests.length === 0 ? (
|
||||
<Box sx={{ p: 4, textAlign: "center", color: "text.secondary" }}>
|
||||
No fetch requests yet
|
||||
</Box>
|
||||
) : (
|
||||
<TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 4 }}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>ID</TableCell>
|
||||
<TableCell>Account</TableCell>
|
||||
<TableCell>Source</TableCell>
|
||||
<TableCell>Date Range</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Retries</TableCell>
|
||||
<TableCell>Created</TableCell>
|
||||
<TableCell align="right">Actions</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{[...requests]
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
|
||||
.map((req: FetchRequest) => (
|
||||
<TableRow
|
||||
key={req.id}
|
||||
hover
|
||||
sx={{ cursor: "pointer" }}
|
||||
onClick={() => navigate(`/fetch-requests/${req.id}`)}
|
||||
>
|
||||
<TableCell>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
|
||||
<Typography variant="body2" sx={{ fontFamily: "monospace", fontSize: "0.8rem" }}>
|
||||
{shortId(req.fingerprint)}
|
||||
</Typography>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigator.clipboard.writeText(req.fingerprint);
|
||||
setSnackbar({ message: "Copied!", severity: "success" });
|
||||
}}
|
||||
sx={{ opacity: 0.5, '&:hover': { opacity: 1 } }}
|
||||
>
|
||||
<ContentCopyIcon sx={{ fontSize: 14 }} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</TableCell>
|
||||
<TableCell>{req.account_name}</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={"path" in req.source ? "File" : "Email"}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
color={"path" in req.source ? "primary" : "secondary"}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2" sx={{ fontSize: "0.8rem", whiteSpace: "nowrap" }}>
|
||||
{(req as any).start_date ? new Date((req as any).start_date).toLocaleDateString() : "?"} → {(req as any).end_date ? new Date((req as any).end_date).toLocaleDateString() : "?"}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Tooltip title={req.error_message || req.status.replace(/_/g, " ")}>
|
||||
<Chip
|
||||
icon={statusIcons[req.status] as any}
|
||||
label={req.status.replace(/_/g, " ")}
|
||||
color={statusColors[req.status]}
|
||||
size="small"
|
||||
/>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2" sx={{ fontSize: "0.8rem" }}>
|
||||
{(req.retry_count ?? 0) > 0 ? `${req.retry_count}/${RETRY_MAX}` : "—"}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2" sx={{ fontSize: "0.8rem", whiteSpace: "nowrap" }}>
|
||||
{new Date(req.created_at).toLocaleString()}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Box sx={{ display: "flex", gap: 0.5, justifyContent: "flex-end" }}>
|
||||
{req.status === "paused" && (
|
||||
<Tooltip title="Resolve ambiguities">
|
||||
<IconButton size="small" onClick={(e) => { e.stopPropagation(); navigate(`/fetch-requests/${req.id}`); }}>
|
||||
<WarningAmberIcon fontSize="small" color="warning" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{req.status === "failed" && (req.retry_count ?? 0) < RETRY_MAX && (
|
||||
<Tooltip title="Retry">
|
||||
<IconButton size="small" onClick={(e) => { e.stopPropagation(); handleRetry(req); }}>
|
||||
<ReplayIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip title="Delete">
|
||||
<IconButton size="small" onClick={(e) => { e.stopPropagation(); setDeleteTarget(req); }}>
|
||||
<DeleteIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)}
|
||||
|
||||
<Snackbar
|
||||
open={!!snackbar}
|
||||
autoHideDuration={4000}
|
||||
onClose={() => setSnackbar(null)}
|
||||
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
|
||||
>
|
||||
{snackbar ? <Alert severity={snackbar.severity} onClose={() => setSnackbar(null)}>{snackbar.message}</Alert> : undefined}
|
||||
</Snackbar>
|
||||
|
||||
<Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>
|
||||
<DialogTitle>Delete Fetch Request?</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText>
|
||||
This will permanently delete the fetch request and all associated data.
|
||||
</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setDeleteTarget(null)}>Cancel</Button>
|
||||
<Button onClick={handleDelete} color="error" disabled={deleteMutation.isPending}>
|
||||
{deleteMutation.isPending ? "Deleting..." : "Delete"}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -1,52 +1,36 @@
|
||||
import * as React from 'react';
|
||||
import Box from '@mui/material/Box';
|
||||
import Container from '@mui/material/Container';
|
||||
import Link from '@mui/material/Link';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import {AppBar, Box, Button, IconButton, Toolbar, Tooltip} from "@mui/material";
|
||||
import MenuIcon from "@mui/icons-material/Menu";
|
||||
import LogoutIcon from "@mui/icons-material/Logout";
|
||||
|
||||
function Copyright() {
|
||||
return (
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
<Link color="text.secondary" href="https://www.aetoskia.com/">
|
||||
{'Copyright © Aetoskia Internal Infrastructure — All rights reserved.'}
|
||||
</Link>
|
||||
|
||||
{new Date().getFullYear()}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Footer() {
|
||||
return (
|
||||
<AppBar
|
||||
position="fixed"
|
||||
color="default"
|
||||
<Box
|
||||
component="footer"
|
||||
sx={{
|
||||
top: 'auto',
|
||||
bottom: 0,
|
||||
backdropFilter: 'blur(8px)',
|
||||
boxShadow: 'none',
|
||||
borderTop: '1px solid',
|
||||
borderColor: 'divider',
|
||||
py: 3,
|
||||
mt: 'auto',
|
||||
}}
|
||||
>
|
||||
<Toolbar>
|
||||
<React.Fragment>
|
||||
<Container
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
gap: { xs: 2, sm: 4 },
|
||||
textAlign: { sm: 'center', md: 'left' },
|
||||
}}
|
||||
>
|
||||
<Copyright />
|
||||
</Container>
|
||||
</React.Fragment>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
<Container
|
||||
maxWidth="lg"
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: 2,
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<Typography variant="body2" color="text.secondary" fontWeight={500}>
|
||||
Khata
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
© {new Date().getFullYear()} Aetoskia Internal Infrastructure — All rights reserved.
|
||||
</Typography>
|
||||
</Container>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
}
|
||||
358
src/Header.tsx
358
src/Header.tsx
@@ -1,8 +1,5 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
useLocation,
|
||||
matchPath
|
||||
} from "react-router-dom";
|
||||
import { useLocation, matchPath, useNavigate } from "react-router-dom";
|
||||
import {
|
||||
AppBar,
|
||||
Toolbar,
|
||||
@@ -11,6 +8,11 @@ import {
|
||||
Tooltip,
|
||||
Button,
|
||||
Box,
|
||||
Drawer,
|
||||
List,
|
||||
ListItemButton,
|
||||
ListItemText,
|
||||
Divider,
|
||||
useMediaQuery,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
@@ -18,7 +20,6 @@ import MenuIcon from "@mui/icons-material/Menu";
|
||||
import LogoutIcon from "@mui/icons-material/Logout";
|
||||
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 "./shared-theme/AppTheme";
|
||||
|
||||
@@ -30,134 +31,261 @@ interface HeaderProps {
|
||||
onDrawerToggle?: () => void;
|
||||
}
|
||||
|
||||
export default function Header({
|
||||
routerMapping,
|
||||
onDrawerToggle,
|
||||
}: HeaderProps) {
|
||||
const location = useLocation();
|
||||
const matchedRoute = routerMapping.find((route) =>
|
||||
matchPath({ path: route.path, end: false }, location.pathname)
|
||||
);
|
||||
const headerTitle = matchedRoute?.headerTitle ?? "Khata";
|
||||
const NAV_LINKS = [
|
||||
{ label: "Home", path: "/" },
|
||||
{ label: "Expenses", path: "/expenses" },
|
||||
{ label: "Reports", path: "/reports" },
|
||||
{ label: "Fetch Requests", path: "/fetch-requests" },
|
||||
];
|
||||
|
||||
function isActive(path: string, locationPath: string): boolean {
|
||||
if (path === "/") return locationPath === "/" || locationPath === "/home";
|
||||
return matchPath({ path, end: false }, locationPath) !== null;
|
||||
}
|
||||
|
||||
export default function Header({ routerMapping, onDrawerToggle }: HeaderProps) {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { currentUser, logout } = useAuth();
|
||||
const { mode, toggleColorMode } = React.useContext(ColorModeContext);
|
||||
|
||||
const theme = useTheme();
|
||||
const isMobile = useMediaQuery(theme.breakpoints.down("md"));
|
||||
const [mobileOpen, setMobileOpen] = React.useState(false);
|
||||
|
||||
const isAuthenticated = !!currentUser;
|
||||
|
||||
return (
|
||||
<AppBar
|
||||
position="fixed"
|
||||
color="default"
|
||||
const navContent = (
|
||||
<Box
|
||||
sx={{
|
||||
zIndex: (theme) => theme.zIndex.drawer + 1,
|
||||
backdropFilter: "blur(8px)",
|
||||
boxShadow: "none",
|
||||
borderBottom: "1px solid",
|
||||
borderColor: "divider",
|
||||
display: { xs: "none", md: "flex" },
|
||||
alignItems: "center",
|
||||
gap: 0.5,
|
||||
ml: 3,
|
||||
}}
|
||||
>
|
||||
<Toolbar>
|
||||
{/* MOBILE MENU BUTTON */}
|
||||
{isMobile && onDrawerToggle && (
|
||||
<IconButton
|
||||
{NAV_LINKS.map((link) => {
|
||||
const active = isActive(link.path, location.pathname);
|
||||
return (
|
||||
<Button
|
||||
key={link.path}
|
||||
color="inherit"
|
||||
edge="start"
|
||||
onClick={onDrawerToggle}
|
||||
sx={{ mr: 2 }}
|
||||
onClick={() => navigate(link.path)}
|
||||
sx={{
|
||||
textTransform: "none",
|
||||
fontWeight: active ? 600 : 500,
|
||||
color: active ? "text.primary" : "text.secondary",
|
||||
px: 1.5,
|
||||
borderRadius: "6px",
|
||||
position: "relative",
|
||||
"&::after":
|
||||
active
|
||||
? {
|
||||
content: '""',
|
||||
position: "absolute",
|
||||
left: 12,
|
||||
right: 12,
|
||||
bottom: 4,
|
||||
height: 2,
|
||||
borderRadius: 1,
|
||||
backgroundColor: "primary.main",
|
||||
}
|
||||
: {},
|
||||
"&:hover": { backgroundColor: "action.hover", color: "text.primary" },
|
||||
}}
|
||||
>
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
{link.label}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
|
||||
{/* THEME TOGGLE */}
|
||||
<IconButton onClick={toggleColorMode} color="inherit" sx={{ mr: 2 }}>
|
||||
{mode === 'dark' ? <LightModeIcon /> : <DarkModeIcon />}
|
||||
</IconButton>
|
||||
|
||||
{/* TITLE */}
|
||||
<Typography
|
||||
variant="h6"
|
||||
noWrap
|
||||
sx={{ fontWeight: "bold", cursor: "pointer" }}
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
{headerTitle}
|
||||
</Typography>
|
||||
|
||||
<span style={{ flexGrow: 1 }} />
|
||||
|
||||
{/* NAV LINKS */}
|
||||
<Box
|
||||
sx={{
|
||||
display: { xs: "none", md: "flex" },
|
||||
alignItems: "center",
|
||||
mr: 2,
|
||||
gap: 1,
|
||||
}}
|
||||
>
|
||||
{[
|
||||
{ label: "Fetch", path: "/fetch-requests" },
|
||||
].map(({ label, path }) => (
|
||||
<Button
|
||||
key={path}
|
||||
color="inherit"
|
||||
onClick={() => navigate(path)}
|
||||
sx={{ textTransform: "none", fontWeight: 500, px: 1.5 }}
|
||||
size="small"
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
{/* AUTH SECTION */}
|
||||
{isAuthenticated ? (
|
||||
<>
|
||||
<Box
|
||||
sx={{
|
||||
display: { xs: "none", sm: "flex" },
|
||||
alignItems: "center",
|
||||
mr: 2,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
color="inherit"
|
||||
onClick={() => navigate("/admin")}
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
>
|
||||
Admin
|
||||
</Button>
|
||||
<Button
|
||||
color="inherit"
|
||||
onClick={() => navigate("/profile/me")}
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
>
|
||||
{currentUser.username}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Tooltip title="Logout">
|
||||
<IconButton color="inherit" onClick={logout}>
|
||||
<LogoutIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</>
|
||||
) : (
|
||||
const authSection = (
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
{isAuthenticated ? (
|
||||
<>
|
||||
<Button
|
||||
color="inherit"
|
||||
variant="outlined"
|
||||
onClick={() => navigate("/login")}
|
||||
sx={{ textTransform: "none" }}
|
||||
onClick={() => navigate("/admin")}
|
||||
sx={{
|
||||
textTransform: "none",
|
||||
fontWeight: isActive("/admin", location.pathname) ? 600 : 500,
|
||||
color: isActive("/admin", location.pathname) ? "text.primary" : "text.secondary",
|
||||
display: { xs: "none", sm: "inline-flex" },
|
||||
}}
|
||||
>
|
||||
Login
|
||||
Admin
|
||||
</Button>
|
||||
)}
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
<Button
|
||||
color="inherit"
|
||||
onClick={() => navigate("/profile/me")}
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
>
|
||||
{currentUser.username}
|
||||
</Button>
|
||||
<Tooltip title="Logout">
|
||||
<IconButton color="inherit" onClick={logout} aria-label="Logout">
|
||||
<LogoutIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
color="inherit"
|
||||
variant="outlined"
|
||||
onClick={() => navigate("/login")}
|
||||
sx={{ textTransform: "none" }}
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const drawerContent = (
|
||||
<Box sx={{ width: 260 }} role="presentation">
|
||||
<Box sx={{ p: 2 }}>
|
||||
<Brand />
|
||||
</Box>
|
||||
<Divider />
|
||||
<List>
|
||||
{routerMapping
|
||||
.filter((r) => !r.path.startsWith("/login") && !r.path.startsWith("/register") && !r.path.startsWith("/profile"))
|
||||
.map((route) => {
|
||||
const active = isActive(route.path, location.pathname);
|
||||
return (
|
||||
<ListItemButton
|
||||
key={route.path}
|
||||
selected={active}
|
||||
onClick={() => {
|
||||
navigate(route.path);
|
||||
setMobileOpen(false);
|
||||
}}
|
||||
sx={{
|
||||
borderRadius: "6px",
|
||||
mx: 1,
|
||||
mb: 0.5,
|
||||
"&.Mui-selected": {
|
||||
backgroundColor: "action.selected",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<ListItemText
|
||||
primary={route.headerTitle}
|
||||
primaryTypographyProps={{ fontWeight: active ? 600 : 500, fontSize: 14 }}
|
||||
/>
|
||||
</ListItemButton>
|
||||
);
|
||||
})}
|
||||
<Divider sx={{ my: 1 }} />
|
||||
{isAuthenticated ? (
|
||||
<>
|
||||
<ListItemButton onClick={() => navigate("/profile/me")} sx={{ borderRadius: "6px", mx: 1 }}>
|
||||
<ListItemText primary="Profile" primaryTypographyProps={{ fontSize: 14 }} />
|
||||
</ListItemButton>
|
||||
<ListItemButton onClick={logout} sx={{ borderRadius: "6px", mx: 1 }}>
|
||||
<ListItemText primary="Logout" primaryTypographyProps={{ fontSize: 14 }} />
|
||||
</ListItemButton>
|
||||
</>
|
||||
) : (
|
||||
<ListItemButton onClick={() => navigate("/login")} sx={{ borderRadius: "6px", mx: 1 }}>
|
||||
<ListItemText primary="Login" primaryTypographyProps={{ fontSize: 14 }} />
|
||||
</ListItemButton>
|
||||
)}
|
||||
</List>
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppBar
|
||||
position="sticky"
|
||||
color="default"
|
||||
sx={{
|
||||
zIndex: (theme) => theme.zIndex.drawer + 1,
|
||||
backdropFilter: "blur(8px)",
|
||||
boxShadow: "none",
|
||||
borderBottom: "1px solid",
|
||||
borderColor: "divider",
|
||||
backgroundColor: "background.default",
|
||||
}}
|
||||
>
|
||||
<Toolbar>
|
||||
{/* MOBILE MENU */}
|
||||
{isMobile && (
|
||||
<IconButton
|
||||
color="inherit"
|
||||
edge="start"
|
||||
onClick={() => setMobileOpen(true)}
|
||||
aria-label="Open navigation"
|
||||
sx={{ mr: 1 }}
|
||||
>
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
{/* BRAND — always leftmost */}
|
||||
<Brand onClick={() => navigate("/")} />
|
||||
|
||||
{navContent}
|
||||
|
||||
<Box sx={{ flexGrow: 1 }} />
|
||||
|
||||
{/* THEME TOGGLE — right side */}
|
||||
<IconButton onClick={toggleColorMode} color="inherit" aria-label="Toggle color mode" sx={{ mr: 1 }}>
|
||||
{mode === "dark" ? <LightModeIcon /> : <DarkModeIcon />}
|
||||
</IconButton>
|
||||
|
||||
{authSection}
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
|
||||
<Drawer
|
||||
open={mobileOpen}
|
||||
onClose={() => setMobileOpen(false)}
|
||||
ModalProps={{ keepMounted: true }}
|
||||
>
|
||||
{drawerContent}
|
||||
</Drawer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Brand({ onClick }: { onClick?: () => void }) {
|
||||
return (
|
||||
<Box
|
||||
onClick={onClick}
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
cursor: onClick ? "pointer" : "default",
|
||||
userSelect: "none",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
borderRadius: "8px",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
background: "linear-gradient(135deg, #635BFF 0%, #8B5CF6 100%)",
|
||||
color: "#fff",
|
||||
fontWeight: 700,
|
||||
fontSize: 15,
|
||||
}}
|
||||
>
|
||||
K
|
||||
</Box>
|
||||
<Typography
|
||||
variant="h6"
|
||||
sx={{ fontWeight: 700, letterSpacing: "-0.02em", color: "text.primary" }}
|
||||
>
|
||||
Khata
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
236
src/Home.tsx
236
src/Home.tsx
@@ -1,11 +1,11 @@
|
||||
import * as React from "react";
|
||||
import { Box, Typography, Button, Container, Grid, Paper, Chip } from "@mui/material";
|
||||
import { useTheme, alpha } from "@mui/material/styles";
|
||||
import { Box, Typography, Button, Container, Grid, Paper, alpha } from "@mui/material";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import DashboardIcon from "@mui/icons-material/Dashboard";
|
||||
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
|
||||
import SyncIcon from "@mui/icons-material/Sync";
|
||||
import BarChartIcon from "@mui/icons-material/BarChart";
|
||||
import SettingsIcon from "@mui/icons-material/Settings";
|
||||
import AccountBalanceWalletIcon from "@mui/icons-material/AccountBalanceWallet";
|
||||
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
|
||||
import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
|
||||
import { useAuth } from "../react-auth";
|
||||
|
||||
@@ -14,11 +14,9 @@ interface FeatureCardProps {
|
||||
title: string;
|
||||
description: string;
|
||||
path: string;
|
||||
label?: string;
|
||||
accent: string;
|
||||
}
|
||||
|
||||
function FeatureCard({ icon, title, description, path, label, accent }: FeatureCardProps) {
|
||||
function FeatureCard({ icon, title, description, path }: FeatureCardProps) {
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
|
||||
@@ -35,206 +33,154 @@ function FeatureCard({ icon, title, description, path, label, accent }: FeatureC
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
transition: "all 0.25s ease",
|
||||
"&::before": {
|
||||
content: '""',
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: 3,
|
||||
background: accent,
|
||||
opacity: 0,
|
||||
transition: "opacity 0.25s ease",
|
||||
},
|
||||
transition: "border-color 180ms ease, box-shadow 180ms ease, transform 180ms ease",
|
||||
"&:hover": {
|
||||
transform: "translateY(-4px)",
|
||||
boxShadow: `0 12px 32px ${alpha(theme.palette.common.black, theme.palette.mode === "dark" ? 0.3 : 0.08)}`,
|
||||
borderColor: "transparent",
|
||||
"&::before": { opacity: 1 },
|
||||
transform: "translateY(-2px)",
|
||||
boxShadow: `0 8px 24px ${alpha(theme.palette.common.black, theme.palette.mode === "dark" ? 0.35 : 0.08)}`,
|
||||
"& .feature-arrow": {
|
||||
opacity: 1,
|
||||
transform: "translateX(0)",
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, mb: 1.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
background: alpha(accent, 0.12),
|
||||
color: accent,
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
<Typography variant="subtitle1" fontWeight={700}>
|
||||
{title}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: 2,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: "action.hover",
|
||||
color: "primary.main",
|
||||
mb: 2,
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
|
||||
<Typography variant="subtitle1" fontWeight={600} sx={{ mb: 0.75 }}>
|
||||
{title}
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body2" color="text.secondary" sx={{ flex: 1, lineHeight: 1.6 }}>
|
||||
{description}
|
||||
</Typography>
|
||||
|
||||
{label && (
|
||||
<Chip
|
||||
label={label}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
sx={{ mt: 2, alignSelf: "flex-start", textTransform: "capitalize" }}
|
||||
/>
|
||||
)}
|
||||
<Box
|
||||
className="feature-arrow"
|
||||
sx={{
|
||||
mt: 2,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 0.5,
|
||||
color: "primary.main",
|
||||
fontWeight: 600,
|
||||
opacity: 0,
|
||||
transform: "translateX(-4px)",
|
||||
transition: "opacity 180ms ease, transform 180ms ease",
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" fontWeight={600} color="primary">
|
||||
Open
|
||||
</Typography>
|
||||
<ArrowForwardIcon sx={{ fontSize: 14 }} />
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
const { currentUser } = useAuth();
|
||||
|
||||
const features = [
|
||||
{
|
||||
icon: <DashboardIcon />,
|
||||
title: "Dashboard",
|
||||
description: "Visualise inflows and outflows with interactive charts, drill into categories, and track trends over daily, weekly, and monthly periods.",
|
||||
path: "/dashboard",
|
||||
accent: theme.palette.mode === "dark" ? "#818cf8" : "#6366f1",
|
||||
icon: <ReceiptLongIcon />,
|
||||
title: "Expenses",
|
||||
description:
|
||||
"Browse every transaction imported from your accounts — grouped by month, with entity, account, tags, and amount at a glance.",
|
||||
path: "/expenses",
|
||||
},
|
||||
{
|
||||
icon: <SyncIcon />,
|
||||
title: "Fetch Requests",
|
||||
description: "Upload bank statements or configure email ingestion to auto-import transactions. Track pipeline status from pending through to completion.",
|
||||
description:
|
||||
"Upload bank statements or configure email ingestion to auto-import transactions. Track pipeline status from pending through to completion.",
|
||||
path: "/fetch-requests",
|
||||
accent: theme.palette.mode === "dark" ? "#34d399" : "#10b981",
|
||||
},
|
||||
{
|
||||
icon: <BarChartIcon />,
|
||||
title: "Report Snapshots",
|
||||
description: "Generate cached report snapshots with custom filters — accounts, date ranges, amount bounds — then pin a snapshot on the dashboard for consistent comparisons.",
|
||||
path: "/reports",
|
||||
accent: theme.palette.mode === "dark" ? "#fbbf24" : "#f59e0b",
|
||||
},
|
||||
{
|
||||
icon: <SettingsIcon />,
|
||||
title: "Admin",
|
||||
description: "Full CRUD over accounts, expenses, tags, and payors. Manage your data programmatically through the OpenAPI-driven admin panel.",
|
||||
icon: <AccountBalanceWalletIcon />,
|
||||
title: "Accounts & Entities",
|
||||
description:
|
||||
"Manage your accounts, expenses, tags, and payors through the OpenAPI-driven admin panel with full CRUD and server-side filters.",
|
||||
path: "/admin",
|
||||
accent: theme.palette.mode === "dark" ? "#e879f9" : "#d946ef",
|
||||
},
|
||||
{
|
||||
icon: <AccountCircleIcon />,
|
||||
title: "Profile",
|
||||
description:
|
||||
"View and edit your user profile — username, email, and account preferences — from the profile page.",
|
||||
path: "/profile/me",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
minHeight: "calc(100vh - 64px)",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
"&::before": {
|
||||
content: '""',
|
||||
position: "absolute",
|
||||
top: "-15%",
|
||||
left: "-8%",
|
||||
width: "45%",
|
||||
height: "55%",
|
||||
background: "radial-gradient(circle, rgba(99,102,241,0.12) 0%, transparent 70%)",
|
||||
zIndex: 0,
|
||||
},
|
||||
"&::after": {
|
||||
content: '""',
|
||||
position: "absolute",
|
||||
bottom: "-15%",
|
||||
right: "-8%",
|
||||
width: "45%",
|
||||
height: "55%",
|
||||
background: "radial-gradient(circle, rgba(236,72,153,0.1) 0%, transparent 70%)",
|
||||
zIndex: 0,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Container maxWidth="lg" sx={{ position: "relative", zIndex: 1, flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", py: 6 }}>
|
||||
<Box
|
||||
sx={{
|
||||
textAlign: "center",
|
||||
mb: 6,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ width: "100%" }}>
|
||||
<Container maxWidth="lg" sx={{ py: { xs: 6, md: 10 } }}>
|
||||
<Box sx={{ maxWidth: 680, mx: { xs: "auto", md: 0 }, textAlign: { xs: "center", md: "left" } }}>
|
||||
<Typography
|
||||
variant="overline"
|
||||
sx={{ color: "primary.main", mb: 1.5, display: "block", fontWeight: 700 }}
|
||||
>
|
||||
Khata · Financial Ledger
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
variant="h1"
|
||||
sx={{
|
||||
fontWeight: 800,
|
||||
fontSize: { xs: "2.5rem", sm: "3.5rem", md: "5rem" },
|
||||
background: "linear-gradient(135deg, #6366f1 0%, #ec4899 50%, #f59e0b 100%)",
|
||||
WebkitBackgroundClip: "text",
|
||||
WebkitTextFillColor: "transparent",
|
||||
color: "text.primary",
|
||||
fontSize: { xs: "2.25rem", md: "3.25rem" },
|
||||
letterSpacing: "-0.03em",
|
||||
mb: 2,
|
||||
}}
|
||||
>
|
||||
Welcome to Khata
|
||||
Your intelligent, extensible financial ledger.
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
variant="h6"
|
||||
variant="body1"
|
||||
color="text.secondary"
|
||||
sx={{
|
||||
maxWidth: 580,
|
||||
mx: "auto",
|
||||
lineHeight: 1.7,
|
||||
fontWeight: 400,
|
||||
fontSize: { xs: "1rem", md: "1.15rem" },
|
||||
}}
|
||||
sx={{ maxWidth: 540, lineHeight: 1.7, fontSize: "1.0625rem" }}
|
||||
>
|
||||
Your intelligent, extensible financial ledger. Import transactions, generate reports, and stay on top of your cashflow.
|
||||
Import transactions from bank statements, enrich them with entity and tag intelligence,
|
||||
and stay on top of your cashflow — all in one place.
|
||||
</Typography>
|
||||
|
||||
<Box sx={{ mt: 4, display: "flex", gap: 2, justifyContent: "center", flexWrap: "wrap" }}>
|
||||
<Box sx={{ mt: 4, display: "flex", gap: 2, justifyContent: { xs: "center", md: "flex-start" }, flexWrap: "wrap" }}>
|
||||
<Button
|
||||
variant="contained"
|
||||
size="large"
|
||||
endIcon={<ArrowForwardIcon />}
|
||||
onClick={() => navigate("/dashboard")}
|
||||
sx={{
|
||||
px: 4,
|
||||
py: 1.4,
|
||||
borderRadius: "50px",
|
||||
fontWeight: 700,
|
||||
background: "linear-gradient(135deg, #6366f1 0%, #ec4899 100%)",
|
||||
transition: "transform 0.2s ease, box-shadow 0.2s",
|
||||
"&:hover": {
|
||||
transform: "translateY(-2px)",
|
||||
boxShadow: `0 8px 24px ${alpha(theme.palette.primary.main, 0.35)}`,
|
||||
},
|
||||
}}
|
||||
onClick={() => navigate(currentUser ? "/fetch-requests" : "/login")}
|
||||
sx={{ px: 3.5, py: 1.4, fontWeight: 600 }}
|
||||
>
|
||||
Enter Dashboard
|
||||
{currentUser ? "Enter App" : "Get Started"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="large"
|
||||
onClick={() => navigate("/fetch-requests")}
|
||||
sx={{
|
||||
px: 4,
|
||||
py: 1.4,
|
||||
borderRadius: "50px",
|
||||
fontWeight: 600,
|
||||
borderWidth: 2,
|
||||
"&:hover": { borderWidth: 2 },
|
||||
}}
|
||||
sx={{ px: 3.5, py: 1.4, fontWeight: 600 }}
|
||||
>
|
||||
Import Data
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Grid container spacing={3}>
|
||||
<Grid container spacing={3} sx={{ mt: { xs: 4, md: 8 } }}>
|
||||
{features.map((f) => (
|
||||
<Grid key={f.title} item xs={12} sm={6} md={3}>
|
||||
<FeatureCard {...f} />
|
||||
|
||||
126
src/Reports/GenerateReportPanel.tsx
Normal file
126
src/Reports/GenerateReportPanel.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Box,
|
||||
Paper,
|
||||
Typography,
|
||||
Button,
|
||||
Grid,
|
||||
Alert,
|
||||
} from "@mui/material";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import {
|
||||
useResource,
|
||||
useAppContext,
|
||||
FormFieldRenderer,
|
||||
extractFields,
|
||||
useFkFieldOptions,
|
||||
} from "../../react-openapi";
|
||||
import type { FieldConfig } from "../../react-openapi";
|
||||
import { useToast } from "../ui/Toast";
|
||||
import { apiErrorMessage } from "./types";
|
||||
|
||||
interface GenerateReportPanelProps {
|
||||
onGenerated: (report: any) => void;
|
||||
}
|
||||
|
||||
export function GenerateReportPanel({ onGenerated }: GenerateReportPanelProps) {
|
||||
const { schemas } = useAppContext();
|
||||
const { create, loading: submitting } = useResource("reports");
|
||||
const { showToast } = useToast();
|
||||
|
||||
const [formData, setFormData] = useState<Record<string, any>>({});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fields: FieldConfig[] = useMemo(() => {
|
||||
const schema = schemas?.ReportQuery;
|
||||
if (!schema) return [];
|
||||
return extractFields("ReportQuery", schema, schemas).sort(
|
||||
(a, b) => a.order - b.order || a.name.localeCompare(b.name)
|
||||
);
|
||||
}, [schemas]);
|
||||
|
||||
const { fkOptions, fkLoading, loadFkOnOpen } = useFkFieldOptions(fields);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData((prev) => {
|
||||
const next = { ...prev };
|
||||
let changed = false;
|
||||
for (const f of fields) {
|
||||
if (next[f.name] === undefined && f.defaultValue !== undefined) {
|
||||
next[f.name] = Array.isArray(f.defaultValue) ? [...f.defaultValue] : f.defaultValue;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
}, [fields]);
|
||||
|
||||
const handleChange = useCallback((name: string, value: any) => {
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
const buildPayload = (): Record<string, any> => {
|
||||
const payload: Record<string, any> = {};
|
||||
for (const f of fields) {
|
||||
const v = formData[f.name];
|
||||
if (v === undefined || v === null || v === "") continue;
|
||||
if (Array.isArray(v) && v.length === 0) continue;
|
||||
payload[f.name] = v;
|
||||
}
|
||||
return payload;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
try {
|
||||
const created = await create(buildPayload());
|
||||
showToast(`Generated snapshot ${created?.name ? `“${created.name}”` : ""}`.trim() || "Generated snapshot");
|
||||
onGenerated(created);
|
||||
} catch (e: any) {
|
||||
setError(apiErrorMessage(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3, mb: 4 }}>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
Generate report
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5, mb: 2 }}>
|
||||
Define the snapshot's scope. Granularity, payee and tag are sliced at view time — the cube is built once and
|
||||
every combination stays cheap to read.
|
||||
</Typography>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Box component="form" onSubmit={handleSubmit}>
|
||||
<Grid container spacing={2}>
|
||||
{fields.map((field) => (
|
||||
<Grid item xs={12} sm={6} md={4} key={field.name}>
|
||||
<FormFieldRenderer
|
||||
field={field}
|
||||
value={formData[field.name]}
|
||||
onChange={(val) => handleChange(field.name, val)}
|
||||
fkOptions={fkOptions[field.name]}
|
||||
fkLoading={fkLoading[field.name]}
|
||||
onFkOpen={loadFkOnOpen}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
<Box sx={{ mt: 2, display: "flex", justifyContent: "flex-end" }}>
|
||||
<Button type="submit" variant="contained" startIcon={<AddIcon />} disabled={submitting}>
|
||||
{submitting ? "Generating…" : "Generate"}
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
184
src/Reports/Report.tsx
Normal file
184
src/Reports/Report.tsx
Normal file
@@ -0,0 +1,184 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Container,
|
||||
Box,
|
||||
Paper,
|
||||
Typography,
|
||||
Alert,
|
||||
Accordion,
|
||||
AccordionSummary,
|
||||
AccordionDetails,
|
||||
} from "@mui/material";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import AssessmentIcon from "@mui/icons-material/Assessment";
|
||||
import { useResource, useAppContext } from "../../react-openapi";
|
||||
import { useToast } from "../ui/Toast";
|
||||
import { PageHeader } from "../ui/PageHeader";
|
||||
import { EmptyState } from "../ui/EmptyState";
|
||||
import { StatCard } from "../common/components/StatCard";
|
||||
import { buildTxnFieldConfigs } from "../common/utils/fieldConfigs";
|
||||
import { GenerateReportPanel } from "./GenerateReportPanel";
|
||||
import { ReportList } from "./ReportList";
|
||||
import { ReportViewer } from "./ReportViewer";
|
||||
import { apiErrorMessage, buildReportFieldConfigs } from "./types";
|
||||
|
||||
export default function Report() {
|
||||
const { resources } = useAppContext();
|
||||
const { showToast } = useToast();
|
||||
const { list, loading, error } = useResource("reports");
|
||||
const { create, remove } = useResource("reports");
|
||||
|
||||
const [reports, setReports] = useState<any[] | null>(null);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [viewerVersion, setViewerVersion] = useState(0);
|
||||
|
||||
const reportFields = useMemo(() => buildReportFieldConfigs(resources), [resources]);
|
||||
const txnFields = useMemo(() => buildTxnFieldConfigs(resources), [resources]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const res = await list({ limit: 200 });
|
||||
setReports(res.items ?? []);
|
||||
}, [list]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const handleGenerated = useCallback(
|
||||
(created: any) => {
|
||||
load();
|
||||
if (created?.id) setSelectedId(created.id);
|
||||
},
|
||||
[load],
|
||||
);
|
||||
|
||||
const handleRegenerate = useCallback(
|
||||
async (report: any) => {
|
||||
try {
|
||||
const created = await create(report.query ?? {});
|
||||
showToast("Report regenerated");
|
||||
setSelectedId(created?.id ?? report.id);
|
||||
setViewerVersion((v) => v + 1);
|
||||
load();
|
||||
} catch (e: any) {
|
||||
showToast(apiErrorMessage(e), "error");
|
||||
}
|
||||
},
|
||||
[create, load, showToast],
|
||||
);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (id: string) => {
|
||||
try {
|
||||
await remove(id);
|
||||
showToast("Report deleted");
|
||||
if (selectedId === id) setSelectedId(null);
|
||||
load();
|
||||
} catch (e: any) {
|
||||
showToast(apiErrorMessage(e), "error");
|
||||
}
|
||||
},
|
||||
[remove, load, selectedId, showToast],
|
||||
);
|
||||
|
||||
const summary = useMemo(() => {
|
||||
const rows = reports ?? [];
|
||||
const granularities = new Set<string>();
|
||||
for (const r of rows) for (const g of r.query?.granularities ?? []) granularities.add(g);
|
||||
return { count: rows.length, granularities: [...granularities].join(", ") };
|
||||
}, [reports]);
|
||||
|
||||
return (
|
||||
<Container maxWidth="lg" sx={{ py: 4 }}>
|
||||
<PageHeader
|
||||
crumbs={[{ label: "Home", path: "/" }, { label: "Reports" }]}
|
||||
title="Reports"
|
||||
subtitle="Build an immutable snapshot cube once, then slice by granularity, period, payee and tag at view time."
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
Failed to load reports: {error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 4 }}>
|
||||
<StatCard label="Reports" value={summary.count.toLocaleString("en-IN")} />
|
||||
<StatCard label="Granularities covered" value={summary.granularities || "—"} />
|
||||
</Box>
|
||||
|
||||
<GenerateReportPanel onGenerated={handleGenerated} />
|
||||
|
||||
<Accordion
|
||||
disableGutters
|
||||
defaultExpanded
|
||||
sx={{
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 2,
|
||||
overflow: "hidden",
|
||||
boxShadow: "none",
|
||||
backgroundColor: "background.paper",
|
||||
"&:before": { display: "none" },
|
||||
mb: 4,
|
||||
}}
|
||||
>
|
||||
<AccordionSummary
|
||||
expandIcon={<ExpandMoreIcon />}
|
||||
sx={{
|
||||
px: 2.5,
|
||||
py: 1,
|
||||
"& .MuiAccordionSummary-content": {
|
||||
alignItems: "center",
|
||||
gap: 1.5,
|
||||
minWidth: 0,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
Saved reports
|
||||
</Typography>
|
||||
{reports !== null && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{reports.length} report{reports.length === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
)}
|
||||
</AccordionSummary>
|
||||
<AccordionDetails sx={{ px: 2.5, pb: 2.5, pt: 0 }}>
|
||||
{reports !== null && reports.length === 0 ? (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 3 }}>
|
||||
<EmptyState
|
||||
icon={<AssessmentIcon />}
|
||||
title="No reports yet"
|
||||
description="Generate your first snapshot above — choose granularities and grouping dimensions, then slice the cached cube by period, payee and tag."
|
||||
/>
|
||||
</Paper>
|
||||
) : (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}>
|
||||
<ReportList
|
||||
reports={reports ?? []}
|
||||
loading={loading}
|
||||
fields={reportFields}
|
||||
selectedId={selectedId}
|
||||
onView={(id) => setSelectedId(id)}
|
||||
onRegenerate={handleRegenerate}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
|
||||
{selectedId && (
|
||||
<ReportViewer
|
||||
key={selectedId}
|
||||
id={selectedId}
|
||||
version={viewerVersion}
|
||||
fields={txnFields}
|
||||
onClose={() => setSelectedId(null)}
|
||||
onRegenerated={handleRegenerate}
|
||||
/>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
116
src/Reports/ReportList.tsx
Normal file
116
src/Reports/ReportList.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
import React from "react";
|
||||
import { Box, Paper, Typography, Button, IconButton, Skeleton, Tooltip } from "@mui/material";
|
||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||
import CachedIcon from "@mui/icons-material/Cached";
|
||||
import { ListCellRenderer } from "../../react-openapi";
|
||||
import type { ReportFieldConfigs } from "./types";
|
||||
|
||||
interface ReportListProps {
|
||||
reports: any[];
|
||||
loading: boolean;
|
||||
fields: ReportFieldConfigs | null;
|
||||
selectedId: string | null;
|
||||
onView: (id: string) => void;
|
||||
onRegenerate: (report: any) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export function ReportList({ reports, loading, fields, selectedId, onView, onRegenerate, onDelete }: ReportListProps) {
|
||||
if (loading && reports.length === 0) {
|
||||
return (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||
{[0, 1, 2].map((i) => (
|
||||
<Skeleton key={i} variant="rounded" height={88} sx={{ borderRadius: 2 }} />
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
|
||||
{reports.map((report) => {
|
||||
const q = report.query ?? {};
|
||||
const range = q.start_date || q.end_date ? `range ${q.start_date || "…"} → ${q.end_date || "…"}` : null;
|
||||
const dims = Array.isArray(q.group_dims) ? q.group_dims.join(", ") : "";
|
||||
const granularities = Array.isArray(q.granularities) ? q.granularities.join(", ") : "";
|
||||
const accounts = Array.isArray(q.accounts) ? `${q.accounts.length} account${q.accounts.length === 1 ? "" : "s"}` : "all accounts";
|
||||
const amounts =
|
||||
q.min_amount != null || q.max_amount != null
|
||||
? `amount ${q.min_amount ?? "0"} → ${q.max_amount ?? "∞"}`
|
||||
: null;
|
||||
return (
|
||||
<Paper
|
||||
key={report.id}
|
||||
variant="outlined"
|
||||
sx={{
|
||||
p: 2,
|
||||
borderRadius: 2,
|
||||
borderColor: selectedId === report.id ? "primary.main" : "divider",
|
||||
transition: "border-color 160ms ease",
|
||||
"&:hover": { borderColor: "primary.light" },
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
|
||||
<Box sx={{ flex: "1 1 260px", minWidth: 0 }}>
|
||||
<Typography variant="body1" fontWeight={600} noWrap sx={{ fontSize: "0.9375rem" }}>
|
||||
{report.name || report.id}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.25 }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{granularities}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
/
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{dims}
|
||||
</Typography>
|
||||
{range && (
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{range}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ display: "flex", gap: 1.5, mt: 0.5 }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{accounts}
|
||||
</Typography>
|
||||
{amounts && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{amounts}
|
||||
</Typography>
|
||||
)}
|
||||
{fields && (
|
||||
<Box sx={{ color: "text.secondary" }}>
|
||||
<ListCellRenderer field={fields.generatedAt} value={report.generated_at} />
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
|
||||
<Button size="small" variant="contained" startIcon={<VisibilityIcon />} onClick={() => onView(report.id)}>
|
||||
View
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
startIcon={<CachedIcon />}
|
||||
onClick={() => onRegenerate(report)}
|
||||
>
|
||||
Regenerate
|
||||
</Button>
|
||||
<Tooltip title="Delete">
|
||||
<IconButton aria-label="Delete report" onClick={() => onDelete(report.id)}>
|
||||
<DeleteOutlineIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
502
src/Reports/ReportViewer.tsx
Normal file
502
src/Reports/ReportViewer.tsx
Normal file
@@ -0,0 +1,502 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Box, Paper, Typography, Button, IconButton, Alert, Skeleton, Chip, MenuItem, Select, FormControl, InputLabel } from "@mui/material";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import CachedIcon from "@mui/icons-material/Cached";
|
||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
|
||||
import { FkMultiSelectField, useResource, formatCurrency } from "../../react-openapi";
|
||||
import type { FieldConfig } from "../../react-openapi";
|
||||
import { StatCard } from "../common/components/StatCard";
|
||||
import { TransactionList } from "../common/components/TransactionList";
|
||||
import type { TxnFieldConfigs } from "../common/types";
|
||||
import type { ListPeriodGroup } from "../common/utils/transactions";
|
||||
import { buildDimensionBars, buildPeriodGroups, sliceSummary, FLOW_OPTIONS, apiErrorMessage } from "./types";
|
||||
import type { ReportDim } from "./types";
|
||||
|
||||
const MAX_VISIBLE_BARS = 10;
|
||||
|
||||
const periodField: FieldConfig = {
|
||||
name: "period",
|
||||
label: "Period",
|
||||
description: "",
|
||||
type: "string",
|
||||
order: 0,
|
||||
hidden: {},
|
||||
filterable: true,
|
||||
sortable: false,
|
||||
readOnly: false,
|
||||
required: false,
|
||||
isArray: true,
|
||||
};
|
||||
|
||||
const payeeField: FieldConfig = {
|
||||
name: "payee",
|
||||
label: "Payee",
|
||||
description: "",
|
||||
type: "string",
|
||||
order: 0,
|
||||
hidden: {},
|
||||
filterable: true,
|
||||
sortable: false,
|
||||
readOnly: false,
|
||||
required: false,
|
||||
isArray: true,
|
||||
};
|
||||
|
||||
const tagField: FieldConfig = {
|
||||
name: "tag",
|
||||
label: "Tag",
|
||||
description: "",
|
||||
type: "string",
|
||||
order: 0,
|
||||
hidden: {},
|
||||
filterable: true,
|
||||
sortable: false,
|
||||
readOnly: false,
|
||||
required: false,
|
||||
isArray: true,
|
||||
};
|
||||
|
||||
interface ReportViewerProps {
|
||||
id: string;
|
||||
version: number;
|
||||
fields: TxnFieldConfigs | null;
|
||||
onClose: () => void;
|
||||
onRegenerated: (report: any) => void;
|
||||
}
|
||||
|
||||
function snapshotGranularities(report: any): string[] {
|
||||
const fromQuery = report?.query?.granularities;
|
||||
if (Array.isArray(fromQuery) && fromQuery.length) return fromQuery;
|
||||
const fromResponse = report?.granularities;
|
||||
if (Array.isArray(fromResponse) && fromResponse.length) return fromResponse;
|
||||
const series = report?.buckets?.[0]?.series;
|
||||
return series ? Object.keys(series) : [];
|
||||
}
|
||||
|
||||
export function ReportViewer({ id, version, fields, onClose, onRegenerated }: ReportViewerProps) {
|
||||
const { get } = useResource("reports");
|
||||
|
||||
const [report, setReport] = useState<any | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reload, setReload] = useState(0);
|
||||
const [granularity, setGranularity] = useState<string | null>(null);
|
||||
const [flow, setFlow] = useState("outflows");
|
||||
const [dim, setDim] = useState<ReportDim>("period");
|
||||
const [selectedPeriods, setSelectedPeriods] = useState<string[]>([]);
|
||||
const [selectedPayees, setSelectedPayees] = useState<string[]>([]);
|
||||
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||
const prevGranularity = useRef<string | null>(null);
|
||||
|
||||
const params = useMemo(() => {
|
||||
const p: Record<string, any> = { flow };
|
||||
if (granularity) p.granularity = [granularity];
|
||||
if (selectedPeriods.length) p.period_ids = selectedPeriods;
|
||||
// The active breakdown dim requests every cube value ("*") when its own
|
||||
// filter is unselected, so bars show the full distribution.
|
||||
if (selectedPayees.length) p.payee = selectedPayees;
|
||||
else if (dim === "payee") p.payee = ["*"];
|
||||
if (selectedTags.length) p.tags = selectedTags;
|
||||
else if (dim === "tag") p.tags = ["*"];
|
||||
return p;
|
||||
}, [granularity, flow, dim, selectedPeriods, selectedPayees, selectedTags]);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const previous = prevGranularity.current;
|
||||
get(id, params)
|
||||
.then((res) => {
|
||||
if (!mounted) return;
|
||||
setReport(res);
|
||||
const options = snapshotGranularities(res);
|
||||
if (granularity === null && options.length) setGranularity(options[0]);
|
||||
if (previous !== null && previous !== granularity) setSelectedPeriods([]);
|
||||
prevGranularity.current = granularity;
|
||||
})
|
||||
.catch((e: any) => {
|
||||
if (!mounted) return;
|
||||
setError(apiErrorMessage(e));
|
||||
})
|
||||
.finally(() => {
|
||||
if (mounted) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [id, version, reload, params, get, granularity]);
|
||||
|
||||
const granularityOptions = useMemo(() => snapshotGranularities(report), [report]);
|
||||
|
||||
const periodOptions = useMemo(
|
||||
() => (Array.isArray(report?.period_ids) ? report.period_ids.map((label: string) => ({ value: label, label })) : []),
|
||||
[report],
|
||||
);
|
||||
const payeeOptions = useMemo(
|
||||
() => (Array.isArray(report?.payees) ? report.payees.map((label: string) => ({ value: label, label })) : []),
|
||||
[report],
|
||||
);
|
||||
const tagOptions = useMemo(
|
||||
() => (Array.isArray(report?.tags) ? report.tags.map((label: string) => ({ value: label, label })) : []),
|
||||
[report],
|
||||
);
|
||||
|
||||
const filter = useMemo(
|
||||
() => ({
|
||||
granularity: granularity ?? granularityOptions[0] ?? "",
|
||||
periods: selectedPeriods,
|
||||
payees: selectedPayees,
|
||||
tags: selectedTags,
|
||||
}),
|
||||
[granularity, granularityOptions, selectedPeriods, selectedPayees, selectedTags],
|
||||
);
|
||||
|
||||
const periodGroups = useMemo(() => buildPeriodGroups(report?.buckets ?? [], filter), [report, filter]);
|
||||
const slice = useMemo(() => sliceSummary(periodGroups), [periodGroups]);
|
||||
const bars = useMemo(() => buildDimensionBars(report?.buckets ?? [], filter, dim), [report, filter, dim]);
|
||||
const visibleBars = useMemo(() => bars.slice(0, MAX_VISIBLE_BARS), [bars]);
|
||||
const listGroups = useMemo<ListPeriodGroup[]>(
|
||||
() =>
|
||||
periodGroups.map((g) => ({
|
||||
key: g.key,
|
||||
label: g.key,
|
||||
items: g.txns,
|
||||
spent: g.metrics.outflows,
|
||||
income: g.metrics.inflows,
|
||||
currency: g.currency,
|
||||
metrics: {
|
||||
sum: g.metrics.sum,
|
||||
count: g.metrics.count,
|
||||
avg: g.metrics.avg,
|
||||
min: g.metrics.min,
|
||||
max: g.metrics.max,
|
||||
cadence: g.metrics.cadence,
|
||||
frequency: g.metrics.frequency,
|
||||
},
|
||||
})),
|
||||
[periodGroups],
|
||||
);
|
||||
|
||||
const barsListRef = useRef<HTMLDivElement>(null);
|
||||
const [barScroll, setBarScroll] = useState({ canUp: false, canDown: false, overflow: false });
|
||||
|
||||
const updateBarScroll = useCallback(() => {
|
||||
const el = barsListRef.current;
|
||||
if (!el) return;
|
||||
const overflow = el.scrollHeight > el.clientHeight + 2;
|
||||
setBarScroll({
|
||||
overflow,
|
||||
canUp: overflow && el.scrollTop > 2,
|
||||
canDown: overflow && el.scrollTop < el.scrollHeight - el.clientHeight - 2,
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = barsListRef.current;
|
||||
if (el) el.scrollTop = 0;
|
||||
updateBarScroll();
|
||||
}, [dim, visibleBars.length, updateBarScroll]);
|
||||
|
||||
const scrollBarsByPage = useCallback((dir: number) => {
|
||||
const el = barsListRef.current;
|
||||
if (!el) return;
|
||||
el.scrollTo({ top: dir > 0 ? el.scrollHeight : 0, behavior: "smooth" });
|
||||
}, []);
|
||||
|
||||
if (loading && !report) {
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3 }}>
|
||||
<Skeleton variant="text" width={220} height={28} />
|
||||
<Skeleton variant="rounded" height={120} sx={{ my: 2, borderRadius: 2 }} />
|
||||
<Skeleton variant="rounded" height={240} sx={{ borderRadius: 2 }} />
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ p: 3, borderRadius: 3 }}>
|
||||
<Alert severity="error" sx={{ borderRadius: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
<Button size="small" sx={{ mt: 2 }} onClick={() => setReload((r) => r + 1)}>
|
||||
Retry
|
||||
</Button>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
|
||||
if (!report) return null;
|
||||
|
||||
const activeGranularity = granularity ?? report.granularities?.[0] ?? "";
|
||||
const maxBar = bars.reduce((m, b) => Math.max(m, Math.abs(b.sum)), 0);
|
||||
const dimOptions: { id: ReportDim; label: string; count: number }[] = [
|
||||
{ id: "period", label: "Period", count: report.period_ids?.length ?? 0 },
|
||||
{ id: "payee", label: "Payees", count: report.payees?.length ?? 0 },
|
||||
{ id: "tag", label: "Tags", count: report.tags?.length ?? 0 },
|
||||
];
|
||||
const activeDimIndex = Math.max(
|
||||
0,
|
||||
dimOptions.findIndex((d) => d.id === dim),
|
||||
);
|
||||
const range =
|
||||
report.query?.start_date || report.query?.end_date
|
||||
? `range ${report.query.start_date || "…"} → ${report.query.end_date || "…"}`
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 3, overflow: "hidden" }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
px: 2.5,
|
||||
py: 2,
|
||||
borderBottom: "1px solid",
|
||||
borderColor: "divider",
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
{report.name}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap" }}>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
flow {report.flow} · generated {report.generated_at ?? report.created_at}
|
||||
</Typography>
|
||||
{range && (
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{range}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{report.payees?.length ?? 0} payees · {report.tags?.length ?? 0} tags
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<IconButton aria-label="Regenerate report" onClick={() => onRegenerated(report)}>
|
||||
<CachedIcon />
|
||||
</IconButton>
|
||||
<IconButton aria-label="Close report" onClick={onClose}>
|
||||
<CloseIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ p: 2.5 }}>
|
||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", alignItems: "center", mb: 2 }}>
|
||||
<Box sx={{ display: "flex", gap: 0.5, flexWrap: "wrap" }}>
|
||||
{granularityOptions.map((g: string) => (
|
||||
<Chip
|
||||
key={g}
|
||||
label={g}
|
||||
clickable
|
||||
size="small"
|
||||
color={activeGranularity === g ? "primary" : "default"}
|
||||
variant={activeGranularity === g ? "filled" : "outlined"}
|
||||
onClick={() => setGranularity(g)}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
<FormControl size="small" sx={{ width: 140 }}>
|
||||
<InputLabel id="viewer-flow-label">Flow</InputLabel>
|
||||
<Select labelId="viewer-flow-label" label="Flow" value={flow} onChange={(e) => setFlow(e.target.value)}>
|
||||
{FLOW_OPTIONS.map((f) => (
|
||||
<MenuItem key={f} value={f}>
|
||||
{f}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 1.5, flexWrap: "wrap", mb: 2.5 }}>
|
||||
<Box sx={{ width: 260 }}>
|
||||
<FkMultiSelectField
|
||||
field={{ ...periodField, readOnly: periodOptions.length === 0 }}
|
||||
fkOptions={periodOptions}
|
||||
value={selectedPeriods}
|
||||
onChange={setSelectedPeriods}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ width: 260 }}>
|
||||
<FkMultiSelectField
|
||||
field={{ ...payeeField, readOnly: payeeOptions.length === 0 }}
|
||||
fkOptions={payeeOptions}
|
||||
value={selectedPayees}
|
||||
onChange={setSelectedPayees}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ width: 260 }}>
|
||||
<FkMultiSelectField
|
||||
field={{ ...tagField, readOnly: tagOptions.length === 0 }}
|
||||
fkOptions={tagOptions}
|
||||
value={selectedTags}
|
||||
onChange={setSelectedTags}
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ alignSelf: "center" }}>
|
||||
{slice.txns.length} transactions · {slice.count} rows
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", mb: 2.5 }}>
|
||||
<StatCard label="Outflows" value={formatCurrency(slice.outflows, slice.currency)} color="error.main" />
|
||||
<StatCard label="Inflows" value={formatCurrency(slice.inflows, slice.currency)} color="success.main" />
|
||||
<StatCard label="Net" value={formatCurrency(slice.inflows - slice.outflows, slice.currency)} color="info.main" />
|
||||
<StatCard label="Transactions" value={slice.count.toLocaleString("en-IN")} />
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mb: 2.5 }}>
|
||||
<Box
|
||||
sx={{
|
||||
position: "relative",
|
||||
display: "flex",
|
||||
alignItems: "stretch",
|
||||
width: "fit-content",
|
||||
maxWidth: "100%",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: "999px",
|
||||
p: 0.5,
|
||||
backgroundColor: "background.default",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
aria-hidden
|
||||
sx={{
|
||||
position: "absolute",
|
||||
top: 4,
|
||||
bottom: 4,
|
||||
left: 4,
|
||||
width: `calc((100% - 8px) / ${dimOptions.length})`,
|
||||
borderRadius: "999px",
|
||||
backgroundColor: "primary.main",
|
||||
transform: `translateX(${activeDimIndex * 100}%)`,
|
||||
transition: "transform 250ms cubic-bezier(0.4, 0, 0.2, 1)",
|
||||
}}
|
||||
/>
|
||||
{dimOptions.map((d) => {
|
||||
const active = d.id === dim;
|
||||
return (
|
||||
<Box
|
||||
key={d.id}
|
||||
component="button"
|
||||
type="button"
|
||||
disabled={d.count <= 1}
|
||||
onClick={() => setDim(d.id)}
|
||||
sx={{
|
||||
position: "relative",
|
||||
zIndex: 1,
|
||||
flex: 1,
|
||||
border: "none",
|
||||
background: "transparent",
|
||||
px: 3,
|
||||
py: 1,
|
||||
borderRadius: "999px",
|
||||
cursor: d.count <= 1 ? "default" : "pointer",
|
||||
typography: "body2",
|
||||
fontWeight: 700,
|
||||
letterSpacing: "-0.01em",
|
||||
color:
|
||||
d.count <= 1
|
||||
? "text.disabled"
|
||||
: active
|
||||
? "primary.contrastText"
|
||||
: "text.secondary",
|
||||
whiteSpace: "nowrap",
|
||||
transition: "color 160ms ease",
|
||||
"&:focus-visible": { outline: "2px solid", outlineColor: "primary.main" },
|
||||
}}
|
||||
>
|
||||
{d.label}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
||||
{visibleBars.length === 0 ? (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 2, p: 3, mt: 1.5 }}>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
No data for this slice. Try another granularity, period or payer.
|
||||
</Typography>
|
||||
</Paper>
|
||||
) : (
|
||||
<Paper variant="outlined" sx={{ borderRadius: 2, mt: 1.5 }}>
|
||||
<Box sx={{ display: "flex", alignItems: "stretch" }}>
|
||||
<Box
|
||||
ref={barsListRef}
|
||||
onScroll={updateBarScroll}
|
||||
sx={{
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
maxHeight: 220,
|
||||
overflowY: "auto",
|
||||
py: 1,
|
||||
px: 2,
|
||||
scrollbarWidth: "none",
|
||||
"&::-webkit-scrollbar": { display: "none" },
|
||||
}}
|
||||
>
|
||||
{visibleBars.map((b) => (
|
||||
<Box key={b.key} sx={{ display: "flex", alignItems: "center", gap: 1.5, py: 0.75 }}>
|
||||
<Typography variant="caption" sx={{ width: 110, flexShrink: 0, textAlign: "right" }}>
|
||||
{b.key}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
height: 20,
|
||||
borderRadius: 1,
|
||||
bgcolor: flow === "outflows" ? "error.main" : "success.main",
|
||||
opacity: 0.85,
|
||||
minWidth: 4,
|
||||
flexGrow: 0,
|
||||
}}
|
||||
style={{
|
||||
width: `${maxBar ? Math.max((Math.abs(b.sum) / maxBar) * 100, 2) : 2}%`,
|
||||
}}
|
||||
/>
|
||||
<Typography variant="body2" fontWeight={600}>
|
||||
{formatCurrency(b.sum, slice.currency)}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.disabled">
|
||||
{b.count} txn{b.count === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
{barScroll.overflow && (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 0.5, pr: 1.5 }}>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label="Scroll bars up"
|
||||
disabled={!barScroll.canUp}
|
||||
onClick={() => scrollBarsByPage(-1)}
|
||||
>
|
||||
<KeyboardArrowUpIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label="Scroll bars down"
|
||||
disabled={!barScroll.canDown}
|
||||
onClick={() => scrollBarsByPage(1)}
|
||||
>
|
||||
<KeyboardArrowDownIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Paper>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{slice.txns.length === 0 ? null : fields ? (
|
||||
<TransactionList fields={fields} groups={listGroups} showMetrics />
|
||||
) : null}
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
288
src/Reports/types.ts
Normal file
288
src/Reports/types.ts
Normal file
@@ -0,0 +1,288 @@
|
||||
import type { FieldConfig, ResourceConfig } from "../../react-openapi";
|
||||
import { parseOccurredAt } from "../common/utils/dates";
|
||||
|
||||
export interface PeriodMetricsVM {
|
||||
outflows: number;
|
||||
inflows: number;
|
||||
sum: number;
|
||||
count: number;
|
||||
avg: number | null;
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
firstDate: string | null;
|
||||
lastDate: string | null;
|
||||
cadence: number | null;
|
||||
frequency: number | null;
|
||||
}
|
||||
|
||||
export interface ReportPeriodGroup {
|
||||
key: string;
|
||||
metrics: PeriodMetricsVM;
|
||||
txns: any[];
|
||||
currency: string;
|
||||
}
|
||||
|
||||
export interface SliceSummary {
|
||||
outflows: number;
|
||||
inflows: number;
|
||||
sum: number;
|
||||
count: number;
|
||||
avg: number | null;
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
firstDate: string | null;
|
||||
lastDate: string | null;
|
||||
txns: any[];
|
||||
currency: string;
|
||||
}
|
||||
|
||||
export interface SliceFilter {
|
||||
granularity: string;
|
||||
periods?: string[];
|
||||
payees?: string[];
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
export interface ReportFieldConfigs {
|
||||
name: FieldConfig;
|
||||
generatedAt: FieldConfig;
|
||||
}
|
||||
|
||||
export interface MetricLabel {
|
||||
key: string;
|
||||
label: string;
|
||||
order: number;
|
||||
}
|
||||
|
||||
export function apiErrorMessage(e: any): string {
|
||||
if (e?.response?.data) {
|
||||
const d = e.response.data;
|
||||
if (Array.isArray(d)) return d.map((x: any) => x?.msg ?? String(x)).join("; ");
|
||||
if (typeof d.detail === "string") return d.detail;
|
||||
if (typeof d.detail?.msg === "string") return d.detail.msg;
|
||||
if (typeof d === "string") return d;
|
||||
}
|
||||
return e?.message ?? "Request failed";
|
||||
}
|
||||
|
||||
export const FLOW_OPTIONS = ["both", "inflows", "outflows"];
|
||||
|
||||
export function metricLabels(schemas: Record<string, any>): MetricLabel[] {
|
||||
const props: Record<string, any> = schemas?.ReportMetrics?.properties ?? {};
|
||||
return Object.entries(props)
|
||||
.filter(([, p]) => p && typeof p === "object")
|
||||
.map(([key, p]) => ({
|
||||
key,
|
||||
label: (p as any)["x-label"] ?? key,
|
||||
order: (p as any)["x-order"] ?? Infinity,
|
||||
}))
|
||||
.sort((a, b) => a.order - b.order);
|
||||
}
|
||||
|
||||
function dateVal(value: string): number {
|
||||
try {
|
||||
return parseOccurredAt(value).getTime();
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function bucketMatches(bucket: any, filter: SliceFilter): boolean {
|
||||
const gk = bucket?.group_key ?? {};
|
||||
if (filter.payees?.length && !(gk.payee ?? []).some((p: string) => filter.payees?.includes(p))) return false;
|
||||
if (filter.tags?.length && !(gk.tag ?? []).some((t: string) => filter.tags?.includes(t))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function num(v: any): number | null {
|
||||
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups cube periods by their canonical period_id, merging buckets per
|
||||
* period. The server returns disjoint slices, so additive metric merge is
|
||||
* safe; txn ids are deduped defensively. Metrics come verbatim from the API
|
||||
* except when multiple buckets contribute to one period — then cadence and
|
||||
* frequency are re-derived from the merged txn dates.
|
||||
*/
|
||||
export function buildPeriodGroups(buckets: any[], filter: SliceFilter): ReportPeriodGroup[] {
|
||||
interface Acc {
|
||||
metrics: PeriodMetricsVM;
|
||||
txns: any[];
|
||||
sources: number;
|
||||
apiCadence: number | null;
|
||||
apiFrequency: number | null;
|
||||
}
|
||||
const byPeriod = new Map<string, Acc>();
|
||||
const seenTxnIds = new Set<string>();
|
||||
let currency = "INR";
|
||||
|
||||
for (const bucket of buckets ?? []) {
|
||||
if (!bucketMatches(bucket, filter)) continue;
|
||||
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
||||
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
||||
const m = period.metrics ?? {};
|
||||
let acc = byPeriod.get(period.period_id);
|
||||
if (!acc) {
|
||||
acc = {
|
||||
metrics: {
|
||||
outflows: 0,
|
||||
inflows: 0,
|
||||
sum: 0,
|
||||
count: 0,
|
||||
avg: null,
|
||||
min: null,
|
||||
max: null,
|
||||
firstDate: null,
|
||||
lastDate: null,
|
||||
cadence: null,
|
||||
frequency: null,
|
||||
},
|
||||
txns: [],
|
||||
sources: 0,
|
||||
apiCadence: num(m.cadence),
|
||||
apiFrequency: num(m.frequency),
|
||||
};
|
||||
byPeriod.set(period.period_id, acc);
|
||||
}
|
||||
acc.sources += 1;
|
||||
const vm = acc.metrics;
|
||||
vm.outflows += m.outflows ?? 0;
|
||||
vm.inflows += m.inflows ?? 0;
|
||||
vm.sum += m.sum ?? 0;
|
||||
vm.count += m.count ?? 0;
|
||||
const mn = num(m.min);
|
||||
if (mn != null) vm.min = vm.min == null ? mn : Math.min(vm.min, mn);
|
||||
const mx = num(m.max);
|
||||
if (mx != null) vm.max = vm.max == null ? mx : Math.max(vm.max, mx);
|
||||
if (m.first_date && (!vm.firstDate || dateVal(String(m.first_date)) < dateVal(vm.firstDate))) {
|
||||
vm.firstDate = String(m.first_date);
|
||||
}
|
||||
if (m.last_date && (!vm.lastDate || dateVal(String(m.last_date)) > dateVal(vm.lastDate))) {
|
||||
vm.lastDate = String(m.last_date);
|
||||
}
|
||||
for (const txn of period.txns ?? []) {
|
||||
if (txn?.id != null) {
|
||||
if (seenTxnIds.has(txn.id)) continue;
|
||||
seenTxnIds.add(txn.id);
|
||||
}
|
||||
acc.txns.push(txn);
|
||||
const c = txn?.account?.currency;
|
||||
if (c) currency = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...byPeriod.entries()]
|
||||
.map(([key, acc]) => {
|
||||
const vm = acc.metrics;
|
||||
vm.avg = vm.count ? Math.round((vm.sum / vm.count) * 100) / 100 : null;
|
||||
if (acc.sources > 1) {
|
||||
const dates = acc.txns
|
||||
.map((t) => {
|
||||
try {
|
||||
return parseOccurredAt(t?.occurred_at).getTime();
|
||||
} catch {
|
||||
return NaN;
|
||||
}
|
||||
})
|
||||
.filter((t) => !Number.isNaN(t))
|
||||
.sort((a, b) => a - b);
|
||||
if (dates.length >= 2) {
|
||||
let gapSum = 0;
|
||||
for (let i = 0; i < dates.length - 1; i += 1) gapSum += (dates[i + 1] - dates[i]) / 86400000;
|
||||
const cadence = Math.round((gapSum / (dates.length - 1)) * 100) / 100;
|
||||
vm.cadence = cadence > 0 ? cadence : null;
|
||||
vm.frequency = cadence > 0 ? Math.round((1 / cadence) * 100) / 100 : null;
|
||||
} else {
|
||||
vm.cadence = null;
|
||||
vm.frequency = null;
|
||||
}
|
||||
} else {
|
||||
vm.cadence = acc.apiCadence;
|
||||
vm.frequency = acc.apiFrequency;
|
||||
}
|
||||
return { key, metrics: vm, txns: acc.txns, currency };
|
||||
})
|
||||
.sort((a, b) => b.key.localeCompare(a.key));
|
||||
}
|
||||
|
||||
export function sliceSummary(groups: ReportPeriodGroup[]): SliceSummary {
|
||||
const outflows = groups.reduce((s, g) => s + g.metrics.outflows, 0);
|
||||
const inflows = groups.reduce((s, g) => s + g.metrics.inflows, 0);
|
||||
const sum = groups.reduce((s, g) => s + g.metrics.sum, 0);
|
||||
const count = groups.reduce((s, g) => s + g.metrics.count, 0);
|
||||
let min: number | null = null;
|
||||
let max: number | null = null;
|
||||
let firstDate: string | null = null;
|
||||
let lastDate: string | null = null;
|
||||
let currency = "INR";
|
||||
const txns: any[] = [];
|
||||
for (const g of groups) {
|
||||
if (g.metrics.min != null) min = min == null ? g.metrics.min : Math.min(min, g.metrics.min);
|
||||
if (g.metrics.max != null) max = max == null ? g.metrics.max : Math.max(max, g.metrics.max);
|
||||
if (g.metrics.firstDate && (!firstDate || dateVal(g.metrics.firstDate) < dateVal(firstDate))) {
|
||||
firstDate = g.metrics.firstDate;
|
||||
}
|
||||
if (g.metrics.lastDate && (!lastDate || dateVal(g.metrics.lastDate) > dateVal(lastDate))) {
|
||||
lastDate = g.metrics.lastDate;
|
||||
}
|
||||
if (g.currency) currency = g.currency;
|
||||
txns.push(...g.txns);
|
||||
}
|
||||
return { outflows, inflows, sum, count, avg: count ? sum / count : null, min, max, firstDate, lastDate, txns, currency };
|
||||
}
|
||||
|
||||
export function buildReportFieldConfigs(resources: ResourceConfig[]): ReportFieldConfigs | null {
|
||||
const reportsRes = resources.find((r) => r.name === "reports");
|
||||
if (!reportsRes) return null;
|
||||
const find = (name: string) => reportsRes.fields.find((f) => f.name === name);
|
||||
const name = find("name");
|
||||
const generatedAt = find("generated_at");
|
||||
if (!name || !generatedAt) return null;
|
||||
return { name, generatedAt };
|
||||
}
|
||||
|
||||
export type ReportDim = "period" | "payee" | "tag";
|
||||
|
||||
export interface DimensionBar {
|
||||
key: string;
|
||||
sum: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bar-chart rows for a given dimension. "period" reuses the period groups;
|
||||
* "payee"/"tag" fold each bucket's metrics into every value listed under
|
||||
* group_key[dim] — safe because server buckets are disjoint slices.
|
||||
*/
|
||||
export function buildDimensionBars(buckets: any[], filter: SliceFilter, dim: ReportDim): DimensionBar[] {
|
||||
if (dim === "period") {
|
||||
return buildPeriodGroups(buckets, filter).map((g) => ({
|
||||
key: g.key,
|
||||
sum: g.metrics.sum,
|
||||
count: g.metrics.count,
|
||||
}));
|
||||
}
|
||||
const acc = new Map<string, DimensionBar>();
|
||||
for (const bucket of buckets ?? []) {
|
||||
if (!bucketMatches(bucket, filter)) continue;
|
||||
const keys: string[] = bucket.group_key?.[dim] ?? [];
|
||||
for (const period of bucket.series?.[filter.granularity] ?? []) {
|
||||
if (filter.periods?.length && !filter.periods.includes(period.period_id)) continue;
|
||||
const m = period.metrics ?? {};
|
||||
const sum = typeof m.sum === "number" ? m.sum : 0;
|
||||
const count = typeof m.count === "number" ? m.count : 0;
|
||||
for (const k of keys) {
|
||||
const cur = acc.get(k);
|
||||
if (cur) {
|
||||
cur.sum += sum;
|
||||
cur.count += count;
|
||||
} else {
|
||||
acc.set(k, { key: k, sum, count });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...acc.values()].sort((a, b) => Math.abs(b.sum) - Math.abs(a.sum));
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import * as React from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuth, AuthPage } from "../react-auth";
|
||||
|
||||
export function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||
const { currentUser, loading, error, login, register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [mode, setMode] = React.useState<"login" | "register">("login");
|
||||
|
||||
if (currentUser) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthPage
|
||||
mode={mode}
|
||||
onBack={() => navigate("/")}
|
||||
onSwitchMode={() => setMode(mode === "login" ? "register" : "login")}
|
||||
login={login}
|
||||
register={register}
|
||||
loading={loading}
|
||||
error={error}
|
||||
currentUser={currentUser}
|
||||
/>
|
||||
);
|
||||
}
|
||||
26
src/common/components/StatCard.tsx
Normal file
26
src/common/components/StatCard.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import { Paper, Typography } from "@mui/material";
|
||||
|
||||
interface StatCardProps {
|
||||
label: string;
|
||||
value: string;
|
||||
color?: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
export function StatCard({ label, value, color, hint }: StatCardProps) {
|
||||
return (
|
||||
<Paper variant="outlined" sx={{ p: 2.5, borderRadius: 3, flex: 1, minWidth: 180 }}>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ textTransform: "uppercase", letterSpacing: "0.05em" }}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="h5" fontWeight={700} sx={{ mt: 0.5, letterSpacing: "-0.02em", color }}>
|
||||
{value}
|
||||
</Typography>
|
||||
{hint && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{hint}
|
||||
</Typography>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
356
src/common/components/TransactionList.tsx
Normal file
356
src/common/components/TransactionList.tsx
Normal file
@@ -0,0 +1,356 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Accordion,
|
||||
AccordionSummary,
|
||||
AccordionDetails,
|
||||
Menu,
|
||||
MenuItem,
|
||||
ListItemText,
|
||||
} from "@mui/material";
|
||||
import { alpha } from "@mui/material/styles";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||
import { formatCurrency } from "../../../react-openapi";
|
||||
import type { ExpenseItem, TxnFieldConfigs } from "../types";
|
||||
import { computeTxnMetrics, groupByDate, groupByPeriod } from "../utils/transactions";
|
||||
import type { ListGroupMetrics, ListPeriodGroup, PeriodGranularity } from "../utils/transactions";
|
||||
import { TransactionRow } from "./TransactionRow";
|
||||
import { StatCard } from "./StatCard";
|
||||
|
||||
interface TransactionListProps {
|
||||
items?: ExpenseItem[];
|
||||
fields: TxnFieldConfigs;
|
||||
granularity?: PeriodGranularity;
|
||||
showMetrics?: boolean;
|
||||
groups?: ListPeriodGroup[];
|
||||
}
|
||||
|
||||
function cadenceRow(cadenceDays: number | null, frequency: number | null): { label: string; value: string } {
|
||||
const fmt = (v: number) => (Number.isInteger(v) ? String(v) : v.toFixed(2));
|
||||
if (cadenceDays != null && cadenceDays < 1) {
|
||||
return { label: "Frequency", value: `${frequency == null ? "—" : fmt(frequency)} /day` };
|
||||
}
|
||||
return {
|
||||
label: "Cadence",
|
||||
value: cadenceDays == null ? "—" : `${fmt(cadenceDays)} days`,
|
||||
};
|
||||
}
|
||||
|
||||
function txnFallbackMetrics(items: ExpenseItem[]): ListGroupMetrics {
|
||||
const t = computeTxnMetrics(items);
|
||||
return {
|
||||
sum: t.sum,
|
||||
count: t.count,
|
||||
avg: t.avg,
|
||||
min: t.min,
|
||||
max: t.max,
|
||||
cadence: t.cadenceDays,
|
||||
frequency: t.frequency,
|
||||
};
|
||||
}
|
||||
|
||||
function GroupMetrics({
|
||||
items,
|
||||
currency,
|
||||
metrics,
|
||||
}: {
|
||||
items: ExpenseItem[];
|
||||
currency: string;
|
||||
metrics?: ListGroupMetrics;
|
||||
}) {
|
||||
const m = metrics ?? txnFallbackMetrics(items);
|
||||
const rows: { label: string; value: string }[] = [
|
||||
{ label: "Sum", value: formatCurrency(m.sum, currency) },
|
||||
{ label: "Avg", value: m.avg == null ? "—" : formatCurrency(m.avg, currency) },
|
||||
{ label: "Min", value: m.min == null ? "—" : formatCurrency(m.min, currency) },
|
||||
{ label: "Max", value: m.max == null ? "—" : formatCurrency(m.max, currency) },
|
||||
cadenceRow(m.cadence, m.frequency),
|
||||
];
|
||||
return (
|
||||
<Box sx={{ display: "flex", gap: 2, flexWrap: "wrap", width: "100%" }}>
|
||||
{rows.map((row) => (
|
||||
<StatCard key={row.label} label={row.label} value={row.value} />
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export function TransactionList({
|
||||
items,
|
||||
fields,
|
||||
granularity = "monthly",
|
||||
showMetrics = false,
|
||||
groups: externalGroups,
|
||||
}: TransactionListProps) {
|
||||
const [activeMonth, setActiveMonth] = useState<string | null>(null);
|
||||
const [openMonth, setOpenMonth] = useState<string | null>(null);
|
||||
const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
|
||||
const groups = useMemo<ListPeriodGroup[]>(
|
||||
() => externalGroups ?? groupByPeriod(items ?? [], granularity),
|
||||
[externalGroups, items, granularity],
|
||||
);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const pillRef = useRef<HTMLDivElement>(null);
|
||||
const didInitOpenMonth = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!didInitOpenMonth.current && groups.length > 0) {
|
||||
didInitOpenMonth.current = true;
|
||||
setOpenMonth(groups[0].key);
|
||||
}
|
||||
}, [groups]);
|
||||
|
||||
const scrollToMonth = useCallback((key: string) => {
|
||||
const anchor = listRef.current?.querySelector<HTMLElement>(
|
||||
`[data-month-anchor="${key}"]`,
|
||||
);
|
||||
if (!anchor) return;
|
||||
const offset = window.matchMedia("(min-width: 900px)").matches ? 64 : 56;
|
||||
const top = anchor.getBoundingClientRect().top + window.scrollY - offset;
|
||||
window.scrollTo({ top, behavior: "smooth" });
|
||||
}, []);
|
||||
|
||||
const handleSelectMonth = useCallback(
|
||||
(key: string) => {
|
||||
setMenuAnchor(null);
|
||||
setOpenMonth(key);
|
||||
scrollToMonth(key);
|
||||
},
|
||||
[scrollToMonth],
|
||||
);
|
||||
|
||||
const handlePillKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
if (pillRef.current) setMenuAnchor(pillRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const selectedMonth = activeMonth ?? openMonth ?? groups[0]?.key ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
const root = listRef.current;
|
||||
if (!root || groups.length === 0) return;
|
||||
let ticking = false;
|
||||
|
||||
const update = () => {
|
||||
ticking = false;
|
||||
const headers = root.querySelectorAll<HTMLElement>("[data-month-header]");
|
||||
let current: string | null = null;
|
||||
for (const header of headers) {
|
||||
if (header.getBoundingClientRect().top <= 72) {
|
||||
current = header.dataset.monthHeader ?? null;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
setActiveMonth(current);
|
||||
};
|
||||
|
||||
const onScroll = () => {
|
||||
if (!ticking) {
|
||||
ticking = true;
|
||||
requestAnimationFrame(update);
|
||||
}
|
||||
};
|
||||
|
||||
update();
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
window.addEventListener("resize", onScroll);
|
||||
return () => {
|
||||
window.removeEventListener("scroll", onScroll);
|
||||
window.removeEventListener("resize", onScroll);
|
||||
};
|
||||
}, [groups]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box ref={listRef} sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}>
|
||||
{groups.map((group) => (
|
||||
<Box key={group.key}>
|
||||
<span data-month-anchor={group.key} aria-hidden="true" style={{ display: "block", height: 0 }} />
|
||||
<Accordion
|
||||
disableGutters
|
||||
data-month-header={group.key}
|
||||
expanded={openMonth === group.key}
|
||||
onChange={(_, isExpanded) => setOpenMonth(isExpanded ? group.key : null)}
|
||||
TransitionProps={{ unmountOnExit: true }}
|
||||
sx={{
|
||||
border: "1px solid",
|
||||
borderColor: openMonth === group.key ? "primary.main" : "divider",
|
||||
borderRadius: 2,
|
||||
overflow: "hidden",
|
||||
boxShadow: "none",
|
||||
backgroundColor: "background.paper",
|
||||
"&:before": { display: "none" },
|
||||
transition: "border-color 160ms ease, background-color 160ms ease",
|
||||
"&:hover": { borderColor: "primary.light" },
|
||||
}}
|
||||
>
|
||||
<AccordionSummary
|
||||
expandIcon={<ExpandMoreIcon />}
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
"& .MuiAccordionSummary-content": {
|
||||
flexDirection: "column",
|
||||
alignItems: "stretch",
|
||||
gap: 0.75,
|
||||
minWidth: 0,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5, minWidth: 0 }}>
|
||||
<Typography variant="h6" fontWeight={700} sx={{ letterSpacing: "-0.01em" }}>
|
||||
{group.label}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{group.items.length} transaction{group.items.length === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Typography variant="body2" fontWeight={700} color="error.main">
|
||||
{formatCurrency(group.spent, group.currency)}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.disabled">
|
||||
/
|
||||
</Typography>
|
||||
<Typography variant="body2" fontWeight={700} color="success.main">
|
||||
{formatCurrency(group.income, group.currency)}
|
||||
</Typography>
|
||||
</Box>
|
||||
{showMetrics && (
|
||||
<GroupMetrics items={group.items} currency={group.currency} metrics={group.metrics} />
|
||||
)}
|
||||
</AccordionSummary>
|
||||
<AccordionDetails sx={{ p: 1.5, pt: 1 }}>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
{groupByDate(group.items).map((dateGroup) => (
|
||||
<Box
|
||||
key={dateGroup.date}
|
||||
sx={{
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 2,
|
||||
backgroundColor: "background.default",
|
||||
p: 1,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 1,
|
||||
px: 1,
|
||||
pb: 1,
|
||||
borderBottom: "1px solid",
|
||||
borderColor: "divider",
|
||||
mb: 1,
|
||||
}}
|
||||
>
|
||||
<Typography variant="subtitle2" fontWeight={600} sx={{ letterSpacing: "-0.01em" }}>
|
||||
{dateGroup.label}
|
||||
</Typography>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{dateGroup.items.length} transaction{dateGroup.items.length === 1 ? "" : "s"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
{dateGroup.items.map((item) => (
|
||||
<TransactionRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
currency={group.currency}
|
||||
fields={fields}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: "fixed",
|
||||
bottom: 16,
|
||||
left: "50%",
|
||||
transform: "translateX(-50%)",
|
||||
zIndex: 3,
|
||||
pointerEvents: activeMonth ? "auto" : "none",
|
||||
opacity: activeMonth ? 1 : 0,
|
||||
transition: "opacity 160ms ease",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
ref={pillRef}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(e) => setMenuAnchor(e.currentTarget)}
|
||||
onKeyDown={handlePillKeyDown}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={Boolean(menuAnchor)}
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 0.5,
|
||||
px: 1.5,
|
||||
py: 0.75,
|
||||
borderRadius: "999px",
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
backgroundColor: (theme) => alpha(theme.palette.background.default, 0.85),
|
||||
backdropFilter: "blur(8px)",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
boxShadow: 1,
|
||||
transition: "background-color 160ms ease, transform 160ms ease",
|
||||
"&:hover": {
|
||||
backgroundColor: (theme) => alpha(theme.palette.background.default, 0.95),
|
||||
transform: "translateY(-1px)",
|
||||
},
|
||||
"&:focus-visible": {
|
||||
outline: "2px solid",
|
||||
outlineColor: "primary.main",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption" fontWeight={700} color="text.secondary">
|
||||
{activeMonth ? (groups.find((g) => g.key === activeMonth)?.label ?? activeMonth) : ""}
|
||||
</Typography>
|
||||
<KeyboardArrowDownIcon sx={{ fontSize: 14, color: "text.secondary" }} />
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Menu
|
||||
anchorEl={menuAnchor}
|
||||
open={Boolean(menuAnchor)}
|
||||
onClose={() => setMenuAnchor(null)}
|
||||
anchorOrigin={{ vertical: "top", horizontal: "center" }}
|
||||
transformOrigin={{ vertical: "bottom", horizontal: "center" }}
|
||||
>
|
||||
{groups.map((group) => (
|
||||
<MenuItem
|
||||
key={group.key}
|
||||
selected={selectedMonth === group.key}
|
||||
onClick={() => handleSelectMonth(group.key)}
|
||||
>
|
||||
<ListItemText
|
||||
primary={group.label}
|
||||
secondary={`${group.items.length} transactions`}
|
||||
/>
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
}
|
||||
71
src/common/components/TransactionRow.tsx
Normal file
71
src/common/components/TransactionRow.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
import React from "react";
|
||||
import { Box, Typography } from "@mui/material";
|
||||
import { ListCellRenderer, CurrencyField, applyDisplayFormat } from "../../../react-openapi";
|
||||
import type { ExpenseItem, TxnFieldConfigs } from "../types";
|
||||
|
||||
interface TransactionRowProps {
|
||||
item: ExpenseItem;
|
||||
currency: string;
|
||||
fields: TxnFieldConfigs;
|
||||
}
|
||||
|
||||
export const TransactionRow = React.memo(function TransactionRow({ item, currency, fields }: TransactionRowProps) {
|
||||
const itemCurrency = item.account?.currency ?? currency;
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
px: 2,
|
||||
py: 1.25,
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 2,
|
||||
backgroundColor: "background.paper",
|
||||
transition: "background-color 160ms ease, border-color 160ms ease",
|
||||
"&:hover": {
|
||||
backgroundColor: "action.hover",
|
||||
borderColor: "primary.light",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 40,
|
||||
flexShrink: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{item.entity?.logo ? (
|
||||
<ListCellRenderer field={fields.logo} value={item.entity.logo} />
|
||||
) : (
|
||||
<Box sx={{ width: 40, height: 40, borderRadius: 2, bgcolor: "action.hover" }} />
|
||||
)}
|
||||
</Box>
|
||||
<Box sx={{ flex: "0 1 auto", minWidth: 0 }}>
|
||||
<Typography
|
||||
variant="body1"
|
||||
fontWeight={600}
|
||||
noWrap
|
||||
sx={{ fontSize: "0.9375rem", lineHeight: 1.3 }}
|
||||
>
|
||||
{item.entity ? applyDisplayFormat(item.entity, fields.formats.entity) : "Unknown"}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
|
||||
<Box sx={{ color: "text.secondary" }}>
|
||||
<ListCellRenderer field={fields.occurredAt} value={item.occurred_at} />
|
||||
</Box>
|
||||
{item.account?.name && (
|
||||
<ListCellRenderer field={fields.account} value={item.account} displayFormat={fields.formats.account} />
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<CurrencyField value={item.amount} currency={itemCurrency} large />
|
||||
</Box>
|
||||
);
|
||||
});
|
||||
21
src/common/types.ts
Normal file
21
src/common/types.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { FieldConfig } from "../../react-openapi";
|
||||
|
||||
export interface ExpenseItem {
|
||||
id: string;
|
||||
entity?: { name?: string; type?: string; logo?: string } | null;
|
||||
amount: number;
|
||||
account?: { name?: string; number?: string; type?: string; currency?: string } | null;
|
||||
tags?: { icon?: string; name?: string }[];
|
||||
occurred_at?: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface TxnFieldConfigs {
|
||||
entity: FieldConfig;
|
||||
amount: FieldConfig;
|
||||
account: FieldConfig;
|
||||
occurredAt: FieldConfig;
|
||||
logo: FieldConfig;
|
||||
formats: { entity: string; account: string };
|
||||
}
|
||||
71
src/common/utils/dates.ts
Normal file
71
src/common/utils/dates.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
const DDMMYYYY = /^(\d{2})-(\d{2})-(\d{4})$/;
|
||||
|
||||
export function parseOccurredAt(value?: string): Date {
|
||||
const m = value?.match(DDMMYYYY);
|
||||
if (!m) {
|
||||
throw new Error(`Expense occurred_at is not DD-MM-YYYY: ${value}`);
|
||||
}
|
||||
const [, dd, mm, yyyy] = m;
|
||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||
if (
|
||||
Number.isNaN(d.getTime()) ||
|
||||
d.getDate() !== Number(dd) ||
|
||||
d.getMonth() !== Number(mm) - 1 ||
|
||||
d.getFullYear() !== Number(yyyy)
|
||||
) {
|
||||
throw new Error(`Invalid expense occurred_at date: ${value}`);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
export function isDdmmyyyy(value?: string): boolean {
|
||||
if (!value) return true;
|
||||
const m = value.match(DDMMYYYY);
|
||||
if (!m) return false;
|
||||
const [, dd, mm, yyyy] = m;
|
||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||
return !(
|
||||
Number.isNaN(d.getTime()) ||
|
||||
d.getDate() !== Number(dd) ||
|
||||
d.getMonth() !== Number(mm) - 1 ||
|
||||
d.getFullYear() !== Number(yyyy)
|
||||
);
|
||||
}
|
||||
|
||||
export function parseDdmmyyyy(value: string): Date {
|
||||
const m = value.match(DDMMYYYY);
|
||||
if (!m) throw new Error(`Date is not DD-MM-YYYY: ${value}`);
|
||||
const [, dd, mm, yyyy] = m;
|
||||
const d = new Date(Number(yyyy), Number(mm) - 1, Number(dd));
|
||||
if (
|
||||
Number.isNaN(d.getTime()) ||
|
||||
d.getDate() !== Number(dd) ||
|
||||
d.getMonth() !== Number(mm) - 1 ||
|
||||
d.getFullYear() !== Number(yyyy)
|
||||
) {
|
||||
throw new Error(`Invalid date: ${value}`);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
export function monthKey(value?: string): string {
|
||||
const d = parseOccurredAt(value);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function currentMonthKey(): string {
|
||||
const now = new Date();
|
||||
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function monthLabel(key: string): string {
|
||||
const [y, m] = key.split("-").map(Number);
|
||||
if (!y || !m) return key;
|
||||
const d = new Date(y, m - 1, 1);
|
||||
return d.toLocaleDateString("en-IN", { month: "long", year: "numeric" });
|
||||
}
|
||||
|
||||
export function dateLabel(value: string): string {
|
||||
const d = parseOccurredAt(value);
|
||||
return d.toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });
|
||||
}
|
||||
26
src/common/utils/fieldConfigs.ts
Normal file
26
src/common/utils/fieldConfigs.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { ResourceConfig } from "../../../react-openapi";
|
||||
import type { TxnFieldConfigs } from "../types";
|
||||
|
||||
export function buildTxnFieldConfigs(resources: ResourceConfig[]): TxnFieldConfigs | null {
|
||||
const expensesRes = resources.find((r) => r.name === "expenses");
|
||||
const entitiesRes = resources.find((r) => r.name === "entities");
|
||||
const accountsRes = resources.find((r) => r.name === "accounts");
|
||||
const find = (res: ResourceConfig | undefined, name: string) => res?.fields.find((f) => f.name === name);
|
||||
const entity = find(expensesRes, "entity");
|
||||
const amount = find(expensesRes, "amount");
|
||||
const account = find(expensesRes, "account");
|
||||
const occurredAt = find(expensesRes, "occurred_at");
|
||||
const logo = find(entitiesRes, "logo");
|
||||
if (!entity || !amount || !account || !occurredAt || !logo) return null;
|
||||
return {
|
||||
entity,
|
||||
amount,
|
||||
account,
|
||||
occurredAt,
|
||||
logo,
|
||||
formats: {
|
||||
entity: entitiesRes?.displayFormat ?? "{name}",
|
||||
account: accountsRes?.displayFormat ?? "{name}",
|
||||
},
|
||||
};
|
||||
}
|
||||
161
src/common/utils/transactions.ts
Normal file
161
src/common/utils/transactions.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
import type { ExpenseItem } from "../types";
|
||||
import { dateLabel, monthKey, monthLabel, parseOccurredAt } from "./dates";
|
||||
|
||||
export function isExpense(item: ExpenseItem): boolean {
|
||||
return (item.amount ?? 0) < 0;
|
||||
}
|
||||
|
||||
export interface DateGroup {
|
||||
date: string;
|
||||
label: string;
|
||||
items: ExpenseItem[];
|
||||
}
|
||||
|
||||
export function groupByDate(items: ExpenseItem[]): DateGroup[] {
|
||||
const sorted = [...items].sort(
|
||||
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
||||
);
|
||||
const map = new Map<string, ExpenseItem[]>();
|
||||
for (const item of sorted) {
|
||||
const key = item.occurred_at ?? "";
|
||||
const list = map.get(key) ?? [];
|
||||
list.push(item);
|
||||
map.set(key, list);
|
||||
}
|
||||
return [...map.entries()].map(([date, list]) => ({
|
||||
date,
|
||||
label: dateLabel(date),
|
||||
items: list,
|
||||
}));
|
||||
}
|
||||
|
||||
export type PeriodGranularity = "weekly" | "monthly" | "quarterly" | "yearly";
|
||||
|
||||
export interface PeriodGroup {
|
||||
key: string;
|
||||
label: string;
|
||||
items: ExpenseItem[];
|
||||
spent: number;
|
||||
income: number;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
/** Metrics verbatim from the API's ReportMetrics (camelCased). */
|
||||
export interface ListGroupMetrics {
|
||||
sum: number;
|
||||
count: number;
|
||||
avg: number | null;
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
cadence: number | null;
|
||||
frequency: number | null;
|
||||
}
|
||||
|
||||
export interface ListPeriodGroup extends PeriodGroup {
|
||||
metrics?: ListGroupMetrics;
|
||||
}
|
||||
|
||||
function isoWeekKey(d: Date): string {
|
||||
const date = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
|
||||
const day = date.getUTCDay() || 7;
|
||||
date.setUTCDate(date.getUTCDate() + 4 - day);
|
||||
const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
|
||||
const week = Math.ceil(((date.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
|
||||
return `${date.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function quarterKey(d: Date): string {
|
||||
return `${d.getFullYear()}-Q${Math.floor(d.getMonth() / 3) + 1}`;
|
||||
}
|
||||
|
||||
export function periodKey(value: string | undefined, granularity: PeriodGranularity): string {
|
||||
const d = parseOccurredAt(value);
|
||||
switch (granularity) {
|
||||
case "weekly":
|
||||
return isoWeekKey(d);
|
||||
case "quarterly":
|
||||
return quarterKey(d);
|
||||
case "yearly":
|
||||
return String(d.getFullYear());
|
||||
default:
|
||||
return monthKey(value);
|
||||
}
|
||||
}
|
||||
|
||||
export function periodLabel(key: string, granularity: PeriodGranularity): string {
|
||||
switch (granularity) {
|
||||
case "weekly":
|
||||
case "yearly":
|
||||
return key;
|
||||
case "quarterly": {
|
||||
const [y, q] = key.split("-Q");
|
||||
return `Q${q} ${y}`;
|
||||
}
|
||||
default:
|
||||
return monthLabel(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function groupByPeriod(items: ExpenseItem[], granularity: PeriodGranularity = "monthly"): PeriodGroup[] {
|
||||
const map = new Map<string, ExpenseItem[]>();
|
||||
for (const item of items) {
|
||||
const key = periodKey(item.occurred_at, granularity);
|
||||
const list = map.get(key) ?? [];
|
||||
list.push(item);
|
||||
map.set(key, list);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.map(([key, list]) => {
|
||||
const sorted = [...list].sort(
|
||||
(a, b) => parseOccurredAt(b.occurred_at).getTime() - parseOccurredAt(a.occurred_at).getTime(),
|
||||
);
|
||||
const currency = sorted.find((it) => it.account?.currency)?.account?.currency ?? "INR";
|
||||
const spent = sorted.filter(isExpense).reduce((sum, it) => sum + Math.abs(it.amount ?? 0), 0);
|
||||
const income = sorted.filter((it) => !isExpense(it)).reduce((sum, it) => sum + (it.amount ?? 0), 0);
|
||||
return { key, label: periodLabel(key, granularity), items: sorted, spent, income, currency };
|
||||
})
|
||||
.sort((a, b) => b.key.localeCompare(a.key));
|
||||
}
|
||||
|
||||
export interface TxnMetrics {
|
||||
sum: number;
|
||||
count: number;
|
||||
avg: number | null;
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
cadenceDays: number | null;
|
||||
frequency: number | null;
|
||||
}
|
||||
|
||||
/** Mirrors backend ReportMetrics.compute_metrics over a list of transactions. */
|
||||
export function computeTxnMetrics(items: ExpenseItem[]): TxnMetrics {
|
||||
const amounts = items.filter((it) => typeof it.amount === "number").map((it) => it.amount as number);
|
||||
const empty = { sum: 0, count: 0, avg: null, min: null, max: null, cadenceDays: null, frequency: null };
|
||||
if (amounts.length === 0) {
|
||||
return empty;
|
||||
}
|
||||
const dates = items
|
||||
.map((it) => it.occurred_at)
|
||||
.filter((d): d is string => !!d)
|
||||
.map((d) => parseOccurredAt(d).getTime())
|
||||
.sort((a, b) => a - b);
|
||||
const sum = amounts.reduce((s, a) => s + a, 0);
|
||||
let cadenceDays: number | null = null;
|
||||
if (dates.length >= 2) {
|
||||
const gaps: number[] = [];
|
||||
for (let i = 0; i < dates.length - 1; i += 1) {
|
||||
gaps.push((dates[i + 1] - dates[i]) / 86400000);
|
||||
}
|
||||
cadenceDays = Math.round((gaps.reduce((s, g) => s + g, 0) / gaps.length) * 100) / 100;
|
||||
}
|
||||
const frequency = cadenceDays != null && cadenceDays > 0 ? Math.round((1 / cadenceDays) * 100) / 100 : null;
|
||||
return {
|
||||
sum,
|
||||
count: amounts.length,
|
||||
avg: sum / amounts.length,
|
||||
min: Math.min(...amounts),
|
||||
max: Math.max(...amounts),
|
||||
cadenceDays,
|
||||
frequency,
|
||||
};
|
||||
}
|
||||
@@ -9,7 +9,7 @@ export type FetchRequestStatus =
|
||||
|
||||
export interface FileSource {
|
||||
path: string;
|
||||
format: string;
|
||||
bank: string;
|
||||
raw_lines?: string[];
|
||||
txn_blocks?: Record<string, any>;
|
||||
txn_dicts?: Record<string, any>[];
|
||||
@@ -18,7 +18,7 @@ export interface FileSource {
|
||||
}
|
||||
|
||||
export interface EmailSource {
|
||||
format: string;
|
||||
bank: string;
|
||||
from_email?: string;
|
||||
subject?: string;
|
||||
raw_terms?: string[];
|
||||
@@ -26,9 +26,12 @@ export interface EmailSource {
|
||||
txn_dicts_count?: number;
|
||||
}
|
||||
|
||||
export type PipelineType = "heuristic" | "llm" | "llama_parser";
|
||||
|
||||
export interface FetchRequestCreate {
|
||||
source: FileSource | EmailSource;
|
||||
account_name: string;
|
||||
pipeline?: PipelineType;
|
||||
payor_username?: string;
|
||||
start_date?: string;
|
||||
end_date?: string;
|
||||
|
||||
@@ -14,6 +14,7 @@ export type {
|
||||
SSEEventStep,
|
||||
SSEEventStatus,
|
||||
ProgressMessage,
|
||||
PipelineType,
|
||||
} from "./fetch-requests.models";
|
||||
export { RETRY_MAX, formatApiError } from "./fetch-requests.models";
|
||||
export {
|
||||
|
||||
76
src/main.jsx
76
src/main.jsx
@@ -5,21 +5,26 @@ import {
|
||||
BrowserRouter,
|
||||
Routes,
|
||||
Route,
|
||||
useNavigate
|
||||
useNavigate,
|
||||
useLocation,
|
||||
matchPath
|
||||
} from "react-router-dom";
|
||||
import {
|
||||
Box,
|
||||
CssBaseline,
|
||||
Toolbar
|
||||
CircularProgress
|
||||
} from "@mui/material";
|
||||
import Home from './Home';
|
||||
import FetchRequests from './FetchRequest/FetchRequestCreate';
|
||||
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
|
||||
import Expense from './Expense';
|
||||
import Reports from './Reports/Report';
|
||||
import { AppProvider, useAppContext, Admin, ProfileRoutes } from '../react-openapi';
|
||||
import { AuthProvider, AuthPage, useAuth, ProfileCreate, ProfileEdit, ProfileView } from "../react-auth";
|
||||
import Header from './Header';
|
||||
import Footer from './Footer';
|
||||
import AppTheme from './shared-theme/AppTheme';
|
||||
import { ToastProvider } from './ui/Toast';
|
||||
import { specConfiguration } from './openapi-config';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
@@ -75,35 +80,70 @@ const routerMapping = [
|
||||
{ path: "/register", component: RegisterPage, headerTitle: "Register" },
|
||||
{ path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
|
||||
{ path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
|
||||
{ path: "/expenses", component: Expense, headerTitle: "Expenses" },
|
||||
{ path: "/reports", component: Reports, headerTitle: "Reports" },
|
||||
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
||||
{ path: "/profile/*", component: ProfileRoutes, headerTitle: "Profile" },
|
||||
];
|
||||
|
||||
/** Reads authConfig from AppProvider context and passes it to AuthProvider. */
|
||||
function AppContent() {
|
||||
const { authConfig } = useAppContext();
|
||||
const { authConfig, loading } = useAppContext();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
React.useEffect(() => {
|
||||
const matched = routerMapping.find((route) =>
|
||||
matchPath({ path: route.path, end: false }, location.pathname),
|
||||
);
|
||||
document.title = matched
|
||||
? `${matched.headerTitle} · Khata`
|
||||
: "Khata — Financial Ledger";
|
||||
}, [location.pathname]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", minHeight: "100vh" }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthProvider authConfig={authConfig} onUnauthorized={() => navigate("/login")}>
|
||||
<AppTheme>
|
||||
<CssBaseline enableColorScheme />
|
||||
<Header routerMapping={routerMapping} />
|
||||
<ToastProvider>
|
||||
<Box sx={{ display: "flex", flexDirection: "column", minHeight: "100vh" }}>
|
||||
<Header routerMapping={routerMapping} />
|
||||
|
||||
<Box sx={{ pb: 8 }}>
|
||||
<Toolbar />
|
||||
<Box
|
||||
component="main"
|
||||
key={location.pathname}
|
||||
sx={{
|
||||
flexGrow: 1,
|
||||
width: "100%",
|
||||
animation: "fadeIn 220ms ease-out",
|
||||
"@keyframes fadeIn": {
|
||||
from: { opacity: 0, transform: "translateY(4px)" },
|
||||
to: { opacity: 1, transform: "translateY(0)" },
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Routes>
|
||||
{routerMapping.map(({ path, component: Component }) => (
|
||||
<Route
|
||||
key={path}
|
||||
path={path}
|
||||
element={<Component basePath={path.replace(/\/\*$/, "")} />}
|
||||
/>
|
||||
))}
|
||||
</Routes>
|
||||
</Box>
|
||||
|
||||
<Routes>
|
||||
{routerMapping.map(({ path, component: Component }) => (
|
||||
<Route
|
||||
key={path}
|
||||
path={path}
|
||||
element={<Component basePath={path.replace(/\/\*$/, "")} />}
|
||||
/>
|
||||
))}
|
||||
</Routes>
|
||||
</Box>
|
||||
|
||||
<Footer />
|
||||
<Footer />
|
||||
</Box>
|
||||
</ToastProvider>
|
||||
</AppTheme>
|
||||
</AuthProvider>
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ export const specConfiguration: SpecConfiguration = {
|
||||
resourceConfig: {
|
||||
expenses: {
|
||||
filterOptions: { mode: "client" },
|
||||
fieldTypes: { amount: "currency" },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,21 +1,14 @@
|
||||
import { Theme, alpha, Components } from '@mui/material/styles';
|
||||
import { gray, orange } from '../themePrimitives';
|
||||
import { gray } from '../themePrimitives';
|
||||
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
export const feedbackCustomizations: Components<Theme> = {
|
||||
MuiAlert: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
borderRadius: 10,
|
||||
backgroundColor: orange[100],
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
border: `1px solid ${alpha(orange[300], 0.5)}`,
|
||||
'& .MuiAlert-icon': {
|
||||
color: orange[500],
|
||||
},
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: alpha(orange[900], 0.35),
|
||||
border: `1px solid ${alpha(orange[800], 0.3)}`,
|
||||
backgroundColor: alpha((theme.vars || theme).palette.background.paper, 0.6),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
@@ -24,7 +17,7 @@ export const feedbackCustomizations: Components<Theme> = {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
'& .MuiDialog-paper': {
|
||||
borderRadius: '10px',
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: '1px solid',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
},
|
||||
|
||||
@@ -58,31 +58,26 @@ export const inputsCustomizations: Components<Theme> = {
|
||||
},
|
||||
style: {
|
||||
color: 'white',
|
||||
backgroundColor: gray[900],
|
||||
backgroundImage: `linear-gradient(to bottom, ${gray[700]}, ${gray[800]})`,
|
||||
boxShadow: `inset 0 1px 0 ${gray[600]}, inset 0 -1px 0 1px hsl(220, 0%, 0%)`,
|
||||
border: `1px solid ${gray[700]}`,
|
||||
backgroundColor: brand[500],
|
||||
border: `1px solid ${brand[600]}`,
|
||||
boxShadow: 'none',
|
||||
'&:hover': {
|
||||
backgroundImage: 'none',
|
||||
backgroundColor: gray[700],
|
||||
backgroundColor: brand[600],
|
||||
boxShadow: 'none',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[800],
|
||||
backgroundColor: brand[700],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
color: 'black',
|
||||
backgroundColor: gray[50],
|
||||
backgroundImage: `linear-gradient(to bottom, ${gray[100]}, ${gray[50]})`,
|
||||
boxShadow: 'inset 0 -1px 0 hsl(220, 30%, 80%)',
|
||||
border: `1px solid ${gray[50]}`,
|
||||
color: brand[50],
|
||||
backgroundColor: brand[500],
|
||||
border: `1px solid ${brand[600]}`,
|
||||
'&:hover': {
|
||||
backgroundImage: 'none',
|
||||
backgroundColor: gray[300],
|
||||
backgroundColor: brand[400],
|
||||
boxShadow: 'none',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[400],
|
||||
backgroundColor: brand[300],
|
||||
},
|
||||
}),
|
||||
},
|
||||
@@ -94,18 +89,28 @@ export const inputsCustomizations: Components<Theme> = {
|
||||
},
|
||||
style: {
|
||||
color: 'white',
|
||||
backgroundColor: brand[300],
|
||||
backgroundImage: `linear-gradient(to bottom, ${alpha(brand[400], 0.8)}, ${brand[500]})`,
|
||||
boxShadow: `inset 0 2px 0 ${alpha(brand[200], 0.2)}, inset 0 -2px 0 ${alpha(brand[700], 0.4)}`,
|
||||
border: `1px solid ${brand[500]}`,
|
||||
backgroundColor: gray[900],
|
||||
border: `1px solid ${gray[700]}`,
|
||||
boxShadow: 'none',
|
||||
'&:hover': {
|
||||
backgroundColor: brand[700],
|
||||
backgroundColor: gray[800],
|
||||
boxShadow: 'none',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: brand[700],
|
||||
backgroundImage: 'none',
|
||||
backgroundColor: gray[700],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
color: 'black',
|
||||
backgroundColor: gray[50],
|
||||
border: `1px solid ${gray[300]}`,
|
||||
'&:hover': {
|
||||
backgroundColor: gray[200],
|
||||
boxShadow: 'none',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[300],
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -36,7 +36,7 @@ export const surfacesCustomizations: Components<Theme> = {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
'&:hover': { backgroundColor: gray[50] },
|
||||
'&:focus-visible': { backgroundColor: 'transparent' },
|
||||
...theme.applyStyles('dark', {
|
||||
|
||||
@@ -35,32 +35,37 @@ const defaultTheme = createTheme();
|
||||
|
||||
const customShadows: Shadows = [...defaultTheme.shadows];
|
||||
|
||||
/**
|
||||
* Stripe-like indigo brand. #635BFF ≈ hsl(243, 76%, 59%).
|
||||
* Single brand hue — no multi-colour accents.
|
||||
*/
|
||||
export const brand = {
|
||||
50: 'hsl(210, 100%, 95%)',
|
||||
100: 'hsl(210, 100%, 92%)',
|
||||
200: 'hsl(210, 100%, 80%)',
|
||||
300: 'hsl(210, 100%, 65%)',
|
||||
400: 'hsl(210, 98%, 48%)',
|
||||
500: 'hsl(210, 98%, 42%)',
|
||||
600: 'hsl(210, 98%, 55%)',
|
||||
700: 'hsl(210, 100%, 35%)',
|
||||
800: 'hsl(210, 100%, 16%)',
|
||||
900: 'hsl(210, 100%, 21%)',
|
||||
50: 'hsl(250, 100%, 98%)',
|
||||
100: 'hsl(250, 95%, 95%)',
|
||||
200: 'hsl(249, 92%, 90%)',
|
||||
300: 'hsl(248, 92%, 80%)',
|
||||
400: 'hsl(245, 90%, 72%)',
|
||||
500: 'hsl(243, 76%, 59%)',
|
||||
600: 'hsl(243, 75%, 51%)',
|
||||
700: 'hsl(243, 78%, 42%)',
|
||||
800: 'hsl(242, 76%, 30%)',
|
||||
900: 'hsl(241, 75%, 20%)',
|
||||
};
|
||||
|
||||
/** Cool, neutral grays. */
|
||||
export const gray = {
|
||||
50: 'hsl(220, 35%, 97%)',
|
||||
100: 'hsl(220, 30%, 94%)',
|
||||
200: 'hsl(220, 20%, 88%)',
|
||||
300: 'hsl(220, 20%, 80%)',
|
||||
400: 'hsl(220, 20%, 65%)',
|
||||
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%)',
|
||||
200: 'hsl(220, 20%, 89%)',
|
||||
300: 'hsl(220, 17%, 80%)',
|
||||
400: 'hsl(220, 15%, 64%)',
|
||||
500: 'hsl(220, 14%, 45%)',
|
||||
600: 'hsl(220, 13%, 36%)',
|
||||
700: 'hsl(220, 13%, 27%)',
|
||||
750: 'hsl(220, 13%, 20%)',
|
||||
800: 'hsl(220, 12%, 12%)',
|
||||
850: 'hsl(220, 10%, 8%)',
|
||||
900: 'hsl(220, 9%, 6%)',
|
||||
};
|
||||
|
||||
export const green = {
|
||||
@@ -116,27 +121,39 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
palette: {
|
||||
mode,
|
||||
primary: {
|
||||
light: brand[200],
|
||||
main: brand[400],
|
||||
light: brand[400],
|
||||
main: brand[500],
|
||||
dark: brand[700],
|
||||
contrastText: brand[50],
|
||||
...(mode === 'dark' && {
|
||||
contrastText: brand[50],
|
||||
light: 'hsl(210, 50%, 65%)',
|
||||
main: 'hsl(210, 55%, 55%)',
|
||||
dark: 'hsl(210, 50%, 35%)',
|
||||
light: 'hsl(245, 85%, 70%)',
|
||||
main: 'hsl(243, 76%, 64%)',
|
||||
dark: 'hsl(243, 78%, 48%)',
|
||||
}),
|
||||
},
|
||||
secondary: {
|
||||
light: gray[300],
|
||||
main: gray[600],
|
||||
dark: gray[800],
|
||||
contrastText: gray[50],
|
||||
...(mode === 'dark' && {
|
||||
light: gray[200],
|
||||
main: gray[400],
|
||||
dark: gray[600],
|
||||
contrastText: gray[900],
|
||||
}),
|
||||
},
|
||||
info: {
|
||||
light: brand[100],
|
||||
main: brand[300],
|
||||
main: brand[400],
|
||||
dark: brand[600],
|
||||
contrastText: gray[50],
|
||||
...(mode === 'dark' && {
|
||||
contrastText: 'hsl(210, 30%, 80%)',
|
||||
light: 'hsl(210, 40%, 50%)',
|
||||
main: 'hsl(210, 35%, 40%)',
|
||||
dark: 'hsl(210, 30%, 25%)',
|
||||
light: 'hsl(245, 60%, 60%)',
|
||||
main: 'hsl(243, 55%, 52%)',
|
||||
dark: 'hsl(243, 50%, 38%)',
|
||||
}),
|
||||
},
|
||||
warning: {
|
||||
@@ -174,7 +191,7 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
},
|
||||
divider: mode === 'dark' ? 'hsla(0, 0%, 100%, 0.08)' : alpha(gray[300], 0.4),
|
||||
background: {
|
||||
default: 'hsl(0, 0%, 99%)',
|
||||
default: 'hsl(0, 0%, 100%)',
|
||||
paper: 'hsl(220, 35%, 97%)',
|
||||
...(mode === 'dark' && { default: darkBg, paper: darkPaper }),
|
||||
},
|
||||
@@ -208,242 +225,73 @@ export const getDesignTokens = (mode: PaletteMode) => {
|
||||
typography: {
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
h1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(48),
|
||||
fontSize: defaultTheme.typography.pxToRem(40),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: -0.5,
|
||||
lineHeight: 1.1,
|
||||
letterSpacing: '-0.025em',
|
||||
},
|
||||
h2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(36),
|
||||
fontSize: defaultTheme.typography.pxToRem(32),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: '-0.02em',
|
||||
},
|
||||
h3: {
|
||||
fontSize: defaultTheme.typography.pxToRem(30),
|
||||
lineHeight: 1.2,
|
||||
fontSize: defaultTheme.typography.pxToRem(26),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.25,
|
||||
letterSpacing: '-0.015em',
|
||||
},
|
||||
h4: {
|
||||
fontSize: defaultTheme.typography.pxToRem(24),
|
||||
fontSize: defaultTheme.typography.pxToRem(20),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.4,
|
||||
letterSpacing: '-0.01em',
|
||||
},
|
||||
h5: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.4,
|
||||
letterSpacing: '-0.005em',
|
||||
},
|
||||
h6: {
|
||||
fontSize: defaultTheme.typography.pxToRem(16),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.5,
|
||||
},
|
||||
h5: {
|
||||
fontSize: defaultTheme.typography.pxToRem(20),
|
||||
fontWeight: 600,
|
||||
},
|
||||
h6: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
fontWeight: 600,
|
||||
},
|
||||
subtitle1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
fontSize: defaultTheme.typography.pxToRem(16),
|
||||
fontWeight: 500,
|
||||
},
|
||||
subtitle2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontSize: defaultTheme.typography.pxToRem(13),
|
||||
fontWeight: 500,
|
||||
},
|
||||
body1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontSize: defaultTheme.typography.pxToRem(15),
|
||||
lineHeight: 1.5,
|
||||
},
|
||||
body2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontWeight: 400,
|
||||
lineHeight: 1.45,
|
||||
},
|
||||
caption: {
|
||||
fontSize: defaultTheme.typography.pxToRem(12),
|
||||
fontWeight: 400,
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
overline: {
|
||||
fontSize: defaultTheme.typography.pxToRem(11),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.5,
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.06em',
|
||||
},
|
||||
},
|
||||
shape: {
|
||||
borderRadius: 8,
|
||||
borderRadius: 6,
|
||||
},
|
||||
shadows: customShadows,
|
||||
};
|
||||
};
|
||||
|
||||
export const colorSchemes = {
|
||||
light: {
|
||||
palette: {
|
||||
primary: {
|
||||
light: brand[200],
|
||||
main: brand[400],
|
||||
dark: brand[700],
|
||||
contrastText: brand[50],
|
||||
},
|
||||
info: {
|
||||
light: brand[100],
|
||||
main: brand[300],
|
||||
dark: brand[600],
|
||||
contrastText: gray[50],
|
||||
},
|
||||
warning: {
|
||||
light: orange[300],
|
||||
main: orange[400],
|
||||
dark: orange[800],
|
||||
},
|
||||
error: {
|
||||
light: red[300],
|
||||
main: red[400],
|
||||
dark: red[800],
|
||||
},
|
||||
success: {
|
||||
light: green[300],
|
||||
main: green[400],
|
||||
dark: green[800],
|
||||
},
|
||||
grey: {
|
||||
...gray,
|
||||
},
|
||||
divider: alpha(gray[300], 0.4),
|
||||
background: {
|
||||
default: 'hsl(0, 0%, 99%)',
|
||||
paper: 'hsl(220, 35%, 97%)',
|
||||
},
|
||||
text: {
|
||||
primary: gray[800],
|
||||
secondary: gray[600],
|
||||
warning: orange[400],
|
||||
},
|
||||
action: {
|
||||
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',
|
||||
},
|
||||
},
|
||||
dark: {
|
||||
palette: {
|
||||
primary: {
|
||||
contrastText: brand[50],
|
||||
light: 'hsl(210, 50%, 65%)',
|
||||
main: 'hsl(210, 55%, 55%)',
|
||||
dark: 'hsl(210, 50%, 35%)',
|
||||
},
|
||||
info: {
|
||||
contrastText: 'hsl(210, 30%, 80%)',
|
||||
light: 'hsl(210, 40%, 50%)',
|
||||
main: 'hsl(210, 35%, 40%)',
|
||||
dark: 'hsl(210, 30%, 25%)',
|
||||
},
|
||||
warning: {
|
||||
light: 'hsl(45, 60%, 55%)',
|
||||
main: 'hsl(45, 55%, 45%)',
|
||||
dark: 'hsl(45, 50%, 30%)',
|
||||
},
|
||||
error: {
|
||||
light: 'hsl(0, 55%, 60%)',
|
||||
main: 'hsl(0, 55%, 50%)',
|
||||
dark: 'hsl(0, 50%, 35%)',
|
||||
},
|
||||
success: {
|
||||
light: 'hsl(120, 40%, 55%)',
|
||||
main: 'hsl(120, 40%, 45%)',
|
||||
dark: 'hsl(120, 35%, 30%)',
|
||||
},
|
||||
grey: {
|
||||
...gray,
|
||||
},
|
||||
divider: 'hsla(0, 0%, 100%, 0.08)',
|
||||
background: {
|
||||
default: darkBg,
|
||||
paper: darkPaper,
|
||||
},
|
||||
text: {
|
||||
primary: 'hsl(0, 0%, 92%)',
|
||||
secondary: 'hsl(0, 0%, 60%)',
|
||||
},
|
||||
action: {
|
||||
hover: 'hsla(0, 0%, 100%, 0.06)',
|
||||
selected: 'hsla(0, 0%, 100%, 0.1)',
|
||||
},
|
||||
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)',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const typography = {
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
h1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(48),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: -0.5,
|
||||
},
|
||||
h2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(36),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
},
|
||||
h3: {
|
||||
fontSize: defaultTheme.typography.pxToRem(30),
|
||||
lineHeight: 1.2,
|
||||
},
|
||||
h4: {
|
||||
fontSize: defaultTheme.typography.pxToRem(24),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.5,
|
||||
},
|
||||
h5: {
|
||||
fontSize: defaultTheme.typography.pxToRem(20),
|
||||
fontWeight: 600,
|
||||
},
|
||||
h6: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
fontWeight: 600,
|
||||
},
|
||||
subtitle1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
},
|
||||
subtitle2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontWeight: 500,
|
||||
},
|
||||
body1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
},
|
||||
body2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontWeight: 400,
|
||||
},
|
||||
caption: {
|
||||
fontSize: defaultTheme.typography.pxToRem(12),
|
||||
fontWeight: 400,
|
||||
},
|
||||
};
|
||||
|
||||
export const shape = {
|
||||
borderRadius: 8,
|
||||
};
|
||||
|
||||
// @ts-ignore
|
||||
const defaultShadows: Shadows = [
|
||||
'none',
|
||||
'var(--template-palette-baseShadow)',
|
||||
...defaultTheme.shadows.slice(2),
|
||||
];
|
||||
export const shadows = defaultShadows;
|
||||
};
|
||||
57
src/ui/EmptyState.tsx
Normal file
57
src/ui/EmptyState.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import * as React from "react";
|
||||
import { Box, Typography, Button } from "@mui/material";
|
||||
|
||||
interface EmptyStateProps {
|
||||
icon?: React.ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
actionLabel?: string;
|
||||
onAction?: () => void;
|
||||
}
|
||||
|
||||
export function EmptyState({ icon, title, description, actionLabel, onAction }: EmptyStateProps) {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
textAlign: "center",
|
||||
py: 6,
|
||||
px: 3,
|
||||
}}
|
||||
>
|
||||
{icon && (
|
||||
<Box
|
||||
sx={{
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 2,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: "action.hover",
|
||||
color: "text.secondary",
|
||||
mb: 2,
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
)}
|
||||
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
|
||||
{title}
|
||||
</Typography>
|
||||
{description && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ maxWidth: 360, lineHeight: 1.6, mb: 2 }}>
|
||||
{description}
|
||||
</Typography>
|
||||
)}
|
||||
{actionLabel && onAction && (
|
||||
<Button variant="contained" size="small" onClick={onAction} sx={{ mt: 1 }}>
|
||||
{actionLabel}
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
67
src/ui/PageHeader.tsx
Normal file
67
src/ui/PageHeader.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import * as React from "react";
|
||||
import { Box, Breadcrumbs, Typography, Link } from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
|
||||
|
||||
export interface Crumb {
|
||||
label: string;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
interface PageHeaderProps {
|
||||
crumbs: Crumb[];
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
actions?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function PageHeader({ crumbs, title, subtitle, actions }: PageHeaderProps) {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<Box sx={{ mb: 3 }}>
|
||||
<Breadcrumbs
|
||||
separator={<NavigateNextIcon fontSize="small" sx={{ color: "text.disabled" }} />}
|
||||
aria-label="breadcrumb"
|
||||
sx={{ mb: 1 }}
|
||||
>
|
||||
{crumbs.map((crumb, i) => {
|
||||
const isLast = i === crumbs.length - 1;
|
||||
if (isLast || !crumb.path) {
|
||||
return (
|
||||
<Typography key={crumb.label} variant="body2" color="text.secondary">
|
||||
{crumb.label}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Link
|
||||
key={crumb.label}
|
||||
component="button"
|
||||
underline="hover"
|
||||
color="text.primary"
|
||||
onClick={() => navigate(crumb.path!)}
|
||||
sx={{ fontWeight: 500, fontSize: "0.875rem" }}
|
||||
>
|
||||
{crumb.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</Breadcrumbs>
|
||||
|
||||
<Box sx={{ display: "flex", alignItems: "flex-start", gap: 2, flexWrap: "wrap" }}>
|
||||
<Box sx={{ flex: 1, minWidth: 0 }}>
|
||||
<Typography variant="h4" fontWeight={700} sx={{ letterSpacing: "-0.02em" }}>
|
||||
{title}
|
||||
</Typography>
|
||||
{subtitle && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
|
||||
{subtitle}
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
{actions && <Box sx={{ display: "flex", gap: 1, alignItems: "center" }}>{actions}</Box>}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
52
src/ui/Toast.tsx
Normal file
52
src/ui/Toast.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import * as React from "react";
|
||||
import { Snackbar, Alert, AlertColor } from "@mui/material";
|
||||
|
||||
interface ToastState {
|
||||
open: boolean;
|
||||
message: string;
|
||||
severity: AlertColor;
|
||||
}
|
||||
|
||||
interface ToastContextValue {
|
||||
showToast: (message: string, severity?: AlertColor) => void;
|
||||
}
|
||||
|
||||
const ToastContext = React.createContext<ToastContextValue | null>(null);
|
||||
|
||||
export function ToastProvider({ children }: { children: React.ReactNode }) {
|
||||
const [toast, setToast] = React.useState<ToastState>({ open: false, message: "", severity: "success" });
|
||||
const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const showToast = React.useCallback((message: string, severity: AlertColor = "success") => {
|
||||
if (timerRef.current) clearTimeout(timerRef.current);
|
||||
setToast({ open: true, message, severity });
|
||||
timerRef.current = setTimeout(() => setToast((t) => ({ ...t, open: false })), 4000);
|
||||
}, []);
|
||||
|
||||
const handleClose = (_?: React.SyntheticEvent | Event, reason?: string) => {
|
||||
if (reason === "clickaway") return;
|
||||
setToast((t) => ({ ...t, open: false }));
|
||||
};
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ showToast }}>
|
||||
{children}
|
||||
<Snackbar
|
||||
open={toast.open}
|
||||
autoHideDuration={4000}
|
||||
onClose={handleClose}
|
||||
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
|
||||
>
|
||||
<Alert severity={toast.severity} onClose={handleClose} sx={{ borderRadius: 2, minWidth: 260 }}>
|
||||
{toast.message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useToast(): ToastContextValue {
|
||||
const ctx = React.useContext(ToastContext);
|
||||
if (!ctx) throw new Error("useToast must be used within a ToastProvider");
|
||||
return ctx;
|
||||
}
|
||||
Reference in New Issue
Block a user