mirror of
https://github.com/elisiariocouto/leggen.git
synced 2025-12-13 21:52:40 +00:00
Compare commits
54 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9fee74e2a9 | ||
|
|
7c06a1d8b9 | ||
|
|
d78f481192 | ||
|
|
b32853e8fd | ||
|
|
0750c41b7b | ||
|
|
1cd63731a3 | ||
|
|
38fddeb281 | ||
|
|
0205e5be0d | ||
|
|
ca7968cc3c | ||
|
|
e6da6ee9ab | ||
|
|
8802d24789 | ||
|
|
d3954f079b | ||
|
|
0b68038739 | ||
|
|
d36568da54 | ||
|
|
473f126d3e | ||
|
|
222bb2ec64 | ||
|
|
22ec0e36b1 | ||
|
|
0122913052 | ||
|
|
7f2a4634c5 | ||
|
|
704c3d4cb7 | ||
|
|
ef7c026db9 | ||
|
|
dc3522220a | ||
|
|
1693b3a50d | ||
|
|
460c5af6ea | ||
|
|
5a8614e019 | ||
|
|
ae5d034d4b | ||
|
|
d4edf69f2c | ||
|
|
d3a1696d4d | ||
|
|
24792744f9 | ||
|
|
b9ca74e7e6 | ||
|
|
a8f704129b | ||
|
|
62cd55e48f | ||
|
|
e4e3f885ea | ||
|
|
36d698f7ce | ||
|
|
d211a14703 | ||
|
|
c332642e64 | ||
|
|
27f3f2dbba | ||
|
|
02748181b9 | ||
|
|
dcb1f39ff1 | ||
|
|
eb38264c68 | ||
|
|
65404848aa | ||
|
|
3f2ff21eac | ||
|
|
61f9592095 | ||
|
|
76a30d23af | ||
|
|
e9924e9d96 | ||
|
|
340e1a3235 | ||
|
|
4ce56fdc04 | ||
|
|
dd24a0e0d3 | ||
|
|
ff9bccc0e9 | ||
|
|
83bb3fcef2 | ||
|
|
fbb9e33279 | ||
|
|
8228974c0c | ||
|
|
848eccb35b | ||
|
|
25747d7d37 |
8
.github/workflows/ci.yml
vendored
8
.github/workflows/ci.yml
vendored
@@ -2,9 +2,9 @@ name: CI
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ "main", "dev" ]
|
branches: ["main", "dev"]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ "main", "dev" ]
|
branches: ["main", "dev"]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test-python:
|
test-python:
|
||||||
@@ -43,8 +43,8 @@ jobs:
|
|||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
node-version: "20"
|
||||||
cache: 'npm'
|
cache: "npm"
|
||||||
cache-dependency-path: frontend/package-lock.json
|
cache-dependency-path: frontend/package-lock.json
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
|
|||||||
21
.github/workflows/release.yml
vendored
21
.github/workflows/release.yml
vendored
@@ -143,24 +143,21 @@ jobs:
|
|||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Install git-cliff
|
|
||||||
run: |
|
|
||||||
wget -qO- https://github.com/orhun/git-cliff/releases/latest/download/git-cliff-2.10.0-x86_64-unknown-linux-gnu.tar.gz | tar xz
|
|
||||||
sudo mv git-cliff-*/git-cliff /usr/local/bin/
|
|
||||||
|
|
||||||
- name: Generate release notes
|
- name: Generate release notes
|
||||||
|
uses: orhun/git-cliff-action@v4
|
||||||
id: release_notes
|
id: release_notes
|
||||||
run: |
|
with:
|
||||||
echo "notes<<EOF" >> $GITHUB_OUTPUT
|
config: cliff.toml
|
||||||
git-cliff --current >> $GITHUB_OUTPUT
|
args: --current
|
||||||
echo "EOF" >> $GITHUB_OUTPUT
|
env:
|
||||||
|
GITHUB_REPO: ${{ github.repository }}
|
||||||
|
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ github.ref_name }}
|
||||||
name: Release ${{ github.ref_name }}
|
name: Release ${{ github.ref_name }}
|
||||||
body: ${{ steps.release_notes.outputs.notes }}
|
body: ${{ steps.release_notes.outputs.content }}
|
||||||
draft: false
|
draft: false
|
||||||
prerelease: false
|
prerelease: false
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -165,3 +165,4 @@ leggen.db
|
|||||||
*.db
|
*.db
|
||||||
config.toml
|
config.toml
|
||||||
.claude/
|
.claude/
|
||||||
|
.playwright-mcp/
|
||||||
|
|||||||
11
.mcp.json
11
.mcp.json
@@ -2,16 +2,11 @@
|
|||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"shadcn": {
|
"shadcn": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": [
|
"args": ["shadcn@latest", "mcp"]
|
||||||
"shadcn@latest",
|
|
||||||
"mcp"
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"browsermcp": {
|
"playwright": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": [
|
"args": ["@playwright/mcp@latest"]
|
||||||
"@browsermcp/mcp@latest"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ repos:
|
|||||||
- id: trailing-whitespace
|
- id: trailing-whitespace
|
||||||
exclude: ".*\\.md$"
|
exclude: ".*\\.md$"
|
||||||
- id: end-of-file-fixer
|
- id: end-of-file-fixer
|
||||||
- id: check-added-large-files
|
|
||||||
- repo: local
|
- repo: local
|
||||||
hooks:
|
hooks:
|
||||||
- id: mypy
|
- id: mypy
|
||||||
|
|||||||
16
AGENTS.md
16
AGENTS.md
@@ -41,7 +41,7 @@ The command outputs instructions for setting the required environment variable t
|
|||||||
uv run leggen server
|
uv run leggen server
|
||||||
```
|
```
|
||||||
- For development mode with auto-reload: `uv run leggen server --reload`
|
- For development mode with auto-reload: `uv run leggen server --reload`
|
||||||
- API will be available at `http://localhost:8000` with docs at `http://localhost:8000/docs`
|
- API will be available at `http://localhost:8000` with docs at `http://localhost:8000/api/v1/docs`
|
||||||
|
|
||||||
### Start the Frontend
|
### Start the Frontend
|
||||||
1. Navigate to the frontend directory: `cd frontend`
|
1. Navigate to the frontend directory: `cd frontend`
|
||||||
@@ -81,6 +81,7 @@ The command outputs instructions for setting the required environment variable t
|
|||||||
- **Naming**: PascalCase for components, camelCase for variables/functions
|
- **Naming**: PascalCase for components, camelCase for variables/functions
|
||||||
- **Types**: Use `import type` for type-only imports, define interfaces/types
|
- **Types**: Use `import type` for type-only imports, define interfaces/types
|
||||||
- **Styling**: Tailwind CSS with `clsx` utility for conditional classes
|
- **Styling**: Tailwind CSS with `clsx` utility for conditional classes
|
||||||
|
- **UI Components**: shadcn/ui components for consistent design system
|
||||||
- **Icons**: lucide-react with consistent naming
|
- **Icons**: lucide-react with consistent naming
|
||||||
- **Data fetching**: @tanstack/react-query with proper error handling
|
- **Data fetching**: @tanstack/react-query with proper error handling
|
||||||
- **Components**: Functional components with hooks, proper TypeScript typing
|
- **Components**: Functional components with hooks, proper TypeScript typing
|
||||||
@@ -94,7 +95,7 @@ The command outputs instructions for setting the required environment variable t
|
|||||||
- **Routes**: `frontend/src/routes/` - TanStack Router file-based routing
|
- **Routes**: `frontend/src/routes/` - TanStack Router file-based routing
|
||||||
|
|
||||||
### Key Components Location
|
### Key Components Location
|
||||||
- **UI Components**: `frontend/src/components/ui/` - Reusable UI primitives
|
- **UI Components**: `frontend/src/components/ui/` - shadcn/ui components and reusable UI primitives
|
||||||
- **Feature Components**: `frontend/src/components/` - Main app components
|
- **Feature Components**: `frontend/src/components/` - Main app components
|
||||||
- **Pages**: `frontend/src/routes/` - Route components (index.tsx, transactions.tsx, etc.)
|
- **Pages**: `frontend/src/routes/` - Route components (index.tsx, transactions.tsx, etc.)
|
||||||
- **Hooks**: `frontend/src/hooks/` - Custom React hooks
|
- **Hooks**: `frontend/src/hooks/` - Custom React hooks
|
||||||
@@ -121,9 +122,20 @@ The command outputs instructions for setting the required environment variable t
|
|||||||
- Avoid including specific numbers, counts, or data-dependent information that may become outdated
|
- Avoid including specific numbers, counts, or data-dependent information that may become outdated
|
||||||
- **Security**: Never log sensitive data, use environment variables for secrets
|
- **Security**: Never log sensitive data, use environment variables for secrets
|
||||||
|
|
||||||
|
## AI Development Support
|
||||||
|
|
||||||
|
### shadcn/ui Integration
|
||||||
|
This project uses shadcn/ui for consistent UI components. The MCP server is configured for AI agents to:
|
||||||
|
- Search and browse available shadcn/ui components
|
||||||
|
- View component implementation details and examples
|
||||||
|
- Generate proper installation commands for new components
|
||||||
|
|
||||||
|
Use the shadcn MCP tools when working with UI components to ensure consistency with the existing design system.
|
||||||
|
|
||||||
## Contributing Guidelines
|
## Contributing Guidelines
|
||||||
|
|
||||||
This repository follows conventional changelog practices. Refer to `CONTRIBUTING.md` for detailed contribution guidelines including:
|
This repository follows conventional changelog practices. Refer to `CONTRIBUTING.md` for detailed contribution guidelines including:
|
||||||
- Commit message format and scoping
|
- Commit message format and scoping
|
||||||
- Release process using `scripts/release.sh`
|
- Release process using `scripts/release.sh`
|
||||||
- Pre-commit hooks setup with `pre-commit install`
|
- Pre-commit hooks setup with `pre-commit install`
|
||||||
|
- When the pre-commit fails, the commit is canceled
|
||||||
|
|||||||
285
CHANGELOG.md
285
CHANGELOG.md
@@ -1,4 +1,289 @@
|
|||||||
|
|
||||||
|
## 2025.10.2 (2025/10/06)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **frontend:** Improve nginx config. ([d78f4811](https://github.com/elisiariocouto/leggen/commit/d78f4811922df7e637abe65b1d0b1157dd331c3c))
|
||||||
|
- **frontend:** Include default mime types. ([7c06a1d8](https://github.com/elisiariocouto/leggen/commit/7c06a1d8b9bca3da2c481d9e89e7564cfffe32a3))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.10.1 (2025/10/05)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **frontend:** Fix PWA caching system, remove prompts. ([1cd63731](https://github.com/elisiariocouto/leggen/commit/1cd63731a35a1c77a59d7ae1a898ad8f22e362e4))
|
||||||
|
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
- Improve documentation, add gif showing web app. ([0750c41b](https://github.com/elisiariocouto/leggen/commit/0750c41b7b6634900ec19b1701d58b06346028e3))
|
||||||
|
|
||||||
|
|
||||||
|
### Refactor
|
||||||
|
|
||||||
|
- **frontend:** Standardize button styling using shadcn Button component. ([38fddeb2](https://github.com/elisiariocouto/leggen/commit/38fddeb281588de41d8ff6292c1dd48443a059a4))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.10.0 (2025/10/01)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **gocardless:** Increase timeout to 30 seconds, some requests take some time. ([ca7968cc](https://github.com/elisiariocouto/leggen/commit/ca7968cc3c625e243fe2d75590a9e56f3100072b))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.26 (2025/09/30)
|
||||||
|
|
||||||
|
### Debug
|
||||||
|
|
||||||
|
- Log different sets of GoCardless rate limits. ([8802d247](https://github.com/elisiariocouto/leggen/commit/8802d24789cbb8e854d857a0d7cc89a25a26f378))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.25 (2025/09/30)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **api:** Fix S3 backup path-style configuration and improve UX. ([22ec0e36](https://github.com/elisiariocouto/leggen/commit/22ec0e36b11e5b017075bee51de0423a53ec4648))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **api:** Add S3 backup functionality to backend ([7f2a4634](https://github.com/elisiariocouto/leggen/commit/7f2a4634c51814b6785433a25ce42d20aea0558c))
|
||||||
|
- **frontend:** Add S3 backup UI and complete backup functionality ([01229130](https://github.com/elisiariocouto/leggen/commit/0122913052793bcbf011cb557ef182be21c5de93))
|
||||||
|
- **frontend:** Add ability to list backups and create a backup on demand. ([473f126d](https://github.com/elisiariocouto/leggen/commit/473f126d3e699521172539f2ca0bff0579ccee51))
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Log more rate limit headers. ([d36568da](https://github.com/elisiariocouto/leggen/commit/d36568da540d4fb4ae1fa10b322a3fa77dcc5360))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.24 (2025/09/25)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Add comprehensive bank account management system. ([ef7c026d](https://github.com/elisiariocouto/leggen/commit/ef7c026db9911cc3be8d5f48e42a4d7beb4b9d0a))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.24 (2025/09/25)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Add comprehensive bank account management system. ([ef7c026d](https://github.com/elisiariocouto/leggen/commit/ef7c026db9911cc3be8d5f48e42a4d7beb4b9d0a))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.23 (2025/09/24)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **cli:** Fix API URL handling for subpaths and improve client robustness. ([ae5d034d](https://github.com/elisiariocouto/leggen/commit/ae5d034d4b1da785e3dc240c1d60c2cae7de8010))
|
||||||
|
- Correct sync trigger types from manual to scheduled/retry. ([460c5af6](https://github.com/elisiariocouto/leggen/commit/460c5af6ea343ef5685b716413d01d7a30fa9acf))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Add version-based cache invalidation for PWA updates ([d4edf69f](https://github.com/elisiariocouto/leggen/commit/d4edf69f2cea2515a00435ee974116948057148d))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.23 (2025/09/24)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **cli:** Fix API URL handling for subpaths and improve client robustness. ([ae5d034d](https://github.com/elisiariocouto/leggen/commit/ae5d034d4b1da785e3dc240c1d60c2cae7de8010))
|
||||||
|
- Correct sync trigger types from manual to scheduled/retry. ([460c5af6](https://github.com/elisiariocouto/leggen/commit/460c5af6ea343ef5685b716413d01d7a30fa9acf))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Add version-based cache invalidation for PWA updates ([d4edf69f](https://github.com/elisiariocouto/leggen/commit/d4edf69f2cea2515a00435ee974116948057148d))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.22 (2025/09/24)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **api:** Add automatic token refresh on 401 errors in GoCardless service. ([36d698f7](https://github.com/elisiariocouto/leggen/commit/36d698f7ce05c7db0e4b07dd07979de2c70b053e))
|
||||||
|
- **api:** Fix banks API test fixtures to match GoCardless response format. ([24792744](https://github.com/elisiariocouto/leggen/commit/24792744f9660063e1a3abb9ed8e925fea9a5e60))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **api:** Add separate sync failure notifications. ([e4e3f885](https://github.com/elisiariocouto/leggen/commit/e4e3f885eab1d45b0e10465ca04eb3f74e9c5a4d))
|
||||||
|
- **api:** Add bank logo support and fix banks endpoint type errors. ([b9ca74e7](https://github.com/elisiariocouto/leggen/commit/b9ca74e7e67c3877728b749a42f15f0c0d906561))
|
||||||
|
- **frontend:** Improve System page and TransactionsTable UX. ([62cd55e4](https://github.com/elisiariocouto/leggen/commit/62cd55e48fff7c2f5db9dd8230a7bd500e8f6eed))
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Add pre-commit instructions to AGENTS.md. ([a8f70412](https://github.com/elisiariocouto/leggen/commit/a8f704129b2453e604cf2ab776791ba1e91e6fc7))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.22 (2025/09/24)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **api:** Add automatic token refresh on 401 errors in GoCardless service. ([36d698f7](https://github.com/elisiariocouto/leggen/commit/36d698f7ce05c7db0e4b07dd07979de2c70b053e))
|
||||||
|
- **api:** Fix banks API test fixtures to match GoCardless response format. ([24792744](https://github.com/elisiariocouto/leggen/commit/24792744f9660063e1a3abb9ed8e925fea9a5e60))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **api:** Add separate sync failure notifications. ([e4e3f885](https://github.com/elisiariocouto/leggen/commit/e4e3f885eab1d45b0e10465ca04eb3f74e9c5a4d))
|
||||||
|
- **api:** Add bank logo support and fix banks endpoint type errors. ([b9ca74e7](https://github.com/elisiariocouto/leggen/commit/b9ca74e7e67c3877728b749a42f15f0c0d906561))
|
||||||
|
- **frontend:** Improve System page and TransactionsTable UX. ([62cd55e4](https://github.com/elisiariocouto/leggen/commit/62cd55e48fff7c2f5db9dd8230a7bd500e8f6eed))
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Add pre-commit instructions to AGENTS.md. ([a8f70412](https://github.com/elisiariocouto/leggen/commit/a8f704129b2453e604cf2ab776791ba1e91e6fc7))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.21 (2025/09/22)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **frontend:** Remove duplicate padding from Analytics page for consistent layout ([27f3f2db](https://github.com/elisiariocouto/leggen/commit/27f3f2dbba91777234769cca08de5dbe8b378f10))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Implement notification settings with separate drawers and improved design. ([c332642e](https://github.com/elisiariocouto/leggen/commit/c332642e648cb0a29100b500c03e17ae322845f8))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.21 (2025/09/22)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **frontend:** Remove duplicate padding from Analytics page for consistent layout ([27f3f2db](https://github.com/elisiariocouto/leggen/commit/27f3f2dbba91777234769cca08de5dbe8b378f10))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Implement notification settings with separate drawers and improved design. ([c332642e](https://github.com/elisiariocouto/leggen/commit/c332642e648cb0a29100b500c03e17ae322845f8))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.20 (2025/09/22)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **api:** Add sync operations tracking and database storage ([61f95920](https://github.com/elisiariocouto/leggen/commit/61f9592095220f47b758e19a63d70096deb35a92))
|
||||||
|
- **frontend:** Rename notifications page to System Status and add sync operations section ([3f2ff21e](https://github.com/elisiariocouto/leggen/commit/3f2ff21eac2c24e04d5957bbd15a6b8a5d0c021d))
|
||||||
|
- Consolidate version display to use health endpoint. ([76a30d23](https://github.com/elisiariocouto/leggen/commit/76a30d23af07466ecfd571e7b7bb6724412652c1))
|
||||||
|
|
||||||
|
|
||||||
|
### Refactor
|
||||||
|
|
||||||
|
- **frontend:** Reorganize pages with tabbed Settings and focused System page ([65404848](https://github.com/elisiariocouto/leggen/commit/65404848aa27cfcb11a371c194ca533b17cb08ff))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.20 (2025/09/22)
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **api:** Add sync operations tracking and database storage ([61f95920](https://github.com/elisiariocouto/leggen/commit/61f9592095220f47b758e19a63d70096deb35a92))
|
||||||
|
- **frontend:** Rename notifications page to System Status and add sync operations section ([3f2ff21e](https://github.com/elisiariocouto/leggen/commit/3f2ff21eac2c24e04d5957bbd15a6b8a5d0c021d))
|
||||||
|
- Consolidate version display to use health endpoint. ([76a30d23](https://github.com/elisiariocouto/leggen/commit/76a30d23af07466ecfd571e7b7bb6724412652c1))
|
||||||
|
|
||||||
|
|
||||||
|
### Refactor
|
||||||
|
|
||||||
|
- **frontend:** Reorganize pages with tabbed Settings and focused System page ([65404848](https://github.com/elisiariocouto/leggen/commit/65404848aa27cfcb11a371c194ca533b17cb08ff))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.19 (2025/09/21)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **frontend:** Close mobile sidebar on navigation item click ([dd24a0e0](https://github.com/elisiariocouto/leggen/commit/dd24a0e0d34c3b2ff37bc75b50162768b4d15cc5))
|
||||||
|
- **frontend:** Resolve mobile horizontal scroll in Time Period filters ([4ce56fdc](https://github.com/elisiariocouto/leggen/commit/4ce56fdc042b0dbf3442a1ab201392700add90d6))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Add version display in header near connection status ([340e1a32](https://github.com/elisiariocouto/leggen/commit/340e1a3235916566a4e403e9ec7b82ea799fbffd))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.19 (2025/09/21)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **frontend:** Close mobile sidebar on navigation item click ([dd24a0e0](https://github.com/elisiariocouto/leggen/commit/dd24a0e0d34c3b2ff37bc75b50162768b4d15cc5))
|
||||||
|
- **frontend:** Resolve mobile horizontal scroll in Time Period filters ([4ce56fdc](https://github.com/elisiariocouto/leggen/commit/4ce56fdc042b0dbf3442a1ab201392700add90d6))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Add version display in header near connection status ([340e1a32](https://github.com/elisiariocouto/leggen/commit/340e1a3235916566a4e403e9ec7b82ea799fbffd))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.18 (2025/09/19)
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
- Add instructions for shadcn/ui. ([83bb3fce](https://github.com/elisiariocouto/leggen/commit/83bb3fcef20d21a210bc53ce77aa533d37771668))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Transform layout to use shadcn dashboard-01 with iOS PWA safe area support. ([fbb9e332](https://github.com/elisiariocouto/leggen/commit/fbb9e33279028a6a7ccf46c3696a012ec16a9ca7))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.18 (2025/09/19)
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
- Add instructions for shadcn/ui. ([83bb3fce](https://github.com/elisiariocouto/leggen/commit/83bb3fcef20d21a210bc53ce77aa533d37771668))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- **frontend:** Transform layout to use shadcn dashboard-01 with iOS PWA safe area support. ([fbb9e332](https://github.com/elisiariocouto/leggen/commit/fbb9e33279028a6a7ccf46c3696a012ec16a9ca7))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.17 (2025/09/18)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **api:** Prevent duplicate notifications for existing transactions during sync. ([25747d7d](https://github.com/elisiariocouto/leggen/commit/25747d7d372e291090764a6814f9d8d0b76aea3b))
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Format files. ([848eccb3](https://github.com/elisiariocouto/leggen/commit/848eccb35b910c8121d15611547dca8da0b12756))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2025.9.17 (2025/09/18)
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- **api:** Prevent duplicate notifications for existing transactions during sync. ([25747d7d](https://github.com/elisiariocouto/leggen/commit/25747d7d372e291090764a6814f9d8d0b76aea3b))
|
||||||
|
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Format files. ([848eccb3](https://github.com/elisiariocouto/leggen/commit/848eccb35b910c8121d15611547dca8da0b12756))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## 2025.9.16 (2025/09/18)
|
## 2025.9.16 (2025/09/18)
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|||||||
@@ -1,9 +1,19 @@
|
|||||||
# Contributing
|
# Contributing
|
||||||
|
|
||||||
Install Poetry and run `poetry install` to install dependencies. Then run `poetry shell` to activate the virtual environment.
|
This project uses **uv** for Python dependency management and **shadcn/ui** for frontend components.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
Install uv and run `uv sync` to install dependencies.
|
||||||
|
|
||||||
Run `pre-commit install` to install the pre-commit hooks.
|
Run `pre-commit install` to install the pre-commit hooks.
|
||||||
|
|
||||||
|
## Frontend Development
|
||||||
|
The frontend uses shadcn/ui components for consistent design. When adding new UI components:
|
||||||
|
- Check if a shadcn/ui component exists for your use case
|
||||||
|
- Follow the existing component patterns in `frontend/src/components/ui/`
|
||||||
|
- Use Tailwind CSS classes for styling
|
||||||
|
- Ensure components are accessible and follow the design system
|
||||||
|
|
||||||
## Commit messages
|
## Commit messages
|
||||||
|
|
||||||
type(scope/[subscope]): Title starting with uppercase and sentence ending with period.
|
type(scope/[subscope]): Title starting with uppercase and sentence ending with period.
|
||||||
|
|||||||
279
README.md
279
README.md
@@ -1,13 +1,21 @@
|
|||||||
# 💲 leggen
|
# 💲 leggen
|
||||||
|
|
||||||
An Open Banking CLI and API service for managing bank connections and transactions.
|
|
||||||
|
|
||||||
This tool provides a **unified command-line interface** (`leggen`) with both CLI commands and an integrated **FastAPI backend service**, plus a **React Web Interface** to connect to banks using the GoCardless Open Banking API.
|
A self hosted Open Banking Dashboard, API and CLI for managing bank connections and transactions.
|
||||||
|
|
||||||
Having your bank data accessible through both CLI and REST API gives you the power to backup, analyze, create reports, and integrate with other applications.
|
Having your bank data accessible through both CLI and REST API gives you the power to backup, analyze, create reports, and integrate with other applications.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## 🛠️ Technologies
|
## 🛠️ Technologies
|
||||||
|
|
||||||
|
### Frontend
|
||||||
|
- [React](https://reactjs.org/): Modern web interface with TypeScript
|
||||||
|
- [Vite](https://vitejs.dev/): Fast build tool and development server
|
||||||
|
- [Tailwind CSS](https://tailwindcss.com/): Utility-first CSS framework
|
||||||
|
- [shadcn/ui](https://ui.shadcn.com/): Modern component system built on Radix UI
|
||||||
|
- [TanStack Query](https://tanstack.com/query): Powerful data synchronization for React
|
||||||
|
|
||||||
### 🔌 API & Backend
|
### 🔌 API & Backend
|
||||||
- [FastAPI](https://fastapi.tiangolo.com/): High-performance async API backend (integrated into `leggen server`)
|
- [FastAPI](https://fastapi.tiangolo.com/): High-performance async API backend (integrated into `leggen server`)
|
||||||
- [GoCardless Open Banking API](https://developer.gocardless.com/bank-account-data/overview): for connecting to banks
|
- [GoCardless Open Banking API](https://developer.gocardless.com/bank-account-data/overview): for connecting to banks
|
||||||
@@ -16,11 +24,6 @@ Having your bank data accessible through both CLI and REST API gives you the pow
|
|||||||
### 📦 Storage
|
### 📦 Storage
|
||||||
- [SQLite](https://www.sqlite.org): for storing transactions, simple and easy to use
|
- [SQLite](https://www.sqlite.org): for storing transactions, simple and easy to use
|
||||||
|
|
||||||
### Frontend
|
|
||||||
- [React](https://reactjs.org/): Modern web interface with TypeScript
|
|
||||||
- [Vite](https://vitejs.dev/): Fast build tool and development server
|
|
||||||
- [Tailwind CSS](https://tailwindcss.com/): Utility-first CSS framework
|
|
||||||
- [TanStack Query](https://tanstack.com/query): Powerful data synchronization for React
|
|
||||||
|
|
||||||
## ✨ Features
|
## ✨ Features
|
||||||
|
|
||||||
@@ -53,10 +56,9 @@ Having your bank data accessible through both CLI and REST API gives you the pow
|
|||||||
1. Create a GoCardless account at [https://gocardless.com/bank-account-data/](https://gocardless.com/bank-account-data/)
|
1. Create a GoCardless account at [https://gocardless.com/bank-account-data/](https://gocardless.com/bank-account-data/)
|
||||||
2. Get your API credentials (key and secret)
|
2. Get your API credentials (key and secret)
|
||||||
|
|
||||||
### Installation Options
|
### Installation
|
||||||
|
|
||||||
#### Option 1: Docker Compose (Recommended)
|
#### Docker Compose (Recommended)
|
||||||
The easiest way to get started is with Docker Compose, which includes both the React frontend and FastAPI backend:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Clone the repository
|
# Clone the repository
|
||||||
@@ -67,50 +69,11 @@ cd leggen
|
|||||||
mkdir -p data && cp config.example.toml data/config.toml
|
mkdir -p data && cp config.example.toml data/config.toml
|
||||||
# Edit data/config.toml with your GoCardless credentials
|
# Edit data/config.toml with your GoCardless credentials
|
||||||
|
|
||||||
# Start all services (frontend + backend)
|
# Start all services
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
|
|
||||||
# Access the web interface at http://localhost:3000
|
# Access the web interface at http://localhost:3000
|
||||||
# API is available at http://localhost:8000
|
# API documentation at http://localhost:3000/api/v1/docs
|
||||||
```
|
|
||||||
|
|
||||||
#### Production Deployment
|
|
||||||
|
|
||||||
For production deployment using published Docker images:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Clone the repository
|
|
||||||
git clone https://github.com/elisiariocouto/leggen.git
|
|
||||||
cd leggen
|
|
||||||
|
|
||||||
# Create your configuration
|
|
||||||
mkdir -p data && cp config.example.toml data/config.toml
|
|
||||||
# Edit data/config.toml with your GoCardless credentials
|
|
||||||
|
|
||||||
# Start production services
|
|
||||||
docker compose up -d
|
|
||||||
|
|
||||||
# Access the web interface at http://localhost:3000
|
|
||||||
# API is available at http://localhost:8000
|
|
||||||
```
|
|
||||||
|
|
||||||
### Development vs Production
|
|
||||||
|
|
||||||
- **Development**: Use `docker compose -f compose.dev.yml up -d` (builds from source)
|
|
||||||
- **Production**: Use `docker compose up -d` (uses published images)
|
|
||||||
|
|
||||||
#### Option 2: Local Development
|
|
||||||
For development or local installation:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Install with uv (recommended) or pip
|
|
||||||
uv sync # or pip install -e .
|
|
||||||
|
|
||||||
# Start the API service
|
|
||||||
uv run leggen server --reload # Development mode with auto-reload
|
|
||||||
|
|
||||||
# Use the CLI (in another terminal)
|
|
||||||
uv run leggen --help
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Configuration
|
### Configuration
|
||||||
@@ -152,214 +115,22 @@ case_sensitive = ["SpecificStore"]
|
|||||||
|
|
||||||
## 📖 Usage
|
## 📖 Usage
|
||||||
|
|
||||||
### API Service (`leggen server`)
|
### Web Interface
|
||||||
|
Access the React web interface at `http://localhost:3000` after starting the services.
|
||||||
|
|
||||||
Start the FastAPI backend service:
|
### API Service
|
||||||
|
Visit `http://localhost:3000/api/v1/docs` for interactive API documentation.
|
||||||
|
|
||||||
|
### CLI Commands
|
||||||
```bash
|
```bash
|
||||||
# Production mode
|
leggen status # Check connection status
|
||||||
leggen server
|
leggen bank add # Connect to a new bank
|
||||||
|
leggen balances # View account balances
|
||||||
# Development mode with auto-reload
|
leggen transactions # List transactions
|
||||||
leggen server --reload
|
leggen sync # Trigger background sync
|
||||||
|
|
||||||
# Custom host and port
|
|
||||||
leggen server --host 127.0.0.1 --port 8080
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**API Documentation**: Visit `http://localhost:8000/docs` for interactive API documentation.
|
For more options, run `leggen --help` or `leggen <command> --help`.
|
||||||
|
|
||||||
### CLI Commands (`leggen`)
|
|
||||||
|
|
||||||
#### Basic Commands
|
|
||||||
```bash
|
|
||||||
# Check connection status
|
|
||||||
leggen status
|
|
||||||
|
|
||||||
# Connect to a new bank
|
|
||||||
leggen bank add
|
|
||||||
|
|
||||||
# View account balances
|
|
||||||
leggen balances
|
|
||||||
|
|
||||||
# List recent transactions
|
|
||||||
leggen transactions --limit 20
|
|
||||||
|
|
||||||
# View detailed transactions
|
|
||||||
leggen transactions --full
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Sync Operations
|
|
||||||
```bash
|
|
||||||
# Start background sync
|
|
||||||
leggen sync
|
|
||||||
|
|
||||||
# Synchronous sync (wait for completion)
|
|
||||||
leggen sync --wait
|
|
||||||
|
|
||||||
# Force sync (override running sync)
|
|
||||||
leggen sync --force --wait
|
|
||||||
```
|
|
||||||
|
|
||||||
#### API Integration
|
|
||||||
```bash
|
|
||||||
# Use custom API URL
|
|
||||||
leggen --api-url http://localhost:8080 status
|
|
||||||
|
|
||||||
# Set via environment variable
|
|
||||||
export LEGGEN_API_URL=http://localhost:8080
|
|
||||||
leggen status
|
|
||||||
```
|
|
||||||
|
|
||||||
### Docker Usage
|
|
||||||
|
|
||||||
#### Development (build from source)
|
|
||||||
```bash
|
|
||||||
# Start development services
|
|
||||||
docker compose -f compose.dev.yml up -d
|
|
||||||
|
|
||||||
# View service status
|
|
||||||
docker compose -f compose.dev.yml ps
|
|
||||||
|
|
||||||
# Check logs
|
|
||||||
docker compose -f compose.dev.yml logs frontend
|
|
||||||
docker compose -f compose.dev.yml logs leggen-server
|
|
||||||
|
|
||||||
# Stop development services
|
|
||||||
docker compose -f compose.dev.yml down
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Production (use published images)
|
|
||||||
```bash
|
|
||||||
# Start production services
|
|
||||||
docker compose up -d
|
|
||||||
|
|
||||||
# View service status
|
|
||||||
docker compose ps
|
|
||||||
|
|
||||||
# Check logs
|
|
||||||
docker compose logs frontend
|
|
||||||
docker compose logs leggen-server
|
|
||||||
|
|
||||||
# Access the web interface at http://localhost:3000
|
|
||||||
# API documentation at http://localhost:8000/docs
|
|
||||||
|
|
||||||
# Stop production services
|
|
||||||
docker compose down
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🔌 API Endpoints
|
|
||||||
|
|
||||||
The FastAPI backend provides comprehensive REST endpoints:
|
|
||||||
|
|
||||||
### Banks & Connections
|
|
||||||
- `GET /api/v1/banks/institutions?country=PT` - List available banks
|
|
||||||
- `POST /api/v1/banks/connect` - Create bank connection
|
|
||||||
- `GET /api/v1/banks/status` - Connection status
|
|
||||||
- `GET /api/v1/banks/countries` - Supported countries
|
|
||||||
|
|
||||||
### Accounts & Balances
|
|
||||||
- `GET /api/v1/accounts` - List all accounts
|
|
||||||
- `GET /api/v1/accounts/{id}` - Account details
|
|
||||||
- `GET /api/v1/accounts/{id}/balances` - Account balances
|
|
||||||
- `GET /api/v1/accounts/{id}/transactions` - Account transactions
|
|
||||||
|
|
||||||
### Transactions
|
|
||||||
- `GET /api/v1/transactions` - All transactions with filtering
|
|
||||||
- `GET /api/v1/transactions/stats` - Transaction statistics
|
|
||||||
|
|
||||||
### Sync & Scheduling
|
|
||||||
- `POST /api/v1/sync` - Trigger background sync
|
|
||||||
- `POST /api/v1/sync/now` - Synchronous sync
|
|
||||||
- `GET /api/v1/sync/status` - Sync status
|
|
||||||
- `GET/PUT /api/v1/sync/scheduler` - Scheduler configuration
|
|
||||||
|
|
||||||
### Notifications
|
|
||||||
- `GET/PUT /api/v1/notifications/settings` - Manage notifications
|
|
||||||
- `POST /api/v1/notifications/test` - Test notifications
|
|
||||||
|
|
||||||
## 🛠️ Development
|
|
||||||
|
|
||||||
### Local Development Setup
|
|
||||||
```bash
|
|
||||||
# Clone and setup
|
|
||||||
git clone https://github.com/elisiariocouto/leggen.git
|
|
||||||
cd leggen
|
|
||||||
|
|
||||||
# Install dependencies
|
|
||||||
uv sync
|
|
||||||
|
|
||||||
# Start API service with auto-reload
|
|
||||||
uv run leggen server --reload
|
|
||||||
|
|
||||||
# Use CLI commands
|
|
||||||
uv run leggen status
|
|
||||||
```
|
|
||||||
|
|
||||||
### Testing
|
|
||||||
|
|
||||||
Run the comprehensive test suite with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Run all tests
|
|
||||||
uv run pytest
|
|
||||||
|
|
||||||
# Run unit tests only
|
|
||||||
uv run pytest tests/unit/
|
|
||||||
|
|
||||||
# Run with verbose output
|
|
||||||
uv run pytest tests/unit/ -v
|
|
||||||
|
|
||||||
# Run specific test files
|
|
||||||
uv run pytest tests/unit/test_config.py -v
|
|
||||||
uv run pytest tests/unit/test_scheduler.py -v
|
|
||||||
uv run pytest tests/unit/test_api_banks.py -v
|
|
||||||
|
|
||||||
# Run tests by markers
|
|
||||||
uv run pytest -m unit # Unit tests
|
|
||||||
uv run pytest -m api # API endpoint tests
|
|
||||||
uv run pytest -m cli # CLI tests
|
|
||||||
```
|
|
||||||
|
|
||||||
The test suite includes:
|
|
||||||
- **Configuration management tests** - TOML config loading/saving
|
|
||||||
- **API endpoint tests** - FastAPI route testing with mocked dependencies
|
|
||||||
- **CLI API client tests** - HTTP client integration testing
|
|
||||||
- **Background scheduler tests** - APScheduler job management
|
|
||||||
- **Mock data and fixtures** - Realistic test data for banks, accounts, transactions
|
|
||||||
|
|
||||||
### Code Structure
|
|
||||||
```
|
|
||||||
leggen/ # CLI application
|
|
||||||
├── commands/ # CLI command implementations
|
|
||||||
├── utils/ # Shared utilities
|
|
||||||
├── api/ # FastAPI API routes and models
|
|
||||||
├── services/ # Business logic
|
|
||||||
├── background/ # Background job scheduler
|
|
||||||
└── api_client.py # API client for server communication
|
|
||||||
|
|
||||||
tests/ # Test suite
|
|
||||||
├── conftest.py # Shared test fixtures
|
|
||||||
└── unit/ # Unit tests
|
|
||||||
├── test_config.py # Configuration tests
|
|
||||||
├── test_scheduler.py # Background scheduler tests
|
|
||||||
├── test_api_banks.py # Banks API tests
|
|
||||||
├── test_api_accounts.py # Accounts API tests
|
|
||||||
└── test_api_client.py # CLI API client tests
|
|
||||||
```
|
|
||||||
|
|
||||||
### Contributing
|
|
||||||
1. Fork the repository
|
|
||||||
2. Create a feature branch
|
|
||||||
3. Make your changes with tests
|
|
||||||
4. Submit a pull request
|
|
||||||
|
|
||||||
The repository uses GitHub Actions for CI/CD:
|
|
||||||
- **CI**: Runs Python tests (`uv run pytest`) and frontend linting/build on every push
|
|
||||||
- **Release**: Creates GitHub releases with changelog when tags are pushed
|
|
||||||
|
|
||||||
## ⚠️ Notes
|
## ⚠️ Notes
|
||||||
- This project is in active development
|
- This project is in active development
|
||||||
- GoCardless API rate limits apply
|
|
||||||
- Some banks may require additional authorization steps
|
|
||||||
- Docker images are automatically built and published on releases
|
|
||||||
|
|||||||
@@ -28,3 +28,13 @@ enabled = true
|
|||||||
[filters]
|
[filters]
|
||||||
case_insensitive = ["salary", "utility"]
|
case_insensitive = ["salary", "utility"]
|
||||||
case_sensitive = ["SpecificStore"]
|
case_sensitive = ["SpecificStore"]
|
||||||
|
|
||||||
|
# Optional: S3 backup configuration
|
||||||
|
[backup.s3]
|
||||||
|
access_key_id = "your-s3-access-key"
|
||||||
|
secret_access_key = "your-s3-secret-key"
|
||||||
|
bucket_name = "your-bucket-name"
|
||||||
|
region = "us-east-1"
|
||||||
|
# endpoint_url = "https://custom-s3-endpoint.com" # Optional: for custom S3-compatible endpoints
|
||||||
|
path_style = false # Set to true for path-style addressing
|
||||||
|
enabled = true
|
||||||
|
|||||||
BIN
docs/leggen_demo.gif
Normal file
BIN
docs/leggen_demo.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 548 KiB |
@@ -1,33 +1,102 @@
|
|||||||
server {
|
server {
|
||||||
|
|
||||||
|
# MIME types for PWA
|
||||||
|
include mime.types;
|
||||||
|
types {
|
||||||
|
application/manifest+json webmanifest;
|
||||||
|
}
|
||||||
|
|
||||||
listen 80;
|
listen 80;
|
||||||
server_name localhost;
|
server_name localhost;
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
|
|
||||||
|
# Trust proxy headers from Caddy/upstream proxy
|
||||||
|
set_real_ip_from 0.0.0.0/0;
|
||||||
|
real_ip_header X-Forwarded-For;
|
||||||
|
real_ip_recursive on;
|
||||||
|
|
||||||
|
# Security headers
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||||
|
|
||||||
# Enable gzip compression
|
# Enable gzip compression
|
||||||
gzip on;
|
gzip on;
|
||||||
gzip_vary on;
|
gzip_vary on;
|
||||||
gzip_min_length 1024;
|
gzip_min_length 1024;
|
||||||
gzip_proxied expired no-cache no-store private auth;
|
gzip_proxied expired no-cache no-store private auth;
|
||||||
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
|
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json application/manifest+json image/svg+xml;
|
||||||
|
|
||||||
# Handle client-side routing
|
# Service worker - no cache, must revalidate
|
||||||
|
location ~ ^/(sw\.js|workbox-.*\.js)$ {
|
||||||
|
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
|
||||||
|
add_header Pragma "no-cache" always;
|
||||||
|
add_header Expires "0" always;
|
||||||
|
add_header Service-Worker-Allowed "/" always;
|
||||||
|
types {
|
||||||
|
application/javascript js;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# PWA manifest - short cache with revalidation
|
||||||
|
location ~ ^/manifest\.webmanifest$ {
|
||||||
|
add_header Cache-Control "public, max-age=3600, must-revalidate" always;
|
||||||
|
types {
|
||||||
|
application/manifest+json webmanifest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Handle client-side routing (SPA)
|
||||||
location / {
|
location / {
|
||||||
try_files $uri $uri/ /index.html;
|
autoindex off;
|
||||||
|
expires off;
|
||||||
|
add_header Cache-Control "public, max-age=0, s-maxage=0, must-revalidate" always;
|
||||||
|
try_files $uri $uri/ /index.html =404;
|
||||||
}
|
}
|
||||||
|
|
||||||
# API proxy to backend (configurable via API_BACKEND_URL env var)
|
# API proxy to backend (configurable via API_BACKEND_URL env var)
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass ${API_BACKEND_URL};
|
proxy_pass ${API_BACKEND_URL};
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $http_host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
|
||||||
|
proxy_set_header X-Forwarded-Host $http_x_forwarded_host;
|
||||||
|
proxy_redirect off;
|
||||||
|
|
||||||
|
# Timeouts
|
||||||
|
proxy_connect_timeout 60s;
|
||||||
|
proxy_send_timeout 60s;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
}
|
}
|
||||||
|
|
||||||
# Cache static assets
|
# Cache static assets with immutable flag
|
||||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
|
location ~* \.(css|js)$ {
|
||||||
expires 1y;
|
expires 1y;
|
||||||
add_header Cache-Control "public, immutable";
|
add_header Cache-Control "public, immutable" always;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cache images and icons
|
||||||
|
location ~* \.(png|jpg|jpeg|gif|ico|svg|webp)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable" always;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cache fonts (if any are added later)
|
||||||
|
location ~* \.(woff|woff2|ttf|eot|otf)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable" always;
|
||||||
|
add_header Access-Control-Allow-Origin "*" always;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Other static files
|
||||||
|
location ~* \.(xml|txt)$ {
|
||||||
|
expires 1d;
|
||||||
|
add_header Cache-Control "public, must-revalidate" always;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,17 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||||
<link rel="icon" href="/favicon.svg" sizes="any" type="image/svg+xml" />
|
<link rel="icon" href="/favicon.svg" sizes="any" type="image/svg+xml" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
<meta
|
||||||
|
name="viewport"
|
||||||
|
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
|
||||||
|
/>
|
||||||
<title>Leggen</title>
|
<title>Leggen</title>
|
||||||
|
|
||||||
<!-- PWA Meta Tags -->
|
<!-- PWA Meta Tags -->
|
||||||
<meta name="description" content="Personal finance management application" />
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Personal finance management application"
|
||||||
|
/>
|
||||||
<meta name="application-name" content="Leggen" />
|
<meta name="application-name" content="Leggen" />
|
||||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||||
@@ -21,8 +27,16 @@
|
|||||||
|
|
||||||
<!-- Dynamic theme-color - will be updated by JavaScript -->
|
<!-- Dynamic theme-color - will be updated by JavaScript -->
|
||||||
<meta name="theme-color" content="#0b74de" id="theme-color-meta" />
|
<meta name="theme-color" content="#0b74de" id="theme-color-meta" />
|
||||||
<meta name="msapplication-navbutton-color" content="#0b74de" id="ms-theme-color-meta" />
|
<meta
|
||||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" id="apple-status-bar-meta" />
|
name="msapplication-navbutton-color"
|
||||||
|
content="#0b74de"
|
||||||
|
id="ms-theme-color-meta"
|
||||||
|
/>
|
||||||
|
<meta
|
||||||
|
name="apple-mobile-web-app-status-bar-style"
|
||||||
|
content="default"
|
||||||
|
id="apple-status-bar-meta"
|
||||||
|
/>
|
||||||
|
|
||||||
<!-- Icons -->
|
<!-- Icons -->
|
||||||
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" />
|
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" />
|
||||||
|
|||||||
752
frontend/package-lock.json
generated
752
frontend/package-lock.json
generated
@@ -8,11 +8,26 @@
|
|||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/modifiers": "^9.0.0",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"@radix-ui/react-avatar": "^1.1.10",
|
||||||
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
|
"@radix-ui/react-label": "^2.1.7",
|
||||||
"@radix-ui/react-popover": "^1.1.15",
|
"@radix-ui/react-popover": "^1.1.15",
|
||||||
"@radix-ui/react-progress": "^1.1.7",
|
"@radix-ui/react-progress": "^1.1.7",
|
||||||
"@radix-ui/react-select": "^2.2.6",
|
"@radix-ui/react-select": "^2.2.6",
|
||||||
|
"@radix-ui/react-separator": "^1.1.7",
|
||||||
"@radix-ui/react-slot": "^1.2.3",
|
"@radix-ui/react-slot": "^1.2.3",
|
||||||
|
"@radix-ui/react-switch": "^1.2.6",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.13",
|
||||||
|
"@radix-ui/react-toggle": "^1.1.10",
|
||||||
|
"@radix-ui/react-toggle-group": "^1.1.11",
|
||||||
|
"@radix-ui/react-tooltip": "^1.2.8",
|
||||||
|
"@tabler/icons-react": "^3.35.0",
|
||||||
"@tailwindcss/forms": "^0.5.10",
|
"@tailwindcss/forms": "^0.5.10",
|
||||||
"@tanstack/react-query": "^5.87.1",
|
"@tanstack/react-query": "^5.87.1",
|
||||||
"@tanstack/react-router": "^1.131.36",
|
"@tanstack/react-router": "^1.131.36",
|
||||||
@@ -25,15 +40,18 @@
|
|||||||
"cmdk": "^1.1.1",
|
"cmdk": "^1.1.1",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"lucide-react": "^0.542.0",
|
"lucide-react": "^0.542.0",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"react": "^19.1.1",
|
"react": "^19.1.1",
|
||||||
"react-day-picker": "^9.10.0",
|
"react-day-picker": "^9.10.0",
|
||||||
"react-dom": "^19.1.1",
|
"react-dom": "^19.1.1",
|
||||||
"recharts": "^3.2.0",
|
"recharts": "^2.15.4",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
"tailwindcss": "^3.4.17",
|
"tailwindcss": "^3.4.17",
|
||||||
"tailwindcss-animate": "^1.0.7"
|
"tailwindcss-animate": "^1.0.7",
|
||||||
|
"vaul": "^1.1.2",
|
||||||
|
"zod": "^3.25.76"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.33.0",
|
"@eslint/js": "^9.33.0",
|
||||||
@@ -1637,7 +1655,6 @@
|
|||||||
"version": "7.28.4",
|
"version": "7.28.4",
|
||||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",
|
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",
|
||||||
"integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
|
"integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
@@ -1721,6 +1738,73 @@
|
|||||||
"integrity": "sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==",
|
"integrity": "sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@dnd-kit/accessibility": {
|
||||||
|
"version": "3.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||||
|
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/core": {
|
||||||
|
"version": "6.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||||
|
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/accessibility": "^3.1.1",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0",
|
||||||
|
"react-dom": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/modifiers": {
|
||||||
|
"version": "9.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/modifiers/-/modifiers-9.0.0.tgz",
|
||||||
|
"integrity": "sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.0",
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/sortable": {
|
||||||
|
"version": "10.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||||
|
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.0",
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/utilities": {
|
||||||
|
"version": "3.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||||
|
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@dotenvx/dotenvx": {
|
"node_modules/@dotenvx/dotenvx": {
|
||||||
"version": "1.50.1",
|
"version": "1.50.1",
|
||||||
"resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-1.50.1.tgz",
|
"resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-1.50.1.tgz",
|
||||||
@@ -3492,6 +3576,63 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-avatar": {
|
||||||
|
"version": "1.1.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.1.10.tgz",
|
||||||
|
"integrity": "sha512-V8piFfWapM5OmNCXTzVQY+E1rDa53zY+MQ4Y7356v4fFz6vqCyUtIz2rUD44ZEdwg78/jKmMJHj07+C/Z/rcog==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-use-callback-ref": "1.1.1",
|
||||||
|
"@radix-ui/react-use-is-hydrated": "0.1.0",
|
||||||
|
"@radix-ui/react-use-layout-effect": "1.1.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-checkbox": {
|
||||||
|
"version": "1.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.3.tgz",
|
||||||
|
"integrity": "sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-compose-refs": "1.1.2",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-presence": "1.1.5",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2",
|
||||||
|
"@radix-ui/react-use-previous": "1.1.1",
|
||||||
|
"@radix-ui/react-use-size": "1.1.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-collection": {
|
"node_modules/@radix-ui/react-collection": {
|
||||||
"version": "1.1.7",
|
"version": "1.1.7",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",
|
||||||
@@ -3626,6 +3767,35 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-dropdown-menu": {
|
||||||
|
"version": "2.1.16",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-dropdown-menu/-/react-dropdown-menu-2.1.16.tgz",
|
||||||
|
"integrity": "sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-compose-refs": "1.1.2",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-id": "1.1.1",
|
||||||
|
"@radix-ui/react-menu": "2.1.16",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-focus-guards": {
|
"node_modules/@radix-ui/react-focus-guards": {
|
||||||
"version": "1.1.3",
|
"version": "1.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-focus-guards/-/react-focus-guards-1.1.3.tgz",
|
||||||
@@ -3684,6 +3854,69 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-label": {
|
||||||
|
"version": "2.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.7.tgz",
|
||||||
|
"integrity": "sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-primitive": "2.1.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-menu": {
|
||||||
|
"version": "2.1.16",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-menu/-/react-menu-2.1.16.tgz",
|
||||||
|
"integrity": "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-collection": "1.1.7",
|
||||||
|
"@radix-ui/react-compose-refs": "1.1.2",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-direction": "1.1.1",
|
||||||
|
"@radix-ui/react-dismissable-layer": "1.1.11",
|
||||||
|
"@radix-ui/react-focus-guards": "1.1.3",
|
||||||
|
"@radix-ui/react-focus-scope": "1.1.7",
|
||||||
|
"@radix-ui/react-id": "1.1.1",
|
||||||
|
"@radix-ui/react-popper": "1.2.8",
|
||||||
|
"@radix-ui/react-portal": "1.1.9",
|
||||||
|
"@radix-ui/react-presence": "1.1.5",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-roving-focus": "1.1.11",
|
||||||
|
"@radix-ui/react-slot": "1.2.3",
|
||||||
|
"@radix-ui/react-use-callback-ref": "1.1.1",
|
||||||
|
"aria-hidden": "^1.2.4",
|
||||||
|
"react-remove-scroll": "^2.6.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-popover": {
|
"node_modules/@radix-ui/react-popover": {
|
||||||
"version": "1.1.15",
|
"version": "1.1.15",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.15.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.15.tgz",
|
||||||
@@ -3848,6 +4081,37 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-roving-focus": {
|
||||||
|
"version": "1.1.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz",
|
||||||
|
"integrity": "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-collection": "1.1.7",
|
||||||
|
"@radix-ui/react-compose-refs": "1.1.2",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-direction": "1.1.1",
|
||||||
|
"@radix-ui/react-id": "1.1.1",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-use-callback-ref": "1.1.1",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-select": {
|
"node_modules/@radix-ui/react-select": {
|
||||||
"version": "2.2.6",
|
"version": "2.2.6",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.2.6.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.2.6.tgz",
|
||||||
@@ -3891,6 +4155,29 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-separator": {
|
||||||
|
"version": "1.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.7.tgz",
|
||||||
|
"integrity": "sha512-0HEb8R9E8A+jZjvmFCy/J4xhbXy3TV+9XSnGJ3KvTtjlIUy/YQ/p6UYZvi7YbeoeXdyU9+Y3scizK6hkY37baA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-primitive": "2.1.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-slot": {
|
"node_modules/@radix-ui/react-slot": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
|
||||||
@@ -3909,6 +4196,153 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-switch": {
|
||||||
|
"version": "1.2.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.2.6.tgz",
|
||||||
|
"integrity": "sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-compose-refs": "1.1.2",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2",
|
||||||
|
"@radix-ui/react-use-previous": "1.1.1",
|
||||||
|
"@radix-ui/react-use-size": "1.1.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-tabs": {
|
||||||
|
"version": "1.1.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.13.tgz",
|
||||||
|
"integrity": "sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-direction": "1.1.1",
|
||||||
|
"@radix-ui/react-id": "1.1.1",
|
||||||
|
"@radix-ui/react-presence": "1.1.5",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-roving-focus": "1.1.11",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-toggle": {
|
||||||
|
"version": "1.1.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.10.tgz",
|
||||||
|
"integrity": "sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-toggle-group": {
|
||||||
|
"version": "1.1.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.1.11.tgz",
|
||||||
|
"integrity": "sha512-5umnS0T8JQzQT6HbPyO7Hh9dgd82NmS36DQr+X/YJ9ctFNCiiQd6IJAYYZ33LUwm8M+taCz5t2ui29fHZc4Y6Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-direction": "1.1.1",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-roving-focus": "1.1.11",
|
||||||
|
"@radix-ui/react-toggle": "1.1.10",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-tooltip": {
|
||||||
|
"version": "1.2.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.2.8.tgz",
|
||||||
|
"integrity": "sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/primitive": "1.1.3",
|
||||||
|
"@radix-ui/react-compose-refs": "1.1.2",
|
||||||
|
"@radix-ui/react-context": "1.1.2",
|
||||||
|
"@radix-ui/react-dismissable-layer": "1.1.11",
|
||||||
|
"@radix-ui/react-id": "1.1.1",
|
||||||
|
"@radix-ui/react-popper": "1.2.8",
|
||||||
|
"@radix-ui/react-portal": "1.1.9",
|
||||||
|
"@radix-ui/react-presence": "1.1.5",
|
||||||
|
"@radix-ui/react-primitive": "2.1.3",
|
||||||
|
"@radix-ui/react-slot": "1.2.3",
|
||||||
|
"@radix-ui/react-use-controllable-state": "1.2.2",
|
||||||
|
"@radix-ui/react-visually-hidden": "1.2.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-use-callback-ref": {
|
"node_modules/@radix-ui/react-use-callback-ref": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
|
||||||
@@ -3979,6 +4413,24 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-use-is-hydrated": {
|
||||||
|
"version": "0.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.0.tgz",
|
||||||
|
"integrity": "sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"use-sync-external-store": "^1.5.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-use-layout-effect": {
|
"node_modules/@radix-ui/react-use-layout-effect": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",
|
||||||
@@ -4074,32 +4526,6 @@
|
|||||||
"integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",
|
"integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@reduxjs/toolkit": {
|
|
||||||
"version": "2.9.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.9.0.tgz",
|
|
||||||
"integrity": "sha512-fSfQlSRu9Z5yBkvsNhYF2rPS8cGXn/TZVrlwN1948QyZ8xMZ0JvP50S2acZNaf+o63u6aEeMjipFyksjIcWrog==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@standard-schema/spec": "^1.0.0",
|
|
||||||
"@standard-schema/utils": "^0.3.0",
|
|
||||||
"immer": "^10.0.3",
|
|
||||||
"redux": "^5.0.1",
|
|
||||||
"redux-thunk": "^3.1.0",
|
|
||||||
"reselect": "^5.1.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"react": "^16.9.0 || ^17.0.0 || ^18 || ^19",
|
|
||||||
"react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"react": {
|
|
||||||
"optional": true
|
|
||||||
},
|
|
||||||
"react-redux": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@rolldown/pluginutils": {
|
"node_modules/@rolldown/pluginutils": {
|
||||||
"version": "1.0.0-beta.35",
|
"version": "1.0.0-beta.35",
|
||||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.35.tgz",
|
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.35.tgz",
|
||||||
@@ -4505,18 +4931,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@standard-schema/spec": {
|
|
||||||
"version": "1.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.0.0.tgz",
|
|
||||||
"integrity": "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@standard-schema/utils": {
|
|
||||||
"version": "0.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
|
|
||||||
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@surma/rollup-plugin-off-main-thread": {
|
"node_modules/@surma/rollup-plugin-off-main-thread": {
|
||||||
"version": "2.2.3",
|
"version": "2.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/@surma/rollup-plugin-off-main-thread/-/rollup-plugin-off-main-thread-2.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/@surma/rollup-plugin-off-main-thread/-/rollup-plugin-off-main-thread-2.2.3.tgz",
|
||||||
@@ -4530,6 +4944,32 @@
|
|||||||
"string.prototype.matchall": "^4.0.6"
|
"string.prototype.matchall": "^4.0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tabler/icons": {
|
||||||
|
"version": "3.35.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tabler/icons/-/icons-3.35.0.tgz",
|
||||||
|
"integrity": "sha512-yYXe+gJ56xlZFiXwV9zVoe3FWCGuZ/D7/G4ZIlDtGxSx5CGQK110wrnT29gUj52kEZoxqF7oURTk97GQxELOFQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/codecalm"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tabler/icons-react": {
|
||||||
|
"version": "3.35.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@tabler/icons-react/-/icons-react-3.35.0.tgz",
|
||||||
|
"integrity": "sha512-XG7t2DYf3DyHT5jxFNp5xyLVbL4hMJYJhiSdHADzAjLRYfL7AnjlRfiHDHeXxkb2N103rEIvTsBRazxXtAUz2g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@tabler/icons": "3.35.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/codecalm"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">= 16"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tailwindcss/forms": {
|
"node_modules/@tailwindcss/forms": {
|
||||||
"version": "0.5.10",
|
"version": "0.5.10",
|
||||||
"resolved": "https://registry.npmjs.org/@tailwindcss/forms/-/forms-0.5.10.tgz",
|
"resolved": "https://registry.npmjs.org/@tailwindcss/forms/-/forms-0.5.10.tgz",
|
||||||
@@ -5036,12 +5476,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/use-sync-external-store": {
|
|
||||||
"version": "0.0.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
|
|
||||||
"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||||
"version": "8.44.0",
|
"version": "8.44.0",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.44.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.44.0.tgz",
|
||||||
@@ -6825,7 +7259,6 @@
|
|||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
|
||||||
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
|
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
|
||||||
"devOptional": true,
|
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/d3-array": {
|
"node_modules/d3-array": {
|
||||||
@@ -7212,6 +7645,16 @@
|
|||||||
"integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
|
"integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/dom-helpers": {
|
||||||
|
"version": "5.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
|
||||||
|
"integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/runtime": "^7.8.7",
|
||||||
|
"csstype": "^3.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/dotenv": {
|
"node_modules/dotenv": {
|
||||||
"version": "17.2.2",
|
"version": "17.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.2.tgz",
|
||||||
@@ -7461,16 +7904,6 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/es-toolkit": {
|
|
||||||
"version": "1.39.10",
|
|
||||||
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.10.tgz",
|
|
||||||
"integrity": "sha512-E0iGnTtbDhkeczB0T+mxmoVlT4YNweEKBLq7oaU4p11mecdsZpNWOglI4895Vh4usbQ+LsJiuLuI2L0Vdmfm2w==",
|
|
||||||
"license": "MIT",
|
|
||||||
"workspaces": [
|
|
||||||
"docs",
|
|
||||||
"benchmarks"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/esbuild": {
|
"node_modules/esbuild": {
|
||||||
"version": "0.25.10",
|
"version": "0.25.10",
|
||||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.10.tgz",
|
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.10.tgz",
|
||||||
@@ -7763,9 +8196,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eventemitter3": {
|
"node_modules/eventemitter3": {
|
||||||
"version": "5.0.1",
|
"version": "4.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
|
||||||
"integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==",
|
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/eventsource": {
|
"node_modules/eventsource": {
|
||||||
@@ -7907,6 +8340,15 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/fast-equals": {
|
||||||
|
"version": "5.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.2.2.tgz",
|
||||||
|
"integrity": "sha512-V7/RktU11J3I36Nwq2JnZEM7tNm17eBJz+u25qdxBZeCKiX6BkVSZQjwWIr+IobgnZy+ag73tTZgZi7tr0LrBw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/fast-glob": {
|
"node_modules/fast-glob": {
|
||||||
"version": "3.3.3",
|
"version": "3.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||||
@@ -8773,16 +9215,6 @@
|
|||||||
"node": ">= 4"
|
"node": ">= 4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/immer": {
|
|
||||||
"version": "10.1.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/immer/-/immer-10.1.3.tgz",
|
|
||||||
"integrity": "sha512-tmjF/k8QDKydUlm3mZU+tjM6zeq9/fFpPqH9SzWmBnVVKsPBg/V66qsMwb3/Bo90cgUN+ghdVBess+hPsxUyRw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "opencollective",
|
|
||||||
"url": "https://opencollective.com/immer"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/import-fresh": {
|
"node_modules/import-fresh": {
|
||||||
"version": "3.3.1",
|
"version": "3.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
|
||||||
@@ -9624,7 +10056,6 @@
|
|||||||
"version": "4.17.21",
|
"version": "4.17.21",
|
||||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
|
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/lodash.debounce": {
|
"node_modules/lodash.debounce": {
|
||||||
@@ -9691,6 +10122,18 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/loose-envify": {
|
||||||
|
"version": "1.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||||
|
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"js-tokens": "^3.0.0 || ^4.0.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"loose-envify": "cli.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/lru-cache": {
|
"node_modules/lru-cache": {
|
||||||
"version": "5.1.1",
|
"version": "5.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
||||||
@@ -9973,6 +10416,16 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/next-themes": {
|
||||||
|
"version": "0.4.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.4.6.tgz",
|
||||||
|
"integrity": "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/node-domexception": {
|
"node_modules/node-domexception": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
|
||||||
@@ -10712,6 +11165,23 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/prop-types": {
|
||||||
|
"version": "15.8.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||||
|
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"loose-envify": "^1.4.0",
|
||||||
|
"object-assign": "^4.1.1",
|
||||||
|
"react-is": "^16.13.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/prop-types/node_modules/react-is": {
|
||||||
|
"version": "16.13.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||||
|
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/proxy-addr": {
|
"node_modules/proxy-addr": {
|
||||||
"version": "2.0.7",
|
"version": "2.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||||
@@ -10891,34 +11361,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-is": {
|
"node_modules/react-is": {
|
||||||
"version": "19.1.1",
|
"version": "18.3.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
|
||||||
"integrity": "sha512-tr41fA15Vn8p4X9ntI+yCyeGSf1TlYaY5vlTZfQmeLBrFo3psOPX6HhTDnFNL9uj3EhP0KAQ80cugCl4b4BERA==",
|
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
|
||||||
"license": "MIT",
|
"license": "MIT"
|
||||||
"peer": true
|
|
||||||
},
|
|
||||||
"node_modules/react-redux": {
|
|
||||||
"version": "9.2.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
|
|
||||||
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@types/use-sync-external-store": "^0.0.6",
|
|
||||||
"use-sync-external-store": "^1.4.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@types/react": "^18.2.25 || ^19",
|
|
||||||
"react": "^18.0 || ^19",
|
|
||||||
"redux": "^5.0.0"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"@types/react": {
|
|
||||||
"optional": true
|
|
||||||
},
|
|
||||||
"redux": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"node_modules/react-refresh": {
|
"node_modules/react-refresh": {
|
||||||
"version": "0.17.0",
|
"version": "0.17.0",
|
||||||
@@ -10977,6 +11423,21 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/react-smooth": {
|
||||||
|
"version": "4.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",
|
||||||
|
"integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"fast-equals": "^5.0.1",
|
||||||
|
"prop-types": "^15.8.1",
|
||||||
|
"react-transition-group": "^4.4.5"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||||
|
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/react-style-singleton": {
|
"node_modules/react-style-singleton": {
|
||||||
"version": "2.2.3",
|
"version": "2.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",
|
||||||
@@ -10999,6 +11460,22 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/react-transition-group": {
|
||||||
|
"version": "4.4.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
|
||||||
|
"integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/runtime": "^7.5.5",
|
||||||
|
"dom-helpers": "^5.0.1",
|
||||||
|
"loose-envify": "^1.4.0",
|
||||||
|
"prop-types": "^15.6.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.6.0",
|
||||||
|
"react-dom": ">=16.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/read-cache": {
|
"node_modules/read-cache": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
|
||||||
@@ -11046,45 +11523,35 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/recharts": {
|
"node_modules/recharts": {
|
||||||
"version": "3.2.1",
|
"version": "2.15.4",
|
||||||
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz",
|
||||||
"integrity": "sha512-0JKwHRiFZdmLq/6nmilxEZl3pqb4T+aKkOkOi/ZISRZwfBhVMgInxzlYU9D4KnCH3KINScLy68m/OvMXoYGZUw==",
|
"integrity": "sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@reduxjs/toolkit": "1.x.x || 2.x.x",
|
"clsx": "^2.0.0",
|
||||||
"clsx": "^2.1.1",
|
"eventemitter3": "^4.0.1",
|
||||||
"decimal.js-light": "^2.5.1",
|
"lodash": "^4.17.21",
|
||||||
"es-toolkit": "^1.39.3",
|
"react-is": "^18.3.1",
|
||||||
"eventemitter3": "^5.0.1",
|
"react-smooth": "^4.0.4",
|
||||||
"immer": "^10.1.1",
|
"recharts-scale": "^0.4.4",
|
||||||
"react-redux": "8.x.x || 9.x.x",
|
"tiny-invariant": "^1.3.1",
|
||||||
"reselect": "5.1.1",
|
"victory-vendor": "^36.6.8"
|
||||||
"tiny-invariant": "^1.3.3",
|
|
||||||
"use-sync-external-store": "^1.2.2",
|
|
||||||
"victory-vendor": "^37.0.2"
|
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=14"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
"react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
||||||
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
|
"react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/redux": {
|
"node_modules/recharts-scale": {
|
||||||
"version": "5.0.1",
|
"version": "0.4.5",
|
||||||
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz",
|
||||||
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
|
"integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==",
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/redux-thunk": {
|
|
||||||
"version": "3.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz",
|
|
||||||
"integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==",
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"dependencies": {
|
||||||
"redux": "^5.0.0"
|
"decimal.js-light": "^2.4.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/reflect.getprototypeof": {
|
"node_modules/reflect.getprototypeof": {
|
||||||
@@ -11221,12 +11688,6 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/reselect": {
|
|
||||||
"version": "5.1.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz",
|
|
||||||
"integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/resolve": {
|
"node_modules/resolve": {
|
||||||
"version": "1.22.10",
|
"version": "1.22.10",
|
||||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
|
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
|
||||||
@@ -13136,10 +13597,23 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/vaul": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-dialog": "^1.1.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/victory-vendor": {
|
"node_modules/victory-vendor": {
|
||||||
"version": "37.3.6",
|
"version": "36.9.2",
|
||||||
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",
|
"resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",
|
||||||
"integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==",
|
"integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==",
|
||||||
"license": "MIT AND ISC",
|
"license": "MIT AND ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/d3-array": "^3.0.3",
|
"@types/d3-array": "^3.0.3",
|
||||||
|
|||||||
@@ -10,11 +10,26 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/modifiers": "^9.0.0",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"@radix-ui/react-avatar": "^1.1.10",
|
||||||
|
"@radix-ui/react-checkbox": "^1.3.3",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
|
"@radix-ui/react-label": "^2.1.7",
|
||||||
"@radix-ui/react-popover": "^1.1.15",
|
"@radix-ui/react-popover": "^1.1.15",
|
||||||
"@radix-ui/react-progress": "^1.1.7",
|
"@radix-ui/react-progress": "^1.1.7",
|
||||||
"@radix-ui/react-select": "^2.2.6",
|
"@radix-ui/react-select": "^2.2.6",
|
||||||
|
"@radix-ui/react-separator": "^1.1.7",
|
||||||
"@radix-ui/react-slot": "^1.2.3",
|
"@radix-ui/react-slot": "^1.2.3",
|
||||||
|
"@radix-ui/react-switch": "^1.2.6",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.13",
|
||||||
|
"@radix-ui/react-toggle": "^1.1.10",
|
||||||
|
"@radix-ui/react-toggle-group": "^1.1.11",
|
||||||
|
"@radix-ui/react-tooltip": "^1.2.8",
|
||||||
|
"@tabler/icons-react": "^3.35.0",
|
||||||
"@tailwindcss/forms": "^0.5.10",
|
"@tailwindcss/forms": "^0.5.10",
|
||||||
"@tanstack/react-query": "^5.87.1",
|
"@tanstack/react-query": "^5.87.1",
|
||||||
"@tanstack/react-router": "^1.131.36",
|
"@tanstack/react-router": "^1.131.36",
|
||||||
@@ -27,15 +42,18 @@
|
|||||||
"cmdk": "^1.1.1",
|
"cmdk": "^1.1.1",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"lucide-react": "^0.542.0",
|
"lucide-react": "^0.542.0",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"react": "^19.1.1",
|
"react": "^19.1.1",
|
||||||
"react-day-picker": "^9.10.0",
|
"react-day-picker": "^9.10.0",
|
||||||
"react-dom": "^19.1.1",
|
"react-dom": "^19.1.1",
|
||||||
"recharts": "^3.2.0",
|
"recharts": "^2.15.4",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
"tailwindcss": "^3.4.17",
|
"tailwindcss": "^3.4.17",
|
||||||
"tailwindcss-animate": "^1.0.7"
|
"tailwindcss-animate": "^1.0.7",
|
||||||
|
"vaul": "^1.1.2",
|
||||||
|
"zod": "^3.25.76"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.33.0",
|
"@eslint/js": "^9.33.0",
|
||||||
|
|||||||
@@ -6,4 +6,4 @@
|
|||||||
<TileColor>#3B82F6</TileColor>
|
<TileColor>#3B82F6</TileColor>
|
||||||
</tile>
|
</tile>
|
||||||
</msapplication>
|
</msapplication>
|
||||||
</browserconfig>
|
</browserconfig>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
User-agent: *
|
User-agent: *
|
||||||
Allow: /
|
Allow: /
|
||||||
|
|
||||||
Sitemap: /sitemap.xml
|
Sitemap: /sitemap.xml
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
{
|
{
|
||||||
"preset": "minimal-2023",
|
"preset": "minimal-2023",
|
||||||
"images": ["public/favicon.svg"]
|
"images": ["public/favicon.svg"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ export default function AccountSettings() {
|
|||||||
|
|
||||||
const [editingAccountId, setEditingAccountId] = useState<string | null>(null);
|
const [editingAccountId, setEditingAccountId] = useState<string | null>(null);
|
||||||
const [editingName, setEditingName] = useState("");
|
const [editingName, setEditingName] = useState("");
|
||||||
|
const [failedImages, setFailedImages] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
@@ -144,7 +145,8 @@ export default function AccountSettings() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Account Management</CardTitle>
|
<CardTitle>Account Management</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Manage your connected bank accounts and customize their display names
|
Manage your connected bank accounts and customize their display
|
||||||
|
names
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
@@ -193,8 +195,24 @@ export default function AccountSettings() {
|
|||||||
{/* Mobile layout - stack vertically */}
|
{/* Mobile layout - stack vertically */}
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
|
||||||
<div className="flex items-start sm:items-center space-x-3 sm:space-x-4 min-w-0 flex-1">
|
<div className="flex items-start sm:items-center space-x-3 sm:space-x-4 min-w-0 flex-1">
|
||||||
<div className="flex-shrink-0 p-2 sm:p-3 bg-muted rounded-full">
|
<div className="flex-shrink-0 w-10 h-10 sm:w-12 sm:h-12 rounded-full overflow-hidden bg-muted flex items-center justify-center">
|
||||||
<Building2 className="h-5 w-5 sm:h-6 sm:w-6 text-muted-foreground" />
|
{account.logo && !failedImages.has(account.id) ? (
|
||||||
|
<img
|
||||||
|
src={account.logo}
|
||||||
|
alt={`${account.institution_id} logo`}
|
||||||
|
className="w-full h-full object-contain"
|
||||||
|
onError={() => {
|
||||||
|
console.warn(
|
||||||
|
`Failed to load bank logo for ${account.institution_id}: ${account.logo}`,
|
||||||
|
);
|
||||||
|
setFailedImages(
|
||||||
|
(prev) => new Set([...prev, account.id]),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Building2 className="h-5 w-5 sm:h-6 sm:w-6 text-muted-foreground" />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
{editingAccountId === account.id ? (
|
{editingAccountId === account.id ? (
|
||||||
@@ -216,24 +234,28 @@ export default function AccountSettings() {
|
|||||||
}}
|
}}
|
||||||
autoFocus
|
autoFocus
|
||||||
/>
|
/>
|
||||||
<button
|
<Button
|
||||||
onClick={handleEditSave}
|
onClick={handleEditSave}
|
||||||
disabled={
|
disabled={
|
||||||
!editingName.trim() ||
|
!editingName.trim() ||
|
||||||
updateAccountMutation.isPending
|
updateAccountMutation.isPending
|
||||||
}
|
}
|
||||||
className="p-1 text-green-600 hover:text-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-100"
|
||||||
title="Save changes"
|
title="Save changes"
|
||||||
>
|
>
|
||||||
<Check className="h-4 w-4" />
|
<Check className="h-4 w-4" />
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button
|
||||||
onClick={handleEditCancel}
|
onClick={handleEditCancel}
|
||||||
className="p-1 text-gray-600 hover:text-gray-700"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8"
|
||||||
title="Cancel editing"
|
title="Cancel editing"
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-muted-foreground truncate">
|
<p className="text-sm text-muted-foreground truncate">
|
||||||
{account.institution_id}
|
{account.institution_id}
|
||||||
@@ -247,13 +269,15 @@ export default function AccountSettings() {
|
|||||||
account.name ||
|
account.name ||
|
||||||
"Unnamed Account"}
|
"Unnamed Account"}
|
||||||
</h4>
|
</h4>
|
||||||
<button
|
<Button
|
||||||
onClick={() => handleEditStart(account)}
|
onClick={() => handleEditStart(account)}
|
||||||
className="flex-shrink-0 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-7 w-7 flex-shrink-0"
|
||||||
title="Edit account name"
|
title="Edit account name"
|
||||||
>
|
>
|
||||||
<Edit2 className="h-4 w-4" />
|
<Edit2 className="h-4 w-4" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-muted-foreground truncate">
|
<p className="text-sm text-muted-foreground truncate">
|
||||||
{account.institution_id}
|
{account.institution_id}
|
||||||
@@ -324,7 +348,8 @@ export default function AccountSettings() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Add New Bank Account</CardTitle>
|
<CardTitle>Add New Bank Account</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Connect additional bank accounts to track all your finances in one place
|
Connect additional bank accounts to track all your finances in one
|
||||||
|
place
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="p-6">
|
<CardContent className="p-6">
|
||||||
@@ -332,7 +357,8 @@ export default function AccountSettings() {
|
|||||||
<div className="p-4 bg-muted rounded-lg">
|
<div className="p-4 bg-muted rounded-lg">
|
||||||
<Plus className="h-8 w-8 text-muted-foreground mx-auto mb-2" />
|
<Plus className="h-8 w-8 text-muted-foreground mx-auto mb-2" />
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
Bank connection functionality is coming soon. Stay tuned for updates!
|
Bank connection functionality is coming soon. Stay tuned for
|
||||||
|
updates!
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button disabled variant="outline">
|
<Button disabled variant="outline">
|
||||||
|
|||||||
@@ -273,24 +273,28 @@ export default function AccountsOverview() {
|
|||||||
}}
|
}}
|
||||||
autoFocus
|
autoFocus
|
||||||
/>
|
/>
|
||||||
<button
|
<Button
|
||||||
onClick={handleEditSave}
|
onClick={handleEditSave}
|
||||||
disabled={
|
disabled={
|
||||||
!editingName.trim() ||
|
!editingName.trim() ||
|
||||||
updateAccountMutation.isPending
|
updateAccountMutation.isPending
|
||||||
}
|
}
|
||||||
className="p-1 text-green-600 hover:text-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-100"
|
||||||
title="Save changes"
|
title="Save changes"
|
||||||
>
|
>
|
||||||
<Check className="h-4 w-4" />
|
<Check className="h-4 w-4" />
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button
|
||||||
onClick={handleEditCancel}
|
onClick={handleEditCancel}
|
||||||
className="p-1 text-gray-600 hover:text-gray-700"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8"
|
||||||
title="Cancel editing"
|
title="Cancel editing"
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-muted-foreground truncate">
|
<p className="text-sm text-muted-foreground truncate">
|
||||||
{account.institution_id}
|
{account.institution_id}
|
||||||
@@ -304,13 +308,15 @@ export default function AccountsOverview() {
|
|||||||
account.name ||
|
account.name ||
|
||||||
"Unnamed Account"}
|
"Unnamed Account"}
|
||||||
</h4>
|
</h4>
|
||||||
<button
|
<Button
|
||||||
onClick={() => handleEditStart(account)}
|
onClick={() => handleEditStart(account)}
|
||||||
className="flex-shrink-0 p-1 text-muted-foreground hover:text-foreground transition-colors"
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-7 w-7 flex-shrink-0"
|
||||||
title="Edit account name"
|
title="Edit account name"
|
||||||
>
|
>
|
||||||
<Edit2 className="h-4 w-4" />
|
<Edit2 className="h-4 w-4" />
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-muted-foreground truncate">
|
<p className="text-sm text-muted-foreground truncate">
|
||||||
{account.institution_id}
|
{account.institution_id}
|
||||||
|
|||||||
203
frontend/src/components/AddBankAccountDrawer.tsx
Normal file
203
frontend/src/components/AddBankAccountDrawer.tsx
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||||
|
import { Plus, Building2, ExternalLink } from "lucide-react";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import { Label } from "./ui/label";
|
||||||
|
import {
|
||||||
|
Drawer,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerDescription,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerTrigger,
|
||||||
|
} from "./ui/drawer";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "./ui/select";
|
||||||
|
import { Alert, AlertDescription } from "./ui/alert";
|
||||||
|
|
||||||
|
export default function AddBankAccountDrawer() {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [selectedCountry, setSelectedCountry] = useState<string>("");
|
||||||
|
const [selectedBank, setSelectedBank] = useState<string>("");
|
||||||
|
|
||||||
|
const { data: countries } = useQuery({
|
||||||
|
queryKey: ["supportedCountries"],
|
||||||
|
queryFn: apiClient.getSupportedCountries,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: banks, isLoading: banksLoading } = useQuery({
|
||||||
|
queryKey: ["bankInstitutions", selectedCountry],
|
||||||
|
queryFn: () => apiClient.getBankInstitutions(selectedCountry),
|
||||||
|
enabled: !!selectedCountry,
|
||||||
|
});
|
||||||
|
|
||||||
|
const connectBankMutation = useMutation({
|
||||||
|
mutationFn: (institutionId: string) =>
|
||||||
|
apiClient.createBankConnection(institutionId),
|
||||||
|
onSuccess: (data) => {
|
||||||
|
// Redirect to the bank's authorization link
|
||||||
|
if (data.link) {
|
||||||
|
window.open(data.link, "_blank");
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to create bank connection:", error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleCountryChange = (country: string) => {
|
||||||
|
setSelectedCountry(country);
|
||||||
|
setSelectedBank("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleConnect = () => {
|
||||||
|
if (selectedBank) {
|
||||||
|
connectBankMutation.mutate(selectedBank);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetForm = () => {
|
||||||
|
setSelectedCountry("");
|
||||||
|
setSelectedBank("");
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(isOpen) => {
|
||||||
|
setOpen(isOpen);
|
||||||
|
if (!isOpen) {
|
||||||
|
resetForm();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DrawerTrigger asChild>
|
||||||
|
<Button size="sm">
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Add New Account
|
||||||
|
</Button>
|
||||||
|
</DrawerTrigger>
|
||||||
|
<DrawerContent className="max-h-[80vh]">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle>Connect Bank Account</DrawerTitle>
|
||||||
|
<DrawerDescription>
|
||||||
|
Select your country and bank to connect your account to Leggen
|
||||||
|
</DrawerDescription>
|
||||||
|
</DrawerHeader>
|
||||||
|
|
||||||
|
<div className="px-6 space-y-6 overflow-y-auto">
|
||||||
|
{/* Country Selection */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="country">Country</Label>
|
||||||
|
<Select value={selectedCountry} onValueChange={handleCountryChange}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select your country" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{countries?.map((country) => (
|
||||||
|
<SelectItem key={country.code} value={country.code}>
|
||||||
|
{country.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bank Selection */}
|
||||||
|
{selectedCountry && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="bank">Bank</Label>
|
||||||
|
{banksLoading ? (
|
||||||
|
<div className="p-4 text-center text-muted-foreground">
|
||||||
|
Loading banks...
|
||||||
|
</div>
|
||||||
|
) : banks && banks.length > 0 ? (
|
||||||
|
<Select value={selectedBank} onValueChange={setSelectedBank}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select your bank" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{banks.map((bank) => (
|
||||||
|
<SelectItem key={bank.id} value={bank.id}>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
{bank.logo ? (
|
||||||
|
<img
|
||||||
|
src={bank.logo}
|
||||||
|
alt={`${bank.name} logo`}
|
||||||
|
className="w-4 h-4 object-contain"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Building2 className="w-4 h-4" />
|
||||||
|
)}
|
||||||
|
<span>{bank.name}</span>
|
||||||
|
</div>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
) : (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>
|
||||||
|
No banks available for the selected country.
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Instructions */}
|
||||||
|
{selectedBank && (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>
|
||||||
|
You'll be redirected to your bank's website to authorize the
|
||||||
|
connection. After approval, you'll return to Leggen and your
|
||||||
|
account will start syncing.
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Error Display */}
|
||||||
|
{connectBankMutation.isError && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>
|
||||||
|
Failed to create bank connection. Please try again.
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DrawerFooter>
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Button
|
||||||
|
onClick={handleConnect}
|
||||||
|
disabled={!selectedBank || connectBankMutation.isPending}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-4 w-4 mr-2" />
|
||||||
|
{connectBankMutation.isPending
|
||||||
|
? "Connecting..."
|
||||||
|
: "Open Bank Authorization"}
|
||||||
|
</Button>
|
||||||
|
<DrawerClose asChild>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
disabled={connectBankMutation.isPending}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</DrawerClose>
|
||||||
|
</div>
|
||||||
|
</DrawerFooter>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
}
|
||||||
180
frontend/src/components/AppSidebar.tsx
Normal file
180
frontend/src/components/AppSidebar.tsx
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
import React from "react";
|
||||||
|
import { Link, useLocation } from "@tanstack/react-router";
|
||||||
|
import {
|
||||||
|
List,
|
||||||
|
BarChart3,
|
||||||
|
Activity,
|
||||||
|
Settings,
|
||||||
|
Building2,
|
||||||
|
TrendingUp,
|
||||||
|
ChevronDown,
|
||||||
|
ChevronUp,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { Logo } from "./ui/logo";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import { formatCurrency } from "../lib/utils";
|
||||||
|
import { useState } from "react";
|
||||||
|
import type { Account } from "../types/api";
|
||||||
|
import {
|
||||||
|
Sidebar,
|
||||||
|
SidebarContent,
|
||||||
|
SidebarFooter,
|
||||||
|
SidebarHeader,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupContent,
|
||||||
|
SidebarGroupLabel,
|
||||||
|
useSidebar,
|
||||||
|
} from "./ui/sidebar";
|
||||||
|
|
||||||
|
const navigation = [
|
||||||
|
{ name: "Overview", icon: List, to: "/" },
|
||||||
|
{ name: "Analytics", icon: BarChart3, to: "/analytics" },
|
||||||
|
{ name: "System", icon: Activity, to: "/system" },
|
||||||
|
{ name: "Settings", icon: Settings, to: "/settings" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||||
|
const location = useLocation();
|
||||||
|
const [accountsExpanded, setAccountsExpanded] = useState(false);
|
||||||
|
const { isMobile, setOpenMobile } = useSidebar();
|
||||||
|
|
||||||
|
const { data: accounts } = useQuery<Account[]>({
|
||||||
|
queryKey: ["accounts"],
|
||||||
|
queryFn: apiClient.getAccounts,
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalBalance =
|
||||||
|
accounts?.reduce((sum, account) => {
|
||||||
|
const primaryBalance = account.balances?.[0]?.amount || 0;
|
||||||
|
return sum + primaryBalance;
|
||||||
|
}, 0) || 0;
|
||||||
|
|
||||||
|
// Handler to close mobile sidebar when navigation item is clicked
|
||||||
|
const handleNavigationClick = () => {
|
||||||
|
if (isMobile) {
|
||||||
|
setOpenMobile(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sidebar collapsible="icon" className="pt-safe-top pl-safe-left" {...props}>
|
||||||
|
<SidebarHeader>
|
||||||
|
<SidebarMenu>
|
||||||
|
<SidebarMenuItem>
|
||||||
|
<SidebarMenuButton
|
||||||
|
asChild
|
||||||
|
className="data-[slot=sidebar-menu-button]:!p-1.5"
|
||||||
|
>
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="flex items-center space-x-2"
|
||||||
|
onClick={handleNavigationClick}
|
||||||
|
>
|
||||||
|
<Logo size={24} />
|
||||||
|
<span className="text-base font-semibold">Leggen</span>
|
||||||
|
</Link>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarHeader>
|
||||||
|
|
||||||
|
<SidebarContent>
|
||||||
|
<SidebarGroup>
|
||||||
|
<SidebarGroupContent>
|
||||||
|
<SidebarMenu>
|
||||||
|
{navigation.map((item) => (
|
||||||
|
<SidebarMenuItem key={item.to}>
|
||||||
|
<SidebarMenuButton
|
||||||
|
asChild
|
||||||
|
tooltip={item.name}
|
||||||
|
isActive={location.pathname === item.to}
|
||||||
|
>
|
||||||
|
<Link to={item.to} onClick={handleNavigationClick}>
|
||||||
|
<item.icon className="h-5 w-5" />
|
||||||
|
<span>{item.name}</span>
|
||||||
|
</Link>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
</SidebarMenuItem>
|
||||||
|
))}
|
||||||
|
</SidebarMenu>
|
||||||
|
</SidebarGroupContent>
|
||||||
|
</SidebarGroup>
|
||||||
|
</SidebarContent>
|
||||||
|
|
||||||
|
<SidebarFooter>
|
||||||
|
{/* Account Summary Section */}
|
||||||
|
<SidebarGroup>
|
||||||
|
<SidebarGroupLabel>Account Summary</SidebarGroupLabel>
|
||||||
|
<div className="bg-muted rounded-lg p-1">
|
||||||
|
{/* Collapsible Header */}
|
||||||
|
<button
|
||||||
|
onClick={() => setAccountsExpanded(!accountsExpanded)}
|
||||||
|
className="w-full p-3 flex items-center justify-between hover:bg-muted/80 transition-colors rounded-lg"
|
||||||
|
>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<span className="text-sm font-medium text-muted-foreground">
|
||||||
|
Total Balance
|
||||||
|
</span>
|
||||||
|
<TrendingUp className="h-4 w-4 text-green-500" />
|
||||||
|
</div>
|
||||||
|
{accountsExpanded ? (
|
||||||
|
<ChevronUp className="h-4 w-4 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="px-3 pb-2">
|
||||||
|
<p className="text-xl font-bold text-foreground">
|
||||||
|
{formatCurrency(totalBalance)}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{accounts?.length || 0} accounts
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Expanded Account Details */}
|
||||||
|
{accountsExpanded && accounts && accounts.length > 0 && (
|
||||||
|
<div className="border-t border-border/50 max-h-48 overflow-y-auto">
|
||||||
|
{accounts.map((account) => {
|
||||||
|
const primaryBalance = account.balances?.[0]?.amount || 0;
|
||||||
|
const currency =
|
||||||
|
account.balances?.[0]?.currency ||
|
||||||
|
account.currency ||
|
||||||
|
"EUR";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={account.id}
|
||||||
|
className="p-2 border-b border-border/30 last:border-b-0 hover:bg-muted/50 transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex items-start space-x-2">
|
||||||
|
<div className="flex-shrink-0 p-1 bg-background rounded">
|
||||||
|
<Building2 className="h-3 w-3 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1 min-w-0 flex-1">
|
||||||
|
<p className="text-xs font-medium text-foreground truncate">
|
||||||
|
{account.display_name ||
|
||||||
|
account.name ||
|
||||||
|
"Unnamed Account"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs font-semibold text-foreground">
|
||||||
|
{formatCurrency(primaryBalance, currency)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SidebarGroup>
|
||||||
|
</SidebarFooter>
|
||||||
|
</Sidebar>
|
||||||
|
);
|
||||||
|
}
|
||||||
200
frontend/src/components/DiscordConfigDrawer.tsx
Normal file
200
frontend/src/components/DiscordConfigDrawer.tsx
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { MessageSquare, TestTube } from "lucide-react";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import { Input } from "./ui/input";
|
||||||
|
import { Label } from "./ui/label";
|
||||||
|
import { Switch } from "./ui/switch";
|
||||||
|
import { EditButton } from "./ui/edit-button";
|
||||||
|
import {
|
||||||
|
Drawer,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerDescription,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerTrigger,
|
||||||
|
} from "./ui/drawer";
|
||||||
|
import type { NotificationSettings, DiscordConfig } from "../types/api";
|
||||||
|
|
||||||
|
interface DiscordConfigDrawerProps {
|
||||||
|
settings: NotificationSettings | undefined;
|
||||||
|
trigger?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DiscordConfigDrawer({
|
||||||
|
settings,
|
||||||
|
trigger,
|
||||||
|
}: DiscordConfigDrawerProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [config, setConfig] = useState<DiscordConfig>({
|
||||||
|
webhook: "",
|
||||||
|
enabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (settings?.discord) {
|
||||||
|
setConfig({ ...settings.discord });
|
||||||
|
}
|
||||||
|
}, [settings]);
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: (discordConfig: DiscordConfig) =>
|
||||||
|
apiClient.updateNotificationSettings({
|
||||||
|
...settings,
|
||||||
|
discord: discordConfig,
|
||||||
|
filters: settings?.filters || {
|
||||||
|
case_insensitive: [],
|
||||||
|
case_sensitive: [],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["notificationSettings"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["notificationServices"] });
|
||||||
|
setOpen(false);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to update Discord configuration:", error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const testMutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
apiClient.testNotification({
|
||||||
|
service: "discord",
|
||||||
|
message:
|
||||||
|
"Test notification from Leggen - Discord configuration is working!",
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
console.log("Test Discord notification sent successfully");
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to send test Discord notification:", error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
updateMutation.mutate(config);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTest = () => {
|
||||||
|
testMutation.mutate();
|
||||||
|
};
|
||||||
|
|
||||||
|
const isConfigValid =
|
||||||
|
config.webhook.trim().length > 0 &&
|
||||||
|
config.webhook.includes("discord.com/api/webhooks");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer open={open} onOpenChange={setOpen}>
|
||||||
|
<DrawerTrigger asChild>{trigger || <EditButton />}</DrawerTrigger>
|
||||||
|
<DrawerContent>
|
||||||
|
<div className="mx-auto w-full max-w-md">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle className="flex items-center space-x-2">
|
||||||
|
<MessageSquare className="h-5 w-5 text-primary" />
|
||||||
|
<span>Discord Configuration</span>
|
||||||
|
</DrawerTitle>
|
||||||
|
<DrawerDescription>
|
||||||
|
Configure Discord webhook notifications for transaction alerts
|
||||||
|
</DrawerDescription>
|
||||||
|
</DrawerHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="p-4 space-y-6">
|
||||||
|
{/* Enable/Disable Toggle */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label className="text-base font-medium">
|
||||||
|
Enable Discord Notifications
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
checked={config.enabled}
|
||||||
|
onCheckedChange={(enabled) => setConfig({ ...config, enabled })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Webhook URL */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="discord-webhook">Discord Webhook URL</Label>
|
||||||
|
<Input
|
||||||
|
id="discord-webhook"
|
||||||
|
type="url"
|
||||||
|
placeholder="https://discord.com/api/webhooks/..."
|
||||||
|
value={config.webhook}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({ ...config, webhook: e.target.value })
|
||||||
|
}
|
||||||
|
disabled={!config.enabled}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Create a webhook in your Discord server settings under
|
||||||
|
Integrations → Webhooks
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Configuration Status */}
|
||||||
|
{config.enabled && (
|
||||||
|
<div className="p-3 bg-muted rounded-md">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<div
|
||||||
|
className={`w-2 h-2 rounded-full ${isConfigValid ? "bg-green-500" : "bg-red-500"}`}
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium">
|
||||||
|
{isConfigValid
|
||||||
|
? "Configuration Valid"
|
||||||
|
: "Invalid Webhook URL"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{!isConfigValid && config.webhook.trim().length > 0 && (
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
Please enter a valid Discord webhook URL
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DrawerFooter className="px-0">
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={updateMutation.isPending || !config.enabled}
|
||||||
|
>
|
||||||
|
{updateMutation.isPending
|
||||||
|
? "Saving..."
|
||||||
|
: "Save Configuration"}
|
||||||
|
</Button>
|
||||||
|
{config.enabled && isConfigValid && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleTest}
|
||||||
|
disabled={testMutation.isPending}
|
||||||
|
>
|
||||||
|
{testMutation.isPending ? (
|
||||||
|
<>
|
||||||
|
<TestTube className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Testing...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<TestTube className="h-4 w-4 mr-2" />
|
||||||
|
Test
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<DrawerClose asChild>
|
||||||
|
<Button variant="ghost">Cancel</Button>
|
||||||
|
</DrawerClose>
|
||||||
|
</DrawerFooter>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
}
|
||||||
259
frontend/src/components/NotificationFiltersDrawer.tsx
Normal file
259
frontend/src/components/NotificationFiltersDrawer.tsx
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Plus, X } from "lucide-react";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import { Input } from "./ui/input";
|
||||||
|
import { Label } from "./ui/label";
|
||||||
|
import { EditButton } from "./ui/edit-button";
|
||||||
|
import {
|
||||||
|
Drawer,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerDescription,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerTrigger,
|
||||||
|
} from "./ui/drawer";
|
||||||
|
import type { NotificationSettings, NotificationFilters } from "../types/api";
|
||||||
|
|
||||||
|
interface NotificationFiltersDrawerProps {
|
||||||
|
settings: NotificationSettings | undefined;
|
||||||
|
trigger?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function NotificationFiltersDrawer({
|
||||||
|
settings,
|
||||||
|
trigger,
|
||||||
|
}: NotificationFiltersDrawerProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [filters, setFilters] = useState<NotificationFilters>({
|
||||||
|
case_insensitive: [],
|
||||||
|
case_sensitive: [],
|
||||||
|
});
|
||||||
|
const [newCaseInsensitive, setNewCaseInsensitive] = useState("");
|
||||||
|
const [newCaseSensitive, setNewCaseSensitive] = useState("");
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (settings?.filters) {
|
||||||
|
setFilters({
|
||||||
|
case_insensitive: [...(settings.filters.case_insensitive || [])],
|
||||||
|
case_sensitive: [...(settings.filters.case_sensitive || [])],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [settings]);
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: (updatedFilters: NotificationFilters) =>
|
||||||
|
apiClient.updateNotificationSettings({
|
||||||
|
...settings,
|
||||||
|
filters: updatedFilters,
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["notificationSettings"] });
|
||||||
|
setOpen(false);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to update notification filters:", error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
updateMutation.mutate(filters);
|
||||||
|
};
|
||||||
|
|
||||||
|
const addCaseInsensitiveFilter = () => {
|
||||||
|
if (
|
||||||
|
newCaseInsensitive.trim() &&
|
||||||
|
!filters.case_insensitive.includes(newCaseInsensitive.trim())
|
||||||
|
) {
|
||||||
|
setFilters({
|
||||||
|
...filters,
|
||||||
|
case_insensitive: [
|
||||||
|
...filters.case_insensitive,
|
||||||
|
newCaseInsensitive.trim(),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
setNewCaseInsensitive("");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const addCaseSensitiveFilter = () => {
|
||||||
|
if (
|
||||||
|
newCaseSensitive.trim() &&
|
||||||
|
!filters.case_sensitive?.includes(newCaseSensitive.trim())
|
||||||
|
) {
|
||||||
|
setFilters({
|
||||||
|
...filters,
|
||||||
|
case_sensitive: [
|
||||||
|
...(filters.case_sensitive || []),
|
||||||
|
newCaseSensitive.trim(),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
setNewCaseSensitive("");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeCaseInsensitiveFilter = (index: number) => {
|
||||||
|
setFilters({
|
||||||
|
...filters,
|
||||||
|
case_insensitive: filters.case_insensitive.filter((_, i) => i !== index),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeCaseSensitiveFilter = (index: number) => {
|
||||||
|
setFilters({
|
||||||
|
...filters,
|
||||||
|
case_sensitive:
|
||||||
|
filters.case_sensitive?.filter((_, i) => i !== index) || [],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer open={open} onOpenChange={setOpen}>
|
||||||
|
<DrawerTrigger asChild>{trigger || <EditButton />}</DrawerTrigger>
|
||||||
|
<DrawerContent>
|
||||||
|
<div className="mx-auto w-full max-w-2xl">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle>Notification Filters</DrawerTitle>
|
||||||
|
<DrawerDescription>
|
||||||
|
Configure which transaction descriptions should trigger
|
||||||
|
notifications
|
||||||
|
</DrawerDescription>
|
||||||
|
</DrawerHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="p-4 space-y-6">
|
||||||
|
{/* Case Insensitive Filters */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
<Label className="text-base font-medium">
|
||||||
|
Case Insensitive Filters
|
||||||
|
</Label>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Filters that match regardless of capitalization (e.g., "AMAZON"
|
||||||
|
matches "amazon")
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Input
|
||||||
|
placeholder="Add filter term..."
|
||||||
|
value={newCaseInsensitive}
|
||||||
|
onChange={(e) => setNewCaseInsensitive(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
addCaseInsensitiveFilter();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={addCaseInsensitiveFilter}
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2 min-h-[2rem] p-3 bg-muted rounded-md">
|
||||||
|
{filters.case_insensitive.length > 0 ? (
|
||||||
|
filters.case_insensitive.map((filter, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center space-x-1 bg-secondary text-secondary-foreground px-2 py-1 rounded-md text-sm"
|
||||||
|
>
|
||||||
|
<span>{filter}</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeCaseInsensitiveFilter(index)}
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-5 w-5 hover:bg-secondary-foreground/10"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground text-sm">
|
||||||
|
No filters added
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Case Sensitive Filters */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
<Label className="text-base font-medium">
|
||||||
|
Case Sensitive Filters
|
||||||
|
</Label>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Filters that match exactly as typed (e.g., "AMAZON" only matches
|
||||||
|
"AMAZON")
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Input
|
||||||
|
placeholder="Add filter term..."
|
||||||
|
value={newCaseSensitive}
|
||||||
|
onChange={(e) => setNewCaseSensitive(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
addCaseSensitiveFilter();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={addCaseSensitiveFilter}
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2 min-h-[2rem] p-3 bg-muted rounded-md">
|
||||||
|
{filters.case_sensitive && filters.case_sensitive.length > 0 ? (
|
||||||
|
filters.case_sensitive.map((filter, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center space-x-1 bg-secondary text-secondary-foreground px-2 py-1 rounded-md text-sm"
|
||||||
|
>
|
||||||
|
<span>{filter}</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeCaseSensitiveFilter(index)}
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-5 w-5 hover:bg-secondary-foreground/10"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground text-sm">
|
||||||
|
No filters added
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DrawerFooter className="px-0">
|
||||||
|
<Button type="submit" disabled={updateMutation.isPending}>
|
||||||
|
{updateMutation.isPending ? "Saving..." : "Save Filters"}
|
||||||
|
</Button>
|
||||||
|
<DrawerClose asChild>
|
||||||
|
<Button variant="outline">Cancel</Button>
|
||||||
|
</DrawerClose>
|
||||||
|
</DrawerFooter>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -10,6 +10,10 @@ import {
|
|||||||
CheckCircle,
|
CheckCircle,
|
||||||
Settings,
|
Settings,
|
||||||
TestTube,
|
TestTube,
|
||||||
|
Activity,
|
||||||
|
Clock,
|
||||||
|
TrendingUp,
|
||||||
|
User,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { apiClient } from "../lib/api";
|
import { apiClient } from "../lib/api";
|
||||||
import NotificationsSkeleton from "./NotificationsSkeleton";
|
import NotificationsSkeleton from "./NotificationsSkeleton";
|
||||||
@@ -32,7 +36,11 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "./ui/select";
|
} from "./ui/select";
|
||||||
import type { NotificationSettings, NotificationService } from "../types/api";
|
import type {
|
||||||
|
NotificationSettings,
|
||||||
|
NotificationService,
|
||||||
|
SyncOperationsResponse,
|
||||||
|
} from "../types/api";
|
||||||
|
|
||||||
export default function Notifications() {
|
export default function Notifications() {
|
||||||
const [testService, setTestService] = useState("");
|
const [testService, setTestService] = useState("");
|
||||||
@@ -61,6 +69,16 @@ export default function Notifications() {
|
|||||||
queryFn: apiClient.getNotificationServices,
|
queryFn: apiClient.getNotificationServices,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: syncOperations,
|
||||||
|
isLoading: syncOperationsLoading,
|
||||||
|
error: syncOperationsError,
|
||||||
|
refetch: refetchSyncOperations,
|
||||||
|
} = useQuery<SyncOperationsResponse>({
|
||||||
|
queryKey: ["syncOperations"],
|
||||||
|
queryFn: () => apiClient.getSyncOperations(10, 0), // Get latest 10 operations
|
||||||
|
});
|
||||||
|
|
||||||
const testMutation = useMutation({
|
const testMutation = useMutation({
|
||||||
mutationFn: apiClient.testNotification,
|
mutationFn: apiClient.testNotification,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
@@ -80,15 +98,15 @@ export default function Notifications() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (settingsLoading || servicesLoading) {
|
if (settingsLoading || servicesLoading || syncOperationsLoading) {
|
||||||
return <NotificationsSkeleton />;
|
return <NotificationsSkeleton />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (settingsError || servicesError) {
|
if (settingsError || servicesError || syncOperationsError) {
|
||||||
return (
|
return (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
<AlertCircle className="h-4 w-4" />
|
<AlertCircle className="h-4 w-4" />
|
||||||
<AlertTitle>Failed to load notifications</AlertTitle>
|
<AlertTitle>Failed to load system data</AlertTitle>
|
||||||
<AlertDescription className="space-y-3">
|
<AlertDescription className="space-y-3">
|
||||||
<p>
|
<p>
|
||||||
Unable to connect to the Leggen API. Please check your configuration
|
Unable to connect to the Leggen API. Please check your configuration
|
||||||
@@ -98,6 +116,7 @@ export default function Notifications() {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
refetchSettings();
|
refetchSettings();
|
||||||
refetchServices();
|
refetchServices();
|
||||||
|
refetchSyncOperations();
|
||||||
}}
|
}}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -131,6 +150,110 @@ export default function Notifications() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
{/* Sync Operations Section */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center space-x-2">
|
||||||
|
<Activity className="h-5 w-5 text-primary" />
|
||||||
|
<span>Sync Operations</span>
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>Recent synchronization activities</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{!syncOperations || syncOperations.operations.length === 0 ? (
|
||||||
|
<div className="text-center py-6">
|
||||||
|
<Activity className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-foreground mb-2">
|
||||||
|
No sync operations yet
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Sync operations will appear here once you start syncing your
|
||||||
|
accounts.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{syncOperations.operations.slice(0, 5).map((operation) => {
|
||||||
|
const startedAt = new Date(operation.started_at);
|
||||||
|
const isRunning = !operation.completed_at;
|
||||||
|
const duration = operation.duration_seconds
|
||||||
|
? `${Math.round(operation.duration_seconds)}s`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={operation.id}
|
||||||
|
className="flex items-center justify-between p-4 border rounded-lg hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div
|
||||||
|
className={`p-2 rounded-full ${
|
||||||
|
isRunning
|
||||||
|
? "bg-blue-100 text-blue-600"
|
||||||
|
: operation.success
|
||||||
|
? "bg-green-100 text-green-600"
|
||||||
|
: "bg-red-100 text-red-600"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{isRunning ? (
|
||||||
|
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||||
|
) : operation.success ? (
|
||||||
|
<CheckCircle className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<h4 className="text-sm font-medium text-foreground">
|
||||||
|
{isRunning
|
||||||
|
? "Sync Running"
|
||||||
|
: operation.success
|
||||||
|
? "Sync Completed"
|
||||||
|
: "Sync Failed"}
|
||||||
|
</h4>
|
||||||
|
<Badge variant="outline" className="text-xs">
|
||||||
|
{operation.trigger_type}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-4 mt-1 text-xs text-muted-foreground">
|
||||||
|
<span className="flex items-center space-x-1">
|
||||||
|
<Clock className="h-3 w-3" />
|
||||||
|
<span>
|
||||||
|
{startedAt.toLocaleDateString()}{" "}
|
||||||
|
{startedAt.toLocaleTimeString()}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
{duration && <span>Duration: {duration}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-right text-sm text-muted-foreground">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<User className="h-3 w-3" />
|
||||||
|
<span>{operation.accounts_processed} accounts</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-2 mt-1">
|
||||||
|
<TrendingUp className="h-3 w-3" />
|
||||||
|
<span>
|
||||||
|
{operation.transactions_added} new transactions
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{operation.errors.length > 0 && (
|
||||||
|
<div className="flex items-center space-x-2 mt-1 text-red-600">
|
||||||
|
<AlertCircle className="h-3 w-3" />
|
||||||
|
<span>{operation.errors.length} errors</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
{/* Test Notification Section */}
|
{/* Test Notification Section */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
|
|||||||
@@ -1,156 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
import { X, Download, RotateCcw } from "lucide-react";
|
|
||||||
|
|
||||||
interface BeforeInstallPromptEvent extends Event {
|
|
||||||
prompt(): Promise<void>;
|
|
||||||
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PWAPromptProps {
|
|
||||||
onInstall?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function PWAInstallPrompt({ onInstall }: PWAPromptProps) {
|
|
||||||
const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null);
|
|
||||||
const [showPrompt, setShowPrompt] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handler = (e: Event) => {
|
|
||||||
// Prevent the mini-infobar from appearing on mobile
|
|
||||||
e.preventDefault();
|
|
||||||
setDeferredPrompt(e as BeforeInstallPromptEvent);
|
|
||||||
setShowPrompt(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener("beforeinstallprompt", handler);
|
|
||||||
|
|
||||||
return () => window.removeEventListener("beforeinstallprompt", handler);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleInstall = async () => {
|
|
||||||
if (!deferredPrompt) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await deferredPrompt.prompt();
|
|
||||||
const { outcome } = await deferredPrompt.userChoice;
|
|
||||||
|
|
||||||
if (outcome === "accepted") {
|
|
||||||
onInstall?.();
|
|
||||||
}
|
|
||||||
|
|
||||||
setDeferredPrompt(null);
|
|
||||||
setShowPrompt(false);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error installing PWA:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDismiss = () => {
|
|
||||||
setShowPrompt(false);
|
|
||||||
setDeferredPrompt(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!showPrompt || !deferredPrompt) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:max-w-sm bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-4 z-50">
|
|
||||||
<div className="flex items-start gap-3">
|
|
||||||
<div className="flex-shrink-0">
|
|
||||||
<Download className="h-5 w-5 text-blue-600 dark:text-blue-400" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
|
||||||
Install Leggen
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
|
||||||
Add to your home screen for quick access
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={handleDismiss}
|
|
||||||
className="flex-shrink-0 text-gray-400 hover:text-gray-500 dark:hover:text-gray-300"
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="mt-3 flex gap-2">
|
|
||||||
<button
|
|
||||||
onClick={handleInstall}
|
|
||||||
className="flex-1 bg-blue-600 text-white text-sm font-medium px-3 py-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
|
||||||
>
|
|
||||||
Install
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={handleDismiss}
|
|
||||||
className="px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100"
|
|
||||||
>
|
|
||||||
Not now
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PWAUpdatePromptProps {
|
|
||||||
updateAvailable: boolean;
|
|
||||||
onUpdate: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function PWAUpdatePrompt({ updateAvailable, onUpdate }: PWAUpdatePromptProps) {
|
|
||||||
const [showPrompt, setShowPrompt] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (updateAvailable) {
|
|
||||||
setShowPrompt(true);
|
|
||||||
}
|
|
||||||
}, [updateAvailable]);
|
|
||||||
|
|
||||||
const handleUpdate = () => {
|
|
||||||
onUpdate();
|
|
||||||
setShowPrompt(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDismiss = () => {
|
|
||||||
setShowPrompt(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!showPrompt || !updateAvailable) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed top-4 left-4 right-4 md:left-auto md:right-4 md:max-w-sm bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-4 z-50">
|
|
||||||
<div className="flex items-start gap-3">
|
|
||||||
<div className="flex-shrink-0">
|
|
||||||
<RotateCcw className="h-5 w-5 text-green-600 dark:text-green-400" />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<p className="text-sm font-medium text-gray-900 dark:text-gray-100">
|
|
||||||
Update Available
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
|
||||||
A new version of Leggen is ready to install
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={handleDismiss}
|
|
||||||
className="flex-shrink-0 text-gray-400 hover:text-gray-500 dark:hover:text-gray-300"
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="mt-3 flex gap-2">
|
|
||||||
<button
|
|
||||||
onClick={handleUpdate}
|
|
||||||
className="flex-1 bg-green-600 text-white text-sm font-medium px-3 py-2 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500"
|
|
||||||
>
|
|
||||||
Update Now
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={handleDismiss}
|
|
||||||
className="px-3 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100"
|
|
||||||
>
|
|
||||||
Later
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
273
frontend/src/components/S3BackupConfigDrawer.tsx
Normal file
273
frontend/src/components/S3BackupConfigDrawer.tsx
Normal file
@@ -0,0 +1,273 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Cloud, TestTube } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import { Input } from "./ui/input";
|
||||||
|
import { Label } from "./ui/label";
|
||||||
|
import { Switch } from "./ui/switch";
|
||||||
|
import { EditButton } from "./ui/edit-button";
|
||||||
|
import {
|
||||||
|
Drawer,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerDescription,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerTrigger,
|
||||||
|
} from "./ui/drawer";
|
||||||
|
import type { BackupSettings, S3Config } from "../types/api";
|
||||||
|
|
||||||
|
interface S3BackupConfigDrawerProps {
|
||||||
|
settings?: BackupSettings;
|
||||||
|
trigger?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function S3BackupConfigDrawer({
|
||||||
|
settings,
|
||||||
|
trigger,
|
||||||
|
}: S3BackupConfigDrawerProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [config, setConfig] = useState<S3Config>({
|
||||||
|
access_key_id: "",
|
||||||
|
secret_access_key: "",
|
||||||
|
bucket_name: "",
|
||||||
|
region: "us-east-1",
|
||||||
|
endpoint_url: "",
|
||||||
|
path_style: false,
|
||||||
|
enabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (settings?.s3) {
|
||||||
|
setConfig({ ...settings.s3 });
|
||||||
|
}
|
||||||
|
}, [settings]);
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: (s3Config: S3Config) =>
|
||||||
|
apiClient.updateBackupSettings({
|
||||||
|
s3: s3Config,
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["backupSettings"] });
|
||||||
|
setOpen(false);
|
||||||
|
toast.success("S3 backup configuration saved successfully");
|
||||||
|
},
|
||||||
|
onError: (error: Error & { response?: { data?: { detail?: string } } }) => {
|
||||||
|
console.error("Failed to update S3 backup configuration:", error);
|
||||||
|
const message =
|
||||||
|
error?.response?.data?.detail ||
|
||||||
|
"Failed to save S3 configuration. Please check your settings and try again.";
|
||||||
|
toast.error(message);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const testMutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
apiClient.testBackupConnection({
|
||||||
|
service: "s3",
|
||||||
|
config: config,
|
||||||
|
}),
|
||||||
|
onSuccess: (response) => {
|
||||||
|
if (response.success) {
|
||||||
|
console.log("S3 connection test successful");
|
||||||
|
toast.success(
|
||||||
|
"S3 connection test successful! Your configuration is working correctly.",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.error("S3 connection test failed:", response.message);
|
||||||
|
toast.error(response.message || "S3 connection test failed. Please verify your credentials and settings.");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (error: Error & { response?: { data?: { detail?: string } } }) => {
|
||||||
|
console.error("Failed to test S3 connection:", error);
|
||||||
|
const message =
|
||||||
|
error?.response?.data?.detail ||
|
||||||
|
"S3 connection test failed. Please verify your credentials and settings.";
|
||||||
|
toast.error(message);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
updateMutation.mutate(config);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTest = () => {
|
||||||
|
testMutation.mutate();
|
||||||
|
};
|
||||||
|
|
||||||
|
const isConfigValid =
|
||||||
|
config.access_key_id.trim().length > 0 &&
|
||||||
|
config.secret_access_key.trim().length > 0 &&
|
||||||
|
config.bucket_name.trim().length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer open={open} onOpenChange={setOpen}>
|
||||||
|
<DrawerTrigger asChild>{trigger || <EditButton />}</DrawerTrigger>
|
||||||
|
<DrawerContent>
|
||||||
|
<div className="mx-auto w-full max-w-sm">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle className="flex items-center space-x-2">
|
||||||
|
<Cloud className="h-5 w-5 text-primary" />
|
||||||
|
<span>S3 Backup Configuration</span>
|
||||||
|
</DrawerTitle>
|
||||||
|
<DrawerDescription>
|
||||||
|
Configure S3 settings for automatic database backups
|
||||||
|
</DrawerDescription>
|
||||||
|
</DrawerHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="px-4 space-y-4">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Switch
|
||||||
|
id="enabled"
|
||||||
|
checked={config.enabled}
|
||||||
|
onCheckedChange={(checked) =>
|
||||||
|
setConfig({ ...config, enabled: checked })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Label htmlFor="enabled">Enable S3 backups</Label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{config.enabled && (
|
||||||
|
<>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="access_key_id">Access Key ID</Label>
|
||||||
|
<Input
|
||||||
|
id="access_key_id"
|
||||||
|
type="text"
|
||||||
|
value={config.access_key_id}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({ ...config, access_key_id: e.target.value })
|
||||||
|
}
|
||||||
|
placeholder="Your AWS Access Key ID"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="secret_access_key">Secret Access Key</Label>
|
||||||
|
<Input
|
||||||
|
id="secret_access_key"
|
||||||
|
type="password"
|
||||||
|
value={config.secret_access_key}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({
|
||||||
|
...config,
|
||||||
|
secret_access_key: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
placeholder="Your AWS Secret Access Key"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="bucket_name">Bucket Name</Label>
|
||||||
|
<Input
|
||||||
|
id="bucket_name"
|
||||||
|
type="text"
|
||||||
|
value={config.bucket_name}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({ ...config, bucket_name: e.target.value })
|
||||||
|
}
|
||||||
|
placeholder="my-backup-bucket"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="region">Region</Label>
|
||||||
|
<Input
|
||||||
|
id="region"
|
||||||
|
type="text"
|
||||||
|
value={config.region}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({ ...config, region: e.target.value })
|
||||||
|
}
|
||||||
|
placeholder="us-east-1"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="endpoint_url">
|
||||||
|
Custom Endpoint URL (Optional)
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="endpoint_url"
|
||||||
|
type="url"
|
||||||
|
value={config.endpoint_url || ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({ ...config, endpoint_url: e.target.value })
|
||||||
|
}
|
||||||
|
placeholder="https://custom-s3-endpoint.com"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
For S3-compatible services like MinIO or DigitalOcean Spaces
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Switch
|
||||||
|
id="path_style"
|
||||||
|
checked={config.path_style}
|
||||||
|
onCheckedChange={(checked) =>
|
||||||
|
setConfig({ ...config, path_style: checked })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Label htmlFor="path_style">Use path-style addressing</Label>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Enable for older S3 implementations or certain S3-compatible
|
||||||
|
services
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DrawerFooter className="px-0">
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={updateMutation.isPending || !config.enabled}
|
||||||
|
>
|
||||||
|
{updateMutation.isPending
|
||||||
|
? "Saving..."
|
||||||
|
: "Save Configuration"}
|
||||||
|
</Button>
|
||||||
|
{config.enabled && isConfigValid && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleTest}
|
||||||
|
disabled={testMutation.isPending}
|
||||||
|
>
|
||||||
|
{testMutation.isPending ? (
|
||||||
|
<>
|
||||||
|
<TestTube className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Testing...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<TestTube className="h-4 w-4 mr-2" />
|
||||||
|
Test
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<DrawerClose asChild>
|
||||||
|
<Button variant="ghost">Cancel</Button>
|
||||||
|
</DrawerClose>
|
||||||
|
</DrawerFooter>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
}
|
||||||
984
frontend/src/components/Settings.tsx
Normal file
984
frontend/src/components/Settings.tsx
Normal file
@@ -0,0 +1,984 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
CreditCard,
|
||||||
|
TrendingUp,
|
||||||
|
TrendingDown,
|
||||||
|
Building2,
|
||||||
|
RefreshCw,
|
||||||
|
AlertCircle,
|
||||||
|
Edit2,
|
||||||
|
Check,
|
||||||
|
X,
|
||||||
|
Bell,
|
||||||
|
MessageSquare,
|
||||||
|
Send,
|
||||||
|
Trash2,
|
||||||
|
User,
|
||||||
|
Filter,
|
||||||
|
Cloud,
|
||||||
|
Archive,
|
||||||
|
Eye,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import { formatCurrency, formatDate } from "../lib/utils";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "./ui/card";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
|
||||||
|
import { Label } from "./ui/label";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
|
||||||
|
import AccountsSkeleton from "./AccountsSkeleton";
|
||||||
|
import NotificationFiltersDrawer from "./NotificationFiltersDrawer";
|
||||||
|
import DiscordConfigDrawer from "./DiscordConfigDrawer";
|
||||||
|
import TelegramConfigDrawer from "./TelegramConfigDrawer";
|
||||||
|
import AddBankAccountDrawer from "./AddBankAccountDrawer";
|
||||||
|
import S3BackupConfigDrawer from "./S3BackupConfigDrawer";
|
||||||
|
import type {
|
||||||
|
Account,
|
||||||
|
Balance,
|
||||||
|
NotificationSettings,
|
||||||
|
NotificationService,
|
||||||
|
BackupSettings,
|
||||||
|
BackupInfo,
|
||||||
|
} from "../types/api";
|
||||||
|
|
||||||
|
// Helper function to get status indicator color and styles
|
||||||
|
const getStatusIndicator = (status: string) => {
|
||||||
|
const statusLower = status.toLowerCase();
|
||||||
|
|
||||||
|
switch (statusLower) {
|
||||||
|
case "ready":
|
||||||
|
return {
|
||||||
|
color: "bg-green-500",
|
||||||
|
tooltip: "Ready",
|
||||||
|
};
|
||||||
|
case "pending":
|
||||||
|
return {
|
||||||
|
color: "bg-amber-500",
|
||||||
|
tooltip: "Pending",
|
||||||
|
};
|
||||||
|
case "error":
|
||||||
|
case "failed":
|
||||||
|
return {
|
||||||
|
color: "bg-destructive",
|
||||||
|
tooltip: "Error",
|
||||||
|
};
|
||||||
|
case "inactive":
|
||||||
|
return {
|
||||||
|
color: "bg-muted-foreground",
|
||||||
|
tooltip: "Inactive",
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return {
|
||||||
|
color: "bg-primary",
|
||||||
|
tooltip: status,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function Settings() {
|
||||||
|
const [editingAccountId, setEditingAccountId] = useState<string | null>(null);
|
||||||
|
const [editingName, setEditingName] = useState("");
|
||||||
|
const [failedImages, setFailedImages] = useState<Set<string>>(new Set());
|
||||||
|
const [showBackups, setShowBackups] = useState(false);
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
// Account queries
|
||||||
|
const {
|
||||||
|
data: accounts,
|
||||||
|
isLoading: accountsLoading,
|
||||||
|
error: accountsError,
|
||||||
|
refetch: refetchAccounts,
|
||||||
|
} = useQuery<Account[]>({
|
||||||
|
queryKey: ["accounts"],
|
||||||
|
queryFn: apiClient.getAccounts,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: balances } = useQuery<Balance[]>({
|
||||||
|
queryKey: ["balances"],
|
||||||
|
queryFn: () => apiClient.getBalances(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Notification queries
|
||||||
|
const {
|
||||||
|
data: notificationSettings,
|
||||||
|
isLoading: settingsLoading,
|
||||||
|
error: settingsError,
|
||||||
|
refetch: refetchSettings,
|
||||||
|
} = useQuery<NotificationSettings>({
|
||||||
|
queryKey: ["notificationSettings"],
|
||||||
|
queryFn: apiClient.getNotificationSettings,
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: services,
|
||||||
|
isLoading: servicesLoading,
|
||||||
|
error: servicesError,
|
||||||
|
refetch: refetchServices,
|
||||||
|
} = useQuery<NotificationService[]>({
|
||||||
|
queryKey: ["notificationServices"],
|
||||||
|
queryFn: apiClient.getNotificationServices,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: bankConnections } = useQuery({
|
||||||
|
queryKey: ["bankConnections"],
|
||||||
|
queryFn: apiClient.getBankConnectionsStatus,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Backup queries
|
||||||
|
const {
|
||||||
|
data: backupSettings,
|
||||||
|
isLoading: backupLoading,
|
||||||
|
error: backupError,
|
||||||
|
refetch: refetchBackup,
|
||||||
|
} = useQuery<BackupSettings>({
|
||||||
|
queryKey: ["backupSettings"],
|
||||||
|
queryFn: apiClient.getBackupSettings,
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: backups,
|
||||||
|
isLoading: backupsLoading,
|
||||||
|
error: backupsError,
|
||||||
|
refetch: refetchBackups,
|
||||||
|
} = useQuery<BackupInfo[]>({
|
||||||
|
queryKey: ["backups"],
|
||||||
|
queryFn: apiClient.listBackups,
|
||||||
|
enabled: showBackups,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Account mutations
|
||||||
|
const updateAccountMutation = useMutation({
|
||||||
|
mutationFn: ({ id, display_name }: { id: string; display_name: string }) =>
|
||||||
|
apiClient.updateAccount(id, { display_name }),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["accounts"] });
|
||||||
|
setEditingAccountId(null);
|
||||||
|
setEditingName("");
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to update account:", error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Notification mutations
|
||||||
|
const deleteServiceMutation = useMutation({
|
||||||
|
mutationFn: apiClient.deleteNotificationService,
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["notificationSettings"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["notificationServices"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Bank connection mutations
|
||||||
|
const deleteBankConnectionMutation = useMutation({
|
||||||
|
mutationFn: apiClient.deleteBankConnection,
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["accounts"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["bankConnections"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["balances"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Backup mutations
|
||||||
|
const createBackupMutation = useMutation({
|
||||||
|
mutationFn: () => apiClient.performBackupOperation({ operation: "backup" }),
|
||||||
|
onSuccess: (response) => {
|
||||||
|
if (response.success) {
|
||||||
|
toast.success(response.message || "Backup created successfully!");
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["backups"] });
|
||||||
|
} else {
|
||||||
|
toast.error(response.message || "Failed to create backup.");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (error: Error & { response?: { data?: { detail?: string } } }) => {
|
||||||
|
console.error("Failed to create backup:", error);
|
||||||
|
const message =
|
||||||
|
error?.response?.data?.detail ||
|
||||||
|
"Failed to create backup. Please check your S3 configuration.";
|
||||||
|
toast.error(message);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Account handlers
|
||||||
|
const handleEditStart = (account: Account) => {
|
||||||
|
setEditingAccountId(account.id);
|
||||||
|
setEditingName(account.display_name || account.name || "");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEditSave = () => {
|
||||||
|
if (editingAccountId && editingName.trim()) {
|
||||||
|
updateAccountMutation.mutate({
|
||||||
|
id: editingAccountId,
|
||||||
|
display_name: editingName.trim(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEditCancel = () => {
|
||||||
|
setEditingAccountId(null);
|
||||||
|
setEditingName("");
|
||||||
|
};
|
||||||
|
|
||||||
|
// Notification handlers
|
||||||
|
const handleDeleteService = (serviceName: string) => {
|
||||||
|
if (
|
||||||
|
confirm(
|
||||||
|
`Are you sure you want to delete the ${serviceName} notification service?`,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
deleteServiceMutation.mutate(serviceName.toLowerCase());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Backup handlers
|
||||||
|
const handleCreateBackup = () => {
|
||||||
|
if (!backupSettings?.s3?.enabled) {
|
||||||
|
toast.error("S3 backup is not enabled. Please configure and enable S3 backup first.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
createBackupMutation.mutate();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleViewBackups = () => {
|
||||||
|
if (!backupSettings?.s3?.enabled) {
|
||||||
|
toast.error("S3 backup is not enabled. Please configure and enable S3 backup first.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setShowBackups(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isLoading =
|
||||||
|
accountsLoading || settingsLoading || servicesLoading || backupLoading;
|
||||||
|
const hasError =
|
||||||
|
accountsError || settingsError || servicesError || backupError;
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <AccountsSkeleton />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasError) {
|
||||||
|
return (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertTitle>Failed to load settings</AlertTitle>
|
||||||
|
<AlertDescription className="space-y-3">
|
||||||
|
<p>
|
||||||
|
Unable to connect to the Leggen API. Please check your configuration
|
||||||
|
and ensure the API server is running.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
refetchAccounts();
|
||||||
|
refetchSettings();
|
||||||
|
refetchServices();
|
||||||
|
refetchBackup();
|
||||||
|
}}
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<RefreshCw className="h-4 w-4 mr-2" />
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<Tabs defaultValue="accounts" className="space-y-6">
|
||||||
|
<TabsList className="grid w-full grid-cols-3">
|
||||||
|
<TabsTrigger value="accounts" className="flex items-center space-x-2">
|
||||||
|
<User className="h-4 w-4" />
|
||||||
|
<span>Accounts</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger
|
||||||
|
value="notifications"
|
||||||
|
className="flex items-center space-x-2"
|
||||||
|
>
|
||||||
|
<Bell className="h-4 w-4" />
|
||||||
|
<span>Notifications</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="backup" className="flex items-center space-x-2">
|
||||||
|
<Cloud className="h-4 w-4" />
|
||||||
|
<span>Backup</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
|
||||||
|
<TabsContent value="accounts" className="space-y-6">
|
||||||
|
{/* Account Management Section */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Account Management</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Manage your connected bank accounts and customize their display
|
||||||
|
names
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
{!accounts || accounts.length === 0 ? (
|
||||||
|
<CardContent className="p-6 text-center">
|
||||||
|
<CreditCard className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-foreground mb-2">
|
||||||
|
No accounts found
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground mb-4">
|
||||||
|
Connect your first bank account to get started with Leggen.
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
) : (
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<div className="divide-y divide-border">
|
||||||
|
{accounts.map((account) => {
|
||||||
|
// Get balance from account's balances array or fallback to balances query
|
||||||
|
const accountBalance = account.balances?.[0];
|
||||||
|
const fallbackBalance = balances?.find(
|
||||||
|
(b) => b.account_id === account.id,
|
||||||
|
);
|
||||||
|
const balance =
|
||||||
|
accountBalance?.amount ||
|
||||||
|
fallbackBalance?.balance_amount ||
|
||||||
|
0;
|
||||||
|
const currency =
|
||||||
|
accountBalance?.currency ||
|
||||||
|
fallbackBalance?.currency ||
|
||||||
|
account.currency ||
|
||||||
|
"EUR";
|
||||||
|
const isPositive = balance >= 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={account.id}
|
||||||
|
className="p-4 sm:p-6 hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
{/* Mobile layout - stack vertically */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4">
|
||||||
|
<div className="flex items-start sm:items-center space-x-3 sm:space-x-4 min-w-0 flex-1">
|
||||||
|
<div className="flex-shrink-0 w-10 h-10 sm:w-12 sm:h-12 rounded-full overflow-hidden bg-muted flex items-center justify-center">
|
||||||
|
{account.logo && !failedImages.has(account.id) ? (
|
||||||
|
<img
|
||||||
|
src={account.logo}
|
||||||
|
alt={`${account.institution_id} logo`}
|
||||||
|
className="w-6 h-6 sm:w-8 sm:h-8 object-contain"
|
||||||
|
onError={() => {
|
||||||
|
console.warn(
|
||||||
|
`Failed to load bank logo for ${account.institution_id}: ${account.logo}`,
|
||||||
|
);
|
||||||
|
setFailedImages(
|
||||||
|
(prev) => new Set([...prev, account.id]),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Building2 className="h-5 w-5 sm:h-6 sm:w-6 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
{editingAccountId === account.id ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={editingName}
|
||||||
|
onChange={(e) =>
|
||||||
|
setEditingName(e.target.value)
|
||||||
|
}
|
||||||
|
className="flex-1 px-3 py-1 text-base sm:text-lg font-medium border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring"
|
||||||
|
placeholder="Custom account name"
|
||||||
|
name="search"
|
||||||
|
autoComplete="off"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") handleEditSave();
|
||||||
|
if (e.key === "Escape")
|
||||||
|
handleEditCancel();
|
||||||
|
}}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
onClick={handleEditSave}
|
||||||
|
disabled={
|
||||||
|
!editingName.trim() ||
|
||||||
|
updateAccountMutation.isPending
|
||||||
|
}
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 text-green-600 hover:text-green-700 hover:bg-green-100"
|
||||||
|
title="Save changes"
|
||||||
|
>
|
||||||
|
<Check className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleEditCancel}
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8"
|
||||||
|
title="Cancel editing"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground truncate">
|
||||||
|
{account.institution_id}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center space-x-2 min-w-0">
|
||||||
|
<h4 className="text-base sm:text-lg font-medium text-foreground truncate">
|
||||||
|
{account.display_name ||
|
||||||
|
account.name ||
|
||||||
|
"Unnamed Account"}
|
||||||
|
</h4>
|
||||||
|
<Button
|
||||||
|
onClick={() => handleEditStart(account)}
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-7 w-7 flex-shrink-0"
|
||||||
|
title="Edit account name"
|
||||||
|
>
|
||||||
|
<Edit2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground truncate">
|
||||||
|
{account.institution_id}
|
||||||
|
</p>
|
||||||
|
{account.iban && (
|
||||||
|
<p className="text-xs text-muted-foreground mt-1 font-mono break-all sm:break-normal">
|
||||||
|
IBAN: {account.iban}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Balance and date section */}
|
||||||
|
<div className="flex items-center justify-between sm:flex-col sm:items-end sm:text-right flex-shrink-0">
|
||||||
|
{/* Date and status indicator - left on mobile, bottom on desktop */}
|
||||||
|
<div className="flex items-center space-x-2 order-1 sm:order-2">
|
||||||
|
<div
|
||||||
|
className={`w-3 h-3 rounded-full ${getStatusIndicator(account.status).color} relative group cursor-help`}
|
||||||
|
role="img"
|
||||||
|
aria-label={`Account status: ${getStatusIndicator(account.status).tooltip}`}
|
||||||
|
>
|
||||||
|
{/* Tooltip */}
|
||||||
|
<div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 hidden group-hover:block bg-gray-900 text-white text-xs rounded py-1 px-2 whitespace-nowrap z-10">
|
||||||
|
{getStatusIndicator(account.status).tooltip}
|
||||||
|
<div className="absolute top-full left-1/2 transform -translate-x-1/2 border-2 border-transparent border-t-gray-900"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs sm:text-sm text-muted-foreground whitespace-nowrap">
|
||||||
|
Updated{" "}
|
||||||
|
{formatDate(
|
||||||
|
account.last_accessed || account.created,
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Balance - right on mobile, top on desktop */}
|
||||||
|
<div className="flex items-center space-x-2 order-2 sm:order-1">
|
||||||
|
{isPositive ? (
|
||||||
|
<TrendingUp className="h-4 w-4 text-green-500" />
|
||||||
|
) : (
|
||||||
|
<TrendingDown className="h-4 w-4 text-red-500" />
|
||||||
|
)}
|
||||||
|
<p
|
||||||
|
className={`text-base sm:text-lg font-semibold ${
|
||||||
|
isPositive ? "text-green-600" : "text-red-600"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{formatCurrency(balance, currency)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Bank Connections Status */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<CardTitle>Bank Connections</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Status of all bank connection requests and their
|
||||||
|
authorization state
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
<AddBankAccountDrawer />
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
{!bankConnections || bankConnections.length === 0 ? (
|
||||||
|
<CardContent className="p-6 text-center">
|
||||||
|
<Building2 className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-foreground mb-2">
|
||||||
|
No bank connections found
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Bank connection requests will appear here after you connect
|
||||||
|
accounts.
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
) : (
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<div className="divide-y divide-border">
|
||||||
|
{bankConnections.map((connection) => {
|
||||||
|
const statusColor =
|
||||||
|
connection.status.toLowerCase() === "ln"
|
||||||
|
? "bg-green-500"
|
||||||
|
: connection.status.toLowerCase() === "cr"
|
||||||
|
? "bg-amber-500"
|
||||||
|
: connection.status.toLowerCase() === "ex"
|
||||||
|
? "bg-red-500"
|
||||||
|
: "bg-muted-foreground";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={connection.requisition_id}
|
||||||
|
className="p-4 sm:p-6 hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center space-x-4 min-w-0 flex-1">
|
||||||
|
<div className="flex-shrink-0 w-10 h-10 rounded-full bg-muted flex items-center justify-center">
|
||||||
|
<Building2 className="h-5 w-5 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<h4 className="text-base font-medium text-foreground truncate">
|
||||||
|
{connection.bank_name}
|
||||||
|
</h4>
|
||||||
|
<div
|
||||||
|
className={`w-3 h-3 rounded-full ${statusColor}`}
|
||||||
|
title={connection.status_display}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{connection.status_display} •{" "}
|
||||||
|
{connection.accounts_count} account
|
||||||
|
{connection.accounts_count !== 1 ? "s" : ""}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground font-mono">
|
||||||
|
ID: {connection.requisition_id}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2 flex-shrink-0">
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Created {formatDate(connection.created_at)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
const isWorking =
|
||||||
|
connection.status.toLowerCase() === "ln";
|
||||||
|
const message = isWorking
|
||||||
|
? `Are you sure you want to disconnect "${connection.bank_name}"? This will stop syncing new transactions but keep your existing transaction history.`
|
||||||
|
: `Delete connection to ${connection.bank_name}?`;
|
||||||
|
|
||||||
|
if (confirm(message)) {
|
||||||
|
deleteBankConnectionMutation.mutate(
|
||||||
|
connection.requisition_id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={deleteBankConnectionMutation.isPending}
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 text-muted-foreground hover:text-destructive"
|
||||||
|
title="Delete connection"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="notifications" className="space-y-6">
|
||||||
|
{/* Notification Services */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center space-x-2">
|
||||||
|
<Bell className="h-5 w-5 text-primary" />
|
||||||
|
<span>Notification Services</span>
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Manage your notification services
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
{!services || services.length === 0 ? (
|
||||||
|
<CardContent className="text-center">
|
||||||
|
<Bell className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-foreground mb-2">
|
||||||
|
No notification services configured
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Configure notification services in your backend to receive
|
||||||
|
alerts.
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
) : (
|
||||||
|
<CardContent className="p-0">
|
||||||
|
<div className="divide-y divide-border">
|
||||||
|
{services.map((service) => (
|
||||||
|
<div
|
||||||
|
key={service.name}
|
||||||
|
className="p-6 hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div className="p-3 bg-muted rounded-full">
|
||||||
|
{service.name.toLowerCase().includes("discord") ? (
|
||||||
|
<MessageSquare className="h-6 w-6 text-muted-foreground" />
|
||||||
|
) : service.name
|
||||||
|
.toLowerCase()
|
||||||
|
.includes("telegram") ? (
|
||||||
|
<Send className="h-6 w-6 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<Bell className="h-6 w-6 text-muted-foreground" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<h4 className="text-lg font-medium text-foreground capitalize">
|
||||||
|
{service.name}
|
||||||
|
</h4>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<div
|
||||||
|
className={`w-2 h-2 rounded-full ${
|
||||||
|
service.enabled && service.configured
|
||||||
|
? "bg-green-500"
|
||||||
|
: service.enabled
|
||||||
|
? "bg-amber-500"
|
||||||
|
: "bg-muted-foreground"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-muted-foreground">
|
||||||
|
{service.enabled && service.configured
|
||||||
|
? "Active"
|
||||||
|
: service.enabled
|
||||||
|
? "Needs Configuration"
|
||||||
|
: "Disabled"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
{service.name.toLowerCase().includes("discord") ? (
|
||||||
|
<DiscordConfigDrawer
|
||||||
|
settings={notificationSettings}
|
||||||
|
/>
|
||||||
|
) : service.name
|
||||||
|
.toLowerCase()
|
||||||
|
.includes("telegram") ? (
|
||||||
|
<TelegramConfigDrawer
|
||||||
|
settings={notificationSettings}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
onClick={() => handleDeleteService(service.name)}
|
||||||
|
disabled={deleteServiceMutation.isPending}
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Notification Filters */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<CardTitle className="flex items-center space-x-2">
|
||||||
|
<Filter className="h-5 w-5 text-primary" />
|
||||||
|
<span>Notification Filters</span>
|
||||||
|
</CardTitle>
|
||||||
|
<NotificationFiltersDrawer settings={notificationSettings} />
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{notificationSettings?.filters ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="bg-muted rounded-md p-4">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs font-medium text-muted-foreground mb-2 block">
|
||||||
|
Case Insensitive Filters
|
||||||
|
</Label>
|
||||||
|
<div className="min-h-[2rem] flex flex-wrap gap-1">
|
||||||
|
{notificationSettings.filters.case_insensitive
|
||||||
|
.length > 0 ? (
|
||||||
|
notificationSettings.filters.case_insensitive.map(
|
||||||
|
(filter, index) => (
|
||||||
|
<span
|
||||||
|
key={index}
|
||||||
|
className="inline-flex items-center px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs"
|
||||||
|
>
|
||||||
|
{filter}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
None
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs font-medium text-muted-foreground mb-2 block">
|
||||||
|
Case Sensitive Filters
|
||||||
|
</Label>
|
||||||
|
<div className="min-h-[2rem] flex flex-wrap gap-1">
|
||||||
|
{notificationSettings.filters.case_sensitive &&
|
||||||
|
notificationSettings.filters.case_sensitive.length >
|
||||||
|
0 ? (
|
||||||
|
notificationSettings.filters.case_sensitive.map(
|
||||||
|
(filter, index) => (
|
||||||
|
<span
|
||||||
|
key={index}
|
||||||
|
className="inline-flex items-center px-2 py-1 bg-secondary text-secondary-foreground rounded text-xs"
|
||||||
|
>
|
||||||
|
{filter}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
None
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Filters determine which transaction descriptions will
|
||||||
|
trigger notifications. Add terms to exclude transactions
|
||||||
|
containing those words.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<Filter className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-foreground mb-2">
|
||||||
|
No notification filters configured
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground mb-4">
|
||||||
|
Set up filters to control which transactions trigger
|
||||||
|
notifications.
|
||||||
|
</p>
|
||||||
|
<NotificationFiltersDrawer settings={notificationSettings} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="backup" className="space-y-6">
|
||||||
|
{/* S3 Backup Configuration */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center space-x-2">
|
||||||
|
<Cloud className="h-5 w-5 text-primary" />
|
||||||
|
<span>S3 Backup Configuration</span>
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Configure automatic database backups to Amazon S3 or
|
||||||
|
S3-compatible storage
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent>
|
||||||
|
{!backupSettings?.s3 ? (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<Cloud className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-foreground mb-2">
|
||||||
|
No S3 backup configured
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground mb-4">
|
||||||
|
Set up S3 backup to automatically backup your database to
|
||||||
|
the cloud.
|
||||||
|
</p>
|
||||||
|
<S3BackupConfigDrawer settings={backupSettings} />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between p-4 border rounded-lg">
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div className="p-3 bg-muted rounded-full">
|
||||||
|
<Cloud className="h-6 w-6 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<h4 className="text-lg font-medium text-foreground">
|
||||||
|
S3 Backup
|
||||||
|
</h4>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<div
|
||||||
|
className={`w-2 h-2 rounded-full ${
|
||||||
|
backupSettings.s3.enabled
|
||||||
|
? "bg-green-500"
|
||||||
|
: "bg-muted-foreground"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-muted-foreground">
|
||||||
|
{backupSettings.s3.enabled
|
||||||
|
? "Enabled"
|
||||||
|
: "Disabled"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 space-y-1">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
<span className="font-medium">Bucket:</span>{" "}
|
||||||
|
{backupSettings.s3.bucket_name}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
<span className="font-medium">Region:</span>{" "}
|
||||||
|
{backupSettings.s3.region}
|
||||||
|
</p>
|
||||||
|
{backupSettings.s3.endpoint_url && (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
<span className="font-medium">Endpoint:</span>{" "}
|
||||||
|
{backupSettings.s3.endpoint_url}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<S3BackupConfigDrawer settings={backupSettings} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-4 bg-muted rounded-lg">
|
||||||
|
<h5 className="font-medium mb-2">Backup Information</h5>
|
||||||
|
<p className="text-sm text-muted-foreground mb-3">
|
||||||
|
Database backups are stored in the "leggen_backups/"
|
||||||
|
folder in your S3 bucket. Backups include the complete
|
||||||
|
SQLite database file.
|
||||||
|
</p>
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleCreateBackup}
|
||||||
|
disabled={createBackupMutation.isPending}
|
||||||
|
>
|
||||||
|
{createBackupMutation.isPending ? (
|
||||||
|
<>
|
||||||
|
<Archive className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Creating...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Archive className="h-4 w-4 mr-2" />
|
||||||
|
Create Backup Now
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleViewBackups}
|
||||||
|
>
|
||||||
|
<Eye className="h-4 w-4 mr-2" />
|
||||||
|
View Backups
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Backup List Modal/View */}
|
||||||
|
{showBackups && (
|
||||||
|
<div className="mt-6 p-4 border rounded-lg bg-background">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h5 className="font-medium">Available Backups</h5>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setShowBackups(false)}
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{backupsLoading ? (
|
||||||
|
<p className="text-sm text-muted-foreground">Loading backups...</p>
|
||||||
|
) : backupsError ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-sm text-destructive">Failed to load backups</p>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => refetchBackups()}
|
||||||
|
>
|
||||||
|
<RefreshCw className="h-4 w-4 mr-2" />
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : !backups || backups.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No backups found</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{backups.map((backup, index) => (
|
||||||
|
<div
|
||||||
|
key={backup.key || index}
|
||||||
|
className="flex items-center justify-between p-3 border rounded bg-muted/50"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium">{backup.key}</p>
|
||||||
|
<div className="flex items-center space-x-4 text-xs text-muted-foreground mt-1">
|
||||||
|
<span>Modified: {formatDate(backup.last_modified)}</span>
|
||||||
|
<span>Size: {(backup.size / 1024 / 1024).toFixed(2)} MB</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
import { Link, useLocation } from "@tanstack/react-router";
|
|
||||||
import {
|
|
||||||
List,
|
|
||||||
BarChart3,
|
|
||||||
Bell,
|
|
||||||
TrendingUp,
|
|
||||||
X,
|
|
||||||
ChevronDown,
|
|
||||||
ChevronUp,
|
|
||||||
Settings,
|
|
||||||
Building2,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { Logo } from "./ui/logo";
|
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
import { apiClient } from "../lib/api";
|
|
||||||
import { formatCurrency } from "../lib/utils";
|
|
||||||
import { cn } from "../lib/utils";
|
|
||||||
import { useState } from "react";
|
|
||||||
import type { Account } from "../types/api";
|
|
||||||
|
|
||||||
|
|
||||||
const navigation = [
|
|
||||||
{ name: "Overview", icon: List, to: "/" },
|
|
||||||
{ name: "Analytics", icon: BarChart3, to: "/analytics" },
|
|
||||||
{ name: "Notifications", icon: Bell, to: "/notifications" },
|
|
||||||
{ name: "Settings", icon: Settings, to: "/settings" },
|
|
||||||
];
|
|
||||||
|
|
||||||
interface SidebarProps {
|
|
||||||
sidebarOpen: boolean;
|
|
||||||
setSidebarOpen: (open: boolean) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Sidebar({ sidebarOpen, setSidebarOpen }: SidebarProps) {
|
|
||||||
const location = useLocation();
|
|
||||||
const [accountsExpanded, setAccountsExpanded] = useState(false);
|
|
||||||
|
|
||||||
const { data: accounts } = useQuery<Account[]>({
|
|
||||||
queryKey: ["accounts"],
|
|
||||||
queryFn: apiClient.getAccounts,
|
|
||||||
});
|
|
||||||
|
|
||||||
const totalBalance =
|
|
||||||
accounts?.reduce((sum, account) => {
|
|
||||||
const primaryBalance = account.balances?.[0]?.amount || 0;
|
|
||||||
return sum + primaryBalance;
|
|
||||||
}, 0) || 0;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-y-0 left-0 z-50 w-64 bg-card shadow-lg transform transition-transform duration-300 ease-in-out lg:translate-x-0 lg:static lg:inset-0",
|
|
||||||
sidebarOpen ? "translate-x-0" : "-translate-x-full",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-between h-16 px-6 border-b border-border">
|
|
||||||
<Link
|
|
||||||
to="/"
|
|
||||||
onClick={() => setSidebarOpen(false)}
|
|
||||||
className="flex items-center space-x-2 hover:opacity-80 transition-opacity"
|
|
||||||
>
|
|
||||||
<Logo size={32} />
|
|
||||||
<h1 className="text-xl font-bold text-card-foreground">Leggen</h1>
|
|
||||||
</Link>
|
|
||||||
<button
|
|
||||||
onClick={() => setSidebarOpen(false)}
|
|
||||||
className="lg:hidden p-1 rounded-md text-muted-foreground hover:text-foreground"
|
|
||||||
>
|
|
||||||
<X className="h-6 w-6" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<nav className="px-6 py-4">
|
|
||||||
<div className="space-y-1">
|
|
||||||
{navigation.map((item) => (
|
|
||||||
<Link
|
|
||||||
key={item.to}
|
|
||||||
to={item.to}
|
|
||||||
onClick={() => setSidebarOpen(false)}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center w-full px-3 py-2 text-sm font-medium rounded-md transition-colors",
|
|
||||||
location.pathname === item.to
|
|
||||||
? "bg-primary text-primary-foreground"
|
|
||||||
: "text-card-foreground hover:text-card-foreground hover:bg-accent",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<item.icon className="mr-3 h-5 w-5" />
|
|
||||||
{item.name}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
{/* Collapsible Account Summary in Sidebar */}
|
|
||||||
<div className="px-6 pt-4 pb-6 border-t border-border mt-auto">
|
|
||||||
<div className="bg-muted rounded-lg">
|
|
||||||
{/* Collapsible Header */}
|
|
||||||
<button
|
|
||||||
onClick={() => setAccountsExpanded(!accountsExpanded)}
|
|
||||||
className="w-full p-4 flex items-center justify-between hover:bg-muted/80 transition-colors rounded-lg"
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-between w-full">
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<span className="text-sm font-medium text-muted-foreground">
|
|
||||||
Total Balance
|
|
||||||
</span>
|
|
||||||
<TrendingUp className="h-4 w-4 text-green-500" />
|
|
||||||
</div>
|
|
||||||
{accountsExpanded ? (
|
|
||||||
<ChevronUp className="h-4 w-4 text-muted-foreground" />
|
|
||||||
) : (
|
|
||||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div className="px-4 pb-2">
|
|
||||||
<p className="text-2xl font-bold text-foreground">
|
|
||||||
{formatCurrency(totalBalance)}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
{accounts?.length || 0} accounts
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Expanded Account Details */}
|
|
||||||
{accountsExpanded && accounts && accounts.length > 0 && (
|
|
||||||
<div className="border-t border-border/50 max-h-64 overflow-y-auto">
|
|
||||||
{accounts.map((account) => {
|
|
||||||
const primaryBalance = account.balances?.[0]?.amount || 0;
|
|
||||||
const currency = account.balances?.[0]?.currency || account.currency || "EUR";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={account.id}
|
|
||||||
className="p-3 border-b border-border/30 last:border-b-0 hover:bg-muted/50 transition-colors"
|
|
||||||
>
|
|
||||||
<div className="flex items-start space-x-2">
|
|
||||||
<div className="flex-shrink-0 p-1 bg-background rounded">
|
|
||||||
<Building2 className="h-3 w-3 text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1 min-w-0 flex-1">
|
|
||||||
<p className="text-sm font-medium text-foreground truncate">
|
|
||||||
{account.display_name || account.name || "Unnamed Account"}
|
|
||||||
</p>
|
|
||||||
<p className="text-sm font-semibold text-foreground">
|
|
||||||
{formatCurrency(primaryBalance, currency)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,22 +1,20 @@
|
|||||||
import { useLocation } from "@tanstack/react-router";
|
import { useLocation } from "@tanstack/react-router";
|
||||||
import { Menu, Activity, Wifi, WifiOff } from "lucide-react";
|
import { Activity, Wifi, WifiOff } from "lucide-react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { apiClient } from "../lib/api";
|
import { apiClient } from "../lib/api";
|
||||||
import { ThemeToggle } from "./ui/theme-toggle";
|
import { ThemeToggle } from "./ui/theme-toggle";
|
||||||
|
import { Separator } from "./ui/separator";
|
||||||
|
import { SidebarTrigger } from "./ui/sidebar";
|
||||||
|
|
||||||
const navigation = [
|
const navigation = [
|
||||||
{ name: "Overview", to: "/" },
|
{ name: "Overview", to: "/" },
|
||||||
{ name: "Transactions", to: "/transactions" },
|
{ name: "Transactions", to: "/transactions" },
|
||||||
{ name: "Analytics", to: "/analytics" },
|
{ name: "Analytics", to: "/analytics" },
|
||||||
{ name: "Notifications", to: "/notifications" },
|
{ name: "System", to: "/system" },
|
||||||
{ name: "Settings", to: "/settings" },
|
{ name: "Settings", to: "/settings" },
|
||||||
];
|
];
|
||||||
|
|
||||||
interface HeaderProps {
|
export function SiteHeader() {
|
||||||
setSidebarOpen: (open: boolean) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Header({ setSidebarOpen }: HeaderProps) {
|
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const currentPage =
|
const currentPage =
|
||||||
navigation.find((item) => item.to === location.pathname)?.name ||
|
navigation.find((item) => item.to === location.pathname)?.name ||
|
||||||
@@ -33,20 +31,32 @@ export default function Header({ setSidebarOpen }: HeaderProps) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="lg:static sticky top-0 z-50 bg-card shadow-sm border-b border-border pt-safe-top">
|
<header className="flex h-16 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear pt-safe-top">
|
||||||
<div className="flex items-center justify-between h-16 px-6">
|
<div className="flex w-full items-center gap-1 px-4 lg:gap-2 lg:px-6">
|
||||||
<div className="flex items-center">
|
<SidebarTrigger className="-ml-1" />
|
||||||
<button
|
<Separator
|
||||||
onClick={() => setSidebarOpen(true)}
|
orientation="vertical"
|
||||||
className="lg:hidden p-1 rounded-md text-muted-foreground hover:text-foreground"
|
className="mx-2 data-[orientation=vertical]:h-4"
|
||||||
>
|
/>
|
||||||
<Menu className="h-6 w-6" />
|
<h1 className="text-lg font-semibold text-card-foreground">
|
||||||
</button>
|
{currentPage}
|
||||||
<h2 className="text-lg font-semibold text-card-foreground lg:ml-0 ml-4">
|
</h1>
|
||||||
{currentPage}
|
|
||||||
</h2>
|
<div className="ml-auto flex items-center space-x-3">
|
||||||
</div>
|
{/* Version display */}
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-1">
|
||||||
|
{healthLoading ? (
|
||||||
|
<span className="text-xs text-muted-foreground">v...</span>
|
||||||
|
) : healthError || !healthStatus ? (
|
||||||
|
<span className="text-xs text-muted-foreground">v?</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
v{healthStatus.version || "?"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Connection status */}
|
||||||
<div className="flex items-center space-x-1">
|
<div className="flex items-center space-x-1">
|
||||||
{healthLoading ? (
|
{healthLoading ? (
|
||||||
<>
|
<>
|
||||||
358
frontend/src/components/System.tsx
Normal file
358
frontend/src/components/System.tsx
Normal file
@@ -0,0 +1,358 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
RefreshCw,
|
||||||
|
AlertCircle,
|
||||||
|
CheckCircle,
|
||||||
|
Activity,
|
||||||
|
Clock,
|
||||||
|
TrendingUp,
|
||||||
|
User,
|
||||||
|
FileText,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "./ui/card";
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from "./ui/alert";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import { Badge } from "./ui/badge";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "./ui/dialog";
|
||||||
|
import { ScrollArea } from "./ui/scroll-area";
|
||||||
|
import type { SyncOperationsResponse, SyncOperation } from "../types/api";
|
||||||
|
|
||||||
|
// Component for viewing sync operation logs
|
||||||
|
function LogsDialog({ operation }: { operation: SyncOperation }) {
|
||||||
|
return (
|
||||||
|
<Dialog>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button variant="outline" size="sm" className="shrink-0">
|
||||||
|
<FileText className="h-3 w-3 mr-1" />
|
||||||
|
<span className="hidden sm:inline">View Logs</span>
|
||||||
|
<span className="sm:hidden">Logs</span>
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Sync Operation Logs</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Operation #{operation.id} - Started at{" "}
|
||||||
|
{new Date(operation.started_at).toLocaleString()}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<ScrollArea className="h-[60vh] w-full rounded border p-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
{operation.logs.length === 0 ? (
|
||||||
|
<p className="text-muted-foreground text-sm">No logs available</p>
|
||||||
|
) : (
|
||||||
|
operation.logs.map((log, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="text-sm font-mono bg-muted/50 p-2 rounded text-wrap break-all"
|
||||||
|
>
|
||||||
|
{log}
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{operation.errors.length > 0 && (
|
||||||
|
<>
|
||||||
|
<div className="mt-4 mb-2 text-sm font-semibold text-destructive">
|
||||||
|
Errors:
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{operation.errors.map((error, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="text-sm font-mono bg-destructive/10 border border-destructive/20 p-2 rounded text-wrap break-all text-destructive"
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</ScrollArea>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function System() {
|
||||||
|
const {
|
||||||
|
data: syncOperations,
|
||||||
|
isLoading: syncOperationsLoading,
|
||||||
|
error: syncOperationsError,
|
||||||
|
refetch: refetchSyncOperations,
|
||||||
|
} = useQuery<SyncOperationsResponse>({
|
||||||
|
queryKey: ["syncOperations"],
|
||||||
|
queryFn: () => apiClient.getSyncOperations(10, 0), // Get latest 10 operations
|
||||||
|
});
|
||||||
|
|
||||||
|
if (syncOperationsLoading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-6">
|
||||||
|
<div className="flex items-center justify-center">
|
||||||
|
<RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||||
|
<span className="ml-2 text-muted-foreground">
|
||||||
|
Loading system status...
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (syncOperationsError) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertTitle>Failed to load system data</AlertTitle>
|
||||||
|
<AlertDescription className="space-y-3">
|
||||||
|
<p>
|
||||||
|
Unable to connect to the Leggen API. Please check your
|
||||||
|
configuration and ensure the API server is running.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
onClick={() => refetchSyncOperations()}
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<RefreshCw className="h-4 w-4 mr-2" />
|
||||||
|
Retry
|
||||||
|
</Button>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Sync Operations Section */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center space-x-2">
|
||||||
|
<Activity className="h-5 w-5 text-primary" />
|
||||||
|
<span>Recent Sync Operations</span>
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Latest synchronization activities and their status
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{!syncOperations || syncOperations.operations.length === 0 ? (
|
||||||
|
<div className="text-center py-6">
|
||||||
|
<Activity className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-medium text-foreground mb-2">
|
||||||
|
No sync operations yet
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Sync operations will appear here once you start syncing your
|
||||||
|
accounts.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{syncOperations.operations.slice(0, 10).map((operation) => {
|
||||||
|
const startedAt = new Date(operation.started_at);
|
||||||
|
const isRunning = !operation.completed_at;
|
||||||
|
const duration = operation.duration_seconds
|
||||||
|
? `${Math.round(operation.duration_seconds)}s`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={operation.id}
|
||||||
|
className="border rounded-lg hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
{/* Desktop Layout */}
|
||||||
|
<div className="hidden md:flex items-center justify-between p-4">
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div
|
||||||
|
className={`p-2 rounded-full ${
|
||||||
|
isRunning
|
||||||
|
? "bg-blue-100 text-blue-600"
|
||||||
|
: operation.success
|
||||||
|
? "bg-green-100 text-green-600"
|
||||||
|
: "bg-red-100 text-red-600"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{isRunning ? (
|
||||||
|
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||||
|
) : operation.success ? (
|
||||||
|
<CheckCircle className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<h4 className="text-sm font-medium text-foreground">
|
||||||
|
{isRunning
|
||||||
|
? "Sync Running"
|
||||||
|
: operation.success
|
||||||
|
? "Sync Completed"
|
||||||
|
: "Sync Failed"}
|
||||||
|
</h4>
|
||||||
|
<Badge variant="outline" className="text-xs">
|
||||||
|
{operation.trigger_type.charAt(0).toUpperCase() +
|
||||||
|
operation.trigger_type.slice(1)}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-4 mt-1 text-xs text-muted-foreground">
|
||||||
|
<span className="flex items-center space-x-1">
|
||||||
|
<Clock className="h-3 w-3" />
|
||||||
|
<span>
|
||||||
|
{startedAt.toLocaleDateString()}{" "}
|
||||||
|
{startedAt.toLocaleTimeString()}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
{duration && <span>Duration: {duration}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div className="text-right text-sm text-muted-foreground">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<User className="h-3 w-3" />
|
||||||
|
<span>{operation.accounts_processed} accounts</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-2 mt-1">
|
||||||
|
<TrendingUp className="h-3 w-3" />
|
||||||
|
<span>
|
||||||
|
{operation.transactions_added} new transactions
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<LogsDialog operation={operation} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Mobile Layout */}
|
||||||
|
<div className="md:hidden p-4 space-y-3">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<div
|
||||||
|
className={`p-2 rounded-full ${
|
||||||
|
isRunning
|
||||||
|
? "bg-blue-100 text-blue-600"
|
||||||
|
: operation.success
|
||||||
|
? "bg-green-100 text-green-600"
|
||||||
|
: "bg-red-100 text-red-600"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{isRunning ? (
|
||||||
|
<RefreshCw className="h-4 w-4 animate-spin" />
|
||||||
|
) : operation.success ? (
|
||||||
|
<CheckCircle className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-medium text-foreground">
|
||||||
|
{isRunning
|
||||||
|
? "Sync Running"
|
||||||
|
: operation.success
|
||||||
|
? "Sync Completed"
|
||||||
|
: "Sync Failed"}
|
||||||
|
</h4>
|
||||||
|
<Badge variant="outline" className="text-xs mt-1">
|
||||||
|
{operation.trigger_type.charAt(0).toUpperCase() +
|
||||||
|
operation.trigger_type.slice(1)}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<LogsDialog operation={operation} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-xs text-muted-foreground space-y-2">
|
||||||
|
<div className="flex items-center space-x-1">
|
||||||
|
<Clock className="h-3 w-3" />
|
||||||
|
<span>
|
||||||
|
{startedAt.toLocaleDateString()}{" "}
|
||||||
|
{startedAt.toLocaleTimeString()}
|
||||||
|
</span>
|
||||||
|
{duration && (
|
||||||
|
<span className="ml-2">• {duration}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-2 text-xs">
|
||||||
|
<div className="flex items-center space-x-1">
|
||||||
|
<User className="h-3 w-3" />
|
||||||
|
<span>{operation.accounts_processed} accounts</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-1">
|
||||||
|
<TrendingUp className="h-3 w-3" />
|
||||||
|
<span>
|
||||||
|
{operation.transactions_added} new transactions
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* System Health Summary Card */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center space-x-2">
|
||||||
|
<CheckCircle className="h-5 w-5 text-green-500" />
|
||||||
|
<span>System Health</span>
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Overall system status and performance
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
|
<div className="text-center p-4 bg-green-50 rounded-lg border border-green-200">
|
||||||
|
<div className="text-2xl font-bold text-green-700">
|
||||||
|
{syncOperations?.operations.filter((op) => op.success).length ||
|
||||||
|
0}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-green-600">Successful Syncs</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-4 bg-red-50 rounded-lg border border-red-200">
|
||||||
|
<div className="text-2xl font-bold text-red-700">
|
||||||
|
{syncOperations?.operations.filter(
|
||||||
|
(op) => !op.success && op.completed_at,
|
||||||
|
).length || 0}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-red-600">Failed Syncs</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center p-4 bg-blue-50 rounded-lg border border-blue-200">
|
||||||
|
<div className="text-2xl font-bold text-blue-700">
|
||||||
|
{syncOperations?.operations.filter((op) => !op.completed_at)
|
||||||
|
.length || 0}
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-blue-600">Running Operations</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
222
frontend/src/components/TelegramConfigDrawer.tsx
Normal file
222
frontend/src/components/TelegramConfigDrawer.tsx
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Send, TestTube } from "lucide-react";
|
||||||
|
import { apiClient } from "../lib/api";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import { Input } from "./ui/input";
|
||||||
|
import { Label } from "./ui/label";
|
||||||
|
import { Switch } from "./ui/switch";
|
||||||
|
import { EditButton } from "./ui/edit-button";
|
||||||
|
import {
|
||||||
|
Drawer,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerDescription,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerTrigger,
|
||||||
|
} from "./ui/drawer";
|
||||||
|
import type { NotificationSettings, TelegramConfig } from "../types/api";
|
||||||
|
|
||||||
|
interface TelegramConfigDrawerProps {
|
||||||
|
settings: NotificationSettings | undefined;
|
||||||
|
trigger?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TelegramConfigDrawer({
|
||||||
|
settings,
|
||||||
|
trigger,
|
||||||
|
}: TelegramConfigDrawerProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [config, setConfig] = useState<TelegramConfig>({
|
||||||
|
token: "",
|
||||||
|
chat_id: 0,
|
||||||
|
enabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (settings?.telegram) {
|
||||||
|
setConfig({ ...settings.telegram });
|
||||||
|
}
|
||||||
|
}, [settings]);
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: (telegramConfig: TelegramConfig) =>
|
||||||
|
apiClient.updateNotificationSettings({
|
||||||
|
...settings,
|
||||||
|
telegram: telegramConfig,
|
||||||
|
filters: settings?.filters || {
|
||||||
|
case_insensitive: [],
|
||||||
|
case_sensitive: [],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["notificationSettings"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["notificationServices"] });
|
||||||
|
setOpen(false);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to update Telegram configuration:", error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const testMutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
apiClient.testNotification({
|
||||||
|
service: "telegram",
|
||||||
|
message:
|
||||||
|
"Test notification from Leggen - Telegram configuration is working!",
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
console.log("Test Telegram notification sent successfully");
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to send test Telegram notification:", error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
updateMutation.mutate(config);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTest = () => {
|
||||||
|
testMutation.mutate();
|
||||||
|
};
|
||||||
|
|
||||||
|
const isConfigValid = config.token.trim().length > 0 && config.chat_id !== 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Drawer open={open} onOpenChange={setOpen}>
|
||||||
|
<DrawerTrigger asChild>{trigger || <EditButton />}</DrawerTrigger>
|
||||||
|
<DrawerContent>
|
||||||
|
<div className="mx-auto w-full max-w-md">
|
||||||
|
<DrawerHeader>
|
||||||
|
<DrawerTitle className="flex items-center space-x-2">
|
||||||
|
<Send className="h-5 w-5 text-primary" />
|
||||||
|
<span>Telegram Configuration</span>
|
||||||
|
</DrawerTitle>
|
||||||
|
<DrawerDescription>
|
||||||
|
Configure Telegram bot notifications for transaction alerts
|
||||||
|
</DrawerDescription>
|
||||||
|
</DrawerHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="p-4 space-y-6">
|
||||||
|
{/* Enable/Disable Toggle */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label className="text-base font-medium">
|
||||||
|
Enable Telegram Notifications
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
checked={config.enabled}
|
||||||
|
onCheckedChange={(enabled) => setConfig({ ...config, enabled })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bot Token */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="telegram-token">Bot Token</Label>
|
||||||
|
<Input
|
||||||
|
id="telegram-token"
|
||||||
|
type="password"
|
||||||
|
placeholder="123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
|
||||||
|
value={config.token}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({ ...config, token: e.target.value })
|
||||||
|
}
|
||||||
|
disabled={!config.enabled}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Create a bot using @BotFather on Telegram to get your token
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chat ID */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="telegram-chat-id">Chat ID</Label>
|
||||||
|
<Input
|
||||||
|
id="telegram-chat-id"
|
||||||
|
type="number"
|
||||||
|
placeholder="123456789"
|
||||||
|
value={config.chat_id || ""}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig({
|
||||||
|
...config,
|
||||||
|
chat_id: parseInt(e.target.value) || 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
disabled={!config.enabled}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Send a message to your bot and visit
|
||||||
|
https://api.telegram.org/bot<token>/getUpdates to find
|
||||||
|
your chat ID
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Configuration Status */}
|
||||||
|
{config.enabled && (
|
||||||
|
<div className="p-3 bg-muted rounded-md">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<div
|
||||||
|
className={`w-2 h-2 rounded-full ${isConfigValid ? "bg-green-500" : "bg-red-500"}`}
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium">
|
||||||
|
{isConfigValid
|
||||||
|
? "Configuration Valid"
|
||||||
|
: "Missing Token or Chat ID"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{!isConfigValid &&
|
||||||
|
(config.token.trim().length > 0 || config.chat_id !== 0) && (
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
Both bot token and chat ID are required
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DrawerFooter className="px-0">
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={updateMutation.isPending || !config.enabled}
|
||||||
|
>
|
||||||
|
{updateMutation.isPending
|
||||||
|
? "Saving..."
|
||||||
|
: "Save Configuration"}
|
||||||
|
</Button>
|
||||||
|
{config.enabled && isConfigValid && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleTest}
|
||||||
|
disabled={testMutation.isPending}
|
||||||
|
>
|
||||||
|
{testMutation.isPending ? (
|
||||||
|
<>
|
||||||
|
<TestTube className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Testing...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<TestTube className="h-4 w-4 mr-2" />
|
||||||
|
Test
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<DrawerClose asChild>
|
||||||
|
<Button variant="ghost">Cancel</Button>
|
||||||
|
</DrawerClose>
|
||||||
|
</DrawerFooter>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</DrawerContent>
|
||||||
|
</Drawer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -97,7 +97,6 @@ export default function TransactionsTable() {
|
|||||||
queryFn: apiClient.getAccounts,
|
queryFn: apiClient.getAccounts,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: transactionsResponse,
|
data: transactionsResponse,
|
||||||
isLoading: transactionsLoading,
|
isLoading: transactionsLoading,
|
||||||
@@ -141,11 +140,7 @@ export default function TransactionsTable() {
|
|||||||
// Reset pagination when filters change
|
// Reset pagination when filters change
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setCurrentPage(1);
|
setCurrentPage(1);
|
||||||
}, [
|
}, [filterState.selectedAccount, filterState.startDate, filterState.endDate]);
|
||||||
filterState.selectedAccount,
|
|
||||||
filterState.startDate,
|
|
||||||
filterState.endDate,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const handleViewRaw = (transaction: Transaction) => {
|
const handleViewRaw = (transaction: Transaction) => {
|
||||||
setSelectedTransaction(transaction);
|
setSelectedTransaction(transaction);
|
||||||
@@ -163,7 +158,6 @@ export default function TransactionsTable() {
|
|||||||
filterState.startDate ||
|
filterState.startDate ||
|
||||||
filterState.endDate;
|
filterState.endDate;
|
||||||
|
|
||||||
|
|
||||||
// Define columns
|
// Define columns
|
||||||
const columns: ColumnDef<Transaction>[] = [
|
const columns: ColumnDef<Transaction>[] = [
|
||||||
{
|
{
|
||||||
@@ -196,8 +190,7 @@ export default function TransactionsTable() {
|
|||||||
<div className="text-xs text-muted-foreground space-y-1">
|
<div className="text-xs text-muted-foreground space-y-1">
|
||||||
{account && (
|
{account && (
|
||||||
<p className="truncate">
|
<p className="truncate">
|
||||||
{account.name || "Unnamed Account"} •{" "}
|
{account.display_name || "Unnamed Account"}
|
||||||
{account.institution_id}
|
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{(transaction.creditor_name || transaction.debtor_name) && (
|
{(transaction.creditor_name || transaction.debtor_name) && (
|
||||||
@@ -266,14 +259,15 @@ export default function TransactionsTable() {
|
|||||||
cell: ({ row }) => {
|
cell: ({ row }) => {
|
||||||
const transaction = row.original;
|
const transaction = row.original;
|
||||||
return (
|
return (
|
||||||
<button
|
<Button
|
||||||
onClick={() => handleViewRaw(transaction)}
|
onClick={() => handleViewRaw(transaction)}
|
||||||
className="inline-flex items-center px-2 py-1 text-xs bg-muted text-muted-foreground rounded hover:bg-accent transition-colors"
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
title="View raw transaction data"
|
title="View raw transaction data"
|
||||||
>
|
>
|
||||||
<Eye className="h-3 w-3 mr-1" />
|
<Eye className="h-3 w-3 mr-1" />
|
||||||
Raw
|
Raw
|
||||||
</button>
|
</Button>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -427,10 +421,7 @@ export default function TransactionsTable() {
|
|||||||
table.getRowModel().rows.map((row) => (
|
table.getRowModel().rows.map((row) => (
|
||||||
<tr key={row.id} className="hover:bg-muted/50">
|
<tr key={row.id} className="hover:bg-muted/50">
|
||||||
{row.getVisibleCells().map((cell) => (
|
{row.getVisibleCells().map((cell) => (
|
||||||
<td
|
<td key={cell.id} className="px-6 py-4 whitespace-nowrap">
|
||||||
key={cell.id}
|
|
||||||
className="px-6 py-4 whitespace-nowrap"
|
|
||||||
>
|
|
||||||
{flexRender(
|
{flexRender(
|
||||||
cell.column.columnDef.cell,
|
cell.column.columnDef.cell,
|
||||||
cell.getContext(),
|
cell.getContext(),
|
||||||
@@ -495,8 +486,7 @@ export default function TransactionsTable() {
|
|||||||
<div className="text-xs text-muted-foreground space-y-1 mt-1">
|
<div className="text-xs text-muted-foreground space-y-1 mt-1">
|
||||||
{account && (
|
{account && (
|
||||||
<p className="break-words">
|
<p className="break-words">
|
||||||
{account.name || "Unnamed Account"} •{" "}
|
{account.display_name || "Unnamed Account"}
|
||||||
{account.institution_id}
|
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{(transaction.creditor_name ||
|
{(transaction.creditor_name ||
|
||||||
@@ -541,14 +531,15 @@ export default function TransactionsTable() {
|
|||||||
transaction.transaction_currency,
|
transaction.transaction_currency,
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
<button
|
<Button
|
||||||
onClick={() => handleViewRaw(transaction)}
|
onClick={() => handleViewRaw(transaction)}
|
||||||
className="inline-flex items-center px-2 py-1 text-xs bg-muted text-muted-foreground rounded hover:bg-accent transition-colors"
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
title="View raw transaction data"
|
title="View raw transaction data"
|
||||||
>
|
>
|
||||||
<Eye className="h-3 w-3 mr-1" />
|
<Eye className="h-3 w-3 mr-1" />
|
||||||
Raw
|
Raw
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -29,13 +29,9 @@ export default function StatCard({
|
|||||||
<CardContent className="p-6">
|
<CardContent className="p-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium text-muted-foreground">
|
<p className="text-sm font-medium text-muted-foreground">{title}</p>
|
||||||
{title}
|
|
||||||
</p>
|
|
||||||
<div className="flex items-baseline">
|
<div className="flex items-baseline">
|
||||||
<p className="text-2xl font-bold text-foreground">
|
<p className="text-2xl font-bold text-foreground">{value}</p>
|
||||||
{value}
|
|
||||||
</p>
|
|
||||||
{trend && (
|
{trend && (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -51,29 +47,31 @@ export default function StatCard({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{subtitle && (
|
{subtitle && (
|
||||||
<p className="text-sm text-muted-foreground mt-1">
|
<p className="text-sm text-muted-foreground mt-1">{subtitle}</p>
|
||||||
{subtitle}
|
|
||||||
</p>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className={cn(
|
<div
|
||||||
"p-3 rounded-full",
|
className={cn(
|
||||||
iconColor === "green" && "bg-green-100 dark:bg-green-900/20",
|
"p-3 rounded-full",
|
||||||
iconColor === "blue" && "bg-blue-100 dark:bg-blue-900/20",
|
iconColor === "green" && "bg-green-100 dark:bg-green-900/20",
|
||||||
iconColor === "red" && "bg-red-100 dark:bg-red-900/20",
|
iconColor === "blue" && "bg-blue-100 dark:bg-blue-900/20",
|
||||||
iconColor === "purple" && "bg-purple-100 dark:bg-purple-900/20",
|
iconColor === "red" && "bg-red-100 dark:bg-red-900/20",
|
||||||
iconColor === "orange" && "bg-orange-100 dark:bg-orange-900/20",
|
iconColor === "purple" && "bg-purple-100 dark:bg-purple-900/20",
|
||||||
iconColor === "default" && "bg-muted"
|
iconColor === "orange" && "bg-orange-100 dark:bg-orange-900/20",
|
||||||
)}>
|
iconColor === "default" && "bg-muted",
|
||||||
<Icon className={cn(
|
)}
|
||||||
"h-6 w-6",
|
>
|
||||||
iconColor === "green" && "text-green-600",
|
<Icon
|
||||||
iconColor === "blue" && "text-blue-600",
|
className={cn(
|
||||||
iconColor === "red" && "text-red-600",
|
"h-6 w-6",
|
||||||
iconColor === "purple" && "text-purple-600",
|
iconColor === "green" && "text-green-600",
|
||||||
iconColor === "orange" && "text-orange-600",
|
iconColor === "blue" && "text-blue-600",
|
||||||
iconColor === "default" && "text-muted-foreground"
|
iconColor === "red" && "text-red-600",
|
||||||
)} />
|
iconColor === "purple" && "text-purple-600",
|
||||||
|
iconColor === "orange" && "text-orange-600",
|
||||||
|
iconColor === "default" && "text-muted-foreground",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -15,12 +15,14 @@ export default function TimePeriodFilter({
|
|||||||
className = "",
|
className = "",
|
||||||
}: TimePeriodFilterProps) {
|
}: TimePeriodFilterProps) {
|
||||||
return (
|
return (
|
||||||
<div className={`flex items-center gap-4 ${className}`}>
|
<div
|
||||||
|
className={`flex flex-col sm:flex-row sm:items-center gap-4 ${className}`}
|
||||||
|
>
|
||||||
<div className="flex items-center gap-2 text-foreground">
|
<div className="flex items-center gap-2 text-foreground">
|
||||||
<Calendar size={20} />
|
<Calendar size={20} />
|
||||||
<span className="font-medium">Time Period:</span>
|
<span className="font-medium">Time Period:</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{TIME_PERIODS.map((period) => (
|
{TIME_PERIODS.map((period) => (
|
||||||
<Button
|
<Button
|
||||||
key={period.value}
|
key={period.value}
|
||||||
|
|||||||
@@ -70,7 +70,6 @@ export function ActiveFilterChips({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const handleRemoveChip = (key: keyof FilterState) => {
|
const handleRemoveChip = (key: keyof FilterState) => {
|
||||||
switch (key) {
|
switch (key) {
|
||||||
case "startDate":
|
case "startDate":
|
||||||
|
|||||||
@@ -91,7 +91,6 @@ export function FilterBar({
|
|||||||
className="w-[220px]"
|
className="w-[220px]"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mobile Layout */}
|
{/* Mobile Layout */}
|
||||||
@@ -129,7 +128,6 @@ export function FilterBar({
|
|||||||
onDateRangeChange={handleDateRangeChange}
|
onDateRangeChange={handleDateRangeChange}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
116
frontend/src/components/ui/drawer.tsx
Normal file
116
frontend/src/components/ui/drawer.tsx
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { Drawer as DrawerPrimitive } from "vaul";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const Drawer = ({
|
||||||
|
shouldScaleBackground = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
|
||||||
|
<DrawerPrimitive.Root
|
||||||
|
shouldScaleBackground={shouldScaleBackground}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
Drawer.displayName = "Drawer";
|
||||||
|
|
||||||
|
const DrawerTrigger = DrawerPrimitive.Trigger;
|
||||||
|
|
||||||
|
const DrawerPortal = DrawerPrimitive.Portal;
|
||||||
|
|
||||||
|
const DrawerClose = DrawerPrimitive.Close;
|
||||||
|
|
||||||
|
const DrawerOverlay = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DrawerPrimitive.Overlay>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DrawerPrimitive.Overlay
|
||||||
|
ref={ref}
|
||||||
|
className={cn("fixed inset-0 z-50 bg-black/80", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
|
||||||
|
|
||||||
|
const DrawerContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DrawerPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<DrawerPortal>
|
||||||
|
<DrawerOverlay />
|
||||||
|
<DrawerPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
|
||||||
|
{children}
|
||||||
|
</DrawerPrimitive.Content>
|
||||||
|
</DrawerPortal>
|
||||||
|
));
|
||||||
|
DrawerContent.displayName = "DrawerContent";
|
||||||
|
|
||||||
|
const DrawerHeader = ({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
|
<div
|
||||||
|
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
DrawerHeader.displayName = "DrawerHeader";
|
||||||
|
|
||||||
|
const DrawerFooter = ({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
|
<div
|
||||||
|
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
DrawerFooter.displayName = "DrawerFooter";
|
||||||
|
|
||||||
|
const DrawerTitle = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DrawerPrimitive.Title>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DrawerPrimitive.Title
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"text-lg font-semibold leading-none tracking-tight",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
|
||||||
|
|
||||||
|
const DrawerDescription = React.forwardRef<
|
||||||
|
React.ElementRef<typeof DrawerPrimitive.Description>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<DrawerPrimitive.Description
|
||||||
|
ref={ref}
|
||||||
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
|
||||||
|
|
||||||
|
export {
|
||||||
|
Drawer,
|
||||||
|
DrawerPortal,
|
||||||
|
DrawerOverlay,
|
||||||
|
DrawerTrigger,
|
||||||
|
DrawerClose,
|
||||||
|
DrawerContent,
|
||||||
|
DrawerHeader,
|
||||||
|
DrawerFooter,
|
||||||
|
DrawerTitle,
|
||||||
|
DrawerDescription,
|
||||||
|
};
|
||||||
45
frontend/src/components/ui/edit-button.tsx
Normal file
45
frontend/src/components/ui/edit-button.tsx
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { Edit3 } from "lucide-react";
|
||||||
|
import { Button } from "./button";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
|
|
||||||
|
interface EditButtonProps {
|
||||||
|
onClick?: () => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
className?: string;
|
||||||
|
size?: "default" | "sm" | "lg" | "icon";
|
||||||
|
variant?:
|
||||||
|
| "default"
|
||||||
|
| "destructive"
|
||||||
|
| "outline"
|
||||||
|
| "secondary"
|
||||||
|
| "ghost"
|
||||||
|
| "link";
|
||||||
|
children?: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditButton({
|
||||||
|
onClick,
|
||||||
|
disabled = false,
|
||||||
|
className,
|
||||||
|
size = "sm",
|
||||||
|
variant = "outline",
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: EditButtonProps) {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
onClick={onClick}
|
||||||
|
disabled={disabled}
|
||||||
|
size={size}
|
||||||
|
variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"h-8 px-3 text-muted-foreground hover:text-foreground transition-colors",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<Edit3 className="h-4 w-4" />
|
||||||
|
<span className="ml-2">{children || "Edit"}</span>
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -15,7 +15,9 @@ export function Logo({ className = "", size = 32 }: LogoProps) {
|
|||||||
aria-labelledby="logo-title logo-desc"
|
aria-labelledby="logo-title logo-desc"
|
||||||
>
|
>
|
||||||
<title id="logo-title">leggen — stylized italic L</title>
|
<title id="logo-title">leggen — stylized italic L</title>
|
||||||
<desc id="logo-desc">Square gradient background with italic white L.</desc>
|
<desc id="logo-desc">
|
||||||
|
Square gradient background with italic white L.
|
||||||
|
</desc>
|
||||||
|
|
||||||
<defs>
|
<defs>
|
||||||
<linearGradient id="logo-bg" x1="0" y1="0" x2="1" y2="1">
|
<linearGradient id="logo-bg" x1="0" y1="0" x2="1" y2="1">
|
||||||
|
|||||||
21
frontend/src/components/ui/scroll-area.tsx
Normal file
21
frontend/src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
|
|
||||||
|
const ScrollArea = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement>
|
||||||
|
>(({ className, children, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"relative overflow-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
));
|
||||||
|
ScrollArea.displayName = "ScrollArea";
|
||||||
|
|
||||||
|
export { ScrollArea };
|
||||||
29
frontend/src/components/ui/separator.tsx
Normal file
29
frontend/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const Separator = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||||
|
>(
|
||||||
|
(
|
||||||
|
{ className, orientation = "horizontal", decorative = true, ...props },
|
||||||
|
ref,
|
||||||
|
) => (
|
||||||
|
<SeparatorPrimitive.Root
|
||||||
|
ref={ref}
|
||||||
|
decorative={decorative}
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"shrink-0 bg-border",
|
||||||
|
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
);
|
||||||
|
Separator.displayName = SeparatorPrimitive.Root.displayName;
|
||||||
|
|
||||||
|
export { Separator };
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import * as SheetPrimitive from "@radix-ui/react-dialog";
|
import * as SheetPrimitive from "@radix-ui/react-dialog";
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
@@ -29,7 +31,7 @@ const SheetOverlay = React.forwardRef<
|
|||||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
|
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
|
||||||
|
|
||||||
const sheetVariants = cva(
|
const sheetVariants = cva(
|
||||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
side: {
|
side: {
|
||||||
@@ -38,7 +40,7 @@ const sheetVariants = cva(
|
|||||||
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
||||||
right:
|
right:
|
||||||
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
@@ -62,11 +64,11 @@ const SheetContent = React.forwardRef<
|
|||||||
className={cn(sheetVariants({ side }), className)}
|
className={cn(sheetVariants({ side }), className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
|
||||||
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Close</span>
|
||||||
</SheetPrimitive.Close>
|
</SheetPrimitive.Close>
|
||||||
|
{children}
|
||||||
</SheetPrimitive.Content>
|
</SheetPrimitive.Content>
|
||||||
</SheetPortal>
|
</SheetPortal>
|
||||||
));
|
));
|
||||||
|
|||||||
779
frontend/src/components/ui/sidebar.tsx
Normal file
779
frontend/src/components/ui/sidebar.tsx
Normal file
@@ -0,0 +1,779 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
import { PanelLeft } from "lucide-react";
|
||||||
|
|
||||||
|
import { useIsMobile } from "@/hooks/use-mobile";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import {
|
||||||
|
Sheet,
|
||||||
|
SheetContent,
|
||||||
|
SheetDescription,
|
||||||
|
SheetHeader,
|
||||||
|
SheetTitle,
|
||||||
|
} from "@/components/ui/sheet";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipProvider,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/components/ui/tooltip";
|
||||||
|
|
||||||
|
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||||
|
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||||
|
const SIDEBAR_WIDTH = "16rem";
|
||||||
|
const SIDEBAR_WIDTH_MOBILE = "18rem";
|
||||||
|
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||||
|
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||||
|
|
||||||
|
type SidebarContextProps = {
|
||||||
|
state: "expanded" | "collapsed";
|
||||||
|
open: boolean;
|
||||||
|
setOpen: (open: boolean) => void;
|
||||||
|
openMobile: boolean;
|
||||||
|
setOpenMobile: (open: boolean) => void;
|
||||||
|
isMobile: boolean;
|
||||||
|
toggleSidebar: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
|
||||||
|
|
||||||
|
function useSidebar() {
|
||||||
|
const context = React.useContext(SidebarContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useSidebar must be used within a SidebarProvider.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SidebarProvider = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
defaultOpen?: boolean;
|
||||||
|
open?: boolean;
|
||||||
|
onOpenChange?: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
>(
|
||||||
|
(
|
||||||
|
{
|
||||||
|
defaultOpen = true,
|
||||||
|
open: openProp,
|
||||||
|
onOpenChange: setOpenProp,
|
||||||
|
className,
|
||||||
|
style,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) => {
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const [openMobile, setOpenMobile] = React.useState(false);
|
||||||
|
|
||||||
|
// This is the internal state of the sidebar.
|
||||||
|
// We use openProp and setOpenProp for control from outside the component.
|
||||||
|
const [_open, _setOpen] = React.useState(defaultOpen);
|
||||||
|
const open = openProp ?? _open;
|
||||||
|
const setOpen = React.useCallback(
|
||||||
|
(value: boolean | ((value: boolean) => boolean)) => {
|
||||||
|
const openState = typeof value === "function" ? value(open) : value;
|
||||||
|
if (setOpenProp) {
|
||||||
|
setOpenProp(openState);
|
||||||
|
} else {
|
||||||
|
_setOpen(openState);
|
||||||
|
}
|
||||||
|
|
||||||
|
// This sets the cookie to keep the sidebar state.
|
||||||
|
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
|
||||||
|
},
|
||||||
|
[setOpenProp, open],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Helper to toggle the sidebar.
|
||||||
|
const toggleSidebar = React.useCallback(() => {
|
||||||
|
return isMobile
|
||||||
|
? setOpenMobile((open) => !open)
|
||||||
|
: setOpen((open) => !open);
|
||||||
|
}, [isMobile, setOpen, setOpenMobile]);
|
||||||
|
|
||||||
|
// Adds a keyboard shortcut to toggle the sidebar.
|
||||||
|
React.useEffect(() => {
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (
|
||||||
|
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||||
|
(event.metaKey || event.ctrlKey)
|
||||||
|
) {
|
||||||
|
event.preventDefault();
|
||||||
|
toggleSidebar();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("keydown", handleKeyDown);
|
||||||
|
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||||
|
}, [toggleSidebar]);
|
||||||
|
|
||||||
|
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||||
|
// This makes it easier to style the sidebar with Tailwind classes.
|
||||||
|
const state = open ? "expanded" : "collapsed";
|
||||||
|
|
||||||
|
const contextValue = React.useMemo<SidebarContextProps>(
|
||||||
|
() => ({
|
||||||
|
state,
|
||||||
|
open,
|
||||||
|
setOpen,
|
||||||
|
isMobile,
|
||||||
|
openMobile,
|
||||||
|
setOpenMobile,
|
||||||
|
toggleSidebar,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
state,
|
||||||
|
open,
|
||||||
|
setOpen,
|
||||||
|
isMobile,
|
||||||
|
openMobile,
|
||||||
|
setOpenMobile,
|
||||||
|
toggleSidebar,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SidebarContext.Provider value={contextValue}>
|
||||||
|
<TooltipProvider delayDuration={0}>
|
||||||
|
<div
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--sidebar-width": SIDEBAR_WIDTH,
|
||||||
|
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||||
|
...style,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
className={cn(
|
||||||
|
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</TooltipProvider>
|
||||||
|
</SidebarContext.Provider>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarProvider.displayName = "SidebarProvider";
|
||||||
|
|
||||||
|
const Sidebar = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
side?: "left" | "right";
|
||||||
|
variant?: "sidebar" | "floating" | "inset";
|
||||||
|
collapsible?: "offcanvas" | "icon" | "none";
|
||||||
|
}
|
||||||
|
>(
|
||||||
|
(
|
||||||
|
{
|
||||||
|
side = "left",
|
||||||
|
variant = "sidebar",
|
||||||
|
collapsible = "offcanvas",
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) => {
|
||||||
|
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
|
||||||
|
|
||||||
|
if (collapsible === "none") {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isMobile) {
|
||||||
|
return (
|
||||||
|
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||||
|
<SheetContent
|
||||||
|
data-sidebar="sidebar"
|
||||||
|
data-mobile="true"
|
||||||
|
className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
side={side}
|
||||||
|
>
|
||||||
|
<SheetHeader className="sr-only">
|
||||||
|
<SheetTitle>Sidebar</SheetTitle>
|
||||||
|
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
|
||||||
|
</SheetHeader>
|
||||||
|
<div className="flex h-full w-full flex-col">{children}</div>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className="group peer hidden text-sidebar-foreground md:block"
|
||||||
|
data-state={state}
|
||||||
|
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||||
|
data-variant={variant}
|
||||||
|
data-side={side}
|
||||||
|
>
|
||||||
|
{/* This is what handles the sidebar gap on desktop */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"relative w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear",
|
||||||
|
"group-data-[collapsible=offcanvas]:w-0",
|
||||||
|
"group-data-[side=right]:rotate-180",
|
||||||
|
variant === "floating" || variant === "inset"
|
||||||
|
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
|
||||||
|
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon]",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||||
|
side === "left"
|
||||||
|
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||||
|
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||||
|
// Adjust the padding for floating and inset variants.
|
||||||
|
variant === "floating" || variant === "inset"
|
||||||
|
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
|
||||||
|
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
data-sidebar="sidebar"
|
||||||
|
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Sidebar.displayName = "Sidebar";
|
||||||
|
|
||||||
|
const SidebarTrigger = React.forwardRef<
|
||||||
|
React.ElementRef<typeof Button>,
|
||||||
|
React.ComponentProps<typeof Button>
|
||||||
|
>(({ className, onClick, ...props }, ref) => {
|
||||||
|
const { toggleSidebar } = useSidebar();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="trigger"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className={cn("h-7 w-7", className)}
|
||||||
|
onClick={(event) => {
|
||||||
|
onClick?.(event);
|
||||||
|
toggleSidebar();
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<PanelLeft />
|
||||||
|
<span className="sr-only">Toggle Sidebar</span>
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarTrigger.displayName = "SidebarTrigger";
|
||||||
|
|
||||||
|
const SidebarRail = React.forwardRef<
|
||||||
|
HTMLButtonElement,
|
||||||
|
React.ComponentProps<"button">
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
const { toggleSidebar } = useSidebar();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="rail"
|
||||||
|
aria-label="Toggle Sidebar"
|
||||||
|
tabIndex={-1}
|
||||||
|
onClick={toggleSidebar}
|
||||||
|
title="Toggle Sidebar"
|
||||||
|
className={cn(
|
||||||
|
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
|
||||||
|
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
|
||||||
|
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||||
|
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
|
||||||
|
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||||
|
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarRail.displayName = "SidebarRail";
|
||||||
|
|
||||||
|
const SidebarInset = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"main">
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<main
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"relative flex w-full flex-1 flex-col bg-background",
|
||||||
|
"md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarInset.displayName = "SidebarInset";
|
||||||
|
|
||||||
|
const SidebarInput = React.forwardRef<
|
||||||
|
React.ElementRef<typeof Input>,
|
||||||
|
React.ComponentProps<typeof Input>
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<Input
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="input"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarInput.displayName = "SidebarInput";
|
||||||
|
|
||||||
|
const SidebarHeader = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div">
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="header"
|
||||||
|
className={cn("flex flex-col gap-2 p-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarHeader.displayName = "SidebarHeader";
|
||||||
|
|
||||||
|
const SidebarFooter = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div">
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="footer"
|
||||||
|
className={cn("flex flex-col gap-2 p-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarFooter.displayName = "SidebarFooter";
|
||||||
|
|
||||||
|
const SidebarSeparator = React.forwardRef<
|
||||||
|
React.ElementRef<typeof Separator>,
|
||||||
|
React.ComponentProps<typeof Separator>
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<Separator
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="separator"
|
||||||
|
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarSeparator.displayName = "SidebarSeparator";
|
||||||
|
|
||||||
|
const SidebarContent = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div">
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="content"
|
||||||
|
className={cn(
|
||||||
|
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarContent.displayName = "SidebarContent";
|
||||||
|
|
||||||
|
const SidebarGroup = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div">
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="group"
|
||||||
|
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarGroup.displayName = "SidebarGroup";
|
||||||
|
|
||||||
|
const SidebarGroupLabel = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div"> & { asChild?: boolean }
|
||||||
|
>(({ className, asChild = false, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "div";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="group-label"
|
||||||
|
className={cn(
|
||||||
|
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarGroupLabel.displayName = "SidebarGroupLabel";
|
||||||
|
|
||||||
|
const SidebarGroupAction = React.forwardRef<
|
||||||
|
HTMLButtonElement,
|
||||||
|
React.ComponentProps<"button"> & { asChild?: boolean }
|
||||||
|
>(({ className, asChild = false, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="group-action"
|
||||||
|
className={cn(
|
||||||
|
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
// Increases the hit area of the button on mobile.
|
||||||
|
"after:absolute after:-inset-2 after:md:hidden",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarGroupAction.displayName = "SidebarGroupAction";
|
||||||
|
|
||||||
|
const SidebarGroupContent = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div">
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="group-content"
|
||||||
|
className={cn("w-full text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
SidebarGroupContent.displayName = "SidebarGroupContent";
|
||||||
|
|
||||||
|
const SidebarMenu = React.forwardRef<
|
||||||
|
HTMLUListElement,
|
||||||
|
React.ComponentProps<"ul">
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<ul
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu"
|
||||||
|
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
SidebarMenu.displayName = "SidebarMenu";
|
||||||
|
|
||||||
|
const SidebarMenuItem = React.forwardRef<
|
||||||
|
HTMLLIElement,
|
||||||
|
React.ComponentProps<"li">
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<li
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-item"
|
||||||
|
className={cn("group/menu-item relative", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
SidebarMenuItem.displayName = "SidebarMenuItem";
|
||||||
|
|
||||||
|
const sidebarMenuButtonVariants = cva(
|
||||||
|
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||||
|
outline:
|
||||||
|
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-8 text-sm",
|
||||||
|
sm: "h-7 text-xs",
|
||||||
|
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const SidebarMenuButton = React.forwardRef<
|
||||||
|
HTMLButtonElement,
|
||||||
|
React.ComponentProps<"button"> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
isActive?: boolean;
|
||||||
|
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
|
||||||
|
} & VariantProps<typeof sidebarMenuButtonVariants>
|
||||||
|
>(
|
||||||
|
(
|
||||||
|
{
|
||||||
|
asChild = false,
|
||||||
|
isActive = false,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
tooltip,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) => {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
const { isMobile, state } = useSidebar();
|
||||||
|
|
||||||
|
const button = (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-button"
|
||||||
|
data-size={size}
|
||||||
|
data-active={isActive}
|
||||||
|
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!tooltip) {
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof tooltip === "string") {
|
||||||
|
tooltip = {
|
||||||
|
children: tooltip,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||||
|
<TooltipContent
|
||||||
|
side="right"
|
||||||
|
align="center"
|
||||||
|
hidden={state !== "collapsed" || isMobile}
|
||||||
|
{...tooltip}
|
||||||
|
/>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
SidebarMenuButton.displayName = "SidebarMenuButton";
|
||||||
|
|
||||||
|
const SidebarMenuAction = React.forwardRef<
|
||||||
|
HTMLButtonElement,
|
||||||
|
React.ComponentProps<"button"> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
showOnHover?: boolean;
|
||||||
|
}
|
||||||
|
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-action"
|
||||||
|
className={cn(
|
||||||
|
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
|
||||||
|
// Increases the hit area of the button on mobile.
|
||||||
|
"after:absolute after:-inset-2 after:md:hidden",
|
||||||
|
"peer-data-[size=sm]/menu-button:top-1",
|
||||||
|
"peer-data-[size=default]/menu-button:top-1.5",
|
||||||
|
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
showOnHover &&
|
||||||
|
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarMenuAction.displayName = "SidebarMenuAction";
|
||||||
|
|
||||||
|
const SidebarMenuBadge = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div">
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-badge"
|
||||||
|
className={cn(
|
||||||
|
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
|
||||||
|
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||||
|
"peer-data-[size=sm]/menu-button:top-1",
|
||||||
|
"peer-data-[size=default]/menu-button:top-1.5",
|
||||||
|
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
SidebarMenuBadge.displayName = "SidebarMenuBadge";
|
||||||
|
|
||||||
|
const SidebarMenuSkeleton = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.ComponentProps<"div"> & {
|
||||||
|
showIcon?: boolean;
|
||||||
|
}
|
||||||
|
>(({ className, showIcon = false, ...props }, ref) => {
|
||||||
|
// Random width between 50 to 90%.
|
||||||
|
const width = React.useMemo(() => {
|
||||||
|
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-skeleton"
|
||||||
|
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{showIcon && (
|
||||||
|
<Skeleton
|
||||||
|
className="size-4 rounded-md"
|
||||||
|
data-sidebar="menu-skeleton-icon"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Skeleton
|
||||||
|
className="h-4 max-w-[--skeleton-width] flex-1"
|
||||||
|
data-sidebar="menu-skeleton-text"
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--skeleton-width": width,
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton";
|
||||||
|
|
||||||
|
const SidebarMenuSub = React.forwardRef<
|
||||||
|
HTMLUListElement,
|
||||||
|
React.ComponentProps<"ul">
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<ul
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-sub"
|
||||||
|
className={cn(
|
||||||
|
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
SidebarMenuSub.displayName = "SidebarMenuSub";
|
||||||
|
|
||||||
|
const SidebarMenuSubItem = React.forwardRef<
|
||||||
|
HTMLLIElement,
|
||||||
|
React.ComponentProps<"li">
|
||||||
|
>(({ ...props }, ref) => <li ref={ref} {...props} />);
|
||||||
|
SidebarMenuSubItem.displayName = "SidebarMenuSubItem";
|
||||||
|
|
||||||
|
const SidebarMenuSubButton = React.forwardRef<
|
||||||
|
HTMLAnchorElement,
|
||||||
|
React.ComponentProps<"a"> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
size?: "sm" | "md";
|
||||||
|
isActive?: boolean;
|
||||||
|
}
|
||||||
|
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
|
||||||
|
const Comp = asChild ? Slot : "a";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
ref={ref}
|
||||||
|
data-sidebar="menu-sub-button"
|
||||||
|
data-size={size}
|
||||||
|
data-active={isActive}
|
||||||
|
className={cn(
|
||||||
|
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||||
|
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||||
|
size === "sm" && "text-xs",
|
||||||
|
size === "md" && "text-sm",
|
||||||
|
"group-data-[collapsible=icon]:hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
SidebarMenuSubButton.displayName = "SidebarMenuSubButton";
|
||||||
|
|
||||||
|
export {
|
||||||
|
Sidebar,
|
||||||
|
SidebarContent,
|
||||||
|
SidebarFooter,
|
||||||
|
SidebarGroup,
|
||||||
|
SidebarGroupAction,
|
||||||
|
SidebarGroupContent,
|
||||||
|
SidebarGroupLabel,
|
||||||
|
SidebarHeader,
|
||||||
|
SidebarInput,
|
||||||
|
SidebarInset,
|
||||||
|
SidebarMenu,
|
||||||
|
SidebarMenuAction,
|
||||||
|
SidebarMenuBadge,
|
||||||
|
SidebarMenuButton,
|
||||||
|
SidebarMenuItem,
|
||||||
|
SidebarMenuSkeleton,
|
||||||
|
SidebarMenuSub,
|
||||||
|
SidebarMenuSubButton,
|
||||||
|
SidebarMenuSubItem,
|
||||||
|
SidebarProvider,
|
||||||
|
SidebarRail,
|
||||||
|
SidebarSeparator,
|
||||||
|
SidebarTrigger,
|
||||||
|
useSidebar,
|
||||||
|
};
|
||||||
@@ -6,7 +6,7 @@ function Skeleton({
|
|||||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
className={cn("animate-pulse rounded-md bg-primary/10", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
27
frontend/src/components/ui/switch.tsx
Normal file
27
frontend/src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import * as SwitchPrimitives from "@radix-ui/react-switch";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const Switch = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<SwitchPrimitives.Root
|
||||||
|
className={cn(
|
||||||
|
"peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
ref={ref}
|
||||||
|
>
|
||||||
|
<SwitchPrimitives.Thumb
|
||||||
|
className={cn(
|
||||||
|
"pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</SwitchPrimitives.Root>
|
||||||
|
));
|
||||||
|
Switch.displayName = SwitchPrimitives.Root.displayName;
|
||||||
|
|
||||||
|
export { Switch };
|
||||||
53
frontend/src/components/ui/tabs.tsx
Normal file
53
frontend/src/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const Tabs = TabsPrimitive.Root;
|
||||||
|
|
||||||
|
const TabsList = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TabsPrimitive.List>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<TabsPrimitive.List
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
TabsList.displayName = TabsPrimitive.List.displayName;
|
||||||
|
|
||||||
|
const TabsTrigger = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<TabsPrimitive.Trigger
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
|
||||||
|
|
||||||
|
const TabsContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TabsPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<TabsPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
));
|
||||||
|
TabsContent.displayName = TabsPrimitive.Content.displayName;
|
||||||
|
|
||||||
|
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||||
30
frontend/src/components/ui/tooltip.tsx
Normal file
30
frontend/src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
const TooltipProvider = TooltipPrimitive.Provider;
|
||||||
|
|
||||||
|
const Tooltip = TooltipPrimitive.Root;
|
||||||
|
|
||||||
|
const TooltipTrigger = TooltipPrimitive.Trigger;
|
||||||
|
|
||||||
|
const TooltipContent = React.forwardRef<
|
||||||
|
React.ElementRef<typeof TooltipPrimitive.Content>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||||
|
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||||
|
<TooltipPrimitive.Portal>
|
||||||
|
<TooltipPrimitive.Content
|
||||||
|
ref={ref}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</TooltipPrimitive.Portal>
|
||||||
|
));
|
||||||
|
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
|
||||||
|
|
||||||
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||||
@@ -51,22 +51,29 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
|||||||
const themeColor = THEME_COLORS[resolvedTheme];
|
const themeColor = THEME_COLORS[resolvedTheme];
|
||||||
|
|
||||||
// Update theme-color meta tag
|
// Update theme-color meta tag
|
||||||
const themeColorMeta = document.getElementById("theme-color-meta") as HTMLMetaElement;
|
const themeColorMeta = document.getElementById(
|
||||||
|
"theme-color-meta",
|
||||||
|
) as HTMLMetaElement;
|
||||||
if (themeColorMeta) {
|
if (themeColorMeta) {
|
||||||
themeColorMeta.content = themeColor;
|
themeColorMeta.content = themeColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update Microsoft tile color
|
// Update Microsoft tile color
|
||||||
const msThemeColorMeta = document.getElementById("ms-theme-color-meta") as HTMLMetaElement;
|
const msThemeColorMeta = document.getElementById(
|
||||||
|
"ms-theme-color-meta",
|
||||||
|
) as HTMLMetaElement;
|
||||||
if (msThemeColorMeta) {
|
if (msThemeColorMeta) {
|
||||||
msThemeColorMeta.content = themeColor;
|
msThemeColorMeta.content = themeColor;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update Apple status bar style for better iOS integration
|
// Update Apple status bar style for better iOS integration
|
||||||
const appleStatusBarMeta = document.getElementById("apple-status-bar-meta") as HTMLMetaElement;
|
const appleStatusBarMeta = document.getElementById(
|
||||||
|
"apple-status-bar-meta",
|
||||||
|
) as HTMLMetaElement;
|
||||||
if (appleStatusBarMeta) {
|
if (appleStatusBarMeta) {
|
||||||
// Use 'black-translucent' for dark theme, 'default' for light theme
|
// Use 'black-translucent' for dark theme, 'default' for light theme
|
||||||
appleStatusBarMeta.content = resolvedTheme === "dark" ? "black-translucent" : "default";
|
appleStatusBarMeta.content =
|
||||||
|
resolvedTheme === "dark" ? "black-translucent" : "default";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
21
frontend/src/hooks/use-mobile.tsx
Normal file
21
frontend/src/hooks/use-mobile.tsx
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
const MOBILE_BREAKPOINT = 768;
|
||||||
|
|
||||||
|
export function useIsMobile() {
|
||||||
|
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||||
|
const onChange = () => {
|
||||||
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||||
|
};
|
||||||
|
mql.addEventListener("change", onChange);
|
||||||
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||||
|
return () => mql.removeEventListener("change", onChange);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return !!isMobile;
|
||||||
|
}
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
interface PWAUpdate {
|
|
||||||
updateAvailable: boolean;
|
|
||||||
updateSW: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function usePWA(): PWAUpdate {
|
|
||||||
const [updateAvailable, setUpdateAvailable] = useState(false);
|
|
||||||
const [updateSW, setUpdateSW] = useState<() => Promise<void>>(() => async () => {});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
// Check if SW registration is available
|
|
||||||
if ("serviceWorker" in navigator) {
|
|
||||||
// Import the registerSW function
|
|
||||||
import("virtual:pwa-register").then(({ registerSW }) => {
|
|
||||||
const updateSWFunction = registerSW({
|
|
||||||
onNeedRefresh() {
|
|
||||||
setUpdateAvailable(true);
|
|
||||||
setUpdateSW(() => updateSWFunction);
|
|
||||||
},
|
|
||||||
onOfflineReady() {
|
|
||||||
console.log("App ready to work offline");
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}).catch(() => {
|
|
||||||
// PWA not available in development mode or when disabled
|
|
||||||
console.log("PWA registration not available");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return {
|
|
||||||
updateAvailable,
|
|
||||||
updateSW,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -29,12 +29,20 @@
|
|||||||
--chart-4: 43 74% 66%;
|
--chart-4: 43 74% 66%;
|
||||||
--chart-5: 27 87% 67%;
|
--chart-5: 27 87% 67%;
|
||||||
--radius: 0.5rem;
|
--radius: 0.5rem;
|
||||||
|
|
||||||
/* iOS Safe Area Support for PWA */
|
/* iOS Safe Area Support for PWA */
|
||||||
--safe-area-inset-top: env(safe-area-inset-top, 0px);
|
--safe-area-inset-top: env(safe-area-inset-top, 0px);
|
||||||
--safe-area-inset-right: env(safe-area-inset-right, 0px);
|
--safe-area-inset-right: env(safe-area-inset-right, 0px);
|
||||||
--safe-area-inset-bottom: env(safe-area-inset-bottom, 0px);
|
--safe-area-inset-bottom: env(safe-area-inset-bottom, 0px);
|
||||||
--safe-area-inset-left: env(safe-area-inset-left, 0px);
|
--safe-area-inset-left: env(safe-area-inset-left, 0px);
|
||||||
|
--sidebar-background: 0 0% 98%;
|
||||||
|
--sidebar-foreground: 240 5.3% 26.1%;
|
||||||
|
--sidebar-primary: 240 5.9% 10%;
|
||||||
|
--sidebar-primary-foreground: 0 0% 98%;
|
||||||
|
--sidebar-accent: 240 4.8% 95.9%;
|
||||||
|
--sidebar-accent-foreground: 240 5.9% 10%;
|
||||||
|
--sidebar-border: 220 13% 91%;
|
||||||
|
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||||
}
|
}
|
||||||
.dark {
|
.dark {
|
||||||
--background: 222.2 84% 4.9%;
|
--background: 222.2 84% 4.9%;
|
||||||
@@ -61,6 +69,14 @@
|
|||||||
--chart-3: 30 80% 55%;
|
--chart-3: 30 80% 55%;
|
||||||
--chart-4: 280 65% 60%;
|
--chart-4: 280 65% 60%;
|
||||||
--chart-5: 340 75% 55%;
|
--chart-5: 340 75% 55%;
|
||||||
|
--sidebar-background: 240 5.9% 10%;
|
||||||
|
--sidebar-foreground: 240 4.8% 95.9%;
|
||||||
|
--sidebar-primary: 224.3 76.3% 48%;
|
||||||
|
--sidebar-primary-foreground: 0 0% 100%;
|
||||||
|
--sidebar-accent: 240 3.7% 15.9%;
|
||||||
|
--sidebar-accent-foreground: 240 4.8% 95.9%;
|
||||||
|
--sidebar-border: 240 3.7% 15.9%;
|
||||||
|
--sidebar-ring: 217.2 91.2% 59.8%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,15 @@ import type {
|
|||||||
HealthData,
|
HealthData,
|
||||||
AccountUpdate,
|
AccountUpdate,
|
||||||
TransactionStats,
|
TransactionStats,
|
||||||
|
SyncOperationsResponse,
|
||||||
|
BankInstitution,
|
||||||
|
BankConnectionStatus,
|
||||||
|
BankRequisition,
|
||||||
|
Country,
|
||||||
|
BackupSettings,
|
||||||
|
BackupTest,
|
||||||
|
BackupInfo,
|
||||||
|
BackupOperation,
|
||||||
} from "../types/api";
|
} from "../types/api";
|
||||||
|
|
||||||
// Use VITE_API_URL for development, relative URLs for production
|
// Use VITE_API_URL for development, relative URLs for production
|
||||||
@@ -217,6 +226,90 @@ export const apiClient = {
|
|||||||
>(`/transactions/monthly-stats?${queryParams.toString()}`);
|
>(`/transactions/monthly-stats?${queryParams.toString()}`);
|
||||||
return response.data.data;
|
return response.data.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Get sync operations history
|
||||||
|
getSyncOperations: async (
|
||||||
|
limit: number = 50,
|
||||||
|
offset: number = 0,
|
||||||
|
): Promise<SyncOperationsResponse> => {
|
||||||
|
const response = await api.get<ApiResponse<SyncOperationsResponse>>(
|
||||||
|
`/sync/operations?limit=${limit}&offset=${offset}`,
|
||||||
|
);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
// Bank management endpoints
|
||||||
|
getBankInstitutions: async (country: string): Promise<BankInstitution[]> => {
|
||||||
|
const response = await api.get<ApiResponse<BankInstitution[]>>(
|
||||||
|
`/banks/institutions?country=${country}`,
|
||||||
|
);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
getBankConnectionsStatus: async (): Promise<BankConnectionStatus[]> => {
|
||||||
|
const response =
|
||||||
|
await api.get<ApiResponse<BankConnectionStatus[]>>("/banks/status");
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
createBankConnection: async (
|
||||||
|
institutionId: string,
|
||||||
|
redirectUrl?: string,
|
||||||
|
): Promise<BankRequisition> => {
|
||||||
|
// If no redirect URL provided, construct it from current location
|
||||||
|
const finalRedirectUrl =
|
||||||
|
redirectUrl || `${window.location.origin}/bank-connected`;
|
||||||
|
|
||||||
|
const response = await api.post<ApiResponse<BankRequisition>>(
|
||||||
|
"/banks/connect",
|
||||||
|
{
|
||||||
|
institution_id: institutionId,
|
||||||
|
redirect_url: finalRedirectUrl,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteBankConnection: async (requisitionId: string): Promise<void> => {
|
||||||
|
await api.delete(`/banks/connections/${requisitionId}`);
|
||||||
|
},
|
||||||
|
|
||||||
|
getSupportedCountries: async (): Promise<Country[]> => {
|
||||||
|
const response = await api.get<ApiResponse<Country[]>>("/banks/countries");
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
// Backup endpoints
|
||||||
|
getBackupSettings: async (): Promise<BackupSettings> => {
|
||||||
|
const response =
|
||||||
|
await api.get<ApiResponse<BackupSettings>>("/backup/settings");
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
updateBackupSettings: async (
|
||||||
|
settings: BackupSettings,
|
||||||
|
): Promise<BackupSettings> => {
|
||||||
|
const response = await api.put<ApiResponse<BackupSettings>>(
|
||||||
|
"/backup/settings",
|
||||||
|
settings,
|
||||||
|
);
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
testBackupConnection: async (test: BackupTest): Promise<ApiResponse<{ connected?: boolean }>> => {
|
||||||
|
const response = await api.post<ApiResponse<{ connected?: boolean }>>("/backup/test", test);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
listBackups: async (): Promise<BackupInfo[]> => {
|
||||||
|
const response = await api.get<ApiResponse<BackupInfo[]>>("/backup/list");
|
||||||
|
return response.data.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
performBackupOperation: async (operation: BackupOperation): Promise<ApiResponse<{ operation: string; completed: boolean }>> => {
|
||||||
|
const response = await api.post<ApiResponse<{ operation: string; completed: boolean }>>("/backup/operation", operation);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default apiClient;
|
export default apiClient;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|||||||
import { ThemeProvider } from "./contexts/ThemeContext";
|
import { ThemeProvider } from "./contexts/ThemeContext";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
import { routeTree } from "./routeTree.gen";
|
import { routeTree } from "./routeTree.gen";
|
||||||
|
import { registerSW } from "virtual:pwa-register";
|
||||||
|
|
||||||
const router = createRouter({ routeTree });
|
const router = createRouter({ routeTree });
|
||||||
|
|
||||||
@@ -17,6 +18,57 @@ const queryClient = new QueryClient({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const intervalMS = 60 * 60 * 1000;
|
||||||
|
|
||||||
|
registerSW({
|
||||||
|
onRegisteredSW(swUrl, r) {
|
||||||
|
console.log("[PWA] Service worker registered successfully");
|
||||||
|
|
||||||
|
if (r) {
|
||||||
|
setInterval(async () => {
|
||||||
|
console.log("[PWA] Checking for updates...");
|
||||||
|
|
||||||
|
if (r.installing) {
|
||||||
|
console.log("[PWA] Update already installing, skipping check");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!navigator) {
|
||||||
|
console.log("[PWA] Navigator not available, skipping check");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ("connection" in navigator && !navigator.onLine) {
|
||||||
|
console.log("[PWA] Device is offline, skipping check");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch(swUrl, {
|
||||||
|
cache: "no-store",
|
||||||
|
headers: {
|
||||||
|
cache: "no-store",
|
||||||
|
"cache-control": "no-cache",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (resp?.status === 200) {
|
||||||
|
console.log("[PWA] Update check successful, triggering update");
|
||||||
|
await r.update();
|
||||||
|
} else {
|
||||||
|
console.log(`[PWA] Update check returned status: ${resp?.status}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[PWA] Error checking for updates:", error);
|
||||||
|
}
|
||||||
|
}, intervalMS);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onOfflineReady() {
|
||||||
|
console.log("[PWA] App ready to work offline");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
createRoot(document.getElementById("root")!).render(
|
createRoot(document.getElementById("root")!).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
|
|||||||
@@ -10,8 +10,10 @@
|
|||||||
|
|
||||||
import { Route as rootRouteImport } from './routes/__root'
|
import { Route as rootRouteImport } from './routes/__root'
|
||||||
import { Route as TransactionsRouteImport } from './routes/transactions'
|
import { Route as TransactionsRouteImport } from './routes/transactions'
|
||||||
|
import { Route as SystemRouteImport } from './routes/system'
|
||||||
import { Route as SettingsRouteImport } from './routes/settings'
|
import { Route as SettingsRouteImport } from './routes/settings'
|
||||||
import { Route as NotificationsRouteImport } from './routes/notifications'
|
import { Route as NotificationsRouteImport } from './routes/notifications'
|
||||||
|
import { Route as BankConnectedRouteImport } from './routes/bank-connected'
|
||||||
import { Route as AnalyticsRouteImport } from './routes/analytics'
|
import { Route as AnalyticsRouteImport } from './routes/analytics'
|
||||||
import { Route as IndexRouteImport } from './routes/index'
|
import { Route as IndexRouteImport } from './routes/index'
|
||||||
|
|
||||||
@@ -20,6 +22,11 @@ const TransactionsRoute = TransactionsRouteImport.update({
|
|||||||
path: '/transactions',
|
path: '/transactions',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const SystemRoute = SystemRouteImport.update({
|
||||||
|
id: '/system',
|
||||||
|
path: '/system',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const SettingsRoute = SettingsRouteImport.update({
|
const SettingsRoute = SettingsRouteImport.update({
|
||||||
id: '/settings',
|
id: '/settings',
|
||||||
path: '/settings',
|
path: '/settings',
|
||||||
@@ -30,6 +37,11 @@ const NotificationsRoute = NotificationsRouteImport.update({
|
|||||||
path: '/notifications',
|
path: '/notifications',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const BankConnectedRoute = BankConnectedRouteImport.update({
|
||||||
|
id: '/bank-connected',
|
||||||
|
path: '/bank-connected',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const AnalyticsRoute = AnalyticsRouteImport.update({
|
const AnalyticsRoute = AnalyticsRouteImport.update({
|
||||||
id: '/analytics',
|
id: '/analytics',
|
||||||
path: '/analytics',
|
path: '/analytics',
|
||||||
@@ -44,23 +56,29 @@ const IndexRoute = IndexRouteImport.update({
|
|||||||
export interface FileRoutesByFullPath {
|
export interface FileRoutesByFullPath {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/analytics': typeof AnalyticsRoute
|
'/analytics': typeof AnalyticsRoute
|
||||||
|
'/bank-connected': typeof BankConnectedRoute
|
||||||
'/notifications': typeof NotificationsRoute
|
'/notifications': typeof NotificationsRoute
|
||||||
'/settings': typeof SettingsRoute
|
'/settings': typeof SettingsRoute
|
||||||
|
'/system': typeof SystemRoute
|
||||||
'/transactions': typeof TransactionsRoute
|
'/transactions': typeof TransactionsRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/analytics': typeof AnalyticsRoute
|
'/analytics': typeof AnalyticsRoute
|
||||||
|
'/bank-connected': typeof BankConnectedRoute
|
||||||
'/notifications': typeof NotificationsRoute
|
'/notifications': typeof NotificationsRoute
|
||||||
'/settings': typeof SettingsRoute
|
'/settings': typeof SettingsRoute
|
||||||
|
'/system': typeof SystemRoute
|
||||||
'/transactions': typeof TransactionsRoute
|
'/transactions': typeof TransactionsRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/analytics': typeof AnalyticsRoute
|
'/analytics': typeof AnalyticsRoute
|
||||||
|
'/bank-connected': typeof BankConnectedRoute
|
||||||
'/notifications': typeof NotificationsRoute
|
'/notifications': typeof NotificationsRoute
|
||||||
'/settings': typeof SettingsRoute
|
'/settings': typeof SettingsRoute
|
||||||
|
'/system': typeof SystemRoute
|
||||||
'/transactions': typeof TransactionsRoute
|
'/transactions': typeof TransactionsRoute
|
||||||
}
|
}
|
||||||
export interface FileRouteTypes {
|
export interface FileRouteTypes {
|
||||||
@@ -68,25 +86,38 @@ export interface FileRouteTypes {
|
|||||||
fullPaths:
|
fullPaths:
|
||||||
| '/'
|
| '/'
|
||||||
| '/analytics'
|
| '/analytics'
|
||||||
|
| '/bank-connected'
|
||||||
| '/notifications'
|
| '/notifications'
|
||||||
| '/settings'
|
| '/settings'
|
||||||
|
| '/system'
|
||||||
| '/transactions'
|
| '/transactions'
|
||||||
fileRoutesByTo: FileRoutesByTo
|
fileRoutesByTo: FileRoutesByTo
|
||||||
to: '/' | '/analytics' | '/notifications' | '/settings' | '/transactions'
|
to:
|
||||||
|
| '/'
|
||||||
|
| '/analytics'
|
||||||
|
| '/bank-connected'
|
||||||
|
| '/notifications'
|
||||||
|
| '/settings'
|
||||||
|
| '/system'
|
||||||
|
| '/transactions'
|
||||||
id:
|
id:
|
||||||
| '__root__'
|
| '__root__'
|
||||||
| '/'
|
| '/'
|
||||||
| '/analytics'
|
| '/analytics'
|
||||||
|
| '/bank-connected'
|
||||||
| '/notifications'
|
| '/notifications'
|
||||||
| '/settings'
|
| '/settings'
|
||||||
|
| '/system'
|
||||||
| '/transactions'
|
| '/transactions'
|
||||||
fileRoutesById: FileRoutesById
|
fileRoutesById: FileRoutesById
|
||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
IndexRoute: typeof IndexRoute
|
IndexRoute: typeof IndexRoute
|
||||||
AnalyticsRoute: typeof AnalyticsRoute
|
AnalyticsRoute: typeof AnalyticsRoute
|
||||||
|
BankConnectedRoute: typeof BankConnectedRoute
|
||||||
NotificationsRoute: typeof NotificationsRoute
|
NotificationsRoute: typeof NotificationsRoute
|
||||||
SettingsRoute: typeof SettingsRoute
|
SettingsRoute: typeof SettingsRoute
|
||||||
|
SystemRoute: typeof SystemRoute
|
||||||
TransactionsRoute: typeof TransactionsRoute
|
TransactionsRoute: typeof TransactionsRoute
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,6 +130,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof TransactionsRouteImport
|
preLoaderRoute: typeof TransactionsRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/system': {
|
||||||
|
id: '/system'
|
||||||
|
path: '/system'
|
||||||
|
fullPath: '/system'
|
||||||
|
preLoaderRoute: typeof SystemRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/settings': {
|
'/settings': {
|
||||||
id: '/settings'
|
id: '/settings'
|
||||||
path: '/settings'
|
path: '/settings'
|
||||||
@@ -113,6 +151,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof NotificationsRouteImport
|
preLoaderRoute: typeof NotificationsRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/bank-connected': {
|
||||||
|
id: '/bank-connected'
|
||||||
|
path: '/bank-connected'
|
||||||
|
fullPath: '/bank-connected'
|
||||||
|
preLoaderRoute: typeof BankConnectedRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/analytics': {
|
'/analytics': {
|
||||||
id: '/analytics'
|
id: '/analytics'
|
||||||
path: '/analytics'
|
path: '/analytics'
|
||||||
@@ -133,8 +178,10 @@ declare module '@tanstack/react-router' {
|
|||||||
const rootRouteChildren: RootRouteChildren = {
|
const rootRouteChildren: RootRouteChildren = {
|
||||||
IndexRoute: IndexRoute,
|
IndexRoute: IndexRoute,
|
||||||
AnalyticsRoute: AnalyticsRoute,
|
AnalyticsRoute: AnalyticsRoute,
|
||||||
|
BankConnectedRoute: BankConnectedRoute,
|
||||||
NotificationsRoute: NotificationsRoute,
|
NotificationsRoute: NotificationsRoute,
|
||||||
SettingsRoute: SettingsRoute,
|
SettingsRoute: SettingsRoute,
|
||||||
|
SystemRoute: SystemRoute,
|
||||||
TransactionsRoute: TransactionsRoute,
|
TransactionsRoute: TransactionsRoute,
|
||||||
}
|
}
|
||||||
export const routeTree = rootRouteImport
|
export const routeTree = rootRouteImport
|
||||||
|
|||||||
@@ -1,53 +1,30 @@
|
|||||||
import { createRootRoute, Outlet } from "@tanstack/react-router";
|
import { createRootRoute, Outlet } from "@tanstack/react-router";
|
||||||
import { useState } from "react";
|
import { AppSidebar } from "../components/AppSidebar";
|
||||||
import Sidebar from "../components/Sidebar";
|
import { SiteHeader } from "../components/SiteHeader";
|
||||||
import Header from "../components/Header";
|
import { SidebarInset, SidebarProvider } from "../components/ui/sidebar";
|
||||||
import { PWAInstallPrompt, PWAUpdatePrompt } from "../components/PWAPrompts";
|
import { Toaster } from "../components/ui/sonner";
|
||||||
import { usePWA } from "../hooks/usePWA";
|
|
||||||
|
|
||||||
function RootLayout() {
|
function RootLayout() {
|
||||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
|
||||||
const { updateAvailable, updateSW } = usePWA();
|
|
||||||
|
|
||||||
const handlePWAInstall = () => {
|
|
||||||
console.log("PWA installed successfully");
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePWAUpdate = async () => {
|
|
||||||
try {
|
|
||||||
await updateSW();
|
|
||||||
console.log("PWA updated successfully");
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error updating PWA:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen bg-background">
|
<SidebarProvider
|
||||||
<Sidebar sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} />
|
style={
|
||||||
|
{
|
||||||
{/* Mobile overlay */}
|
"--sidebar-width": "16rem",
|
||||||
{sidebarOpen && (
|
"--header-height": "4rem",
|
||||||
<div
|
} as React.CSSProperties
|
||||||
className="fixed inset-0 z-40 bg-black/50 lg:hidden"
|
}
|
||||||
onClick={() => setSidebarOpen(false)}
|
>
|
||||||
/>
|
<AppSidebar />
|
||||||
)}
|
<SidebarInset>
|
||||||
|
<SiteHeader />
|
||||||
<div className="flex flex-col flex-1 min-w-0">
|
|
||||||
<Header setSidebarOpen={setSidebarOpen} />
|
|
||||||
<main className="flex-1 p-6 min-w-0">
|
<main className="flex-1 p-6 min-w-0">
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</SidebarInset>
|
||||||
|
|
||||||
{/* PWA Prompts */}
|
{/* Toast Notifications */}
|
||||||
<PWAInstallPrompt onInstall={handlePWAInstall} />
|
<Toaster />
|
||||||
<PWAUpdatePrompt
|
</SidebarProvider>
|
||||||
updateAvailable={updateAvailable}
|
|
||||||
onUpdate={handlePWAUpdate}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ function AnalyticsDashboard() {
|
|||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="p-6">
|
<div className="space-y-8">
|
||||||
<div className="animate-pulse">
|
<div className="animate-pulse">
|
||||||
<div className="h-8 bg-muted rounded w-48 mb-6"></div>
|
<div className="h-8 bg-muted rounded w-48 mb-6"></div>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
|
||||||
@@ -62,7 +62,7 @@ function AnalyticsDashboard() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-8">
|
<div className="space-y-8">
|
||||||
{/* Time Period Filter */}
|
{/* Time Period Filter */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardContent className="p-4">
|
<CardContent className="p-4">
|
||||||
|
|||||||
57
frontend/src/routes/bank-connected.tsx
Normal file
57
frontend/src/routes/bank-connected.tsx
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { createFileRoute, useSearch } from "@tanstack/react-router";
|
||||||
|
import { CheckCircle, ArrowLeft } from "lucide-react";
|
||||||
|
import { Button } from "../components/ui/button";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "../components/ui/card";
|
||||||
|
|
||||||
|
function BankConnected() {
|
||||||
|
const search = useSearch({ from: "/bank-connected" });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader className="text-center pb-2">
|
||||||
|
<div className="mx-auto mb-4">
|
||||||
|
<CheckCircle className="h-16 w-16 text-green-500" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-2xl">Account Connected!</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="text-center space-y-4">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Your bank account has been successfully connected to Leggen. We'll
|
||||||
|
start syncing your transactions shortly.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{search?.bank && (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Connected to: <strong>{search.bank}</strong>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="pt-4">
|
||||||
|
<Button
|
||||||
|
onClick={() => (window.location.href = "/settings")}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||||
|
Go to Settings
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Route = createFileRoute("/bank-connected")({
|
||||||
|
component: BankConnected,
|
||||||
|
validateSearch: (search: Record<string, unknown>) => {
|
||||||
|
return {
|
||||||
|
bank: (search.bank as string) || undefined,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createFileRoute } from "@tanstack/react-router";
|
import { createFileRoute } from "@tanstack/react-router";
|
||||||
import Notifications from "../components/Notifications";
|
import System from "../components/System";
|
||||||
|
|
||||||
export const Route = createFileRoute("/notifications")({
|
export const Route = createFileRoute("/notifications")({
|
||||||
component: Notifications,
|
component: System,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { createFileRoute } from "@tanstack/react-router";
|
import { createFileRoute } from "@tanstack/react-router";
|
||||||
import AccountSettings from "../components/AccountSettings";
|
import Settings from "../components/Settings";
|
||||||
|
|
||||||
export const Route = createFileRoute("/settings")({
|
export const Route = createFileRoute("/settings")({
|
||||||
component: AccountSettings,
|
component: Settings,
|
||||||
});
|
});
|
||||||
|
|||||||
6
frontend/src/routes/system.tsx
Normal file
6
frontend/src/routes/system.tsx
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { createFileRoute } from "@tanstack/react-router";
|
||||||
|
import System from "../components/System";
|
||||||
|
|
||||||
|
export const Route = createFileRoute("/system")({
|
||||||
|
component: System,
|
||||||
|
});
|
||||||
@@ -13,6 +13,7 @@ export interface Account {
|
|||||||
name?: string;
|
name?: string;
|
||||||
display_name?: string;
|
display_name?: string;
|
||||||
currency?: string;
|
currency?: string;
|
||||||
|
logo?: string;
|
||||||
created: string;
|
created: string;
|
||||||
last_accessed?: string;
|
last_accessed?: string;
|
||||||
balances: AccountBalance[];
|
balances: AccountBalance[];
|
||||||
@@ -197,10 +198,17 @@ export interface NotificationServicesResponse {
|
|||||||
export interface HealthData {
|
export interface HealthData {
|
||||||
status: string;
|
status: string;
|
||||||
config_loaded?: boolean;
|
config_loaded?: boolean;
|
||||||
|
version?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Version information from root endpoint
|
||||||
|
export interface VersionData {
|
||||||
|
message: string;
|
||||||
|
version: string;
|
||||||
|
}
|
||||||
|
|
||||||
// Analytics data types
|
// Analytics data types
|
||||||
export interface TransactionStats {
|
export interface TransactionStats {
|
||||||
period_days: number;
|
period_days: number;
|
||||||
@@ -213,3 +221,90 @@ export interface TransactionStats {
|
|||||||
average_transaction: number;
|
average_transaction: number;
|
||||||
accounts_included: number;
|
accounts_included: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sync operations types
|
||||||
|
export interface SyncOperation {
|
||||||
|
id: number;
|
||||||
|
started_at: string;
|
||||||
|
completed_at?: string;
|
||||||
|
success?: boolean;
|
||||||
|
accounts_processed: number;
|
||||||
|
transactions_added: number;
|
||||||
|
transactions_updated: number;
|
||||||
|
balances_updated: number;
|
||||||
|
duration_seconds?: number;
|
||||||
|
errors: string[];
|
||||||
|
logs: string[];
|
||||||
|
trigger_type: "manual" | "scheduled" | "api";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncOperationsResponse {
|
||||||
|
operations: SyncOperation[];
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bank-related types
|
||||||
|
export interface BankInstitution {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
bic?: string;
|
||||||
|
transaction_total_days: number;
|
||||||
|
countries: string[];
|
||||||
|
logo?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BankRequisition {
|
||||||
|
id: string;
|
||||||
|
institution_id: string;
|
||||||
|
status: string;
|
||||||
|
status_display?: string;
|
||||||
|
created: string;
|
||||||
|
link: string;
|
||||||
|
accounts: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BankConnectionStatus {
|
||||||
|
bank_id: string;
|
||||||
|
bank_name: string;
|
||||||
|
status: string;
|
||||||
|
status_display: string;
|
||||||
|
created_at: string;
|
||||||
|
requisition_id: string;
|
||||||
|
accounts_count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Country {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backup types
|
||||||
|
export interface S3Config {
|
||||||
|
access_key_id: string;
|
||||||
|
secret_access_key: string;
|
||||||
|
bucket_name: string;
|
||||||
|
region: string;
|
||||||
|
endpoint_url?: string;
|
||||||
|
path_style: boolean;
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupSettings {
|
||||||
|
s3?: S3Config;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupTest {
|
||||||
|
service: string;
|
||||||
|
config: S3Config;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupInfo {
|
||||||
|
key: string;
|
||||||
|
last_modified: string;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackupOperation {
|
||||||
|
operation: string;
|
||||||
|
backup_key?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,10 +10,10 @@ export default {
|
|||||||
sm: "calc(var(--radius) - 4px)",
|
sm: "calc(var(--radius) - 4px)",
|
||||||
},
|
},
|
||||||
spacing: {
|
spacing: {
|
||||||
'safe-top': 'var(--safe-area-inset-top)',
|
"safe-top": "var(--safe-area-inset-top)",
|
||||||
'safe-bottom': 'var(--safe-area-inset-bottom)',
|
"safe-bottom": "var(--safe-area-inset-bottom)",
|
||||||
'safe-left': 'var(--safe-area-inset-left)',
|
"safe-left": "var(--safe-area-inset-left)",
|
||||||
'safe-right': 'var(--safe-area-inset-right)',
|
"safe-right": "var(--safe-area-inset-right)",
|
||||||
},
|
},
|
||||||
colors: {
|
colors: {
|
||||||
background: "hsl(var(--background))",
|
background: "hsl(var(--background))",
|
||||||
@@ -56,6 +56,16 @@ export default {
|
|||||||
4: "hsl(var(--chart-4))",
|
4: "hsl(var(--chart-4))",
|
||||||
5: "hsl(var(--chart-5))",
|
5: "hsl(var(--chart-5))",
|
||||||
},
|
},
|
||||||
|
sidebar: {
|
||||||
|
DEFAULT: "hsl(var(--sidebar-background))",
|
||||||
|
foreground: "hsl(var(--sidebar-foreground))",
|
||||||
|
primary: "hsl(var(--sidebar-primary))",
|
||||||
|
"primary-foreground": "hsl(var(--sidebar-primary-foreground))",
|
||||||
|
accent: "hsl(var(--sidebar-accent))",
|
||||||
|
"accent-foreground": "hsl(var(--sidebar-accent-foreground))",
|
||||||
|
border: "hsl(var(--sidebar-border))",
|
||||||
|
ring: "hsl(var(--sidebar-ring))",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
import { TanStackRouterVite } from "@tanstack/router-vite-plugin";
|
import { tanstackRouter } from "@tanstack/router-vite-plugin";
|
||||||
import { VitePWA } from "vite-plugin-pwa";
|
import { VitePWA } from "vite-plugin-pwa";
|
||||||
|
|
||||||
// https://vite.dev/config/
|
// https://vite.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [
|
plugins: [
|
||||||
TanStackRouterVite(),
|
tanstackRouter(),
|
||||||
react(),
|
react(),
|
||||||
VitePWA({
|
VitePWA({
|
||||||
registerType: "autoUpdate",
|
registerType: "autoUpdate",
|
||||||
includeAssets: ["favicon.ico", "apple-touch-icon-180x180.png", "maskable-icon-512x512.png", "robots.txt"],
|
includeAssets: [
|
||||||
|
"robots.txt"
|
||||||
|
],
|
||||||
manifest: {
|
manifest: {
|
||||||
name: "Leggen",
|
name: "Leggen",
|
||||||
short_name: "Leggen",
|
short_name: "Leggen",
|
||||||
@@ -28,38 +30,38 @@ export default defineConfig({
|
|||||||
short_name: "Transactions",
|
short_name: "Transactions",
|
||||||
description: "View and manage transactions",
|
description: "View and manage transactions",
|
||||||
url: "/transactions",
|
url: "/transactions",
|
||||||
icons: [{ src: "/pwa-192x192.png", sizes: "192x192" }]
|
icons: [{ src: "/pwa-192x192.png", sizes: "192x192" }],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Analytics",
|
name: "Analytics",
|
||||||
short_name: "Analytics",
|
short_name: "Analytics",
|
||||||
description: "View financial analytics",
|
description: "View financial analytics",
|
||||||
url: "/analytics",
|
url: "/analytics",
|
||||||
icons: [{ src: "/pwa-192x192.png", sizes: "192x192" }]
|
icons: [{ src: "/pwa-192x192.png", sizes: "192x192" }],
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
icons: [
|
icons: [
|
||||||
{
|
{
|
||||||
src: "pwa-64x64.png",
|
src: "pwa-64x64.png",
|
||||||
sizes: "64x64",
|
sizes: "64x64",
|
||||||
type: "image/png"
|
type: "image/png",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
src: "pwa-192x192.png",
|
src: "pwa-192x192.png",
|
||||||
sizes: "192x192",
|
sizes: "192x192",
|
||||||
type: "image/png"
|
type: "image/png",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
src: "pwa-512x512.png",
|
src: "pwa-512x512.png",
|
||||||
sizes: "512x512",
|
sizes: "512x512",
|
||||||
type: "image/png"
|
type: "image/png",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
src: "maskable-icon-512x512.png",
|
src: "maskable-icon-512x512.png",
|
||||||
sizes: "512x512",
|
sizes: "512x512",
|
||||||
type: "image/png",
|
type: "image/png",
|
||||||
purpose: "maskable"
|
purpose: "maskable",
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
workbox: {
|
workbox: {
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ class AccountDetails(BaseModel):
|
|||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
display_name: Optional[str] = None
|
display_name: Optional[str] = None
|
||||||
currency: Optional[str] = None
|
currency: Optional[str] = None
|
||||||
|
logo: Optional[str] = None
|
||||||
created: datetime
|
created: datetime
|
||||||
last_accessed: Optional[datetime] = None
|
last_accessed: Optional[datetime] = None
|
||||||
balances: List[AccountBalance] = []
|
balances: List[AccountBalance] = []
|
||||||
|
|||||||
49
leggen/api/models/backup.py
Normal file
49
leggen/api/models/backup.py
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
"""API models for backup endpoints."""
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class S3Config(BaseModel):
|
||||||
|
"""S3 backup configuration model for API."""
|
||||||
|
|
||||||
|
access_key_id: str = Field(..., description="AWS S3 access key ID")
|
||||||
|
secret_access_key: str = Field(..., description="AWS S3 secret access key")
|
||||||
|
bucket_name: str = Field(..., description="S3 bucket name")
|
||||||
|
region: str = Field(default="us-east-1", description="AWS S3 region")
|
||||||
|
endpoint_url: Optional[str] = Field(
|
||||||
|
default=None, description="Custom S3 endpoint URL"
|
||||||
|
)
|
||||||
|
path_style: bool = Field(default=False, description="Use path-style addressing")
|
||||||
|
enabled: bool = Field(default=True, description="Enable S3 backups")
|
||||||
|
|
||||||
|
|
||||||
|
class BackupSettings(BaseModel):
|
||||||
|
"""Backup settings model for API."""
|
||||||
|
|
||||||
|
s3: Optional[S3Config] = None
|
||||||
|
|
||||||
|
|
||||||
|
class BackupTest(BaseModel):
|
||||||
|
"""Backup connection test request model."""
|
||||||
|
|
||||||
|
service: str = Field(..., description="Backup service type (s3)")
|
||||||
|
config: S3Config = Field(..., description="S3 configuration to test")
|
||||||
|
|
||||||
|
|
||||||
|
class BackupInfo(BaseModel):
|
||||||
|
"""Backup file information model."""
|
||||||
|
|
||||||
|
key: str = Field(..., description="S3 object key")
|
||||||
|
last_modified: str = Field(..., description="Last modified timestamp (ISO format)")
|
||||||
|
size: int = Field(..., description="File size in bytes")
|
||||||
|
|
||||||
|
|
||||||
|
class BackupOperation(BaseModel):
|
||||||
|
"""Backup operation request model."""
|
||||||
|
|
||||||
|
operation: str = Field(..., description="Operation type (backup, restore)")
|
||||||
|
backup_key: Optional[str] = Field(
|
||||||
|
default=None, description="Backup key for restore operations"
|
||||||
|
)
|
||||||
@@ -4,6 +4,26 @@ from typing import Optional
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class SyncOperation(BaseModel):
|
||||||
|
"""Sync operation record for tracking sync history"""
|
||||||
|
|
||||||
|
id: Optional[int] = None
|
||||||
|
started_at: datetime
|
||||||
|
completed_at: Optional[datetime] = None
|
||||||
|
success: Optional[bool] = None
|
||||||
|
accounts_processed: int = 0
|
||||||
|
transactions_added: int = 0
|
||||||
|
transactions_updated: int = 0
|
||||||
|
balances_updated: int = 0
|
||||||
|
duration_seconds: Optional[float] = None
|
||||||
|
errors: list[str] = []
|
||||||
|
logs: list[str] = []
|
||||||
|
trigger_type: str = "manual" # manual, scheduled, retry, api
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
json_encoders = {datetime: lambda v: v.isoformat() if v else None}
|
||||||
|
|
||||||
|
|
||||||
class SyncRequest(BaseModel):
|
class SyncRequest(BaseModel):
|
||||||
"""Request to trigger a sync"""
|
"""Request to trigger a sync"""
|
||||||
|
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ async def get_all_accounts() -> APIResponse:
|
|||||||
name=db_account.get("name"),
|
name=db_account.get("name"),
|
||||||
display_name=db_account.get("display_name"),
|
display_name=db_account.get("display_name"),
|
||||||
currency=db_account.get("currency"),
|
currency=db_account.get("currency"),
|
||||||
|
logo=db_account.get("logo"),
|
||||||
created=db_account["created"],
|
created=db_account["created"],
|
||||||
last_accessed=db_account.get("last_accessed"),
|
last_accessed=db_account.get("last_accessed"),
|
||||||
balances=balances,
|
balances=balances,
|
||||||
@@ -115,6 +116,7 @@ async def get_account_details(account_id: str) -> APIResponse:
|
|||||||
name=db_account.get("name"),
|
name=db_account.get("name"),
|
||||||
display_name=db_account.get("display_name"),
|
display_name=db_account.get("display_name"),
|
||||||
currency=db_account.get("currency"),
|
currency=db_account.get("currency"),
|
||||||
|
logo=db_account.get("logo"),
|
||||||
created=db_account["created"],
|
created=db_account["created"],
|
||||||
last_accessed=db_account.get("last_accessed"),
|
last_accessed=db_account.get("last_accessed"),
|
||||||
balances=balances,
|
balances=balances,
|
||||||
|
|||||||
264
leggen/api/routes/backup.py
Normal file
264
leggen/api/routes/backup.py
Normal file
@@ -0,0 +1,264 @@
|
|||||||
|
"""API routes for backup management."""
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from leggen.api.models.backup import (
|
||||||
|
BackupOperation,
|
||||||
|
BackupSettings,
|
||||||
|
BackupTest,
|
||||||
|
S3Config,
|
||||||
|
)
|
||||||
|
from leggen.api.models.common import APIResponse
|
||||||
|
from leggen.models.config import S3BackupConfig
|
||||||
|
from leggen.services.backup_service import BackupService
|
||||||
|
from leggen.utils.config import config
|
||||||
|
from leggen.utils.paths import path_manager
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/settings", response_model=APIResponse)
|
||||||
|
async def get_backup_settings() -> APIResponse:
|
||||||
|
"""Get current backup settings."""
|
||||||
|
try:
|
||||||
|
backup_config = config.backup_config
|
||||||
|
|
||||||
|
# Build response safely without exposing secrets
|
||||||
|
s3_config = backup_config.get("s3", {})
|
||||||
|
|
||||||
|
settings = BackupSettings(
|
||||||
|
s3=S3Config(
|
||||||
|
access_key_id="***" if s3_config.get("access_key_id") else "",
|
||||||
|
secret_access_key="***" if s3_config.get("secret_access_key") else "",
|
||||||
|
bucket_name=s3_config.get("bucket_name", ""),
|
||||||
|
region=s3_config.get("region", "us-east-1"),
|
||||||
|
endpoint_url=s3_config.get("endpoint_url"),
|
||||||
|
path_style=s3_config.get("path_style", False),
|
||||||
|
enabled=s3_config.get("enabled", True),
|
||||||
|
)
|
||||||
|
if s3_config.get("bucket_name")
|
||||||
|
else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data=settings,
|
||||||
|
message="Backup settings retrieved successfully",
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to get backup settings: {e}")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Failed to get backup settings: {str(e)}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/backup/settings", response_model=APIResponse)
|
||||||
|
async def update_backup_settings(settings: BackupSettings) -> APIResponse:
|
||||||
|
"""Update backup settings."""
|
||||||
|
try:
|
||||||
|
# First test the connection if S3 config is provided
|
||||||
|
if settings.s3:
|
||||||
|
# Convert API model to config model
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id=settings.s3.access_key_id,
|
||||||
|
secret_access_key=settings.s3.secret_access_key,
|
||||||
|
bucket_name=settings.s3.bucket_name,
|
||||||
|
region=settings.s3.region,
|
||||||
|
endpoint_url=settings.s3.endpoint_url,
|
||||||
|
path_style=settings.s3.path_style,
|
||||||
|
enabled=settings.s3.enabled,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Test connection
|
||||||
|
backup_service = BackupService()
|
||||||
|
connection_success = await backup_service.test_connection(s3_config)
|
||||||
|
|
||||||
|
if not connection_success:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="S3 connection test failed. Please check your configuration.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Update backup config
|
||||||
|
backup_config = {}
|
||||||
|
|
||||||
|
if settings.s3:
|
||||||
|
backup_config["s3"] = {
|
||||||
|
"access_key_id": settings.s3.access_key_id,
|
||||||
|
"secret_access_key": settings.s3.secret_access_key,
|
||||||
|
"bucket_name": settings.s3.bucket_name,
|
||||||
|
"region": settings.s3.region,
|
||||||
|
"endpoint_url": settings.s3.endpoint_url,
|
||||||
|
"path_style": settings.s3.path_style,
|
||||||
|
"enabled": settings.s3.enabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Save to config
|
||||||
|
if backup_config:
|
||||||
|
config.update_section("backup", backup_config)
|
||||||
|
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data={"updated": True},
|
||||||
|
message="Backup settings updated successfully",
|
||||||
|
)
|
||||||
|
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to update backup settings: {e}")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Failed to update backup settings: {str(e)}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/test", response_model=APIResponse)
|
||||||
|
async def test_backup_connection(test_request: BackupTest) -> APIResponse:
|
||||||
|
"""Test backup connection."""
|
||||||
|
try:
|
||||||
|
if test_request.service != "s3":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400, detail="Only 's3' service is supported"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Convert API model to config model
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id=test_request.config.access_key_id,
|
||||||
|
secret_access_key=test_request.config.secret_access_key,
|
||||||
|
bucket_name=test_request.config.bucket_name,
|
||||||
|
region=test_request.config.region,
|
||||||
|
endpoint_url=test_request.config.endpoint_url,
|
||||||
|
path_style=test_request.config.path_style,
|
||||||
|
enabled=test_request.config.enabled,
|
||||||
|
)
|
||||||
|
|
||||||
|
backup_service = BackupService()
|
||||||
|
success = await backup_service.test_connection(s3_config)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data={"connected": True},
|
||||||
|
message="S3 connection test successful",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return APIResponse(
|
||||||
|
success=False,
|
||||||
|
message="S3 connection test failed",
|
||||||
|
)
|
||||||
|
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to test backup connection: {e}")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Failed to test backup connection: {str(e)}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/backup/list", response_model=APIResponse)
|
||||||
|
async def list_backups() -> APIResponse:
|
||||||
|
"""List available backups."""
|
||||||
|
try:
|
||||||
|
backup_config = config.backup_config.get("s3", {})
|
||||||
|
|
||||||
|
if not backup_config.get("bucket_name"):
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data=[],
|
||||||
|
message="No S3 backup configuration found",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Convert config to model
|
||||||
|
s3_config = S3BackupConfig(**backup_config)
|
||||||
|
backup_service = BackupService(s3_config)
|
||||||
|
|
||||||
|
backups = await backup_service.list_backups()
|
||||||
|
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data=backups,
|
||||||
|
message=f"Found {len(backups)} backups",
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to list backups: {e}")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Failed to list backups: {str(e)}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/backup/operation", response_model=APIResponse)
|
||||||
|
async def backup_operation(operation_request: BackupOperation) -> APIResponse:
|
||||||
|
"""Perform backup operation (backup or restore)."""
|
||||||
|
try:
|
||||||
|
backup_config = config.backup_config.get("s3", {})
|
||||||
|
|
||||||
|
if not backup_config.get("bucket_name"):
|
||||||
|
raise HTTPException(status_code=400, detail="S3 backup is not configured")
|
||||||
|
|
||||||
|
# Convert config to model with validation
|
||||||
|
try:
|
||||||
|
s3_config = S3BackupConfig(**backup_config)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400, detail=f"Invalid S3 configuration: {str(e)}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
backup_service = BackupService(s3_config)
|
||||||
|
|
||||||
|
if operation_request.operation == "backup":
|
||||||
|
# Backup database
|
||||||
|
database_path = path_manager.get_database_path()
|
||||||
|
success = await backup_service.backup_database(database_path)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data={"operation": "backup", "completed": True},
|
||||||
|
message="Database backup completed successfully",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return APIResponse(
|
||||||
|
success=False,
|
||||||
|
message="Database backup failed",
|
||||||
|
)
|
||||||
|
|
||||||
|
elif operation_request.operation == "restore":
|
||||||
|
if not operation_request.backup_key:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="backup_key is required for restore operation",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Restore database
|
||||||
|
database_path = path_manager.get_database_path()
|
||||||
|
success = await backup_service.restore_database(
|
||||||
|
operation_request.backup_key, database_path
|
||||||
|
)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data={"operation": "restore", "completed": True},
|
||||||
|
message="Database restore completed successfully",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return APIResponse(
|
||||||
|
success=False,
|
||||||
|
message="Database restore failed",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400, detail="Invalid operation. Use 'backup' or 'restore'"
|
||||||
|
)
|
||||||
|
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to perform backup operation: {e}")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Failed to perform backup operation: {str(e)}"
|
||||||
|
) from e
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import httpx
|
||||||
from fastapi import APIRouter, HTTPException, Query
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
|
||||||
@@ -21,14 +22,19 @@ async def get_bank_institutions(
|
|||||||
) -> APIResponse:
|
) -> APIResponse:
|
||||||
"""Get available bank institutions for a country"""
|
"""Get available bank institutions for a country"""
|
||||||
try:
|
try:
|
||||||
institutions_data = await gocardless_service.get_institutions(country)
|
institutions_response = await gocardless_service.get_institutions(country)
|
||||||
|
# Handle both list and dict responses
|
||||||
|
if isinstance(institutions_response, list):
|
||||||
|
institutions_data = institutions_response
|
||||||
|
else:
|
||||||
|
institutions_data = institutions_response.get("results", [])
|
||||||
|
|
||||||
institutions = [
|
institutions = [
|
||||||
BankInstitution(
|
BankInstitution(
|
||||||
id=inst["id"],
|
id=inst["id"],
|
||||||
name=inst["name"],
|
name=inst["name"],
|
||||||
bic=inst.get("bic"),
|
bic=inst.get("bic"),
|
||||||
transaction_total_days=inst["transaction_total_days"],
|
transaction_total_days=int(inst["transaction_total_days"]),
|
||||||
countries=inst["countries"],
|
countries=inst["countries"],
|
||||||
logo=inst.get("logo"),
|
logo=inst.get("logo"),
|
||||||
)
|
)
|
||||||
@@ -121,13 +127,36 @@ async def get_bank_connections_status() -> APIResponse:
|
|||||||
async def delete_bank_connection(requisition_id: str) -> APIResponse:
|
async def delete_bank_connection(requisition_id: str) -> APIResponse:
|
||||||
"""Delete a bank connection"""
|
"""Delete a bank connection"""
|
||||||
try:
|
try:
|
||||||
# This would need to be implemented in GoCardlessService
|
# Delete the requisition from GoCardless
|
||||||
# For now, return success
|
result = await gocardless_service.delete_requisition(requisition_id)
|
||||||
|
|
||||||
|
# GoCardless returns different responses for successful deletes
|
||||||
|
# We should check if the operation was actually successful
|
||||||
|
logger.info(f"GoCardless delete response for {requisition_id}: {result}")
|
||||||
|
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
success=True,
|
success=True,
|
||||||
message=f"Bank connection {requisition_id} deleted successfully",
|
message=f"Bank connection {requisition_id} deleted successfully",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
except httpx.HTTPStatusError as http_err:
|
||||||
|
logger.error(
|
||||||
|
f"HTTP error deleting bank connection {requisition_id}: {http_err}"
|
||||||
|
)
|
||||||
|
if http_err.response.status_code == 404:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404, detail=f"Bank connection {requisition_id} not found"
|
||||||
|
) from http_err
|
||||||
|
elif http_err.response.status_code == 400:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Invalid request to delete connection {requisition_id}",
|
||||||
|
) from http_err
|
||||||
|
else:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=http_err.response.status_code,
|
||||||
|
detail=f"GoCardless API error: {http_err}",
|
||||||
|
) from http_err
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to delete bank connection {requisition_id}: {e}")
|
logger.error(f"Failed to delete bank connection {requisition_id}: {e}")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ async def trigger_sync(
|
|||||||
sync_service.sync_specific_accounts,
|
sync_service.sync_specific_accounts,
|
||||||
sync_request.account_ids,
|
sync_request.account_ids,
|
||||||
sync_request.force if sync_request else False,
|
sync_request.force if sync_request else False,
|
||||||
|
"api", # trigger_type
|
||||||
)
|
)
|
||||||
message = (
|
message = (
|
||||||
f"Started sync for {len(sync_request.account_ids)} specific accounts"
|
f"Started sync for {len(sync_request.account_ids)} specific accounts"
|
||||||
@@ -65,6 +66,7 @@ async def trigger_sync(
|
|||||||
background_tasks.add_task(
|
background_tasks.add_task(
|
||||||
sync_service.sync_all_accounts,
|
sync_service.sync_all_accounts,
|
||||||
sync_request.force if sync_request else False,
|
sync_request.force if sync_request else False,
|
||||||
|
"api", # trigger_type
|
||||||
)
|
)
|
||||||
message = "Started sync for all accounts"
|
message = "Started sync for all accounts"
|
||||||
|
|
||||||
@@ -90,11 +92,11 @@ async def sync_now(sync_request: Optional[SyncRequest] = None) -> APIResponse:
|
|||||||
try:
|
try:
|
||||||
if sync_request and sync_request.account_ids:
|
if sync_request and sync_request.account_ids:
|
||||||
result = await sync_service.sync_specific_accounts(
|
result = await sync_service.sync_specific_accounts(
|
||||||
sync_request.account_ids, sync_request.force
|
sync_request.account_ids, sync_request.force, "api"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
result = await sync_service.sync_all_accounts(
|
result = await sync_service.sync_all_accounts(
|
||||||
sync_request.force if sync_request else False
|
sync_request.force if sync_request else False, "api"
|
||||||
)
|
)
|
||||||
|
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
@@ -211,3 +213,24 @@ async def stop_scheduler() -> APIResponse:
|
|||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=500, detail=f"Failed to stop scheduler: {str(e)}"
|
status_code=500, detail=f"Failed to stop scheduler: {str(e)}"
|
||||||
) from e
|
) from e
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/sync/operations", response_model=APIResponse)
|
||||||
|
async def get_sync_operations(limit: int = 50, offset: int = 0) -> APIResponse:
|
||||||
|
"""Get sync operations history"""
|
||||||
|
try:
|
||||||
|
operations = await sync_service.database.get_sync_operations(
|
||||||
|
limit=limit, offset=offset
|
||||||
|
)
|
||||||
|
|
||||||
|
return APIResponse(
|
||||||
|
success=True,
|
||||||
|
data={"operations": operations, "count": len(operations)},
|
||||||
|
message="Sync operations retrieved successfully",
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to get sync operations: {e}")
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500, detail=f"Failed to get sync operations: {str(e)}"
|
||||||
|
) from e
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import os
|
import os
|
||||||
from typing import Any, Dict, List, Optional, Union
|
from typing import Any, Dict, List, Optional, Union
|
||||||
from urllib.parse import urljoin
|
from urllib.parse import urljoin, urlparse
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
@@ -13,11 +13,22 @@ class LeggenAPIClient:
|
|||||||
base_url: str
|
base_url: str
|
||||||
|
|
||||||
def __init__(self, base_url: Optional[str] = None):
|
def __init__(self, base_url: Optional[str] = None):
|
||||||
self.base_url = (
|
raw_url = (
|
||||||
base_url
|
base_url
|
||||||
or os.environ.get("LEGGEN_API_URL", "http://localhost:8000")
|
or os.environ.get("LEGGEN_API_URL", "http://localhost:8000")
|
||||||
or "http://localhost:8000"
|
or "http://localhost:8000"
|
||||||
)
|
)
|
||||||
|
# Ensure base_url includes /api/v1 path if not already present
|
||||||
|
parsed = urlparse(raw_url)
|
||||||
|
if not parsed.path or parsed.path == "/":
|
||||||
|
# No path or just root, add /api/v1
|
||||||
|
self.base_url = f"{raw_url.rstrip('/')}/api/v1"
|
||||||
|
elif not parsed.path.startswith("/api/v1"):
|
||||||
|
# Has a path but not /api/v1, add it
|
||||||
|
self.base_url = f"{raw_url.rstrip('/')}/api/v1"
|
||||||
|
else:
|
||||||
|
# Already has /api/v1 path
|
||||||
|
self.base_url = raw_url.rstrip("/")
|
||||||
self.session = requests.Session()
|
self.session = requests.Session()
|
||||||
self.session.headers.update(
|
self.session.headers.update(
|
||||||
{"Content-Type": "application/json", "Accept": "application/json"}
|
{"Content-Type": "application/json", "Accept": "application/json"}
|
||||||
@@ -25,7 +36,14 @@ class LeggenAPIClient:
|
|||||||
|
|
||||||
def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
|
def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
|
||||||
"""Make HTTP request to the API"""
|
"""Make HTTP request to the API"""
|
||||||
url = urljoin(self.base_url, endpoint)
|
# Construct URL by joining base_url with endpoint
|
||||||
|
# Handle both relative endpoints (starting with /) and paths
|
||||||
|
if endpoint.startswith("/"):
|
||||||
|
# Absolute endpoint path - append to base_url
|
||||||
|
url = f"{self.base_url}{endpoint}"
|
||||||
|
else:
|
||||||
|
# Relative endpoint, use urljoin
|
||||||
|
url = urljoin(f"{self.base_url}/", endpoint)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = self.session.request(method, url, **kwargs)
|
response = self.session.request(method, url, **kwargs)
|
||||||
@@ -52,7 +70,9 @@ class LeggenAPIClient:
|
|||||||
"""Check if the leggen server is healthy"""
|
"""Check if the leggen server is healthy"""
|
||||||
try:
|
try:
|
||||||
response = self._make_request("GET", "/health")
|
response = self._make_request("GET", "/health")
|
||||||
return response.get("status") == "healthy"
|
# The API now returns nested data structure
|
||||||
|
data = response.get("data", {})
|
||||||
|
return data.get("status") == "healthy"
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -60,7 +80,7 @@ class LeggenAPIClient:
|
|||||||
def get_institutions(self, country: str = "PT") -> List[Dict[str, Any]]:
|
def get_institutions(self, country: str = "PT") -> List[Dict[str, Any]]:
|
||||||
"""Get bank institutions for a country"""
|
"""Get bank institutions for a country"""
|
||||||
response = self._make_request(
|
response = self._make_request(
|
||||||
"GET", "/api/v1/banks/institutions", params={"country": country}
|
"GET", "/banks/institutions", params={"country": country}
|
||||||
)
|
)
|
||||||
return response.get("data", [])
|
return response.get("data", [])
|
||||||
|
|
||||||
@@ -70,35 +90,35 @@ class LeggenAPIClient:
|
|||||||
"""Connect to a bank"""
|
"""Connect to a bank"""
|
||||||
response = self._make_request(
|
response = self._make_request(
|
||||||
"POST",
|
"POST",
|
||||||
"/api/v1/banks/connect",
|
"/banks/connect",
|
||||||
json={"institution_id": institution_id, "redirect_url": redirect_url},
|
json={"institution_id": institution_id, "redirect_url": redirect_url},
|
||||||
)
|
)
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|
||||||
def get_bank_status(self) -> List[Dict[str, Any]]:
|
def get_bank_status(self) -> List[Dict[str, Any]]:
|
||||||
"""Get bank connection status"""
|
"""Get bank connection status"""
|
||||||
response = self._make_request("GET", "/api/v1/banks/status")
|
response = self._make_request("GET", "/banks/status")
|
||||||
return response.get("data", [])
|
return response.get("data", [])
|
||||||
|
|
||||||
def get_supported_countries(self) -> List[Dict[str, Any]]:
|
def get_supported_countries(self) -> List[Dict[str, Any]]:
|
||||||
"""Get supported countries"""
|
"""Get supported countries"""
|
||||||
response = self._make_request("GET", "/api/v1/banks/countries")
|
response = self._make_request("GET", "/banks/countries")
|
||||||
return response.get("data", [])
|
return response.get("data", [])
|
||||||
|
|
||||||
# Account endpoints
|
# Account endpoints
|
||||||
def get_accounts(self) -> List[Dict[str, Any]]:
|
def get_accounts(self) -> List[Dict[str, Any]]:
|
||||||
"""Get all accounts"""
|
"""Get all accounts"""
|
||||||
response = self._make_request("GET", "/api/v1/accounts")
|
response = self._make_request("GET", "/accounts")
|
||||||
return response.get("data", [])
|
return response.get("data", [])
|
||||||
|
|
||||||
def get_account_details(self, account_id: str) -> Dict[str, Any]:
|
def get_account_details(self, account_id: str) -> Dict[str, Any]:
|
||||||
"""Get account details"""
|
"""Get account details"""
|
||||||
response = self._make_request("GET", f"/api/v1/accounts/{account_id}")
|
response = self._make_request("GET", f"/accounts/{account_id}")
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|
||||||
def get_account_balances(self, account_id: str) -> List[Dict[str, Any]]:
|
def get_account_balances(self, account_id: str) -> List[Dict[str, Any]]:
|
||||||
"""Get account balances"""
|
"""Get account balances"""
|
||||||
response = self._make_request("GET", f"/api/v1/accounts/{account_id}/balances")
|
response = self._make_request("GET", f"/accounts/{account_id}/balances")
|
||||||
return response.get("data", [])
|
return response.get("data", [])
|
||||||
|
|
||||||
def get_account_transactions(
|
def get_account_transactions(
|
||||||
@@ -107,7 +127,7 @@ class LeggenAPIClient:
|
|||||||
"""Get account transactions"""
|
"""Get account transactions"""
|
||||||
response = self._make_request(
|
response = self._make_request(
|
||||||
"GET",
|
"GET",
|
||||||
f"/api/v1/accounts/{account_id}/transactions",
|
f"/accounts/{account_id}/transactions",
|
||||||
params={"limit": limit, "summary_only": summary_only},
|
params={"limit": limit, "summary_only": summary_only},
|
||||||
)
|
)
|
||||||
return response.get("data", [])
|
return response.get("data", [])
|
||||||
@@ -120,7 +140,7 @@ class LeggenAPIClient:
|
|||||||
params = {"limit": limit, "summary_only": summary_only}
|
params = {"limit": limit, "summary_only": summary_only}
|
||||||
params.update(filters)
|
params.update(filters)
|
||||||
|
|
||||||
response = self._make_request("GET", "/api/v1/transactions", params=params)
|
response = self._make_request("GET", "/transactions", params=params)
|
||||||
return response.get("data", [])
|
return response.get("data", [])
|
||||||
|
|
||||||
def get_transaction_stats(
|
def get_transaction_stats(
|
||||||
@@ -131,15 +151,13 @@ class LeggenAPIClient:
|
|||||||
if account_id:
|
if account_id:
|
||||||
params["account_id"] = account_id
|
params["account_id"] = account_id
|
||||||
|
|
||||||
response = self._make_request(
|
response = self._make_request("GET", "/transactions/stats", params=params)
|
||||||
"GET", "/api/v1/transactions/stats", params=params
|
|
||||||
)
|
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|
||||||
# Sync endpoints
|
# Sync endpoints
|
||||||
def get_sync_status(self) -> Dict[str, Any]:
|
def get_sync_status(self) -> Dict[str, Any]:
|
||||||
"""Get sync status"""
|
"""Get sync status"""
|
||||||
response = self._make_request("GET", "/api/v1/sync/status")
|
response = self._make_request("GET", "/sync/status")
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|
||||||
def trigger_sync(
|
def trigger_sync(
|
||||||
@@ -150,7 +168,7 @@ class LeggenAPIClient:
|
|||||||
if account_ids:
|
if account_ids:
|
||||||
data["account_ids"] = account_ids
|
data["account_ids"] = account_ids
|
||||||
|
|
||||||
response = self._make_request("POST", "/api/v1/sync", json=data)
|
response = self._make_request("POST", "/sync", json=data)
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|
||||||
def sync_now(
|
def sync_now(
|
||||||
@@ -161,12 +179,12 @@ class LeggenAPIClient:
|
|||||||
if account_ids:
|
if account_ids:
|
||||||
data["account_ids"] = account_ids
|
data["account_ids"] = account_ids
|
||||||
|
|
||||||
response = self._make_request("POST", "/api/v1/sync/now", json=data)
|
response = self._make_request("POST", "/sync/now", json=data)
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|
||||||
def get_scheduler_config(self) -> Dict[str, Any]:
|
def get_scheduler_config(self) -> Dict[str, Any]:
|
||||||
"""Get scheduler configuration"""
|
"""Get scheduler configuration"""
|
||||||
response = self._make_request("GET", "/api/v1/sync/scheduler")
|
response = self._make_request("GET", "/sync/scheduler")
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|
||||||
def update_scheduler_config(
|
def update_scheduler_config(
|
||||||
@@ -185,5 +203,5 @@ class LeggenAPIClient:
|
|||||||
if cron:
|
if cron:
|
||||||
data["cron"] = cron
|
data["cron"] = cron
|
||||||
|
|
||||||
response = self._make_request("PUT", "/api/v1/sync/scheduler", json=data)
|
response = self._make_request("PUT", "/sync/scheduler", json=data)
|
||||||
return response.get("data", {})
|
return response.get("data", {})
|
||||||
|
|||||||
@@ -102,17 +102,19 @@ class BackgroundScheduler:
|
|||||||
async def _run_sync(self, retry_count: int = 0):
|
async def _run_sync(self, retry_count: int = 0):
|
||||||
"""Run sync with enhanced error handling and retry logic"""
|
"""Run sync with enhanced error handling and retry logic"""
|
||||||
try:
|
try:
|
||||||
logger.info("Starting scheduled sync job")
|
trigger_type = "retry" if retry_count > 0 else "scheduled"
|
||||||
await self.sync_service.sync_all_accounts()
|
logger.info(f"Starting {trigger_type} sync job")
|
||||||
logger.info("Scheduled sync job completed successfully")
|
await self.sync_service.sync_all_accounts(trigger_type=trigger_type)
|
||||||
|
logger.info(f"{trigger_type.capitalize()} sync job completed successfully")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
trigger_type = "retry" if retry_count > 0 else "scheduled"
|
||||||
logger.error(
|
logger.error(
|
||||||
f"Scheduled sync job failed (attempt {retry_count + 1}/{self.max_retries}): {e}"
|
f"{trigger_type.capitalize()} sync job failed (attempt {retry_count + 1}/{self.max_retries}): {e}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Send notification about the failure
|
# Send notification about the failure
|
||||||
try:
|
try:
|
||||||
await self.notification_service.send_expiry_notification(
|
await self.notification_service.send_sync_failure_notification(
|
||||||
{
|
{
|
||||||
"type": "sync_failure",
|
"type": "sync_failure",
|
||||||
"error": str(e),
|
"error": str(e),
|
||||||
@@ -145,7 +147,7 @@ class BackgroundScheduler:
|
|||||||
logger.error("Maximum retries exceeded for sync job")
|
logger.error("Maximum retries exceeded for sync job")
|
||||||
# Send final failure notification
|
# Send final failure notification
|
||||||
try:
|
try:
|
||||||
await self.notification_service.send_expiry_notification(
|
await self.notification_service.send_sync_failure_notification(
|
||||||
{
|
{
|
||||||
"type": "sync_final_failure",
|
"type": "sync_final_failure",
|
||||||
"error": str(e),
|
"error": str(e),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import click
|
import click
|
||||||
|
|
||||||
|
from leggen.api_client import LeggenAPIClient
|
||||||
from leggen.main import cli
|
from leggen.main import cli
|
||||||
from leggen.utils.text import info, success
|
from leggen.utils.text import info, success
|
||||||
|
|
||||||
@@ -15,12 +16,11 @@ def delete(ctx, requisition_id: str):
|
|||||||
|
|
||||||
Check `leggen status` to get the REQUISITION_ID
|
Check `leggen status` to get the REQUISITION_ID
|
||||||
"""
|
"""
|
||||||
import requests
|
api_client = LeggenAPIClient(ctx.obj.get("api_url"))
|
||||||
|
|
||||||
info(f"Deleting Bank Requisition: {requisition_id}")
|
info(f"Deleting Bank Requisition: {requisition_id}")
|
||||||
|
|
||||||
api_url = ctx.obj.get("api_url", "http://localhost:8000")
|
# Use API client to make the delete request
|
||||||
res = requests.delete(f"{api_url}/requisitions/{requisition_id}")
|
api_client._make_request("DELETE", f"/requisitions/{requisition_id}")
|
||||||
res.raise_for_status()
|
|
||||||
|
|
||||||
success(f"Bank Requisition {requisition_id} deleted")
|
success(f"Bank Requisition {requisition_id} deleted")
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from fastapi import FastAPI
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
|
||||||
from leggen.api.routes import accounts, banks, notifications, sync, transactions
|
from leggen.api.routes import accounts, backup, banks, notifications, sync, transactions
|
||||||
from leggen.background.scheduler import scheduler
|
from leggen.background.scheduler import scheduler
|
||||||
from leggen.utils.config import config
|
from leggen.utils.config import config
|
||||||
from leggen.utils.paths import path_manager
|
from leggen.utils.paths import path_manager
|
||||||
@@ -60,6 +60,8 @@ def create_app() -> FastAPI:
|
|||||||
description="Open Banking API for Leggen",
|
description="Open Banking API for Leggen",
|
||||||
version=version,
|
version=version,
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
|
docs_url="/api/v1/docs",
|
||||||
|
openapi_url="/api/v1/openapi.json",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Add CORS middleware
|
# Add CORS middleware
|
||||||
@@ -81,15 +83,7 @@ def create_app() -> FastAPI:
|
|||||||
app.include_router(transactions.router, prefix="/api/v1", tags=["transactions"])
|
app.include_router(transactions.router, prefix="/api/v1", tags=["transactions"])
|
||||||
app.include_router(sync.router, prefix="/api/v1", tags=["sync"])
|
app.include_router(sync.router, prefix="/api/v1", tags=["sync"])
|
||||||
app.include_router(notifications.router, prefix="/api/v1", tags=["notifications"])
|
app.include_router(notifications.router, prefix="/api/v1", tags=["notifications"])
|
||||||
|
app.include_router(backup.router, prefix="/api/v1", tags=["backup"])
|
||||||
@app.get("/")
|
|
||||||
async def root():
|
|
||||||
# Get version dynamically
|
|
||||||
try:
|
|
||||||
version = metadata.version("leggen")
|
|
||||||
except metadata.PackageNotFoundError:
|
|
||||||
version = "unknown"
|
|
||||||
return {"message": "Leggen API is running", "version": version}
|
|
||||||
|
|
||||||
@app.get("/api/v1/health")
|
@app.get("/api/v1/health")
|
||||||
async def health():
|
async def health():
|
||||||
@@ -99,11 +93,18 @@ def create_app() -> FastAPI:
|
|||||||
|
|
||||||
config_loaded = config._config is not None
|
config_loaded = config._config is not None
|
||||||
|
|
||||||
|
# Get version dynamically
|
||||||
|
try:
|
||||||
|
version = metadata.version("leggen")
|
||||||
|
except metadata.PackageNotFoundError:
|
||||||
|
version = "dev"
|
||||||
|
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
success=True,
|
success=True,
|
||||||
data={
|
data={
|
||||||
"status": "healthy",
|
"status": "healthy",
|
||||||
"config_loaded": config_loaded,
|
"config_loaded": config_loaded,
|
||||||
|
"version": version,
|
||||||
"message": "API is running and responsive",
|
"message": "API is running and responsive",
|
||||||
},
|
},
|
||||||
message="Health check successful",
|
message="Health check successful",
|
||||||
|
|||||||
@@ -32,6 +32,22 @@ class NotificationConfig(BaseModel):
|
|||||||
telegram: Optional[TelegramNotificationConfig] = None
|
telegram: Optional[TelegramNotificationConfig] = None
|
||||||
|
|
||||||
|
|
||||||
|
class S3BackupConfig(BaseModel):
|
||||||
|
access_key_id: str = Field(..., description="AWS S3 access key ID")
|
||||||
|
secret_access_key: str = Field(..., description="AWS S3 secret access key")
|
||||||
|
bucket_name: str = Field(..., description="S3 bucket name")
|
||||||
|
region: str = Field(default="us-east-1", description="AWS S3 region")
|
||||||
|
endpoint_url: Optional[str] = Field(
|
||||||
|
default=None, description="Custom S3 endpoint URL"
|
||||||
|
)
|
||||||
|
path_style: bool = Field(default=False, description="Use path-style addressing")
|
||||||
|
enabled: bool = Field(default=True, description="Enable S3 backups")
|
||||||
|
|
||||||
|
|
||||||
|
class BackupConfig(BaseModel):
|
||||||
|
s3: Optional[S3BackupConfig] = None
|
||||||
|
|
||||||
|
|
||||||
class FilterConfig(BaseModel):
|
class FilterConfig(BaseModel):
|
||||||
case_insensitive: Optional[List[str]] = Field(default_factory=list)
|
case_insensitive: Optional[List[str]] = Field(default_factory=list)
|
||||||
case_sensitive: Optional[List[str]] = Field(default_factory=list)
|
case_sensitive: Optional[List[str]] = Field(default_factory=list)
|
||||||
@@ -56,3 +72,4 @@ class Config(BaseModel):
|
|||||||
notifications: Optional[NotificationConfig] = None
|
notifications: Optional[NotificationConfig] = None
|
||||||
filters: Optional[FilterConfig] = None
|
filters: Optional[FilterConfig] = None
|
||||||
scheduler: SchedulerConfig = Field(default_factory=SchedulerConfig)
|
scheduler: SchedulerConfig = Field(default_factory=SchedulerConfig)
|
||||||
|
backup: Optional[BackupConfig] = None
|
||||||
|
|||||||
@@ -55,3 +55,44 @@ def send_transactions_message(ctx: click.Context, transactions: list):
|
|||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise Exception(f"Discord notification failed: {e}\n{response.text}") from e
|
raise Exception(f"Discord notification failed: {e}\n{response.text}") from e
|
||||||
|
|
||||||
|
|
||||||
|
def send_sync_failure_notification(ctx: click.Context, notification: dict):
|
||||||
|
info("Sending sync failure notification to Discord")
|
||||||
|
webhook = DiscordWebhook(url=ctx.obj["notifications"]["discord"]["webhook"])
|
||||||
|
|
||||||
|
# Determine color and title based on failure type
|
||||||
|
if notification.get("type") == "sync_final_failure":
|
||||||
|
color = "ff0000" # Red for final failure
|
||||||
|
title = "🚨 Sync Final Failure"
|
||||||
|
description = (
|
||||||
|
f"Sync failed permanently after {notification['retry_count']} attempts"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
color = "ffaa00" # Orange for retry
|
||||||
|
title = "⚠️ Sync Failure"
|
||||||
|
description = f"Sync failed (attempt {notification['retry_count']}/{notification['max_retries']}). Will retry automatically..."
|
||||||
|
|
||||||
|
embed = DiscordEmbed(
|
||||||
|
title=title,
|
||||||
|
description=description,
|
||||||
|
color=color,
|
||||||
|
)
|
||||||
|
embed.set_author(
|
||||||
|
name="Leggen",
|
||||||
|
url="https://github.com/elisiariocouto/leggen",
|
||||||
|
)
|
||||||
|
embed.add_embed_field(
|
||||||
|
name="Error",
|
||||||
|
value=notification["error"][:1024], # Discord has field value limits
|
||||||
|
inline=False,
|
||||||
|
)
|
||||||
|
embed.set_footer(text="Sync failure notification")
|
||||||
|
embed.set_timestamp()
|
||||||
|
|
||||||
|
webhook.add_embed(embed)
|
||||||
|
response = webhook.execute()
|
||||||
|
try:
|
||||||
|
response.raise_for_status()
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Discord notification failed: {e}\n{response.text}") from e
|
||||||
|
|||||||
@@ -79,3 +79,38 @@ def send_transaction_message(ctx: click.Context, transactions: list):
|
|||||||
res.raise_for_status()
|
res.raise_for_status()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise Exception(f"Telegram notification failed: {e}\n{res.text}") from e
|
raise Exception(f"Telegram notification failed: {e}\n{res.text}") from e
|
||||||
|
|
||||||
|
|
||||||
|
def send_sync_failure_notification(ctx: click.Context, notification: dict):
|
||||||
|
token = ctx.obj["notifications"]["telegram"]["token"]
|
||||||
|
chat_id = ctx.obj["notifications"]["telegram"]["chat_id"]
|
||||||
|
bot_url = f"https://api.telegram.org/bot{token}/sendMessage"
|
||||||
|
info("Sending sync failure notification to Telegram")
|
||||||
|
|
||||||
|
message = "*🚨 [Leggen](https://github.com/elisiariocouto/leggen)*\n"
|
||||||
|
message += "*Sync Failed*\n\n"
|
||||||
|
message += escape_markdown(f"Error: {notification['error']}\n")
|
||||||
|
|
||||||
|
if notification.get("type") == "sync_final_failure":
|
||||||
|
message += escape_markdown(
|
||||||
|
f"❌ Final failure after {notification['retry_count']} attempts\n"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
message += escape_markdown(
|
||||||
|
f"🔄 Attempt {notification['retry_count']}/{notification['max_retries']}\n"
|
||||||
|
)
|
||||||
|
message += escape_markdown("Will retry automatically...\n")
|
||||||
|
|
||||||
|
res = requests.post(
|
||||||
|
bot_url,
|
||||||
|
json={
|
||||||
|
"chat_id": chat_id,
|
||||||
|
"text": message,
|
||||||
|
"parse_mode": "MarkdownV2",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
res.raise_for_status()
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Telegram notification failed: {e}\n{res.text}") from e
|
||||||
|
|||||||
192
leggen/services/backup_service.py
Normal file
192
leggen/services/backup_service.py
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
"""Backup service for S3 storage."""
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.exceptions import ClientError, NoCredentialsError
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from leggen.models.config import S3BackupConfig
|
||||||
|
|
||||||
|
|
||||||
|
class BackupService:
|
||||||
|
"""Service for managing S3 backups."""
|
||||||
|
|
||||||
|
def __init__(self, s3_config: Optional[S3BackupConfig] = None):
|
||||||
|
"""Initialize backup service with S3 configuration."""
|
||||||
|
self.s3_config = s3_config
|
||||||
|
self._s3_client = None
|
||||||
|
|
||||||
|
def _get_s3_client(self, config: Optional[S3BackupConfig] = None):
|
||||||
|
"""Get or create S3 client with current configuration."""
|
||||||
|
current_config = config or self.s3_config
|
||||||
|
if not current_config:
|
||||||
|
raise ValueError("S3 configuration is required")
|
||||||
|
|
||||||
|
# Create S3 client with configuration
|
||||||
|
session = boto3.Session(
|
||||||
|
aws_access_key_id=current_config.access_key_id,
|
||||||
|
aws_secret_access_key=current_config.secret_access_key,
|
||||||
|
region_name=current_config.region,
|
||||||
|
)
|
||||||
|
|
||||||
|
s3_kwargs = {}
|
||||||
|
if current_config.endpoint_url:
|
||||||
|
s3_kwargs["endpoint_url"] = current_config.endpoint_url
|
||||||
|
|
||||||
|
if current_config.path_style:
|
||||||
|
from botocore.config import Config
|
||||||
|
|
||||||
|
s3_kwargs["config"] = Config(s3={"addressing_style": "path"})
|
||||||
|
|
||||||
|
return session.client("s3", **s3_kwargs)
|
||||||
|
|
||||||
|
async def test_connection(self, config: S3BackupConfig) -> bool:
|
||||||
|
"""Test S3 connection with provided configuration.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config: S3 configuration to test
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if connection successful, False otherwise
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
s3_client = self._get_s3_client(config)
|
||||||
|
|
||||||
|
# Try to list objects in the bucket (limited to 1 to minimize cost)
|
||||||
|
s3_client.list_objects_v2(Bucket=config.bucket_name, MaxKeys=1)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"S3 connection test successful for bucket: {config.bucket_name}"
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
|
||||||
|
except NoCredentialsError:
|
||||||
|
logger.error("S3 credentials not found or invalid")
|
||||||
|
return False
|
||||||
|
except ClientError as e:
|
||||||
|
error_code = e.response["Error"]["Code"]
|
||||||
|
logger.error(
|
||||||
|
f"S3 connection test failed: {error_code} - {e.response['Error']['Message']}"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Unexpected error during S3 connection test: {str(e)}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def backup_database(self, database_path: Path) -> bool:
|
||||||
|
"""Backup database file to S3.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
database_path: Path to the SQLite database file
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if backup successful, False otherwise
|
||||||
|
"""
|
||||||
|
if not self.s3_config or not self.s3_config.enabled:
|
||||||
|
logger.warning("S3 backup is not configured or disabled")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not database_path.exists():
|
||||||
|
logger.error(f"Database file not found: {database_path}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
s3_client = self._get_s3_client()
|
||||||
|
|
||||||
|
# Generate backup filename with timestamp
|
||||||
|
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
backup_key = f"leggen_backups/database_backup_{timestamp}.db"
|
||||||
|
|
||||||
|
# Upload database file
|
||||||
|
logger.info(f"Starting database backup to S3: {backup_key}")
|
||||||
|
s3_client.upload_file(
|
||||||
|
str(database_path), self.s3_config.bucket_name, backup_key
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(f"Database backup completed successfully: {backup_key}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Database backup failed: {str(e)}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def list_backups(self) -> list[dict]:
|
||||||
|
"""List available backups in S3.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of backup metadata dictionaries
|
||||||
|
"""
|
||||||
|
if not self.s3_config or not self.s3_config.enabled:
|
||||||
|
logger.warning("S3 backup is not configured or disabled")
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
s3_client = self._get_s3_client()
|
||||||
|
|
||||||
|
# List objects with backup prefix
|
||||||
|
response = s3_client.list_objects_v2(
|
||||||
|
Bucket=self.s3_config.bucket_name, Prefix="leggen_backups/"
|
||||||
|
)
|
||||||
|
|
||||||
|
backups = []
|
||||||
|
for obj in response.get("Contents", []):
|
||||||
|
backups.append(
|
||||||
|
{
|
||||||
|
"key": obj["Key"],
|
||||||
|
"last_modified": obj["LastModified"].isoformat(),
|
||||||
|
"size": obj["Size"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Sort by last modified (newest first)
|
||||||
|
backups.sort(key=lambda x: x["last_modified"], reverse=True)
|
||||||
|
|
||||||
|
return backups
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to list backups: {str(e)}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
async def restore_database(self, backup_key: str, restore_path: Path) -> bool:
|
||||||
|
"""Restore database from S3 backup.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
backup_key: S3 key of the backup to restore
|
||||||
|
restore_path: Path where to restore the database
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if restore successful, False otherwise
|
||||||
|
"""
|
||||||
|
if not self.s3_config or not self.s3_config.enabled:
|
||||||
|
logger.warning("S3 backup is not configured or disabled")
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
s3_client = self._get_s3_client()
|
||||||
|
|
||||||
|
# Download backup file
|
||||||
|
logger.info(f"Starting database restore from S3: {backup_key}")
|
||||||
|
|
||||||
|
# Create parent directory if it doesn't exist
|
||||||
|
restore_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# Download to temporary file first, then move to final location
|
||||||
|
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||||
|
s3_client.download_file(
|
||||||
|
self.s3_config.bucket_name, backup_key, temp_file.name
|
||||||
|
)
|
||||||
|
|
||||||
|
# Move temp file to final location
|
||||||
|
temp_path = Path(temp_file.name)
|
||||||
|
temp_path.replace(restore_path)
|
||||||
|
|
||||||
|
logger.info(f"Database restore completed successfully: {restore_path}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Database restore failed: {str(e)}")
|
||||||
|
return False
|
||||||
@@ -216,6 +216,8 @@ class DatabaseService:
|
|||||||
await self._migrate_null_transaction_ids_if_needed()
|
await self._migrate_null_transaction_ids_if_needed()
|
||||||
await self._migrate_to_composite_key_if_needed()
|
await self._migrate_to_composite_key_if_needed()
|
||||||
await self._migrate_add_display_name_if_needed()
|
await self._migrate_add_display_name_if_needed()
|
||||||
|
await self._migrate_add_sync_operations_if_needed()
|
||||||
|
await self._migrate_add_logo_if_needed()
|
||||||
|
|
||||||
async def _migrate_balance_timestamps_if_needed(self):
|
async def _migrate_balance_timestamps_if_needed(self):
|
||||||
"""Check and migrate balance timestamps if needed"""
|
"""Check and migrate balance timestamps if needed"""
|
||||||
@@ -693,7 +695,7 @@ class DatabaseService:
|
|||||||
|
|
||||||
# Add the display_name column
|
# Add the display_name column
|
||||||
cursor.execute("""
|
cursor.execute("""
|
||||||
ALTER TABLE accounts
|
ALTER TABLE accounts
|
||||||
ADD COLUMN display_name TEXT
|
ADD COLUMN display_name TEXT
|
||||||
""")
|
""")
|
||||||
|
|
||||||
@@ -857,6 +859,14 @@ class DatabaseService:
|
|||||||
|
|
||||||
for transaction in transactions:
|
for transaction in transactions:
|
||||||
try:
|
try:
|
||||||
|
# Check if transaction already exists before insertion
|
||||||
|
cursor.execute(
|
||||||
|
"""SELECT COUNT(*) FROM transactions
|
||||||
|
WHERE accountId = ? AND transactionId = ?""",
|
||||||
|
(transaction["accountId"], transaction["transactionId"]),
|
||||||
|
)
|
||||||
|
exists = cursor.fetchone()[0] > 0
|
||||||
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
insert_sql,
|
insert_sql,
|
||||||
(
|
(
|
||||||
@@ -873,7 +883,11 @@ class DatabaseService:
|
|||||||
json.dumps(transaction["rawTransaction"]),
|
json.dumps(transaction["rawTransaction"]),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
new_transactions.append(transaction)
|
|
||||||
|
# Only add to new_transactions if it didn't exist before
|
||||||
|
if not exists:
|
||||||
|
new_transactions.append(transaction)
|
||||||
|
|
||||||
except sqlite3.IntegrityError as e:
|
except sqlite3.IntegrityError as e:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Failed to insert transaction {transaction.get('transactionId')}: {e}"
|
f"Failed to insert transaction {transaction.get('transactionId')}: {e}"
|
||||||
@@ -1120,7 +1134,8 @@ class DatabaseService:
|
|||||||
created DATETIME,
|
created DATETIME,
|
||||||
last_accessed DATETIME,
|
last_accessed DATETIME,
|
||||||
last_updated DATETIME,
|
last_updated DATETIME,
|
||||||
display_name TEXT
|
display_name TEXT,
|
||||||
|
logo TEXT
|
||||||
)"""
|
)"""
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1157,8 +1172,9 @@ class DatabaseService:
|
|||||||
created,
|
created,
|
||||||
last_accessed,
|
last_accessed,
|
||||||
last_updated,
|
last_updated,
|
||||||
display_name
|
display_name,
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
logo
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||||
(
|
(
|
||||||
account_data["id"],
|
account_data["id"],
|
||||||
account_data["institution_id"],
|
account_data["institution_id"],
|
||||||
@@ -1170,6 +1186,7 @@ class DatabaseService:
|
|||||||
account_data.get("last_accessed"),
|
account_data.get("last_accessed"),
|
||||||
account_data.get("last_updated", account_data["created"]),
|
account_data.get("last_updated", account_data["created"]),
|
||||||
display_name,
|
display_name,
|
||||||
|
account_data.get("logo"),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
@@ -1415,3 +1432,265 @@ class DatabaseService:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
conn.close()
|
conn.close()
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
async def _check_sync_operations_migration_needed(self) -> bool:
|
||||||
|
"""Check if sync_operations table needs to be created"""
|
||||||
|
db_path = path_manager.get_database_path()
|
||||||
|
if not db_path.exists():
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# Check if sync_operations table exists
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='table' AND name='sync_operations'"
|
||||||
|
)
|
||||||
|
table_exists = cursor.fetchone() is not None
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
return not table_exists
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to check sync_operations migration status: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _migrate_add_sync_operations(self):
|
||||||
|
"""Add sync_operations table"""
|
||||||
|
db_path = path_manager.get_database_path()
|
||||||
|
if not db_path.exists():
|
||||||
|
logger.warning("Database file not found, skipping migration")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
logger.info("Creating sync_operations table...")
|
||||||
|
|
||||||
|
# Create the sync_operations table
|
||||||
|
cursor.execute("""
|
||||||
|
CREATE TABLE sync_operations (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
started_at DATETIME NOT NULL,
|
||||||
|
completed_at DATETIME,
|
||||||
|
success BOOLEAN,
|
||||||
|
accounts_processed INTEGER DEFAULT 0,
|
||||||
|
transactions_added INTEGER DEFAULT 0,
|
||||||
|
transactions_updated INTEGER DEFAULT 0,
|
||||||
|
balances_updated INTEGER DEFAULT 0,
|
||||||
|
duration_seconds REAL,
|
||||||
|
errors TEXT,
|
||||||
|
logs TEXT,
|
||||||
|
trigger_type TEXT DEFAULT 'manual'
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
# Create indexes for better performance
|
||||||
|
cursor.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_sync_operations_started_at ON sync_operations(started_at)"
|
||||||
|
)
|
||||||
|
cursor.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_sync_operations_success ON sync_operations(success)"
|
||||||
|
)
|
||||||
|
cursor.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_sync_operations_trigger_type ON sync_operations(trigger_type)"
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
logger.info("Sync operations table migration completed successfully")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Sync operations table migration failed: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def _migrate_add_sync_operations_if_needed(self):
|
||||||
|
"""Check and add sync_operations table if needed"""
|
||||||
|
try:
|
||||||
|
if await self._check_sync_operations_migration_needed():
|
||||||
|
logger.info("Sync operations table migration needed, starting...")
|
||||||
|
await self._migrate_add_sync_operations()
|
||||||
|
logger.info("Sync operations table migration completed")
|
||||||
|
else:
|
||||||
|
logger.info("Sync operations table already exists")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Sync operations table migration failed: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def _migrate_add_logo_if_needed(self):
|
||||||
|
"""Check and add logo column to accounts table if needed"""
|
||||||
|
try:
|
||||||
|
if await self._check_logo_migration_needed():
|
||||||
|
logger.info("Logo column migration needed, starting...")
|
||||||
|
await self._migrate_add_logo()
|
||||||
|
logger.info("Logo column migration completed")
|
||||||
|
else:
|
||||||
|
logger.info("Logo column already exists")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Logo column migration failed: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def _check_logo_migration_needed(self) -> bool:
|
||||||
|
"""Check if logo column needs to be added to accounts table"""
|
||||||
|
db_path = path_manager.get_database_path()
|
||||||
|
if not db_path.exists():
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# Check if accounts table exists
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='table' AND name='accounts'"
|
||||||
|
)
|
||||||
|
if not cursor.fetchone():
|
||||||
|
conn.close()
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Check if logo column exists
|
||||||
|
cursor.execute("PRAGMA table_info(accounts)")
|
||||||
|
columns = cursor.fetchall()
|
||||||
|
|
||||||
|
# Check if logo column exists
|
||||||
|
has_logo = any(col[1] == "logo" for col in columns)
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
return not has_logo
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to check logo migration status: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _migrate_add_logo(self):
|
||||||
|
"""Add logo column to accounts table"""
|
||||||
|
db_path = path_manager.get_database_path()
|
||||||
|
if not db_path.exists():
|
||||||
|
logger.warning("Database file not found, skipping migration")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
logger.info("Adding logo column to accounts table...")
|
||||||
|
|
||||||
|
# Add the logo column
|
||||||
|
cursor.execute("""
|
||||||
|
ALTER TABLE accounts
|
||||||
|
ADD COLUMN logo TEXT
|
||||||
|
""")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
logger.info("Logo column migration completed successfully")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Logo column migration failed: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def persist_sync_operation(self, sync_operation: Dict[str, Any]) -> int:
|
||||||
|
"""Persist sync operation to database and return the ID"""
|
||||||
|
if not self.sqlite_enabled:
|
||||||
|
logger.warning("SQLite database disabled, cannot persist sync operation")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
db_path = path_manager.get_database_path()
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# Insert sync operation
|
||||||
|
cursor.execute(
|
||||||
|
"""INSERT INTO sync_operations (
|
||||||
|
started_at, completed_at, success, accounts_processed,
|
||||||
|
transactions_added, transactions_updated, balances_updated,
|
||||||
|
duration_seconds, errors, logs, trigger_type
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||||
|
(
|
||||||
|
sync_operation.get("started_at"),
|
||||||
|
sync_operation.get("completed_at"),
|
||||||
|
sync_operation.get("success"),
|
||||||
|
sync_operation.get("accounts_processed", 0),
|
||||||
|
sync_operation.get("transactions_added", 0),
|
||||||
|
sync_operation.get("transactions_updated", 0),
|
||||||
|
sync_operation.get("balances_updated", 0),
|
||||||
|
sync_operation.get("duration_seconds"),
|
||||||
|
json.dumps(sync_operation.get("errors", [])),
|
||||||
|
json.dumps(sync_operation.get("logs", [])),
|
||||||
|
sync_operation.get("trigger_type", "manual"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
operation_id = cursor.lastrowid
|
||||||
|
if operation_id is None:
|
||||||
|
raise ValueError("Failed to get operation ID after insert")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
logger.debug(f"Persisted sync operation with ID: {operation_id}")
|
||||||
|
return operation_id
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to persist sync operation: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def get_sync_operations(
|
||||||
|
self, limit: int = 50, offset: int = 0
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Get sync operations from database"""
|
||||||
|
if not self.sqlite_enabled:
|
||||||
|
logger.warning("SQLite database disabled, cannot get sync operations")
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
db_path = path_manager.get_database_path()
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
# Get sync operations ordered by started_at descending
|
||||||
|
cursor.execute(
|
||||||
|
"""SELECT id, started_at, completed_at, success, accounts_processed,
|
||||||
|
transactions_added, transactions_updated, balances_updated,
|
||||||
|
duration_seconds, errors, logs, trigger_type
|
||||||
|
FROM sync_operations
|
||||||
|
ORDER BY started_at DESC
|
||||||
|
LIMIT ? OFFSET ?""",
|
||||||
|
(limit, offset),
|
||||||
|
)
|
||||||
|
|
||||||
|
operations = []
|
||||||
|
for row in cursor.fetchall():
|
||||||
|
operation = {
|
||||||
|
"id": row[0],
|
||||||
|
"started_at": row[1],
|
||||||
|
"completed_at": row[2],
|
||||||
|
"success": bool(row[3]) if row[3] is not None else None,
|
||||||
|
"accounts_processed": row[4],
|
||||||
|
"transactions_added": row[5],
|
||||||
|
"transactions_updated": row[6],
|
||||||
|
"balances_updated": row[7],
|
||||||
|
"duration_seconds": row[8],
|
||||||
|
"errors": json.loads(row[9]) if row[9] else [],
|
||||||
|
"logs": json.loads(row[10]) if row[10] else [],
|
||||||
|
"trigger_type": row[11],
|
||||||
|
}
|
||||||
|
operations.append(operation)
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
return operations
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to get sync operations: {e}")
|
||||||
|
return []
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List
|
from typing import Any, Dict
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
@@ -9,17 +9,21 @@ from leggen.utils.config import config
|
|||||||
from leggen.utils.paths import path_manager
|
from leggen.utils.paths import path_manager
|
||||||
|
|
||||||
|
|
||||||
def _log_rate_limits(response):
|
def _log_rate_limits(response, method, url):
|
||||||
"""Log GoCardless API rate limit headers"""
|
"""Log GoCardless API rate limit headers"""
|
||||||
limit = response.headers.get("X-RateLimit-Limit")
|
limit = response.headers.get("http_x_ratelimit_limit")
|
||||||
remaining = response.headers.get("X-RateLimit-Remaining")
|
remaining = response.headers.get("http_x_ratelimit_remaining")
|
||||||
reset = response.headers.get("X-RateLimit-Reset")
|
reset = response.headers.get("http_x_ratelimit_reset")
|
||||||
account_success_reset = response.headers.get("X-RateLimit-Account-Success-Reset")
|
|
||||||
|
|
||||||
if limit or remaining or reset or account_success_reset:
|
account_limit = response.headers.get("http_x_ratelimit_account_success_limit")
|
||||||
logger.info(
|
account_remaining = response.headers.get(
|
||||||
f"GoCardless rate limits - Limit: {limit}, Remaining: {remaining}, Reset: {reset}s, Account Success Reset: {account_success_reset}"
|
"http_x_ratelimit_account_success_remaining"
|
||||||
)
|
)
|
||||||
|
account_reset = response.headers.get("http_x_ratelimit_account_success_reset")
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
f"{method} {url} Limit/Remaining/Reset (Global: {limit}/{remaining}/{reset}s) (Account: {account_limit}/{account_remaining}/{account_reset}s)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class GoCardlessService:
|
class GoCardlessService:
|
||||||
@@ -30,6 +34,31 @@ class GoCardlessService:
|
|||||||
)
|
)
|
||||||
self._token = None
|
self._token = None
|
||||||
|
|
||||||
|
async def _make_authenticated_request(
|
||||||
|
self, method: str, url: str, **kwargs
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""Make authenticated request with automatic token refresh on 401"""
|
||||||
|
headers = await self._get_auth_headers()
|
||||||
|
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.request(
|
||||||
|
method, url, headers=headers, timeout=30, **kwargs
|
||||||
|
)
|
||||||
|
_log_rate_limits(response, method, url)
|
||||||
|
|
||||||
|
# If we get 401, clear token cache and retry once
|
||||||
|
if response.status_code == 401:
|
||||||
|
logger.warning("Got 401, clearing token cache and retrying")
|
||||||
|
self._token = None
|
||||||
|
headers = await self._get_auth_headers()
|
||||||
|
response = await client.request(
|
||||||
|
method, url, headers=headers, timeout=30, **kwargs
|
||||||
|
)
|
||||||
|
_log_rate_limits(response, method, url)
|
||||||
|
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
|
||||||
async def _get_auth_headers(self) -> Dict[str, str]:
|
async def _get_auth_headers(self) -> Dict[str, str]:
|
||||||
"""Get authentication headers for GoCardless API"""
|
"""Get authentication headers for GoCardless API"""
|
||||||
token = await self._get_token()
|
token = await self._get_token()
|
||||||
@@ -56,7 +85,9 @@ class GoCardlessService:
|
|||||||
f"{self.base_url}/token/refresh/",
|
f"{self.base_url}/token/refresh/",
|
||||||
json={"refresh": auth["refresh"]},
|
json={"refresh": auth["refresh"]},
|
||||||
)
|
)
|
||||||
_log_rate_limits(response)
|
_log_rate_limits(
|
||||||
|
response, "POST", f"{self.base_url}/token/refresh/"
|
||||||
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
auth.update(response.json())
|
auth.update(response.json())
|
||||||
self._save_auth(auth)
|
self._save_auth(auth)
|
||||||
@@ -84,7 +115,7 @@ class GoCardlessService:
|
|||||||
"secret_key": self.config["secret"],
|
"secret_key": self.config["secret"],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
_log_rate_limits(response)
|
_log_rate_limits(response, "POST", f"{self.base_url}/token/new/")
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
auth = response.json()
|
auth = response.json()
|
||||||
self._save_auth(auth)
|
self._save_auth(auth)
|
||||||
@@ -102,74 +133,54 @@ class GoCardlessService:
|
|||||||
with open(auth_file, "w") as f:
|
with open(auth_file, "w") as f:
|
||||||
json.dump(auth_data, f)
|
json.dump(auth_data, f)
|
||||||
|
|
||||||
async def get_institutions(self, country: str = "PT") -> List[Dict[str, Any]]:
|
async def get_institutions(self, country: str = "PT") -> Dict[str, Any]:
|
||||||
"""Get available bank institutions for a country"""
|
"""Get available bank institutions for a country"""
|
||||||
headers = await self._get_auth_headers()
|
return await self._make_authenticated_request(
|
||||||
async with httpx.AsyncClient() as client:
|
"GET", f"{self.base_url}/institutions/", params={"country": country}
|
||||||
response = await client.get(
|
)
|
||||||
f"{self.base_url}/institutions/",
|
|
||||||
headers=headers,
|
|
||||||
params={"country": country},
|
|
||||||
)
|
|
||||||
_log_rate_limits(response)
|
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
async def create_requisition(
|
async def create_requisition(
|
||||||
self, institution_id: str, redirect_url: str
|
self, institution_id: str, redirect_url: str
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create a bank connection requisition"""
|
"""Create a bank connection requisition"""
|
||||||
headers = await self._get_auth_headers()
|
return await self._make_authenticated_request(
|
||||||
async with httpx.AsyncClient() as client:
|
"POST",
|
||||||
response = await client.post(
|
f"{self.base_url}/requisitions/",
|
||||||
f"{self.base_url}/requisitions/",
|
json={"institution_id": institution_id, "redirect": redirect_url},
|
||||||
headers=headers,
|
)
|
||||||
json={"institution_id": institution_id, "redirect": redirect_url},
|
|
||||||
)
|
|
||||||
_log_rate_limits(response)
|
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
async def get_requisitions(self) -> Dict[str, Any]:
|
async def get_requisitions(self) -> Dict[str, Any]:
|
||||||
"""Get all requisitions"""
|
"""Get all requisitions"""
|
||||||
headers = await self._get_auth_headers()
|
return await self._make_authenticated_request(
|
||||||
async with httpx.AsyncClient() as client:
|
"GET", f"{self.base_url}/requisitions/"
|
||||||
response = await client.get(
|
)
|
||||||
f"{self.base_url}/requisitions/", headers=headers
|
|
||||||
)
|
async def delete_requisition(self, requisition_id: str) -> Dict[str, Any]:
|
||||||
_log_rate_limits(response)
|
"""Delete a requisition"""
|
||||||
response.raise_for_status()
|
return await self._make_authenticated_request(
|
||||||
return response.json()
|
"DELETE", f"{self.base_url}/requisitions/{requisition_id}/"
|
||||||
|
)
|
||||||
|
|
||||||
async def get_account_details(self, account_id: str) -> Dict[str, Any]:
|
async def get_account_details(self, account_id: str) -> Dict[str, Any]:
|
||||||
"""Get account details"""
|
"""Get account details"""
|
||||||
headers = await self._get_auth_headers()
|
return await self._make_authenticated_request(
|
||||||
async with httpx.AsyncClient() as client:
|
"GET", f"{self.base_url}/accounts/{account_id}/"
|
||||||
response = await client.get(
|
)
|
||||||
f"{self.base_url}/accounts/{account_id}/", headers=headers
|
|
||||||
)
|
|
||||||
_log_rate_limits(response)
|
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
async def get_account_balances(self, account_id: str) -> Dict[str, Any]:
|
async def get_account_balances(self, account_id: str) -> Dict[str, Any]:
|
||||||
"""Get account balances"""
|
"""Get account balances"""
|
||||||
headers = await self._get_auth_headers()
|
return await self._make_authenticated_request(
|
||||||
async with httpx.AsyncClient() as client:
|
"GET", f"{self.base_url}/accounts/{account_id}/balances/"
|
||||||
response = await client.get(
|
)
|
||||||
f"{self.base_url}/accounts/{account_id}/balances/", headers=headers
|
|
||||||
)
|
|
||||||
_log_rate_limits(response)
|
|
||||||
response.raise_for_status()
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
async def get_account_transactions(self, account_id: str) -> Dict[str, Any]:
|
async def get_account_transactions(self, account_id: str) -> Dict[str, Any]:
|
||||||
"""Get account transactions"""
|
"""Get account transactions"""
|
||||||
headers = await self._get_auth_headers()
|
return await self._make_authenticated_request(
|
||||||
async with httpx.AsyncClient() as client:
|
"GET", f"{self.base_url}/accounts/{account_id}/transactions/"
|
||||||
response = await client.get(
|
)
|
||||||
f"{self.base_url}/accounts/{account_id}/transactions/", headers=headers
|
|
||||||
)
|
async def get_institution_details(self, institution_id: str) -> Dict[str, Any]:
|
||||||
_log_rate_limits(response)
|
"""Get institution details by ID"""
|
||||||
response.raise_for_status()
|
return await self._make_authenticated_request(
|
||||||
return response.json()
|
"GET", f"{self.base_url}/institutions/{institution_id}/"
|
||||||
|
)
|
||||||
|
|||||||
@@ -289,3 +289,69 @@ class NotificationService:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to send Telegram expiry notification: {e}")
|
logger.error(f"Failed to send Telegram expiry notification: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
async def send_sync_failure_notification(
|
||||||
|
self, notification_data: Dict[str, Any]
|
||||||
|
) -> None:
|
||||||
|
"""Send notification about sync failure"""
|
||||||
|
if self._is_discord_enabled():
|
||||||
|
await self._send_discord_sync_failure(notification_data)
|
||||||
|
|
||||||
|
if self._is_telegram_enabled():
|
||||||
|
await self._send_telegram_sync_failure(notification_data)
|
||||||
|
|
||||||
|
async def _send_discord_sync_failure(
|
||||||
|
self, notification_data: Dict[str, Any]
|
||||||
|
) -> None:
|
||||||
|
"""Send Discord sync failure notification"""
|
||||||
|
try:
|
||||||
|
import click
|
||||||
|
|
||||||
|
from leggen.notifications.discord import send_sync_failure_notification
|
||||||
|
|
||||||
|
# Create a mock context with the webhook
|
||||||
|
ctx = click.Context(click.Command("sync_failure"))
|
||||||
|
ctx.obj = {
|
||||||
|
"notifications": {
|
||||||
|
"discord": {
|
||||||
|
"webhook": self.notifications_config.get("discord", {}).get(
|
||||||
|
"webhook"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Send sync failure notification using the actual implementation
|
||||||
|
send_sync_failure_notification(ctx, notification_data)
|
||||||
|
logger.info(f"Sent Discord sync failure notification: {notification_data}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to send Discord sync failure notification: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def _send_telegram_sync_failure(
|
||||||
|
self, notification_data: Dict[str, Any]
|
||||||
|
) -> None:
|
||||||
|
"""Send Telegram sync failure notification"""
|
||||||
|
try:
|
||||||
|
import click
|
||||||
|
|
||||||
|
from leggen.notifications.telegram import send_sync_failure_notification
|
||||||
|
|
||||||
|
# Create a mock context with the telegram config
|
||||||
|
ctx = click.Context(click.Command("sync_failure"))
|
||||||
|
telegram_config = self.notifications_config.get("telegram", {})
|
||||||
|
ctx.obj = {
|
||||||
|
"notifications": {
|
||||||
|
"telegram": {
|
||||||
|
"token": telegram_config.get("token"),
|
||||||
|
"chat_id": telegram_config.get("chat_id"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Send sync failure notification using the actual implementation
|
||||||
|
send_sync_failure_notification(ctx, notification_data)
|
||||||
|
logger.info(f"Sent Telegram sync failure notification: {notification_data}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to send Telegram sync failure notification: {e}")
|
||||||
|
raise
|
||||||
|
|||||||
@@ -15,12 +15,15 @@ class SyncService:
|
|||||||
self.database = DatabaseService()
|
self.database = DatabaseService()
|
||||||
self.notifications = NotificationService()
|
self.notifications = NotificationService()
|
||||||
self._sync_status = SyncStatus(is_running=False)
|
self._sync_status = SyncStatus(is_running=False)
|
||||||
|
self._institution_logos = {} # Cache for institution logos
|
||||||
|
|
||||||
async def get_sync_status(self) -> SyncStatus:
|
async def get_sync_status(self) -> SyncStatus:
|
||||||
"""Get current sync status"""
|
"""Get current sync status"""
|
||||||
return self._sync_status
|
return self._sync_status
|
||||||
|
|
||||||
async def sync_all_accounts(self, force: bool = False) -> SyncResult:
|
async def sync_all_accounts(
|
||||||
|
self, force: bool = False, trigger_type: str = "manual"
|
||||||
|
) -> SyncResult:
|
||||||
"""Sync all connected accounts"""
|
"""Sync all connected accounts"""
|
||||||
if self._sync_status.is_running and not force:
|
if self._sync_status.is_running and not force:
|
||||||
raise Exception("Sync is already running")
|
raise Exception("Sync is already running")
|
||||||
@@ -34,9 +37,25 @@ class SyncService:
|
|||||||
transactions_updated = 0
|
transactions_updated = 0
|
||||||
balances_updated = 0
|
balances_updated = 0
|
||||||
errors = []
|
errors = []
|
||||||
|
logs = [f"Sync started at {start_time.isoformat()}"]
|
||||||
|
|
||||||
|
# Initialize sync operation record
|
||||||
|
sync_operation = {
|
||||||
|
"started_at": start_time.isoformat(),
|
||||||
|
"trigger_type": trigger_type,
|
||||||
|
"accounts_processed": 0,
|
||||||
|
"transactions_added": 0,
|
||||||
|
"transactions_updated": 0,
|
||||||
|
"balances_updated": 0,
|
||||||
|
"errors": [],
|
||||||
|
"logs": logs,
|
||||||
|
}
|
||||||
|
|
||||||
|
operation_id = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.info("Starting sync of all accounts")
|
logger.info("Starting sync of all accounts")
|
||||||
|
logs.append("Starting sync of all accounts")
|
||||||
|
|
||||||
# Get all requisitions and accounts
|
# Get all requisitions and accounts
|
||||||
requisitions = await self.gocardless.get_requisitions()
|
requisitions = await self.gocardless.get_requisitions()
|
||||||
@@ -46,6 +65,7 @@ class SyncService:
|
|||||||
all_accounts.update(req.get("accounts", []))
|
all_accounts.update(req.get("accounts", []))
|
||||||
|
|
||||||
self._sync_status.total_accounts = len(all_accounts)
|
self._sync_status.total_accounts = len(all_accounts)
|
||||||
|
logs.append(f"Found {len(all_accounts)} accounts to sync")
|
||||||
|
|
||||||
# Process each account
|
# Process each account
|
||||||
for account_id in all_accounts:
|
for account_id in all_accounts:
|
||||||
@@ -58,7 +78,7 @@ class SyncService:
|
|||||||
# Get balances to extract currency information
|
# Get balances to extract currency information
|
||||||
balances = await self.gocardless.get_account_balances(account_id)
|
balances = await self.gocardless.get_account_balances(account_id)
|
||||||
|
|
||||||
# Enrich account details with currency and persist
|
# Enrich account details with currency and institution logo
|
||||||
if account_details and balances:
|
if account_details and balances:
|
||||||
enriched_account_details = account_details.copy()
|
enriched_account_details = account_details.copy()
|
||||||
|
|
||||||
@@ -71,6 +91,26 @@ class SyncService:
|
|||||||
if currency:
|
if currency:
|
||||||
enriched_account_details["currency"] = currency
|
enriched_account_details["currency"] = currency
|
||||||
|
|
||||||
|
# Get institution details to fetch logo
|
||||||
|
institution_id = enriched_account_details.get("institution_id")
|
||||||
|
if institution_id:
|
||||||
|
try:
|
||||||
|
institution_details = (
|
||||||
|
await self.gocardless.get_institution_details(
|
||||||
|
institution_id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
enriched_account_details["logo"] = (
|
||||||
|
institution_details.get("logo", "")
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f"Fetched logo for institution {institution_id}: {enriched_account_details.get('logo', 'No logo')}"
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(
|
||||||
|
f"Failed to fetch institution details for {institution_id}: {e}"
|
||||||
|
)
|
||||||
|
|
||||||
# Persist enriched account details to database
|
# Persist enriched account details to database
|
||||||
await self.database.persist_account_details(
|
await self.database.persist_account_details(
|
||||||
enriched_account_details
|
enriched_account_details
|
||||||
@@ -118,17 +158,43 @@ class SyncService:
|
|||||||
self._sync_status.accounts_synced = accounts_processed
|
self._sync_status.accounts_synced = accounts_processed
|
||||||
|
|
||||||
logger.info(f"Synced account {account_id} successfully")
|
logger.info(f"Synced account {account_id} successfully")
|
||||||
|
logs.append(f"Synced account {account_id} successfully")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_msg = f"Failed to sync account {account_id}: {str(e)}"
|
error_msg = f"Failed to sync account {account_id}: {str(e)}"
|
||||||
errors.append(error_msg)
|
errors.append(error_msg)
|
||||||
logger.error(error_msg)
|
logger.error(error_msg)
|
||||||
|
logs.append(error_msg)
|
||||||
|
|
||||||
end_time = datetime.now()
|
end_time = datetime.now()
|
||||||
duration = (end_time - start_time).total_seconds()
|
duration = (end_time - start_time).total_seconds()
|
||||||
|
|
||||||
self._sync_status.last_sync = end_time
|
self._sync_status.last_sync = end_time
|
||||||
|
|
||||||
|
# Update sync operation with final results
|
||||||
|
sync_operation.update(
|
||||||
|
{
|
||||||
|
"completed_at": end_time.isoformat(),
|
||||||
|
"success": len(errors) == 0,
|
||||||
|
"accounts_processed": accounts_processed,
|
||||||
|
"transactions_added": transactions_added,
|
||||||
|
"transactions_updated": transactions_updated,
|
||||||
|
"balances_updated": balances_updated,
|
||||||
|
"duration_seconds": duration,
|
||||||
|
"errors": errors,
|
||||||
|
"logs": logs,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Persist sync operation to database
|
||||||
|
try:
|
||||||
|
operation_id = await self.database.persist_sync_operation(
|
||||||
|
sync_operation
|
||||||
|
)
|
||||||
|
logger.debug(f"Saved sync operation with ID: {operation_id}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to persist sync operation: {e}")
|
||||||
|
|
||||||
result = SyncResult(
|
result = SyncResult(
|
||||||
success=len(errors) == 0,
|
success=len(errors) == 0,
|
||||||
accounts_processed=accounts_processed,
|
accounts_processed=accounts_processed,
|
||||||
@@ -144,44 +210,67 @@ class SyncService:
|
|||||||
logger.info(
|
logger.info(
|
||||||
f"Sync completed: {accounts_processed} accounts, {transactions_added} new transactions"
|
f"Sync completed: {accounts_processed} accounts, {transactions_added} new transactions"
|
||||||
)
|
)
|
||||||
|
logs.append(
|
||||||
|
f"Sync completed: {accounts_processed} accounts, {transactions_added} new transactions"
|
||||||
|
)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_msg = f"Sync failed: {str(e)}"
|
error_msg = f"Sync failed: {str(e)}"
|
||||||
errors.append(error_msg)
|
errors.append(error_msg)
|
||||||
|
logs.append(error_msg)
|
||||||
logger.error(error_msg)
|
logger.error(error_msg)
|
||||||
|
|
||||||
|
# Save failed sync operation
|
||||||
|
end_time = datetime.now()
|
||||||
|
duration = (end_time - start_time).total_seconds()
|
||||||
|
sync_operation.update(
|
||||||
|
{
|
||||||
|
"completed_at": end_time.isoformat(),
|
||||||
|
"success": False,
|
||||||
|
"accounts_processed": accounts_processed,
|
||||||
|
"transactions_added": transactions_added,
|
||||||
|
"transactions_updated": transactions_updated,
|
||||||
|
"balances_updated": balances_updated,
|
||||||
|
"duration_seconds": duration,
|
||||||
|
"errors": errors,
|
||||||
|
"logs": logs,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
operation_id = await self.database.persist_sync_operation(
|
||||||
|
sync_operation
|
||||||
|
)
|
||||||
|
logger.debug(f"Saved failed sync operation with ID: {operation_id}")
|
||||||
|
except Exception as persist_error:
|
||||||
|
logger.error(
|
||||||
|
f"Failed to persist failed sync operation: {persist_error}"
|
||||||
|
)
|
||||||
|
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
self._sync_status.is_running = False
|
self._sync_status.is_running = False
|
||||||
|
|
||||||
async def sync_specific_accounts(
|
async def sync_specific_accounts(
|
||||||
self, account_ids: List[str], force: bool = False
|
self, account_ids: List[str], force: bool = False, trigger_type: str = "manual"
|
||||||
) -> SyncResult:
|
) -> SyncResult:
|
||||||
"""Sync specific accounts"""
|
"""Sync specific accounts"""
|
||||||
if self._sync_status.is_running and not force:
|
if self._sync_status.is_running and not force:
|
||||||
raise Exception("Sync is already running")
|
raise Exception("Sync is already running")
|
||||||
|
|
||||||
# Similar implementation but only for specified accounts
|
|
||||||
# For brevity, implementing a simplified version
|
|
||||||
start_time = datetime.now()
|
|
||||||
self._sync_status.is_running = True
|
self._sync_status.is_running = True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Process only specified accounts
|
# For now, delegate to sync_all_accounts but with specific filtering
|
||||||
# Implementation would be similar to sync_all_accounts
|
# This could be optimized later to only process specified accounts
|
||||||
# but filtered to only the specified account_ids
|
result = await self.sync_all_accounts(
|
||||||
|
force=force, trigger_type=trigger_type
|
||||||
end_time = datetime.now()
|
|
||||||
return SyncResult(
|
|
||||||
success=True,
|
|
||||||
accounts_processed=len(account_ids),
|
|
||||||
transactions_added=0,
|
|
||||||
transactions_updated=0,
|
|
||||||
balances_updated=0,
|
|
||||||
duration_seconds=(end_time - start_time).total_seconds(),
|
|
||||||
errors=[],
|
|
||||||
started_at=start_time,
|
|
||||||
completed_at=end_time,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Filter results to only specified accounts if needed
|
||||||
|
# For simplicity, we'll return the full result for now
|
||||||
|
return result
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
self._sync_status.is_running = False
|
self._sync_status.is_running = False
|
||||||
|
|||||||
@@ -39,13 +39,11 @@ class Config:
|
|||||||
try:
|
try:
|
||||||
with open(config_path, "rb") as f:
|
with open(config_path, "rb") as f:
|
||||||
raw_config = tomllib.load(f)
|
raw_config = tomllib.load(f)
|
||||||
logger.info(f"Configuration loaded from {config_path}")
|
|
||||||
|
|
||||||
# Validate configuration using Pydantic
|
# Validate configuration using Pydantic
|
||||||
try:
|
try:
|
||||||
self._config_model = ConfigModel(**raw_config)
|
self._config_model = ConfigModel(**raw_config)
|
||||||
self._config = self._config_model.dict(by_alias=True, exclude_none=True)
|
self._config = self._config_model.dict(by_alias=True, exclude_none=True)
|
||||||
logger.info("Configuration validation successful")
|
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
logger.error(f"Configuration validation failed: {e}")
|
logger.error(f"Configuration validation failed: {e}")
|
||||||
raise ValueError(f"Invalid configuration: {e}") from e
|
raise ValueError(f"Invalid configuration: {e}") from e
|
||||||
@@ -164,6 +162,11 @@ class Config:
|
|||||||
}
|
}
|
||||||
return self.config.get("scheduler", default_schedule)
|
return self.config.get("scheduler", default_schedule)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def backup_config(self) -> Dict[str, Any]:
|
||||||
|
"""Get backup configuration"""
|
||||||
|
return self.config.get("backup", {})
|
||||||
|
|
||||||
|
|
||||||
def load_config(ctx: click.Context, _, filename):
|
def load_config(ctx: click.Context, _, filename):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "leggen"
|
name = "leggen"
|
||||||
version = "2025.9.16"
|
version = "2025.10.2"
|
||||||
description = "An Open Banking CLI"
|
description = "An Open Banking CLI"
|
||||||
authors = [{ name = "Elisiário Couto", email = "elisiario@couto.io" }]
|
authors = [{ name = "Elisiário Couto", email = "elisiario@couto.io" }]
|
||||||
requires-python = "~=3.13.0"
|
requires-python = "~=3.13.0"
|
||||||
@@ -35,6 +35,7 @@ dependencies = [
|
|||||||
"tomli-w>=1.0.0,<2",
|
"tomli-w>=1.0.0,<2",
|
||||||
"httpx>=0.28.1",
|
"httpx>=0.28.1",
|
||||||
"pydantic>=2.0.0,<3",
|
"pydantic>=2.0.0,<3",
|
||||||
|
"boto3>=1.35.0,<2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
@@ -88,5 +89,5 @@ markers = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[tool.mypy.overrides]]
|
[[tool.mypy.overrides]]
|
||||||
module = ["apscheduler.*", "discord_webhook.*"]
|
module = ["apscheduler.*", "discord_webhook.*", "botocore.*", "boto3.*"]
|
||||||
ignore_missing_imports = true
|
ignore_missing_imports = true
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ echo " > Version bumped to $NEXT_VERSION"
|
|||||||
echo "Updating CHANGELOG.md"
|
echo "Updating CHANGELOG.md"
|
||||||
git-cliff --unreleased --tag "$NEXT_VERSION" --prepend CHANGELOG.md > /dev/null
|
git-cliff --unreleased --tag "$NEXT_VERSION" --prepend CHANGELOG.md > /dev/null
|
||||||
|
|
||||||
|
echo "Locking dependencies"
|
||||||
|
uv lock
|
||||||
|
|
||||||
echo " > Commiting changes and adding git tag"
|
echo " > Commiting changes and adding git tag"
|
||||||
git add pyproject.toml CHANGELOG.md uv.lock
|
git add pyproject.toml CHANGELOG.md uv.lock
|
||||||
git commit -m "chore(ci): Bump version to $NEXT_VERSION"
|
git commit -m "chore(ci): Bump version to $NEXT_VERSION"
|
||||||
|
|||||||
@@ -103,22 +103,24 @@ def mock_db_path(temp_db_path):
|
|||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def sample_bank_data():
|
def sample_bank_data():
|
||||||
"""Sample bank/institution data for testing."""
|
"""Sample bank/institution data for testing."""
|
||||||
return [
|
return {
|
||||||
{
|
"results": [
|
||||||
"id": "REVOLUT_REVOLT21",
|
{
|
||||||
"name": "Revolut",
|
"id": "REVOLUT_REVOLT21",
|
||||||
"bic": "REVOLT21",
|
"name": "Revolut",
|
||||||
"transaction_total_days": 90,
|
"bic": "REVOLT21",
|
||||||
"countries": ["GB", "LT"],
|
"transaction_total_days": 90,
|
||||||
},
|
"countries": ["GB", "LT"],
|
||||||
{
|
},
|
||||||
"id": "BANCOBPI_BBPIPTPL",
|
{
|
||||||
"name": "Banco BPI",
|
"id": "BANCOBPI_BBPIPTPL",
|
||||||
"bic": "BBPIPTPL",
|
"name": "Banco BPI",
|
||||||
"transaction_total_days": 90,
|
"bic": "BBPIPTPL",
|
||||||
"countries": ["PT"],
|
"transaction_total_days": 90,
|
||||||
},
|
"countries": ["PT"],
|
||||||
]
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
|
|||||||
303
tests/unit/test_api_backup.py
Normal file
303
tests/unit/test_api_backup.py
Normal file
@@ -0,0 +1,303 @@
|
|||||||
|
"""Tests for backup API endpoints."""
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.api
|
||||||
|
class TestBackupAPI:
|
||||||
|
"""Test backup-related API endpoints."""
|
||||||
|
|
||||||
|
def test_get_backup_settings_no_config(self, api_client, mock_config):
|
||||||
|
"""Test getting backup settings with no configuration."""
|
||||||
|
# Mock empty backup config by updating the config dict
|
||||||
|
mock_config._config["backup"] = {}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.get("/api/v1/backup/settings")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["data"]["s3"] is None
|
||||||
|
|
||||||
|
def test_get_backup_settings_with_s3_config(self, api_client, mock_config):
|
||||||
|
"""Test getting backup settings with S3 configuration."""
|
||||||
|
# Mock S3 backup config (with masked credentials)
|
||||||
|
mock_config._config["backup"] = {
|
||||||
|
"s3": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "test-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"endpoint_url": None,
|
||||||
|
"path_style": False,
|
||||||
|
"enabled": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.get("/api/v1/backup/settings")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["data"]["s3"] is not None
|
||||||
|
|
||||||
|
s3_config = data["data"]["s3"]
|
||||||
|
assert s3_config["access_key_id"] == "***" # Masked
|
||||||
|
assert s3_config["secret_access_key"] == "***" # Masked
|
||||||
|
assert s3_config["bucket_name"] == "test-bucket"
|
||||||
|
assert s3_config["region"] == "us-east-1"
|
||||||
|
assert s3_config["enabled"] is True
|
||||||
|
|
||||||
|
@patch("leggen.services.backup_service.BackupService.test_connection")
|
||||||
|
def test_update_backup_settings_success(
|
||||||
|
self, mock_test_connection, api_client, mock_config
|
||||||
|
):
|
||||||
|
"""Test successful backup settings update."""
|
||||||
|
mock_test_connection.return_value = True
|
||||||
|
mock_config._config["backup"] = {}
|
||||||
|
|
||||||
|
request_data = {
|
||||||
|
"s3": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "test-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"endpoint_url": None,
|
||||||
|
"path_style": False,
|
||||||
|
"enabled": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.put("/api/v1/backup/settings", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["data"]["updated"] is True
|
||||||
|
|
||||||
|
# Verify connection test was called
|
||||||
|
mock_test_connection.assert_called_once()
|
||||||
|
|
||||||
|
@patch("leggen.services.backup_service.BackupService.test_connection")
|
||||||
|
def test_update_backup_settings_connection_failure(
|
||||||
|
self, mock_test_connection, api_client, mock_config
|
||||||
|
):
|
||||||
|
"""Test backup settings update with connection test failure."""
|
||||||
|
mock_test_connection.return_value = False
|
||||||
|
mock_config._config["backup"] = {}
|
||||||
|
|
||||||
|
request_data = {
|
||||||
|
"s3": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "invalid-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"endpoint_url": None,
|
||||||
|
"path_style": False,
|
||||||
|
"enabled": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.put("/api/v1/backup/settings", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
data = response.json()
|
||||||
|
assert "S3 connection test failed" in data["detail"]
|
||||||
|
|
||||||
|
@patch("leggen.services.backup_service.BackupService.test_connection")
|
||||||
|
def test_test_backup_connection_success(self, mock_test_connection, api_client):
|
||||||
|
"""Test successful backup connection test."""
|
||||||
|
mock_test_connection.return_value = True
|
||||||
|
|
||||||
|
request_data = {
|
||||||
|
"service": "s3",
|
||||||
|
"config": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "test-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"endpoint_url": None,
|
||||||
|
"path_style": False,
|
||||||
|
"enabled": True,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
response = api_client.post("/api/v1/backup/test", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["data"]["connected"] is True
|
||||||
|
|
||||||
|
# Verify connection test was called
|
||||||
|
mock_test_connection.assert_called_once()
|
||||||
|
|
||||||
|
@patch("leggen.services.backup_service.BackupService.test_connection")
|
||||||
|
def test_test_backup_connection_failure(self, mock_test_connection, api_client):
|
||||||
|
"""Test failed backup connection test."""
|
||||||
|
mock_test_connection.return_value = False
|
||||||
|
|
||||||
|
request_data = {
|
||||||
|
"service": "s3",
|
||||||
|
"config": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "invalid-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"endpoint_url": None,
|
||||||
|
"path_style": False,
|
||||||
|
"enabled": True,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
response = api_client.post("/api/v1/backup/test", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is False
|
||||||
|
|
||||||
|
def test_test_backup_connection_invalid_service(self, api_client):
|
||||||
|
"""Test backup connection test with invalid service."""
|
||||||
|
request_data = {
|
||||||
|
"service": "invalid",
|
||||||
|
"config": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "test-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"endpoint_url": None,
|
||||||
|
"path_style": False,
|
||||||
|
"enabled": True,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
response = api_client.post("/api/v1/backup/test", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
data = response.json()
|
||||||
|
assert "Only 's3' service is supported" in data["detail"]
|
||||||
|
|
||||||
|
@patch("leggen.services.backup_service.BackupService.list_backups")
|
||||||
|
def test_list_backups_success(self, mock_list_backups, api_client, mock_config):
|
||||||
|
"""Test successful backup listing."""
|
||||||
|
mock_list_backups.return_value = [
|
||||||
|
{
|
||||||
|
"key": "leggen_backups/database_backup_20250101_120000.db",
|
||||||
|
"last_modified": "2025-01-01T12:00:00",
|
||||||
|
"size": 1024,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "leggen_backups/database_backup_20250101_110000.db",
|
||||||
|
"last_modified": "2025-01-01T11:00:00",
|
||||||
|
"size": 512,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
mock_config._config["backup"] = {
|
||||||
|
"s3": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "test-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"enabled": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.get("/api/v1/backup/list")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert len(data["data"]) == 2
|
||||||
|
assert (
|
||||||
|
data["data"][0]["key"]
|
||||||
|
== "leggen_backups/database_backup_20250101_120000.db"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_list_backups_no_config(self, api_client, mock_config):
|
||||||
|
"""Test backup listing with no configuration."""
|
||||||
|
mock_config._config["backup"] = {}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.get("/api/v1/backup/list")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["data"] == []
|
||||||
|
|
||||||
|
@patch("leggen.services.backup_service.BackupService.backup_database")
|
||||||
|
@patch("leggen.utils.paths.path_manager.get_database_path")
|
||||||
|
def test_backup_operation_success(
|
||||||
|
self, mock_get_db_path, mock_backup_db, api_client, mock_config
|
||||||
|
):
|
||||||
|
"""Test successful backup operation."""
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
mock_get_db_path.return_value = Path("/test/database.db")
|
||||||
|
mock_backup_db.return_value = True
|
||||||
|
|
||||||
|
mock_config._config["backup"] = {
|
||||||
|
"s3": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "test-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"enabled": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
request_data = {"operation": "backup"}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.post("/api/v1/backup/operation", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["success"] is True
|
||||||
|
assert data["data"]["operation"] == "backup"
|
||||||
|
assert data["data"]["completed"] is True
|
||||||
|
|
||||||
|
# Verify backup was called
|
||||||
|
mock_backup_db.assert_called_once()
|
||||||
|
|
||||||
|
def test_backup_operation_no_config(self, api_client, mock_config):
|
||||||
|
"""Test backup operation with no configuration."""
|
||||||
|
mock_config._config["backup"] = {}
|
||||||
|
|
||||||
|
request_data = {"operation": "backup"}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.post("/api/v1/backup/operation", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
data = response.json()
|
||||||
|
assert "S3 backup is not configured" in data["detail"]
|
||||||
|
|
||||||
|
def test_backup_operation_invalid_operation(self, api_client, mock_config):
|
||||||
|
"""Test backup operation with invalid operation type."""
|
||||||
|
mock_config._config["backup"] = {
|
||||||
|
"s3": {
|
||||||
|
"access_key_id": "AKIATEST123",
|
||||||
|
"secret_access_key": "secret123",
|
||||||
|
"bucket_name": "test-bucket",
|
||||||
|
"region": "us-east-1",
|
||||||
|
"enabled": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
request_data = {"operation": "invalid"}
|
||||||
|
|
||||||
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
response = api_client.post("/api/v1/backup/operation", json=request_data)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
data = response.json()
|
||||||
|
assert "Invalid operation" in data["detail"]
|
||||||
@@ -50,7 +50,7 @@ class TestBanksAPI:
|
|||||||
|
|
||||||
# Mock empty institutions response for invalid country
|
# Mock empty institutions response for invalid country
|
||||||
respx.get("https://bankaccountdata.gocardless.com/api/v2/institutions/").mock(
|
respx.get("https://bankaccountdata.gocardless.com/api/v2/institutions/").mock(
|
||||||
return_value=httpx.Response(200, json=[])
|
return_value=httpx.Response(200, json={"results": []})
|
||||||
)
|
)
|
||||||
|
|
||||||
with patch("leggen.utils.config.config", mock_config):
|
with patch("leggen.utils.config.config", mock_config):
|
||||||
|
|||||||
@@ -18,7 +18,10 @@ class TestLeggenAPIClient:
|
|||||||
client = LeggenAPIClient("http://localhost:8000")
|
client = LeggenAPIClient("http://localhost:8000")
|
||||||
|
|
||||||
with requests_mock.Mocker() as m:
|
with requests_mock.Mocker() as m:
|
||||||
m.get("http://localhost:8000/health", json={"status": "healthy"})
|
m.get(
|
||||||
|
"http://localhost:8000/api/v1/health",
|
||||||
|
json={"data": {"status": "healthy"}},
|
||||||
|
)
|
||||||
|
|
||||||
result = client.health_check()
|
result = client.health_check()
|
||||||
assert result is True
|
assert result is True
|
||||||
@@ -37,9 +40,12 @@ class TestLeggenAPIClient:
|
|||||||
"""Test getting institutions via API client."""
|
"""Test getting institutions via API client."""
|
||||||
client = LeggenAPIClient("http://localhost:8000")
|
client = LeggenAPIClient("http://localhost:8000")
|
||||||
|
|
||||||
|
# The API returns processed institutions, not raw GoCardless data
|
||||||
|
processed_institutions = sample_bank_data["results"]
|
||||||
|
|
||||||
api_response = {
|
api_response = {
|
||||||
"success": True,
|
"success": True,
|
||||||
"data": sample_bank_data,
|
"data": processed_institutions,
|
||||||
"message": "Found 2 institutions for PT",
|
"message": "Found 2 institutions for PT",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,13 +115,13 @@ class TestLeggenAPIClient:
|
|||||||
custom_url = "http://custom-host:9000"
|
custom_url = "http://custom-host:9000"
|
||||||
client = LeggenAPIClient(custom_url)
|
client = LeggenAPIClient(custom_url)
|
||||||
|
|
||||||
assert client.base_url == custom_url
|
assert client.base_url == f"{custom_url}/api/v1"
|
||||||
|
|
||||||
def test_environment_variable_url(self):
|
def test_environment_variable_url(self):
|
||||||
"""Test using environment variable for API URL."""
|
"""Test using environment variable for API URL."""
|
||||||
with patch.dict("os.environ", {"LEGGEN_API_URL": "http://env-host:7000"}):
|
with patch.dict("os.environ", {"LEGGEN_API_URL": "http://env-host:7000"}):
|
||||||
client = LeggenAPIClient()
|
client = LeggenAPIClient()
|
||||||
assert client.base_url == "http://env-host:7000"
|
assert client.base_url == "http://env-host:7000/api/v1"
|
||||||
|
|
||||||
def test_sync_with_options(self):
|
def test_sync_with_options(self):
|
||||||
"""Test sync with various options."""
|
"""Test sync with various options."""
|
||||||
|
|||||||
226
tests/unit/test_backup_service.py
Normal file
226
tests/unit/test_backup_service.py
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
"""Tests for backup service functionality."""
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from botocore.exceptions import ClientError, NoCredentialsError
|
||||||
|
|
||||||
|
from leggen.models.config import S3BackupConfig
|
||||||
|
from leggen.services.backup_service import BackupService
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.unit
|
||||||
|
class TestBackupService:
|
||||||
|
"""Test backup service functionality."""
|
||||||
|
|
||||||
|
def test_backup_service_initialization(self):
|
||||||
|
"""Test backup service can be initialized."""
|
||||||
|
service = BackupService()
|
||||||
|
assert service.s3_config is None
|
||||||
|
assert service._s3_client is None
|
||||||
|
|
||||||
|
def test_backup_service_with_config(self):
|
||||||
|
"""Test backup service initialization with config."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
)
|
||||||
|
service = BackupService(s3_config)
|
||||||
|
assert service.s3_config == s3_config
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_test_connection_success(self):
|
||||||
|
"""Test successful S3 connection test."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
)
|
||||||
|
|
||||||
|
service = BackupService()
|
||||||
|
|
||||||
|
# Mock S3 client
|
||||||
|
with patch("boto3.Session") as mock_session:
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_session.return_value.client.return_value = mock_client
|
||||||
|
|
||||||
|
# Mock successful list_objects_v2 call
|
||||||
|
mock_client.list_objects_v2.return_value = {"Contents": []}
|
||||||
|
|
||||||
|
result = await service.test_connection(s3_config)
|
||||||
|
assert result is True
|
||||||
|
|
||||||
|
# Verify the client was called correctly
|
||||||
|
mock_client.list_objects_v2.assert_called_once_with(
|
||||||
|
Bucket="test-bucket", MaxKeys=1
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_test_connection_no_credentials(self):
|
||||||
|
"""Test S3 connection test with no credentials."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
)
|
||||||
|
|
||||||
|
service = BackupService()
|
||||||
|
|
||||||
|
# Mock S3 client to raise NoCredentialsError
|
||||||
|
with patch("boto3.Session") as mock_session:
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_session.return_value.client.return_value = mock_client
|
||||||
|
mock_client.list_objects_v2.side_effect = NoCredentialsError()
|
||||||
|
|
||||||
|
result = await service.test_connection(s3_config)
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_test_connection_client_error(self):
|
||||||
|
"""Test S3 connection test with client error."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
)
|
||||||
|
|
||||||
|
service = BackupService()
|
||||||
|
|
||||||
|
# Mock S3 client to raise ClientError
|
||||||
|
with patch("boto3.Session") as mock_session:
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_session.return_value.client.return_value = mock_client
|
||||||
|
error_response = {
|
||||||
|
"Error": {"Code": "NoSuchBucket", "Message": "Bucket not found"}
|
||||||
|
}
|
||||||
|
mock_client.list_objects_v2.side_effect = ClientError(
|
||||||
|
error_response, "ListObjectsV2"
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await service.test_connection(s3_config)
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_backup_database_no_config(self):
|
||||||
|
"""Test backup database with no configuration."""
|
||||||
|
service = BackupService()
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
db_path = Path(tmpdir) / "test.db"
|
||||||
|
db_path.write_text("test database content")
|
||||||
|
|
||||||
|
result = await service.backup_database(db_path)
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_backup_database_disabled(self):
|
||||||
|
"""Test backup database with disabled configuration."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
enabled=False,
|
||||||
|
)
|
||||||
|
service = BackupService(s3_config)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
db_path = Path(tmpdir) / "test.db"
|
||||||
|
db_path.write_text("test database content")
|
||||||
|
|
||||||
|
result = await service.backup_database(db_path)
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_backup_database_file_not_found(self):
|
||||||
|
"""Test backup database with non-existent file."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
)
|
||||||
|
service = BackupService(s3_config)
|
||||||
|
|
||||||
|
non_existent_path = Path("/non/existent/path.db")
|
||||||
|
result = await service.backup_database(non_existent_path)
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_backup_database_success(self):
|
||||||
|
"""Test successful database backup."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
)
|
||||||
|
service = BackupService(s3_config)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
db_path = Path(tmpdir) / "test.db"
|
||||||
|
db_path.write_text("test database content")
|
||||||
|
|
||||||
|
# Mock S3 client
|
||||||
|
with patch("boto3.Session") as mock_session:
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_session.return_value.client.return_value = mock_client
|
||||||
|
|
||||||
|
result = await service.backup_database(db_path)
|
||||||
|
assert result is True
|
||||||
|
|
||||||
|
# Verify upload_file was called
|
||||||
|
mock_client.upload_file.assert_called_once()
|
||||||
|
args = mock_client.upload_file.call_args[0]
|
||||||
|
assert args[0] == str(db_path) # source file
|
||||||
|
assert args[1] == "test-bucket" # bucket name
|
||||||
|
assert args[2].startswith("leggen_backups/database_backup_") # key
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_list_backups_success(self):
|
||||||
|
"""Test successful backup listing."""
|
||||||
|
s3_config = S3BackupConfig(
|
||||||
|
access_key_id="test-key",
|
||||||
|
secret_access_key="test-secret",
|
||||||
|
bucket_name="test-bucket",
|
||||||
|
region="us-east-1",
|
||||||
|
)
|
||||||
|
service = BackupService(s3_config)
|
||||||
|
|
||||||
|
# Mock S3 client response
|
||||||
|
with patch("boto3.Session") as mock_session:
|
||||||
|
mock_client = MagicMock()
|
||||||
|
mock_session.return_value.client.return_value = mock_client
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
mock_response = {
|
||||||
|
"Contents": [
|
||||||
|
{
|
||||||
|
"Key": "leggen_backups/database_backup_20250101_120000.db",
|
||||||
|
"LastModified": datetime(2025, 1, 1, 12, 0, 0),
|
||||||
|
"Size": 1024,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Key": "leggen_backups/database_backup_20250101_130000.db",
|
||||||
|
"LastModified": datetime(2025, 1, 1, 13, 0, 0),
|
||||||
|
"Size": 2048,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
mock_client.list_objects_v2.return_value = mock_response
|
||||||
|
|
||||||
|
backups = await service.list_backups()
|
||||||
|
assert len(backups) == 2
|
||||||
|
|
||||||
|
# Check that backups are sorted by last modified (newest first)
|
||||||
|
assert backups[0]["last_modified"] > backups[1]["last_modified"]
|
||||||
|
assert backups[0]["size"] == 2048
|
||||||
|
assert backups[1]["size"] == 1024
|
||||||
@@ -324,6 +324,8 @@ class TestDatabaseService:
|
|||||||
with patch("sqlite3.connect") as mock_connect:
|
with patch("sqlite3.connect") as mock_connect:
|
||||||
mock_conn = mock_connect.return_value
|
mock_conn = mock_connect.return_value
|
||||||
mock_cursor = mock_conn.cursor.return_value
|
mock_cursor = mock_conn.cursor.return_value
|
||||||
|
# Mock fetchone to return (0,) indicating transaction doesn't exist yet
|
||||||
|
mock_cursor.fetchone.return_value = (0,)
|
||||||
|
|
||||||
result = await database_service._persist_transactions_sqlite(
|
result = await database_service._persist_transactions_sqlite(
|
||||||
"test-account-123", sample_transactions_db_format
|
"test-account-123", sample_transactions_db_format
|
||||||
@@ -338,6 +340,29 @@ class TestDatabaseService:
|
|||||||
mock_conn.commit.assert_called_once()
|
mock_conn.commit.assert_called_once()
|
||||||
mock_conn.close.assert_called_once()
|
mock_conn.close.assert_called_once()
|
||||||
|
|
||||||
|
async def test_persist_transactions_sqlite_duplicate_detection(
|
||||||
|
self, database_service, sample_transactions_db_format
|
||||||
|
):
|
||||||
|
"""Test that existing transactions are not returned as new."""
|
||||||
|
with patch("sqlite3.connect") as mock_connect:
|
||||||
|
mock_conn = mock_connect.return_value
|
||||||
|
mock_cursor = mock_conn.cursor.return_value
|
||||||
|
# Mock fetchone to return (1,) indicating transaction already exists
|
||||||
|
mock_cursor.fetchone.return_value = (1,)
|
||||||
|
|
||||||
|
result = await database_service._persist_transactions_sqlite(
|
||||||
|
"test-account-123", sample_transactions_db_format
|
||||||
|
)
|
||||||
|
|
||||||
|
# Should return empty list since all transactions already exist
|
||||||
|
assert len(result) == 0
|
||||||
|
|
||||||
|
# Verify database operations still happened (INSERT OR REPLACE executed)
|
||||||
|
mock_connect.assert_called()
|
||||||
|
mock_cursor.execute.assert_called()
|
||||||
|
mock_conn.commit.assert_called_once()
|
||||||
|
mock_conn.close.assert_called_once()
|
||||||
|
|
||||||
async def test_persist_transactions_sqlite_error(self, database_service):
|
async def test_persist_transactions_sqlite_error(self, database_service):
|
||||||
"""Test handling error during transaction persistence."""
|
"""Test handling error during transaction persistence."""
|
||||||
with patch("sqlite3.connect") as mock_connect:
|
with patch("sqlite3.connect") as mock_connect:
|
||||||
|
|||||||
74
uv.lock
generated
74
uv.lock
generated
@@ -36,6 +36,34 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/d0/ae/9a053dd9229c0fde6b1f1f33f609ccff1ee79ddda364c756a924c6d8563b/APScheduler-3.11.0-py3-none-any.whl", hash = "sha256:fc134ca32e50f5eadcc4938e3a4545ab19131435e851abb40b34d63d5141c6da", size = 64004, upload-time = "2024-11-24T19:39:24.442Z" },
|
{ url = "https://files.pythonhosted.org/packages/d0/ae/9a053dd9229c0fde6b1f1f33f609ccff1ee79ddda364c756a924c6d8563b/APScheduler-3.11.0-py3-none-any.whl", hash = "sha256:fc134ca32e50f5eadcc4938e3a4545ab19131435e851abb40b34d63d5141c6da", size = 64004, upload-time = "2024-11-24T19:39:24.442Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "boto3"
|
||||||
|
version = "1.40.36"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "botocore" },
|
||||||
|
{ name = "jmespath" },
|
||||||
|
{ name = "s3transfer" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/8d/21/7bc857b155e8264c92b6fa8e0860a67dc01a19cbe6ba4342500299f2ae5b/boto3-1.40.36.tar.gz", hash = "sha256:bfc1f3d5c4f5d12b8458406b8972f8794ac57e2da1ee441469e143bc0440a5c3", size = 111552, upload-time = "2025-09-22T19:26:17.357Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/70/4c/428b728d5cf9003f83f735d10dd522945ab20c7d67e6c987909f29be12a0/boto3-1.40.36-py3-none-any.whl", hash = "sha256:d7c1fe033f491f560cd26022a9dcf28baf877ae854f33bc64fffd0df3b9c98be", size = 139345, upload-time = "2025-09-22T19:26:15.194Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "botocore"
|
||||||
|
version = "1.40.36"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "jmespath" },
|
||||||
|
{ name = "python-dateutil" },
|
||||||
|
{ name = "urllib3" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/4b/30/75fdc75933d3bc1c8dd7fbaee771438328b518936906b411075b1eacac93/botocore-1.40.36.tar.gz", hash = "sha256:93386a8dc54173267ddfc6cd8636c9171e021f7c032aa1df3af7de816e3df616", size = 14349583, upload-time = "2025-09-22T19:26:05.957Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d8/51/95c0324ac20b5bbafad4c89dd610c8e0dd6cbadbb2c8ca66dc95ccde98b8/botocore-1.40.36-py3-none-any.whl", hash = "sha256:d6edf75875e4013cb7078875a1d6c289afb4cc6675d99d80700c692d8d8e0b72", size = 14020478, upload-time = "2025-09-22T19:26:02.054Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "certifi"
|
name = "certifi"
|
||||||
version = "2025.8.3"
|
version = "2025.8.3"
|
||||||
@@ -218,12 +246,22 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050, upload-time = "2025-03-19T20:10:01.071Z" },
|
{ url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050, upload-time = "2025-03-19T20:10:01.071Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jmespath"
|
||||||
|
version = "1.0.1"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/00/2a/e867e8531cf3e36b41201936b7fa7ba7b5702dbef42922193f05c8976cd6/jmespath-1.0.1.tar.gz", hash = "sha256:90261b206d6defd58fdd5e85f478bf633a2901798906be2ad389150c5c60edbe", size = 25843, upload-time = "2022-06-17T18:00:12.224Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/31/b4/b9b800c45527aadd64d5b442f9b932b00648617eb5d63d2c7a6587b7cafc/jmespath-1.0.1-py3-none-any.whl", hash = "sha256:02e2e4cc71b5bcab88332eebf907519190dd9e6e82107fa7f83b1003a6252980", size = 20256, upload-time = "2022-06-17T18:00:10.251Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "leggen"
|
name = "leggen"
|
||||||
version = "2025.9.16"
|
version = "2025.10.2"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "apscheduler" },
|
{ name = "apscheduler" },
|
||||||
|
{ name = "boto3" },
|
||||||
{ name = "click" },
|
{ name = "click" },
|
||||||
{ name = "discord-webhook" },
|
{ name = "discord-webhook" },
|
||||||
{ name = "fastapi" },
|
{ name = "fastapi" },
|
||||||
@@ -253,6 +291,7 @@ dev = [
|
|||||||
[package.metadata]
|
[package.metadata]
|
||||||
requires-dist = [
|
requires-dist = [
|
||||||
{ name = "apscheduler", specifier = ">=3.10.0,<4" },
|
{ name = "apscheduler", specifier = ">=3.10.0,<4" },
|
||||||
|
{ name = "boto3", specifier = ">=1.35.0,<2" },
|
||||||
{ name = "click", specifier = ">=8.1.7,<9" },
|
{ name = "click", specifier = ">=8.1.7,<9" },
|
||||||
{ name = "discord-webhook", specifier = ">=1.3.1,<2" },
|
{ name = "discord-webhook", specifier = ">=1.3.1,<2" },
|
||||||
{ name = "fastapi", specifier = ">=0.104.0,<1" },
|
{ name = "fastapi", specifier = ">=0.104.0,<1" },
|
||||||
@@ -474,6 +513,18 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/2b/b3/7fefc43fb706380144bcd293cc6e446e6f637ddfa8b83f48d1734156b529/pytest_mock-3.15.0-py3-none-any.whl", hash = "sha256:ef2219485fb1bd256b00e7ad7466ce26729b30eadfc7cbcdb4fa9a92ca68db6f", size = 10050, upload-time = "2025-09-04T20:57:47.274Z" },
|
{ url = "https://files.pythonhosted.org/packages/2b/b3/7fefc43fb706380144bcd293cc6e446e6f637ddfa8b83f48d1734156b529/pytest_mock-3.15.0-py3-none-any.whl", hash = "sha256:ef2219485fb1bd256b00e7ad7466ce26729b30eadfc7cbcdb4fa9a92ca68db6f", size = 10050, upload-time = "2025-09-04T20:57:47.274Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "python-dateutil"
|
||||||
|
version = "2.9.0.post0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "six" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "python-dotenv"
|
name = "python-dotenv"
|
||||||
version = "1.1.1"
|
version = "1.1.1"
|
||||||
@@ -565,6 +616,27 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/e1/a3/03216a6a86c706df54422612981fb0f9041dbb452c3401501d4a22b942c9/ruff-0.13.0-py3-none-win_arm64.whl", hash = "sha256:ab80525317b1e1d38614addec8ac954f1b3e662de9d59114ecbf771d00cf613e", size = 12312357, upload-time = "2025-09-10T16:25:35.595Z" },
|
{ url = "https://files.pythonhosted.org/packages/e1/a3/03216a6a86c706df54422612981fb0f9041dbb452c3401501d4a22b942c9/ruff-0.13.0-py3-none-win_arm64.whl", hash = "sha256:ab80525317b1e1d38614addec8ac954f1b3e662de9d59114ecbf771d00cf613e", size = 12312357, upload-time = "2025-09-10T16:25:35.595Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "s3transfer"
|
||||||
|
version = "0.14.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "botocore" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/62/74/8d69dcb7a9efe8baa2046891735e5dfe433ad558ae23d9e3c14c633d1d58/s3transfer-0.14.0.tar.gz", hash = "sha256:eff12264e7c8b4985074ccce27a3b38a485bb7f7422cc8046fee9be4983e4125", size = 151547, upload-time = "2025-09-09T19:23:31.089Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/48/f0/ae7ca09223a81a1d890b2557186ea015f6e0502e9b8cb8e1813f1d8cfa4e/s3transfer-0.14.0-py3-none-any.whl", hash = "sha256:ea3b790c7077558ed1f02a3072fb3cb992bbbd253392f4b6e9e8976941c7d456", size = 85712, upload-time = "2025-09-09T19:23:30.041Z" },
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "six"
|
||||||
|
version = "1.17.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sniffio"
|
name = "sniffio"
|
||||||
version = "1.3.1"
|
version = "1.3.1"
|
||||||
|
|||||||
Reference in New Issue
Block a user