Compare commits
24 Commits
5470bebfc4
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adfcd90dcf | ||
|
|
bb610e0480 | ||
|
|
44d6cf6352 | ||
|
|
74529d8b19 | ||
|
|
bd7c6dddbf | ||
|
|
8e8d93e4a6 | ||
|
|
fee9f02faa | ||
|
|
bcd7eea1b4 | ||
|
|
281754de22 | ||
|
|
d60da0a7aa | ||
|
|
46c9e9b97d | ||
|
|
096d4d0530 | ||
|
|
20cd0b34bc | ||
|
|
da435d2e66 | ||
|
|
5c416c77f0 | ||
|
|
3886e64ef6 | ||
|
|
3f2cad2426 | ||
|
|
89d481bbbf | ||
|
|
6218fc3c12 | ||
|
|
cbc826a4e1 | ||
|
|
fbfd918d81 | ||
|
|
6cde543938 | ||
|
|
481f4db389 | ||
|
|
976c802b11 |
@@ -1,6 +1,4 @@
|
|||||||
---
|
---
|
||||||
alwaysApply: true
|
alwaysApply: true
|
||||||
---
|
---
|
||||||
sqlcmd -C -S tcp:192.168.56.1,1497 -U app -P 'readonly' -d eazybusiness -W
|
|
||||||
|
|
||||||
sqlcmd -C -S tcp:192.168.56.1,1497 -U sa -P 'sa_tekno23' -d eazybusiness -W
|
sqlcmd -C -S tcp:192.168.56.1,1497 -U sa -P 'sa_tekno23' -d eazybusiness -W
|
||||||
7
.cursor/rules/devserver.mdc
Normal file
7
.cursor/rules/devserver.mdc
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
pm2 restart 10 -> restart backend (configured as "npm run dev:backend")
|
||||||
|
pm2 restart 11 -> restart backend (configured as "npm run dev:frontend")
|
||||||
|
|
||||||
|
(both should rarely neer restart because in dev mode HMR for frontend, and nodemon for backend should already do that)
|
||||||
@@ -8,6 +8,9 @@ REACT_APP_GOOGLE_CLIENT_ID=your_google_client_id_here
|
|||||||
# JWT Secret
|
# JWT Secret
|
||||||
JWT_SECRET=your_jwt_secret_here
|
JWT_SECRET=your_jwt_secret_here
|
||||||
|
|
||||||
|
# OpenAI API Configuration
|
||||||
|
OPENAI_API_KEY=your_openai_api_key_here
|
||||||
|
|
||||||
# Authorized Email Addresses (comma-separated)
|
# Authorized Email Addresses (comma-separated)
|
||||||
AUTHORIZED_EMAILS=admin@example.com,user1@example.com,user2@example.com
|
AUTHORIZED_EMAILS=admin@example.com,user1@example.com,user2@example.com
|
||||||
|
|
||||||
|
|||||||
4
.kilocode/rules/mssql.md
Normal file
4
.kilocode/rules/mssql.md
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# mssql.md
|
||||||
|
|
||||||
|
sqlcmd -C -S tcp:192.168.56.1,1497 -U app -P 'readonly' -d eazybusiness -W
|
||||||
|
|
||||||
478
README.md
478
README.md
@@ -1,18 +1,20 @@
|
|||||||
# FibDash
|
# FibDash
|
||||||
|
|
||||||
A modern React Material-UI dashboard application with Google SSO authentication and MSSQL database integration.
|
A modern React Material-UI dashboard for financial reconciliation with Google SSO authentication, CSV import/analysis, DATEV export, and optional MSSQL integration with JTL tables.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- 🚀 **React 18** with class components
|
- 🚀 React 18 (class components)
|
||||||
- 🎨 **Material-UI (MUI)** for beautiful, modern UI
|
- 🎨 Material-UI (MUI) UI with responsive layout
|
||||||
- 🔐 **Google SSO Authentication**
|
- 🔐 Google SSO (Google Identity Services) + JWT API auth
|
||||||
- 🗄️ **MSSQL Database** integration
|
- 🗄️ MSSQL integration (optional; app runs without DB)
|
||||||
- ⚡ **Webpack Dev Server** with Hot Module Reload
|
- 📥 CSV import of bank transactions (German MT940-like CSV)
|
||||||
- 🔄 **Express API** with hot reload via nodemon
|
- 🔍 Reconciliation view: CSV vs JTL (if DB available)
|
||||||
- 🛡️ **JWT Authentication** for API security
|
- 📤 DATEV export for selected month/quarter/year
|
||||||
- 📱 **Responsive Design**
|
- 🧩 Admin data management (Kreditor, Konto, BU)
|
||||||
- 🎯 **Production Ready** build configuration
|
- ⚡ Webpack dev server (HMR) + nodemon hot-reload
|
||||||
|
- 🛡️ Email allowlist authorization
|
||||||
|
- 🧰 Production single-process build (Express serves React)
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -27,337 +29,249 @@ fibdash/
|
|||||||
│ └── public/
|
│ └── public/
|
||||||
│ └── index.html # HTML template
|
│ └── index.html # HTML template
|
||||||
├── src/ # Backend Express API
|
├── src/ # Backend Express API
|
||||||
│ ├── config/ # Database configuration
|
│ ├── config/ # Database configuration (MSSQL)
|
||||||
│ ├── middleware/ # Authentication middleware
|
│ ├── middleware/ # Auth + email allowlist middleware
|
||||||
│ ├── routes/ # API routes
|
│ ├── routes/ # API routes (auth, data, admin, dashboard)
|
||||||
│ ├── database/ # Database schema
|
│ ├── database/ # SQL schema and CSV import schema
|
||||||
│ └── index.js # Express server entry point
|
│ └── index.js # Express server entry point
|
||||||
├── webpack.config.js # Webpack configuration
|
├── nginx.*.conf # Nginx reverse-proxy configs (dev/prod/simple)
|
||||||
|
├── webpack*.config.js # Webpack configs
|
||||||
|
├── docker-compose.dev.yml # Optional dev docker-compose for proxying
|
||||||
|
├── data.csv # Sample CSV for local analysis
|
||||||
└── package.json # Dependencies and scripts
|
└── package.json # Dependencies and scripts
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Functional Overview
|
||||||
|
|
||||||
|
Authentication and Authorization
|
||||||
|
- Login: Frontend uses Google Identity Services. The backend validates the ID token and issues a JWT.
|
||||||
|
- Email allowlist: Only emails in AUTHORIZED_EMAILS or matching DB rule are allowed.
|
||||||
|
- ENV allowlist: fast path check.
|
||||||
|
- DB check: optional, queries JTL tables to verify access by attributes 219/220.
|
||||||
|
- JWT middleware guards all /api routes.
|
||||||
|
|
||||||
|
CSV Analysis and Reconciliation
|
||||||
|
- Upload or place CSV at project root (data.csv) for quick testing.
|
||||||
|
- CSV parsing: German semicolon-separated format with headers like Buchungstag, Betrag, Verwendungszweck, IBAN, etc.
|
||||||
|
- Reconciliation:
|
||||||
|
- If MSSQL available: fetch JTL transactions (tZahlungsabgleichUmsatz), related PDFs (tUmsatzBeleg, tPdfObjekt), and links; match by date+amount.
|
||||||
|
- Kreditor lookup: optional mapping via fibdash.Kreditor using IBAN; also supports banking accounts via is_banking.
|
||||||
|
- Summary totals: income, expenses, net, match counts.
|
||||||
|
|
||||||
|
DATEV Export
|
||||||
|
- Endpoint returns CSV in DATEV format for the chosen period (month, quarter, year).
|
||||||
|
- Headers and column mapping created server-side; amounts normalized; encoding served as text/csv.
|
||||||
|
|
||||||
|
Admin Management
|
||||||
|
- Kreditor: CRUD for name, kreditorId, IBAN (optional if is_banking=true).
|
||||||
|
- Konto: CRUD account numbers/names used for accounting.
|
||||||
|
- BU (Buchungsschlüssel): CRUD including optional VSt.
|
||||||
|
- System info endpoint.
|
||||||
|
|
||||||
|
Health
|
||||||
|
- /api/health returns OK and timestamp.
|
||||||
|
|
||||||
|
## API Surface (key endpoints)
|
||||||
|
|
||||||
|
Auth
|
||||||
|
- POST /api/auth/google — Google token exchange → JWT
|
||||||
|
- GET /api/auth/verify — Validate JWT, returns user
|
||||||
|
- POST /api/auth/logout — Stateless logout success
|
||||||
|
|
||||||
|
Dashboard
|
||||||
|
- GET /api/dashboard — Mock dashboard stats
|
||||||
|
- GET /api/dashboard/user — Returns current JWT user
|
||||||
|
|
||||||
|
Data and Reconciliation
|
||||||
|
- GET /api/data/months — Available months inferred from data.csv
|
||||||
|
- GET /api/data/transactions/:timeRange — Combined CSV + JTL view with summary
|
||||||
|
- timeRange supports YYYY-MM, YYYY, YYYY-Q1..Q4
|
||||||
|
- GET /api/data/datev/:timeRange — Download DATEV CSV
|
||||||
|
- GET /api/data/pdf/umsatzbeleg/:kUmsatzBeleg — Stream PDF from tUmsatzBeleg
|
||||||
|
- GET /api/data/pdf/pdfobject/:kPdfObjekt — Stream PDF from tPdfObjekt
|
||||||
|
|
||||||
|
Kreditor, Konto, BU
|
||||||
|
- GET /api/data/kreditors
|
||||||
|
- GET /api/data/kreditors/:id
|
||||||
|
- POST /api/data/kreditors
|
||||||
|
- PUT /api/data/kreditors/:id
|
||||||
|
- DELETE /api/data/kreditors/:id
|
||||||
|
- GET /api/data/assignable-kreditors — only non-banking
|
||||||
|
- BankingAccountTransactions assignments: POST/PUT/DELETE, and GET /api/data/banking-transactions/:transactionId
|
||||||
|
- Admin counterparts exist under /api/admin for Kreditor/Konto/BU CRUD.
|
||||||
|
|
||||||
|
CSV Import (to DB)
|
||||||
|
- POST /api/data/import-csv-transactions — Validates rows and inserts into fibdash.CSVTransactions
|
||||||
|
- GET /api/data/csv-transactions — Paginated list with kreditor joins and assignment info
|
||||||
|
- GET /api/data/csv-import-batches — Import batch summaries
|
||||||
|
|
||||||
|
## Frontend UX Summary
|
||||||
|
|
||||||
|
App shell
|
||||||
|
- Top AppBar with title, tabs (Dashboard, Stammdaten), current user, DATEV export button when applicable, and logout.
|
||||||
|
|
||||||
|
Login
|
||||||
|
- Button triggers Google prompt; robust error messaging for SSO, service unavailability, authorization.
|
||||||
|
|
||||||
|
Dashboard view
|
||||||
|
- Month selector, summary header, and a transactions table with reconciliation indicators (CSV-only, JTL-only, matched), PDF links when available.
|
||||||
|
|
||||||
|
Stammdaten view
|
||||||
|
- Management UI for Kreditors, Konten, and Buchungsschlüssel (class-based components under client/src/components/admin).
|
||||||
|
|
||||||
|
CSV Import
|
||||||
|
- Modal dialog with drag-and-drop or file picker, header detection, basic validation, progress, and results summary; uses /api/data/import-csv-transactions.
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
- Node.js (v16 or higher)
|
- Node.js (v16+)
|
||||||
- MSSQL Server instance
|
- Optionally: MSSQL Server for JTL and fibdash schema
|
||||||
- Google Cloud Platform account for OAuth setup
|
- Google Cloud project and OAuth 2.0 Client ID
|
||||||
|
|
||||||
## Setup Instructions
|
## Setup
|
||||||
|
|
||||||
### 1. Clone and Install Dependencies
|
|
||||||
|
|
||||||
|
1) Clone and install
|
||||||
```bash
|
```bash
|
||||||
git clone <your-repo-url>
|
git clone <your-repo-url>
|
||||||
cd fibdash
|
cd fibdash
|
||||||
npm install
|
npm install
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Environment Configuration
|
2) Environment
|
||||||
|
|
||||||
Copy the example environment file and configure your settings:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
|
# then edit .env
|
||||||
```
|
```
|
||||||
|
|
||||||
Edit `.env` with your actual configuration:
|
Required variables
|
||||||
|
- GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
|
||||||
|
- REACT_APP_GOOGLE_CLIENT_ID (must match GOOGLE_CLIENT_ID)
|
||||||
|
- JWT_SECRET
|
||||||
|
- Optional authorization: AUTHORIZED_EMAILS=admin@company.com,user@company.com
|
||||||
|
- MSSQL: DB_SERVER, DB_DATABASE, DB_USERNAME, DB_PASSWORD, DB_PORT=1433
|
||||||
|
- Server: PORT=5000, NODE_ENV=development
|
||||||
|
|
||||||
```env
|
3) Google OAuth
|
||||||
# Google OAuth Configuration
|
- Create OAuth 2.0 Web Client in Google Cloud Console.
|
||||||
GOOGLE_CLIENT_ID=your_google_client_id_here
|
- Authorized origins: http://localhost:5001 (dev), your domain(s).
|
||||||
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
|
- Authorized redirects: matching roots (e.g., http://localhost:5001/).
|
||||||
|
- See detailed guide: [docs/GOOGLE_OAUTH_SETUP.md](docs/GOOGLE_OAUTH_SETUP.md)
|
||||||
|
|
||||||
# Frontend Environment Variables (REACT_APP_ prefix required)
|
4) Database (optional but required for JTL features)
|
||||||
REACT_APP_GOOGLE_CLIENT_ID=your_google_client_id_here
|
- Create DB and run schemas:
|
||||||
|
- Core schema: see src/database/schema.sql
|
||||||
# JWT Secret (generate a secure random string)
|
- CSV import table schemas if needed
|
||||||
JWT_SECRET=your_jwt_secret_here
|
- The app will run without DB; JTL features and admin CRUD will error if DB not configured.
|
||||||
|
|
||||||
# MSSQL Database Configuration
|
|
||||||
DB_SERVER=your_mssql_server_here
|
|
||||||
DB_DATABASE=your_database_name_here
|
|
||||||
DB_USERNAME=your_db_username_here
|
|
||||||
DB_PASSWORD=your_db_password_here
|
|
||||||
DB_PORT=1433
|
|
||||||
|
|
||||||
# Server Configuration
|
|
||||||
PORT=5000
|
|
||||||
NODE_ENV=development
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Google OAuth Setup
|
|
||||||
|
|
||||||
1. Go to the [Google Cloud Console](https://console.cloud.google.com/)
|
|
||||||
2. Create a new project or select an existing one
|
|
||||||
3. Enable the Google+ API
|
|
||||||
4. Create OAuth 2.0 credentials:
|
|
||||||
- Application type: Web application
|
|
||||||
- Authorized JavaScript origins: `http://localhost:3000`
|
|
||||||
- Authorized redirect URIs: `http://localhost:3000`
|
|
||||||
5. Copy the Client ID and Client Secret to your `.env` file
|
|
||||||
|
|
||||||
### 4. Database Setup
|
|
||||||
|
|
||||||
1. Create a new MSSQL database
|
|
||||||
2. Run the schema creation script:
|
|
||||||
|
|
||||||
|
5) Development
|
||||||
```bash
|
```bash
|
||||||
# Connect to your MSSQL server and run:
|
npm run dev # runs frontend at 5001 and backend at 5000
|
||||||
sqlcmd -S your_server -d your_database -i src/database/schema.sql
|
# or separately:
|
||||||
```
|
|
||||||
|
|
||||||
Or manually execute the SQL commands in `src/database/schema.sql`
|
|
||||||
|
|
||||||
### 5. Start Development Servers
|
|
||||||
|
|
||||||
Run both frontend and backend development servers:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
This will start:
|
|
||||||
- Frontend dev server on `http://localhost:5001` (with hot reload)
|
|
||||||
- Backend API server on `http://localhost:5000` (with nodemon auto-restart)
|
|
||||||
|
|
||||||
Or run them separately:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Frontend only
|
|
||||||
npm run dev:frontend
|
npm run dev:frontend
|
||||||
|
|
||||||
# Backend only
|
|
||||||
npm run dev:backend
|
npm run dev:backend
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6. Optional: Nginx Setup for Development
|
6) Optional Nginx for dev
|
||||||
|
- Automatic:
|
||||||
For a more production-like development environment, you can set up nginx as a reverse proxy:
|
|
||||||
|
|
||||||
#### Automatic Setup (Linux/macOS)
|
|
||||||
```bash
|
```bash
|
||||||
npm run setup:nginx
|
npm run setup:nginx
|
||||||
```
|
```
|
||||||
|
- Manual:
|
||||||
#### Manual Setup
|
|
||||||
1. Install nginx on your system
|
|
||||||
2. Copy the nginx configuration:
|
|
||||||
```bash
|
```bash
|
||||||
sudo cp nginx.simple.conf /etc/nginx/sites-available/fibdash-dev
|
sudo cp nginx.simple.conf /etc/nginx/sites-available/fibdash-dev
|
||||||
sudo ln -s /etc/nginx/sites-available/fibdash-dev /etc/nginx/sites-enabled/
|
sudo ln -s /etc/nginx/sites-available/fibdash-dev /etc/nginx/sites-enabled/
|
||||||
sudo nginx -t && sudo systemctl reload nginx
|
sudo nginx -t && sudo systemctl reload nginx
|
||||||
```
|
```
|
||||||
|
- Hosts entry (optional): 127.0.0.1 fibdash.local
|
||||||
|
|
||||||
3. Add to your hosts file (optional):
|
With nginx:
|
||||||
|
- App: http://localhost/ or http://fibdash.local/
|
||||||
|
- API: http://localhost/api/
|
||||||
|
- Direct FE: http://localhost:5001/
|
||||||
|
- Direct BE: http://localhost:5000/
|
||||||
|
|
||||||
|
## Production
|
||||||
|
|
||||||
|
Single-process model
|
||||||
|
- Express serves built React app and handles APIs and auth.
|
||||||
|
|
||||||
|
Build and run
|
||||||
```bash
|
```bash
|
||||||
echo "127.0.0.1 fibdash.local" | sudo tee -a /etc/hosts
|
npm start # build frontend and start backend
|
||||||
|
# or:
|
||||||
|
npm run build
|
||||||
|
npm run start:prod
|
||||||
```
|
```
|
||||||
|
|
||||||
With nginx setup, you can access:
|
Nginx production reverse proxy
|
||||||
- **Main app**: `http://localhost/` or `http://fibdash.local/`
|
|
||||||
- **API**: `http://localhost/api/` or `http://fibdash.local/api/`
|
|
||||||
- **Direct Frontend**: `http://localhost:5001/`
|
|
||||||
- **Direct Backend**: `http://localhost:5000/`
|
|
||||||
|
|
||||||
### Production Nginx Setup
|
|
||||||
|
|
||||||
For production deployment, use the production nginx configuration:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Copy production nginx config
|
|
||||||
sudo cp nginx.prod.conf /etc/nginx/sites-available/fibdash-prod
|
sudo cp nginx.prod.conf /etc/nginx/sites-available/fibdash-prod
|
||||||
sudo ln -s /etc/nginx/sites-available/fibdash-prod /etc/nginx/sites-enabled/
|
sudo ln -s /etc/nginx/sites-available/fibdash-prod /etc/nginx/sites-enabled/
|
||||||
sudo nginx -t && sudo systemctl reload nginx
|
sudo nginx -t && sudo systemctl reload nginx
|
||||||
```
|
```
|
||||||
|
|
||||||
The production config includes:
|
Prod features:
|
||||||
- **Security headers** (CSP, XSS protection, etc.)
|
- Static asset caching, gzip, security headers, optional TLS.
|
||||||
- **Static asset caching** (1 year for JS/CSS/images)
|
|
||||||
- **Gzip compression** for better performance
|
|
||||||
- **SSL/HTTPS support** (commented out, ready to enable)
|
|
||||||
|
|
||||||
## Email Authorization
|
## Environment variables
|
||||||
|
|
||||||
FibDash includes built-in email authorization to restrict access to specific users.
|
- GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET
|
||||||
|
- REACT_APP_GOOGLE_CLIENT_ID
|
||||||
|
- JWT_SECRET
|
||||||
|
- AUTHORIZED_EMAILS (comma-separated; if unset/empty, no users can access)
|
||||||
|
- DB_SERVER, DB_DATABASE, DB_USERNAME, DB_PASSWORD, DB_PORT
|
||||||
|
- PORT, NODE_ENV
|
||||||
|
|
||||||
### Setup Authorization
|
## Data model (MSSQL)
|
||||||
|
|
||||||
1. **Add authorized emails to your `.env` file:**
|
Core tables referenced
|
||||||
```env
|
- eazybusiness.dbo.tZahlungsabgleichUmsatz (+ tUmsatzKontierung)
|
||||||
AUTHORIZED_EMAILS=admin@yourcompany.com,user1@yourcompany.com,user2@yourcompany.com
|
- tUmsatzBeleg (PDF storage), tPdfObjekt (PDF objects), tZahlungsabgleichUmsatzLink (links)
|
||||||
```
|
- fibdash.Kreditor (id, iban, name, kreditorId, is_banking)
|
||||||
|
- fibdash.Konto (id, konto, name)
|
||||||
|
- fibdash.BU (id, bu, name, vst)
|
||||||
|
- fibdash.BankingAccountTransactions (assignment records)
|
||||||
|
- fibdash.CSVTransactions (imported CSV rows)
|
||||||
|
|
||||||
2. **First email is admin**: The first email in the list automatically gets admin privileges
|
See SQL in src/database/schema.sql and src/database/csv_transactions_schema.sql for exact DDL.
|
||||||
|
|
||||||
3. **No authorization**: If `AUTHORIZED_EMAILS` is not set or empty, **NO USERS** can access the app
|
## Developer notes
|
||||||
|
|
||||||
### Admin Features
|
- Backend auto-detects DB availability. If DB env is missing, it logs a warning and continues. Endpoints that require DB will respond with 500/404 as applicable.
|
||||||
|
- data.csv at repo root is used by /api/data/months and /api/data/transactions/* for local CSV-based analysis.
|
||||||
|
- Matching logic between CSV and JTL uses exact amount and same-day date to mark matches.
|
||||||
|
- DATEV export uses well-formed header, consistent number formatting, and limited text field lengths.
|
||||||
|
|
||||||
Admins (first email in the authorized list) can:
|
## Scripts
|
||||||
- View all authorized emails: `GET /api/admin/authorized-emails`
|
|
||||||
- Add new authorized email: `POST /api/admin/authorized-emails`
|
|
||||||
- Remove authorized email: `DELETE /api/admin/authorized-emails/:email`
|
|
||||||
- View system info: `GET /api/admin/system-info`
|
|
||||||
|
|
||||||
**Note**: Admin changes via API are temporary. For permanent changes, update the `.env` file.
|
- npm run dev — run FE+BE
|
||||||
|
- npm run dev:frontend — FE only (HMR)
|
||||||
### Authorization Flow
|
- npm run dev:backend — BE only (nodemon)
|
||||||
|
- npm run build — FE production build
|
||||||
1. User signs in with Google
|
- npm run build:prod — build and start production server
|
||||||
2. Backend checks if email is in `AUTHORIZED_EMAILS` list
|
- npm start — build FE and start BE
|
||||||
3. If authorized → login succeeds
|
- npm run start:prod — start BE with existing build
|
||||||
4. If not authorized → "Access denied" error
|
- npm run setup:nginx — dev nginx setup
|
||||||
5. All API endpoints check authorization via middleware
|
- npm run nginx:test|reload|start|stop|status — helpers
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
### Frontend Development
|
|
||||||
|
|
||||||
- Frontend code is in the `client/` directory
|
|
||||||
- Uses Webpack dev server with hot module reload
|
|
||||||
- All components are class components (no function components)
|
|
||||||
- Material-UI for styling and components
|
|
||||||
- Authentication handled via Google SSO
|
|
||||||
|
|
||||||
### Backend Development
|
|
||||||
|
|
||||||
- Backend code is in the `src/` directory
|
|
||||||
- Express.js API server with CORS enabled
|
|
||||||
- JWT authentication middleware
|
|
||||||
- MSSQL database integration
|
|
||||||
- Auto-restart on file changes via nodemon
|
|
||||||
|
|
||||||
### API Endpoints
|
|
||||||
|
|
||||||
- `POST /api/auth/google` - Google OAuth login
|
|
||||||
- `GET /api/auth/verify` - Verify JWT token
|
|
||||||
- `POST /api/auth/logout` - Logout user
|
|
||||||
- `GET /api/dashboard` - Get dashboard data
|
|
||||||
- `GET /api/dashboard/user` - Get user-specific data
|
|
||||||
- `GET /api/health` - Health check
|
|
||||||
|
|
||||||
### Available Scripts
|
|
||||||
|
|
||||||
| Script | Description |
|
|
||||||
|--------|-------------|
|
|
||||||
| `npm run dev` | Start both frontend and backend in development mode |
|
|
||||||
| `npm run dev:frontend` | Start only the frontend webpack dev server |
|
|
||||||
| `npm run dev:backend` | Start only the backend API server with nodemon |
|
|
||||||
| `npm run build` | Create production build of frontend |
|
|
||||||
| `npm run build:prod` | Build and start production server |
|
|
||||||
| `npm start` | Build frontend and start production server |
|
|
||||||
| `npm run start:prod` | Start production server (assumes build exists) |
|
|
||||||
| `npm run setup:nginx` | Automatically setup nginx for development |
|
|
||||||
| `npm run nginx:test` | Test nginx configuration |
|
|
||||||
| `npm run nginx:reload` | Reload nginx configuration |
|
|
||||||
| `npm run nginx:start` | Start nginx service |
|
|
||||||
| `npm run nginx:stop` | Stop nginx service |
|
|
||||||
| `npm run nginx:status` | Check nginx service status |
|
|
||||||
|
|
||||||
## Production Deployment
|
|
||||||
|
|
||||||
### Single-Process Production Setup
|
|
||||||
|
|
||||||
In production, the Express backend builds the React frontend and serves it as static files. No separate frontend server is needed.
|
|
||||||
|
|
||||||
#### Build and Start Production Server
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Build frontend and start server in one command
|
|
||||||
npm start
|
|
||||||
|
|
||||||
# Or build and start separately
|
|
||||||
npm run build
|
|
||||||
npm run start:prod
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Production Architecture
|
|
||||||
|
|
||||||
```
|
|
||||||
Production Setup:
|
|
||||||
┌─────────────────────────────────────┐
|
|
||||||
│ Single Express Server (Port 5000) │
|
|
||||||
├─────────────────────────────────────┤
|
|
||||||
│ • Serves static React files │
|
|
||||||
│ • Handles API routes (/api/*) │
|
|
||||||
│ • Manages authentication │
|
|
||||||
│ • Connects to MSSQL database │
|
|
||||||
└─────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Production Features
|
|
||||||
|
|
||||||
- **Single Process**: One Node.js server handles everything
|
|
||||||
- **Static File Serving**: Built React app served with caching headers
|
|
||||||
- **Optimized Build**: Minified JS/CSS with content hashing
|
|
||||||
- **Code Splitting**: Vendor libraries separated for better caching
|
|
||||||
- **Production Security**: CSP headers and security optimizations
|
|
||||||
|
|
||||||
## Project Structure Details
|
|
||||||
|
|
||||||
### Frontend (`client/`)
|
|
||||||
|
|
||||||
- **Components**: All React components using class-based architecture
|
|
||||||
- **Services**: API communication classes
|
|
||||||
- **Material-UI**: Modern UI components with custom theming
|
|
||||||
- **Hot Reload**: Webpack dev server with HMR enabled
|
|
||||||
|
|
||||||
### Backend (`src/`)
|
|
||||||
|
|
||||||
- **Express Server**: RESTful API with middleware
|
|
||||||
- **Authentication**: Google OAuth + JWT tokens
|
|
||||||
- **Database**: MSSQL with connection pooling
|
|
||||||
- **Hot Reload**: Nodemon for automatic server restart
|
|
||||||
|
|
||||||
## Environment Variables
|
|
||||||
|
|
||||||
| Variable | Description | Required |
|
|
||||||
|----------|-------------|----------|
|
|
||||||
| `GOOGLE_CLIENT_ID` | Google OAuth Client ID (backend) | Yes |
|
|
||||||
| `GOOGLE_CLIENT_SECRET` | Google OAuth Client Secret (backend) | Yes |
|
|
||||||
| `REACT_APP_GOOGLE_CLIENT_ID` | Google OAuth Client ID (frontend) | Yes |
|
|
||||||
| `JWT_SECRET` | Secret for JWT token signing | Yes |
|
|
||||||
| `AUTHORIZED_EMAILS` | Comma-separated list of authorized email addresses | No* |
|
|
||||||
| `DB_SERVER` | MSSQL server address | Yes |
|
|
||||||
| `DB_DATABASE` | Database name | Yes |
|
|
||||||
| `DB_USERNAME` | Database username | Yes |
|
|
||||||
| `DB_PASSWORD` | Database password | Yes |
|
|
||||||
| `DB_PORT` | Database port (default: 1433) | No |
|
|
||||||
| `PORT` | API server port (default: 5000) | No |
|
|
||||||
| `NODE_ENV` | Environment mode | No |
|
|
||||||
|
|
||||||
*If `AUTHORIZED_EMAILS` is not set or empty, **NO USERS** can access the application. Only email addresses listed in `AUTHORIZED_EMAILS` can log in.
|
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
### Database Connection Issues
|
Database
|
||||||
|
- Ensure MSSQL reachable; set DB_* env; firewall allows 1433; check logs.
|
||||||
|
- Without DB, JTL and admin features won’t function; CSV-only features still work.
|
||||||
|
|
||||||
1. Verify your MSSQL server is running and accessible
|
Google OAuth
|
||||||
2. Check firewall settings allow connections on port 1433
|
- Ensure both GOOGLE_CLIENT_ID and REACT_APP_GOOGLE_CLIENT_ID set and equal.
|
||||||
3. Ensure your database credentials are correct
|
- Add dev/prod origins and redirects in Google Cloud Console.
|
||||||
4. Check the server logs for detailed error messages
|
- Use HTTPS in production and ensure CSP allows Google domains.
|
||||||
|
- See docs/GOOGLE_OAUTH_SETUP.md.
|
||||||
|
|
||||||
### Google OAuth Issues
|
CORS/Headers
|
||||||
|
- Dev CORS is open. Tighten in prod behind nginx.
|
||||||
|
|
||||||
1. Verify your Google Client ID is correctly set
|
Hot reload
|
||||||
2. Check that your domain is authorized in Google Cloud Console
|
- Make sure both dev servers run; clear cache; check proxy configs.
|
||||||
3. Ensure the OAuth consent screen is configured
|
|
||||||
4. Make sure you're testing on the correct domain/port
|
|
||||||
|
|
||||||
**For detailed Google OAuth troubleshooting, see: [docs/GOOGLE_OAUTH_SETUP.md](docs/GOOGLE_OAUTH_SETUP.md)**
|
|
||||||
|
|
||||||
Common fixes for CORS/GSI errors:
|
|
||||||
- Add your domain to Google Cloud Console authorized origins
|
|
||||||
- Ensure both `GOOGLE_CLIENT_ID` and `REACT_APP_GOOGLE_CLIENT_ID` are set
|
|
||||||
- Use the "Alternative Google Sign-In" button as fallback
|
|
||||||
- Consider enabling HTTPS for better OAuth compatibility
|
|
||||||
|
|
||||||
### Hot Reload Not Working
|
|
||||||
|
|
||||||
1. Check that both dev servers are running
|
|
||||||
2. Verify webpack proxy configuration
|
|
||||||
3. Clear browser cache and restart dev servers
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
ISC
|
ISC
|
||||||
@@ -70,9 +70,7 @@
|
|||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const betragHeader = document.querySelector('.ag-header-cell[col-id="numericAmount"]');
|
const betragHeader = document.querySelector('.ag-header-cell[col-id="numericAmount"]');
|
||||||
if (betragHeader) {
|
if (betragHeader) {
|
||||||
console.log('Found Betrag header:', betragHeader);
|
|
||||||
console.log('Header classes:', betragHeader.className);
|
console.log('Header classes:', betragHeader.className);
|
||||||
console.log('Header HTML:', betragHeader.innerHTML);
|
|
||||||
} else {
|
} else {
|
||||||
console.log('Could not find Betrag header with col-id="numericAmount"');
|
console.log('Could not find Betrag header with col-id="numericAmount"');
|
||||||
// Try to find it by text content
|
// Try to find it by text content
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
import React, { Component } from 'react';
|
import React, { Component } from 'react';
|
||||||
import { ThemeProvider, createTheme } from '@mui/material/styles';
|
import { ThemeProvider, createTheme } from '@mui/material/styles';
|
||||||
import CssBaseline from '@mui/material/CssBaseline';
|
import CssBaseline from '@mui/material/CssBaseline';
|
||||||
import { Container, AppBar, Toolbar, Typography, Button, Box } from '@mui/material';
|
import { Container, AppBar, Toolbar, Typography, Button, Box, Tabs, Tab, Badge, Chip, Divider, Snackbar, Alert, LinearProgress, Tooltip, CircularProgress } from '@mui/material';
|
||||||
import LoginIcon from '@mui/icons-material/Login';
|
import LoginIcon from '@mui/icons-material/Login';
|
||||||
import DashboardIcon from '@mui/icons-material/Dashboard';
|
import DashboardIcon from '@mui/icons-material/Dashboard';
|
||||||
import DownloadIcon from '@mui/icons-material/Download';
|
import DownloadIcon from '@mui/icons-material/Download';
|
||||||
|
import TableChart from '@mui/icons-material/TableChart';
|
||||||
|
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
|
||||||
|
import DocumentScannerIcon from '@mui/icons-material/DocumentScanner';
|
||||||
|
import ExtractIcon from '@mui/icons-material/TextSnippet';
|
||||||
|
import EmailIcon from '@mui/icons-material/Email';
|
||||||
|
import UploadIcon from '@mui/icons-material/Upload';
|
||||||
import AuthService from './services/AuthService';
|
import AuthService from './services/AuthService';
|
||||||
import DataViewer from './components/DataViewer';
|
import DataViewer from './components/DataViewer';
|
||||||
import Login from './components/Login';
|
import Login from './components/Login';
|
||||||
|
import OAuthCallback from './components/OAuthCallback';
|
||||||
|
|
||||||
const theme = createTheme({
|
const theme = createTheme({
|
||||||
palette: {
|
palette: {
|
||||||
@@ -29,6 +36,19 @@ class App extends Component {
|
|||||||
user: null,
|
user: null,
|
||||||
loading: true,
|
loading: true,
|
||||||
exportData: null, // { selectedMonth, canExport, onExport }
|
exportData: null, // { selectedMonth, canExport, onExport }
|
||||||
|
currentView: 'dashboard', // 'dashboard' or 'tables'
|
||||||
|
documentStatus: null,
|
||||||
|
processingStatus: {
|
||||||
|
markdown: false,
|
||||||
|
extraction: false,
|
||||||
|
datevSync: false,
|
||||||
|
datevUpload: false
|
||||||
|
},
|
||||||
|
snackbar: {
|
||||||
|
open: false,
|
||||||
|
message: '',
|
||||||
|
severity: 'info' // 'success', 'error', 'warning', 'info'
|
||||||
|
}
|
||||||
};
|
};
|
||||||
this.authService = new AuthService();
|
this.authService = new AuthService();
|
||||||
}
|
}
|
||||||
@@ -37,6 +57,15 @@ class App extends Component {
|
|||||||
this.checkAuthStatus();
|
this.checkAuthStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevState) {
|
||||||
|
// Clear targetTab after navigation is complete
|
||||||
|
if (this.state.targetTab && prevState.currentView !== this.state.currentView) {
|
||||||
|
setTimeout(() => {
|
||||||
|
this.setState({ targetTab: null });
|
||||||
|
}, 100); // Small delay to ensure navigation completes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
checkAuthStatus = async () => {
|
checkAuthStatus = async () => {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem('token');
|
const token = localStorage.getItem('token');
|
||||||
@@ -44,6 +73,7 @@ class App extends Component {
|
|||||||
const user = await this.authService.verifyToken(token);
|
const user = await this.authService.verifyToken(token);
|
||||||
if (user) {
|
if (user) {
|
||||||
this.setState({ isAuthenticated: true, user, loading: false });
|
this.setState({ isAuthenticated: true, user, loading: false });
|
||||||
|
this.fetchDocumentStatus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,6 +90,7 @@ class App extends Component {
|
|||||||
if (result.success) {
|
if (result.success) {
|
||||||
localStorage.setItem('token', result.token);
|
localStorage.setItem('token', result.token);
|
||||||
this.setState({ isAuthenticated: true, user: result.user });
|
this.setState({ isAuthenticated: true, user: result.user });
|
||||||
|
this.fetchDocumentStatus();
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Login failed:', error);
|
console.error('Login failed:', error);
|
||||||
@@ -77,8 +108,139 @@ class App extends Component {
|
|||||||
this.setState({ exportData });
|
this.setState({ exportData });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
handleViewChange = (event, newValue) => {
|
||||||
|
this.setState({ currentView: newValue });
|
||||||
|
};
|
||||||
|
|
||||||
|
showSnackbar = (message, severity = 'info') => {
|
||||||
|
this.setState({
|
||||||
|
snackbar: {
|
||||||
|
open: true,
|
||||||
|
message,
|
||||||
|
severity
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
handleSnackbarClose = (event, reason) => {
|
||||||
|
if (reason === 'clickaway') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.setState({
|
||||||
|
snackbar: {
|
||||||
|
...this.state.snackbar,
|
||||||
|
open: false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchDocumentStatus = async () => {
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (!token) {
|
||||||
|
console.log('No token found for document status');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Fetching document status...');
|
||||||
|
const response = await fetch('/api/data/document-status', {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const status = await response.json();
|
||||||
|
console.log('Document status received:', status);
|
||||||
|
this.setState({ documentStatus: status });
|
||||||
|
} else {
|
||||||
|
console.error('Failed to fetch document status:', response.status, await response.text());
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching document status:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleProcessing = async (processType) => {
|
||||||
|
if (this.state.processingStatus[processType]) {
|
||||||
|
return; // Already processing
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle datev upload navigation
|
||||||
|
if (processType === 'datev-upload') {
|
||||||
|
this.setState({
|
||||||
|
currentView: 'tables',
|
||||||
|
targetTab: {
|
||||||
|
level1: 3, // CSV Import tab
|
||||||
|
level2: 'DATEV_LINKS' // DATEV Beleglinks tab
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there are documents to process
|
||||||
|
const statusKey = processType === 'datev-sync' ? 'needDatevSync' :
|
||||||
|
processType === 'extraction' ? 'needExtraction' : 'needMarkdown';
|
||||||
|
|
||||||
|
if (!this.state.documentStatus || this.state.documentStatus[statusKey] === 0) {
|
||||||
|
this.showSnackbar(`No documents need ${processType} processing at this time.`, 'info');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.setState(prevState => ({
|
||||||
|
processingStatus: {
|
||||||
|
...prevState.processingStatus,
|
||||||
|
[processType]: true
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (!token) return;
|
||||||
|
|
||||||
|
const response = await fetch(`/api/data/process-${processType}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const result = await response.json();
|
||||||
|
console.log(`${processType} processing result:`, result);
|
||||||
|
this.showSnackbar(`${processType} processing completed successfully!`, 'success');
|
||||||
|
// Refresh document status after successful processing
|
||||||
|
await this.fetchDocumentStatus();
|
||||||
|
} else {
|
||||||
|
const error = await response.json();
|
||||||
|
console.error(`Failed to process ${processType}:`, error);
|
||||||
|
this.showSnackbar(`Failed to process ${processType}: ${error.error || response.status}`, 'error');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error processing ${processType}:`, error);
|
||||||
|
this.showSnackbar(`Error processing ${processType}: ${error.message}`, 'error');
|
||||||
|
} finally {
|
||||||
|
this.setState(prevState => ({
|
||||||
|
processingStatus: {
|
||||||
|
...prevState.processingStatus,
|
||||||
|
[processType]: false
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
isOAuthCallback = () => {
|
||||||
|
return window.location.pathname === '/auth/callback';
|
||||||
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { isAuthenticated, user, loading } = this.state;
|
const { isAuthenticated, user, loading, currentView, documentStatus, processingStatus, snackbar } = this.state;
|
||||||
|
|
||||||
|
// Debug logging
|
||||||
|
console.log('App render - documentStatus:', documentStatus);
|
||||||
|
console.log('App render - isAuthenticated:', isAuthenticated);
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
@@ -99,7 +261,7 @@ class App extends Component {
|
|||||||
<AppBar position="static">
|
<AppBar position="static">
|
||||||
<Toolbar>
|
<Toolbar>
|
||||||
<DashboardIcon sx={{ mr: { xs: 1, sm: 2 } }} />
|
<DashboardIcon sx={{ mr: { xs: 1, sm: 2 } }} />
|
||||||
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
|
<Typography variant="h6" component="div" sx={{ mr: 3 }}>
|
||||||
FibDash
|
FibDash
|
||||||
</Typography>
|
</Typography>
|
||||||
{isAuthenticated && user && (
|
{isAuthenticated && user && (
|
||||||
@@ -107,12 +269,148 @@ class App extends Component {
|
|||||||
<Typography
|
<Typography
|
||||||
variant="body2"
|
variant="body2"
|
||||||
sx={{
|
sx={{
|
||||||
mr: { xs: 1, sm: 2 },
|
mr: { xs: 2, sm: 3 },
|
||||||
display: { xs: 'none', sm: 'block' }
|
display: { xs: 'none', sm: 'block' }
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Willkommen, {user.name}
|
Willkommen, {user.name}
|
||||||
</Typography>
|
</Typography>
|
||||||
|
<Tabs
|
||||||
|
value={currentView}
|
||||||
|
onChange={this.handleViewChange}
|
||||||
|
sx={{
|
||||||
|
mr: 'auto',
|
||||||
|
'& .MuiTab-root': {
|
||||||
|
color: 'rgba(255, 255, 255, 0.7)',
|
||||||
|
minHeight: 48,
|
||||||
|
'&.Mui-selected': {
|
||||||
|
color: 'white'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'& .MuiTabs-indicator': {
|
||||||
|
backgroundColor: 'white'
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Tab
|
||||||
|
icon={<DashboardIcon />}
|
||||||
|
label="Dashboard"
|
||||||
|
value="dashboard"
|
||||||
|
sx={{ minHeight: 48 }}
|
||||||
|
/>
|
||||||
|
<Tab
|
||||||
|
icon={<TableChart />}
|
||||||
|
label="Stammdaten"
|
||||||
|
value="tables"
|
||||||
|
sx={{ minHeight: 48 }}
|
||||||
|
/>
|
||||||
|
</Tabs>
|
||||||
|
<Divider orientation="vertical" flexItem sx={{ mx: 2, backgroundColor: 'rgba(255, 255, 255, 0.3)' }} />
|
||||||
|
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||||
|
<Tooltip title={processingStatus.markdown ? 'Running markdown conversion… this can take a while' : 'Process markdown conversion'} arrow>
|
||||||
|
<span>
|
||||||
|
<Button
|
||||||
|
color="inherit"
|
||||||
|
size="small"
|
||||||
|
onClick={() => this.handleProcessing('markdown')}
|
||||||
|
disabled={processingStatus.markdown || !documentStatus}
|
||||||
|
sx={{
|
||||||
|
minWidth: 'auto',
|
||||||
|
px: 1,
|
||||||
|
'&:hover': { backgroundColor: 'rgba(255, 255, 255, 0.1)' }
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
badgeContent={documentStatus?.needMarkdown || 0}
|
||||||
|
color={documentStatus?.needMarkdown > 0 ? "error" : "default"}
|
||||||
|
max={999999}
|
||||||
|
sx={{ mr: 0.5 }}
|
||||||
|
>
|
||||||
|
<DocumentScannerIcon fontSize="small" />
|
||||||
|
</Badge>
|
||||||
|
{processingStatus.markdown && (
|
||||||
|
<CircularProgress size={14} color="inherit" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title={processingStatus.extraction ? 'Running data extraction… this can take a while' : 'Process data extraction'} arrow>
|
||||||
|
<span>
|
||||||
|
<Button
|
||||||
|
color="inherit"
|
||||||
|
size="small"
|
||||||
|
onClick={() => this.handleProcessing('extraction')}
|
||||||
|
disabled={processingStatus.extraction || !documentStatus}
|
||||||
|
sx={{
|
||||||
|
minWidth: 'auto',
|
||||||
|
px: 1,
|
||||||
|
'&:hover': { backgroundColor: 'rgba(255, 255, 255, 0.1)' }
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
badgeContent={documentStatus?.needExtraction || 0}
|
||||||
|
color={documentStatus?.needExtraction > 0 ? "warning" : "default"}
|
||||||
|
max={999999}
|
||||||
|
sx={{ mr: 0.5 }}
|
||||||
|
>
|
||||||
|
<ExtractIcon fontSize="small" />
|
||||||
|
</Badge>
|
||||||
|
{processingStatus.extraction && (
|
||||||
|
<CircularProgress size={14} color="inherit" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title={processingStatus.datevSync ? 'Running DATEV sync… this can take a while' : 'Process Datev sync'} arrow>
|
||||||
|
<span>
|
||||||
|
<Button
|
||||||
|
color="inherit"
|
||||||
|
size="small"
|
||||||
|
onClick={() => this.handleProcessing('datev-sync')}
|
||||||
|
disabled={processingStatus.datevSync || !documentStatus}
|
||||||
|
sx={{
|
||||||
|
minWidth: 'auto',
|
||||||
|
px: 1,
|
||||||
|
'&:hover': { backgroundColor: 'rgba(255, 255, 255, 0.1)' }
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
badgeContent={documentStatus?.needDatevSync || 0}
|
||||||
|
color={documentStatus?.needDatevSync > 0 ? "info" : "default"}
|
||||||
|
max={999999}
|
||||||
|
sx={{ mr: 0.5 }}
|
||||||
|
>
|
||||||
|
<EmailIcon fontSize="small" />
|
||||||
|
</Badge>
|
||||||
|
{processingStatus.datevSync && (
|
||||||
|
<CircularProgress size={14} color="inherit" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
|
</Tooltip>
|
||||||
|
<Button
|
||||||
|
color="inherit"
|
||||||
|
size="small"
|
||||||
|
onClick={() => this.handleProcessing('datev-upload')}
|
||||||
|
disabled={processingStatus.datevUpload || !documentStatus}
|
||||||
|
sx={{
|
||||||
|
minWidth: 'auto',
|
||||||
|
px: 1,
|
||||||
|
'&:hover': { backgroundColor: 'rgba(255, 255, 255, 0.1)' }
|
||||||
|
}}
|
||||||
|
title="Process Datev CSV upload"
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
badgeContent={documentStatus?.needDatevUpload || 0}
|
||||||
|
color={documentStatus?.needDatevUpload > 0 ? "secondary" : "default"}
|
||||||
|
max={999999}
|
||||||
|
sx={{ mr: 0.5 }}
|
||||||
|
>
|
||||||
|
<UploadIcon fontSize="small" />
|
||||||
|
</Badge>
|
||||||
|
{processingStatus.datevUpload && <PlayArrowIcon fontSize="small" />}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
{this.state.exportData && (
|
{this.state.exportData && (
|
||||||
<Button
|
<Button
|
||||||
color="inherit"
|
color="inherit"
|
||||||
@@ -148,17 +446,44 @@ class App extends Component {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Toolbar>
|
</Toolbar>
|
||||||
|
{(processingStatus.markdown || processingStatus.extraction || processingStatus.datevSync) && (
|
||||||
|
<LinearProgress color="secondary" />
|
||||||
|
)}
|
||||||
</AppBar>
|
</AppBar>
|
||||||
|
|
||||||
<Box sx={{ height: 'calc(100vh - 64px)', display: 'flex', flexDirection: 'column' }}>
|
<Box sx={{ height: 'calc(100vh - 64px)', display: 'flex', flexDirection: 'column' }}>
|
||||||
<Container maxWidth={false} sx={{ mt: 4, flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', width: '100%' }}>
|
<Container maxWidth={false} sx={{ mt: 4, flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', width: '100%' }}>
|
||||||
{isAuthenticated ? (
|
{this.isOAuthCallback() ? (
|
||||||
<DataViewer user={user} onUpdateExportData={this.updateExportData} />
|
<OAuthCallback />
|
||||||
|
) : isAuthenticated ? (
|
||||||
|
<DataViewer
|
||||||
|
user={user}
|
||||||
|
onUpdateExportData={this.updateExportData}
|
||||||
|
currentView={currentView}
|
||||||
|
onViewChange={this.handleViewChange}
|
||||||
|
targetTab={this.state.targetTab}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Login onLogin={this.handleLogin} />
|
<Login onLogin={this.handleLogin} />
|
||||||
)}
|
)}
|
||||||
</Container>
|
</Container>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
<Snackbar
|
||||||
|
open={snackbar.open}
|
||||||
|
autoHideDuration={6000}
|
||||||
|
onClose={this.handleSnackbarClose}
|
||||||
|
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
||||||
|
>
|
||||||
|
<Alert
|
||||||
|
onClose={this.handleSnackbarClose}
|
||||||
|
severity={snackbar.severity}
|
||||||
|
variant="filled"
|
||||||
|
sx={{ width: '100%' }}
|
||||||
|
>
|
||||||
|
{snackbar.message}
|
||||||
|
</Alert>
|
||||||
|
</Snackbar>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
550
client/src/components/AccountingItemsManager.js
Normal file
550
client/src/components/AccountingItemsManager.js
Normal file
@@ -0,0 +1,550 @@
|
|||||||
|
import React, { Component } from 'react';
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
Typography,
|
||||||
|
Button,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableContainer,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
Paper,
|
||||||
|
TextField,
|
||||||
|
Select,
|
||||||
|
MenuItem,
|
||||||
|
FormControl,
|
||||||
|
InputLabel,
|
||||||
|
IconButton,
|
||||||
|
Dialog,
|
||||||
|
DialogTitle,
|
||||||
|
DialogContent,
|
||||||
|
DialogActions,
|
||||||
|
Alert,
|
||||||
|
Chip
|
||||||
|
} from '@mui/material';
|
||||||
|
import {
|
||||||
|
Add as AddIcon,
|
||||||
|
Delete as DeleteIcon,
|
||||||
|
Edit as EditIcon,
|
||||||
|
Save as SaveIcon,
|
||||||
|
Cancel as CancelIcon
|
||||||
|
} from '@mui/icons-material';
|
||||||
|
import AuthService from '../services/AuthService';
|
||||||
|
|
||||||
|
class AccountingItemsManager extends Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
|
||||||
|
this.state = {
|
||||||
|
accountingItems: [],
|
||||||
|
kontos: [],
|
||||||
|
bus: [],
|
||||||
|
loading: true,
|
||||||
|
editingItem: null,
|
||||||
|
showCreateDialog: false,
|
||||||
|
showCreateKontoDialog: false,
|
||||||
|
jtlKontierung: null,
|
||||||
|
newItem: {
|
||||||
|
umsatz_brutto: '',
|
||||||
|
soll_haben_kz: 'S',
|
||||||
|
konto: '',
|
||||||
|
bu: '',
|
||||||
|
rechnungsnummer: '',
|
||||||
|
buchungstext: ''
|
||||||
|
},
|
||||||
|
newKonto: {
|
||||||
|
konto: '',
|
||||||
|
name: ''
|
||||||
|
},
|
||||||
|
error: null,
|
||||||
|
saving: false
|
||||||
|
};
|
||||||
|
|
||||||
|
this.authService = new AuthService();
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
this.loadData();
|
||||||
|
this.loadJtlKontierung();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadData = async () => {
|
||||||
|
try {
|
||||||
|
// Load accounting items for this transaction
|
||||||
|
await this.loadAccountingItems();
|
||||||
|
|
||||||
|
// Load Konto and BU options
|
||||||
|
await Promise.all([
|
||||||
|
this.loadKontos(),
|
||||||
|
this.loadBUs()
|
||||||
|
]);
|
||||||
|
|
||||||
|
this.setState({ loading: false });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading data:', error);
|
||||||
|
this.setState({
|
||||||
|
error: 'Fehler beim Laden der Daten',
|
||||||
|
loading: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadJtlKontierung = async () => {
|
||||||
|
try {
|
||||||
|
const { transaction } = this.props;
|
||||||
|
if (!transaction || !transaction.jtlId) {
|
||||||
|
this.setState({ jtlKontierung: undefined });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await this.authService.apiCall(`/data/jtl-kontierung/${transaction.jtlId}`);
|
||||||
|
if (!response) return;
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const data = await response.json();
|
||||||
|
this.setState({ jtlKontierung: data });
|
||||||
|
} else {
|
||||||
|
const err = await response.json();
|
||||||
|
console.error('Failed to load JTL Kontierung:', err);
|
||||||
|
this.setState({ jtlKontierung: undefined });
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error loading JTL Kontierung:', e);
|
||||||
|
this.setState({ jtlKontierung: undefined });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadAccountingItems = async () => {
|
||||||
|
const { transaction } = this.props;
|
||||||
|
if (!transaction?.id) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.authService.apiCall(`/data/accounting-items/${transaction.id}`);
|
||||||
|
if (response && response.ok) {
|
||||||
|
const items = await response.json();
|
||||||
|
this.setState({ accountingItems: items });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading accounting items:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadKontos = async () => {
|
||||||
|
try {
|
||||||
|
const response = await this.authService.apiCall('/data/kontos');
|
||||||
|
if (response && response.ok) {
|
||||||
|
const kontos = await response.json();
|
||||||
|
this.setState({ kontos });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading kontos:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadBUs = async () => {
|
||||||
|
try {
|
||||||
|
const response = await this.authService.apiCall('/data/bus');
|
||||||
|
if (response && response.ok) {
|
||||||
|
const bus = await response.json();
|
||||||
|
this.setState({ bus });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading BUs:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleCreateItem = () => {
|
||||||
|
const { transaction } = this.props;
|
||||||
|
this.setState({
|
||||||
|
showCreateDialog: true,
|
||||||
|
newItem: {
|
||||||
|
umsatz_brutto: Math.abs(transaction.numericAmount || 0).toString(),
|
||||||
|
soll_haben_kz: (transaction.numericAmount || 0) >= 0 ? 'H' : 'S',
|
||||||
|
konto: '',
|
||||||
|
bu: '',
|
||||||
|
rechnungsnummer: '',
|
||||||
|
buchungstext: transaction.description || ''
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
handleSaveItem = async () => {
|
||||||
|
const { transaction } = this.props;
|
||||||
|
const { newItem } = this.state;
|
||||||
|
|
||||||
|
if (!newItem.umsatz_brutto || !newItem.konto) {
|
||||||
|
this.setState({ error: 'Betrag und Konto sind erforderlich' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.setState({ saving: true, error: null });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const itemData = {
|
||||||
|
...newItem,
|
||||||
|
transaction_id: transaction.isFromCSV ? null : transaction.id,
|
||||||
|
csv_transaction_id: transaction.isFromCSV ? transaction.id : null,
|
||||||
|
buchungsdatum: transaction.parsed_date || new Date().toISOString().split('T')[0]
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.authService.apiCall('/data/accounting-items', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(itemData)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response && response.ok) {
|
||||||
|
await this.loadAccountingItems();
|
||||||
|
this.setState({
|
||||||
|
showCreateDialog: false,
|
||||||
|
saving: false,
|
||||||
|
newItem: {
|
||||||
|
umsatz_brutto: '',
|
||||||
|
soll_haben_kz: 'S',
|
||||||
|
konto: '',
|
||||||
|
bu: '',
|
||||||
|
rechnungsnummer: '',
|
||||||
|
buchungstext: ''
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const errorData = await response.json();
|
||||||
|
this.setState({
|
||||||
|
error: errorData.error || 'Fehler beim Speichern',
|
||||||
|
saving: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving accounting item:', error);
|
||||||
|
this.setState({
|
||||||
|
error: 'Fehler beim Speichern',
|
||||||
|
saving: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleCreateKonto = async () => {
|
||||||
|
const { newKonto } = this.state;
|
||||||
|
|
||||||
|
if (!newKonto.konto || !newKonto.name) {
|
||||||
|
this.setState({ error: 'Konto-Nummer und Name sind erforderlich' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.setState({ saving: true, error: null });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.authService.apiCall('/data/kontos', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(newKonto)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response && response.ok) {
|
||||||
|
await this.loadKontos();
|
||||||
|
this.setState({
|
||||||
|
showCreateKontoDialog: false,
|
||||||
|
saving: false,
|
||||||
|
newKonto: { konto: '', name: '' }
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const errorData = await response.json();
|
||||||
|
this.setState({
|
||||||
|
error: errorData.error || 'Fehler beim Erstellen des Kontos',
|
||||||
|
saving: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating konto:', error);
|
||||||
|
this.setState({
|
||||||
|
error: 'Fehler beim Erstellen des Kontos',
|
||||||
|
saving: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleDeleteItem = async (itemId) => {
|
||||||
|
if (!window.confirm('Buchungsposten wirklich löschen?')) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.authService.apiCall(`/data/accounting-items/${itemId}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response && response.ok) {
|
||||||
|
await this.loadAccountingItems();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting accounting item:', error);
|
||||||
|
this.setState({ error: 'Fehler beim Löschen' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
calculateTotal = () => {
|
||||||
|
return this.state.accountingItems.reduce((sum, item) => {
|
||||||
|
const amount = parseFloat(item.umsatz_brutto) || 0;
|
||||||
|
return sum + (item.soll_haben_kz === 'S' ? amount : -amount);
|
||||||
|
}, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const { transaction } = this.props;
|
||||||
|
const {
|
||||||
|
accountingItems,
|
||||||
|
kontos,
|
||||||
|
bus,
|
||||||
|
loading,
|
||||||
|
showCreateDialog,
|
||||||
|
showCreateKontoDialog,
|
||||||
|
newItem,
|
||||||
|
newKonto,
|
||||||
|
error,
|
||||||
|
saving
|
||||||
|
} = this.state;
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <Typography>Lade Buchungsdaten...</Typography>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const transactionAmount = transaction.numericAmount || 0;
|
||||||
|
const currentTotal = this.calculateTotal();
|
||||||
|
const isBalanced = Math.abs(currentTotal - Math.abs(transactionAmount)) < 0.01;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
|
||||||
|
<Typography variant="h6">
|
||||||
|
Buchungsposten
|
||||||
|
</Typography>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
startIcon={<AddIcon />}
|
||||||
|
onClick={this.handleCreateItem}
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
Hinzufügen
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Box sx={{ mb: 2, p: 2, bgcolor: isBalanced ? '#e8f5e8' : '#fff3e0', borderRadius: 1 }}>
|
||||||
|
<Typography variant="body2">
|
||||||
|
<strong>Transaktionsbetrag:</strong> {Math.abs(transactionAmount).toFixed(2)} €
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2">
|
||||||
|
<strong>Summe Buchungsposten:</strong> {Math.abs(currentTotal).toFixed(2)} €
|
||||||
|
</Typography>
|
||||||
|
<Chip
|
||||||
|
label={isBalanced ? "✅ Ausgeglichen" : "⚠️ Nicht ausgeglichen"}
|
||||||
|
color={isBalanced ? "success" : "warning"}
|
||||||
|
size="small"
|
||||||
|
sx={{ mt: 1 }}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{transaction?.jtlId && (
|
||||||
|
<Box sx={{ mb: 2, p: 2, border: '1px dashed #999', borderRadius: 1 }}>
|
||||||
|
<Typography variant="subtitle2">Debug: tUmsatzKontierung.data</Typography>
|
||||||
|
<Typography variant="caption" component="div" sx={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
|
||||||
|
{this.state.jtlKontierung === undefined
|
||||||
|
? 'undefined'
|
||||||
|
: this.state.jtlKontierung === null
|
||||||
|
? 'null'
|
||||||
|
: typeof this.state.jtlKontierung === 'object'
|
||||||
|
? JSON.stringify(this.state.jtlKontierung, null, 2)
|
||||||
|
: String(this.state.jtlKontierung)}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<TableContainer component={Paper}>
|
||||||
|
<Table size="small">
|
||||||
|
<TableHead>
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>Betrag</TableCell>
|
||||||
|
<TableCell>S/H</TableCell>
|
||||||
|
<TableCell>Konto</TableCell>
|
||||||
|
<TableCell>BU</TableCell>
|
||||||
|
<TableCell>Buchungstext</TableCell>
|
||||||
|
<TableCell>Aktionen</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
</TableHead>
|
||||||
|
<TableBody>
|
||||||
|
{accountingItems.map((item) => (
|
||||||
|
<TableRow key={item.id}>
|
||||||
|
<TableCell>{parseFloat(item.umsatz_brutto).toFixed(2)} €</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Chip
|
||||||
|
label={item.soll_haben_kz}
|
||||||
|
color={item.soll_haben_kz === 'S' ? 'primary' : 'secondary'}
|
||||||
|
size="small"
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{item.konto} - {item.konto_name}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{item.bu ? `${item.bu} - ${item.bu_name}` : '-'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{item.buchungstext || '-'}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
onClick={() => this.handleDeleteItem(item.id)}
|
||||||
|
color="error"
|
||||||
|
>
|
||||||
|
<DeleteIcon />
|
||||||
|
</IconButton>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))}
|
||||||
|
{accountingItems.length === 0 && (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={6} align="center">
|
||||||
|
<Typography color="textSecondary">
|
||||||
|
Keine Buchungsposten vorhanden
|
||||||
|
</Typography>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</TableContainer>
|
||||||
|
|
||||||
|
{/* Create Item Dialog */}
|
||||||
|
<Dialog open={showCreateDialog} onClose={() => this.setState({ showCreateDialog: false })} maxWidth="sm" fullWidth>
|
||||||
|
<DialogTitle>Neuen Buchungsposten erstellen</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 1 }}>
|
||||||
|
<TextField
|
||||||
|
label="Betrag"
|
||||||
|
type="number"
|
||||||
|
value={newItem.umsatz_brutto}
|
||||||
|
onChange={(e) => this.setState({
|
||||||
|
newItem: { ...newItem, umsatz_brutto: e.target.value }
|
||||||
|
})}
|
||||||
|
required
|
||||||
|
fullWidth
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormControl fullWidth>
|
||||||
|
<InputLabel>Soll/Haben</InputLabel>
|
||||||
|
<Select
|
||||||
|
value={newItem.soll_haben_kz}
|
||||||
|
onChange={(e) => this.setState({
|
||||||
|
newItem: { ...newItem, soll_haben_kz: e.target.value }
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<MenuItem value="S">Soll (S)</MenuItem>
|
||||||
|
<MenuItem value="H">Haben (H)</MenuItem>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-end' }}>
|
||||||
|
<FormControl fullWidth>
|
||||||
|
<InputLabel>Konto</InputLabel>
|
||||||
|
<Select
|
||||||
|
value={newItem.konto}
|
||||||
|
onChange={(e) => this.setState({
|
||||||
|
newItem: { ...newItem, konto: e.target.value }
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
{kontos.map((konto) => (
|
||||||
|
<MenuItem key={konto.id} value={konto.konto}>
|
||||||
|
{konto.konto} - {konto.name}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => this.setState({ showCreateKontoDialog: true })}
|
||||||
|
sx={{ minWidth: 'auto', px: 1 }}
|
||||||
|
>
|
||||||
|
<AddIcon />
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<FormControl fullWidth>
|
||||||
|
<InputLabel>BU (Steuercode)</InputLabel>
|
||||||
|
<Select
|
||||||
|
value={newItem.bu}
|
||||||
|
onChange={(e) => this.setState({
|
||||||
|
newItem: { ...newItem, bu: e.target.value }
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<MenuItem value="">Kein BU</MenuItem>
|
||||||
|
{bus.map((bu) => (
|
||||||
|
<MenuItem key={bu.id} value={bu.bu}>
|
||||||
|
{bu.bu} - {bu.name} ({bu.vst}%)
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
label="Buchungstext"
|
||||||
|
value={newItem.buchungstext}
|
||||||
|
onChange={(e) => this.setState({
|
||||||
|
newItem: { ...newItem, buchungstext: e.target.value }
|
||||||
|
})}
|
||||||
|
fullWidth
|
||||||
|
multiline
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={() => this.setState({ showCreateDialog: false })}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button onClick={this.handleSaveItem} variant="contained" disabled={saving}>
|
||||||
|
{saving ? 'Speichern...' : 'Speichern'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Create Konto Dialog */}
|
||||||
|
<Dialog open={showCreateKontoDialog} onClose={() => this.setState({ showCreateKontoDialog: false })} maxWidth="xs" fullWidth>
|
||||||
|
<DialogTitle>Neues Konto erstellen</DialogTitle>
|
||||||
|
<DialogContent>
|
||||||
|
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 1 }}>
|
||||||
|
<TextField
|
||||||
|
label="Konto-Nummer"
|
||||||
|
value={newKonto.konto}
|
||||||
|
onChange={(e) => this.setState({
|
||||||
|
newKonto: { ...newKonto, konto: e.target.value }
|
||||||
|
})}
|
||||||
|
required
|
||||||
|
fullWidth
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
label="Konto-Name"
|
||||||
|
value={newKonto.name}
|
||||||
|
onChange={(e) => this.setState({
|
||||||
|
newKonto: { ...newKonto, name: e.target.value }
|
||||||
|
})}
|
||||||
|
required
|
||||||
|
fullWidth
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={() => this.setState({ showCreateKontoDialog: false })}>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
<Button onClick={this.handleCreateKonto} variant="contained" disabled={saving}>
|
||||||
|
{saving ? 'Erstellen...' : 'Erstellen'}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AccountingItemsManager;
|
||||||
429
client/src/components/BankingKreditorSelector.js
Normal file
429
client/src/components/BankingKreditorSelector.js
Normal file
@@ -0,0 +1,429 @@
|
|||||||
|
import React, { Component } from 'react';
|
||||||
|
import {
|
||||||
|
Box,
|
||||||
|
FormControl,
|
||||||
|
InputLabel,
|
||||||
|
Select,
|
||||||
|
MenuItem,
|
||||||
|
TextField,
|
||||||
|
Button,
|
||||||
|
Alert,
|
||||||
|
CircularProgress,
|
||||||
|
Typography,
|
||||||
|
} from '@mui/material';
|
||||||
|
import { Add as AddIcon } from '@mui/icons-material';
|
||||||
|
import AuthService from '../services/AuthService';
|
||||||
|
import KreditorService from '../services/KreditorService';
|
||||||
|
|
||||||
|
class BankingKreditorSelector extends Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
this.state = {
|
||||||
|
assignableKreditors: [],
|
||||||
|
selectedKreditorId: '',
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
saving: false,
|
||||||
|
showCreateKreditor: false,
|
||||||
|
newKreditor: {
|
||||||
|
name: '',
|
||||||
|
kreditorId: ''
|
||||||
|
},
|
||||||
|
creating: false,
|
||||||
|
validationErrors: []
|
||||||
|
};
|
||||||
|
this.authService = new AuthService();
|
||||||
|
this.kreditorService = new KreditorService();
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
this.loadAssignableKreditors();
|
||||||
|
this.loadExistingAssignment();
|
||||||
|
|
||||||
|
// Pre-fill new kreditor data with description (actual company name) instead of Beguenstigter (banking service name)
|
||||||
|
const prefilledName = this.props.transaction?.description || '';
|
||||||
|
if (prefilledName) {
|
||||||
|
this.setState({
|
||||||
|
newKreditor: {
|
||||||
|
...this.state.newKreditor,
|
||||||
|
name: prefilledName
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps) {
|
||||||
|
// Reload data when transaction changes (only for database transactions)
|
||||||
|
const currentTransactionId = this.props.transaction?.id;
|
||||||
|
const prevTransactionId = prevProps.transaction?.id;
|
||||||
|
|
||||||
|
console.log('componentDidUpdate - current:', currentTransactionId, 'prev:', prevTransactionId);
|
||||||
|
|
||||||
|
if (currentTransactionId !== prevTransactionId) {
|
||||||
|
console.log('Transaction changed, reloading assignment');
|
||||||
|
this.loadExistingAssignment();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadAssignableKreditors = async () => {
|
||||||
|
try {
|
||||||
|
this.setState({ loading: true, error: null });
|
||||||
|
const response = await this.authService.apiCall('/data/assignable-kreditors');
|
||||||
|
|
||||||
|
if (response && response.ok) {
|
||||||
|
const kreditors = await response.json();
|
||||||
|
this.setState({ assignableKreditors: kreditors, loading: false });
|
||||||
|
} else {
|
||||||
|
this.setState({
|
||||||
|
error: 'Fehler beim Laden der verfügbaren Kreditoren',
|
||||||
|
loading: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading assignable kreditors:', error);
|
||||||
|
this.setState({
|
||||||
|
error: 'Fehler beim Laden der verfügbaren Kreditoren',
|
||||||
|
loading: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadExistingAssignment = async () => {
|
||||||
|
// Only load assignments for regular database transactions, not CSV transactions
|
||||||
|
const transactionId = this.props.transaction?.id;
|
||||||
|
console.log('loadExistingAssignment called with:', {
|
||||||
|
transactionId,
|
||||||
|
csv_id: this.props.transaction?.csv_id,
|
||||||
|
fullTransaction: this.props.transaction
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!transactionId) {
|
||||||
|
console.log('Skipping loadExistingAssignment - no transaction ID');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.authService.apiCall(
|
||||||
|
`/data/banking-transactions/${transactionId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response && response.ok) {
|
||||||
|
const assignments = await response.json();
|
||||||
|
if (assignments.length > 0) {
|
||||||
|
const assignment = assignments[0];
|
||||||
|
this.setState({
|
||||||
|
selectedKreditorId: assignment.assigned_kreditor_id || '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading existing assignment:', error);
|
||||||
|
// Don't show error for missing assignments - it's normal
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleKreditorChange = (event) => {
|
||||||
|
const value = event.target.value;
|
||||||
|
if (value === 'create_new') {
|
||||||
|
this.setState({ showCreateKreditor: true, selectedKreditorId: '' });
|
||||||
|
} else {
|
||||||
|
this.setState({ selectedKreditorId: value, showCreateKreditor: false });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleNewKreditorChange = (field, value) => {
|
||||||
|
this.setState({
|
||||||
|
newKreditor: {
|
||||||
|
...this.state.newKreditor,
|
||||||
|
[field]: value
|
||||||
|
},
|
||||||
|
validationErrors: []
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
generateKreditorId = () => {
|
||||||
|
const randomDigits = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
|
||||||
|
const kreditorId = `70${randomDigits}`;
|
||||||
|
|
||||||
|
this.setState({
|
||||||
|
newKreditor: {
|
||||||
|
...this.state.newKreditor,
|
||||||
|
kreditorId
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
handleCreateKreditor = async () => {
|
||||||
|
const { newKreditor } = this.state;
|
||||||
|
|
||||||
|
// Create regular kreditor data (no IBAN because transaction was processed through banking account)
|
||||||
|
const kreditorDataToValidate = {
|
||||||
|
...newKreditor,
|
||||||
|
iban: null,
|
||||||
|
is_banking: false, // This is a regular kreditor (actual company) that will be assigned to banking transactions
|
||||||
|
is_manual_assignment: true // This is a manual assignment for a banking transaction, so no IBAN is required
|
||||||
|
};
|
||||||
|
|
||||||
|
// Validate the data
|
||||||
|
const validationErrors = this.kreditorService.validateKreditorData(kreditorDataToValidate);
|
||||||
|
if (validationErrors.length > 0) {
|
||||||
|
this.setState({ validationErrors });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.setState({ creating: true, error: null });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const createdKreditor = await this.kreditorService.createKreditor(kreditorDataToValidate);
|
||||||
|
|
||||||
|
// Add the new kreditor to the list and select it
|
||||||
|
this.setState({
|
||||||
|
assignableKreditors: [...this.state.assignableKreditors, createdKreditor],
|
||||||
|
selectedKreditorId: createdKreditor.id,
|
||||||
|
showCreateKreditor: false,
|
||||||
|
creating: false,
|
||||||
|
newKreditor: { name: '', kreditorId: '' },
|
||||||
|
validationErrors: []
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating kreditor:', error);
|
||||||
|
this.setState({
|
||||||
|
error: error.message,
|
||||||
|
creating: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleSave = async () => {
|
||||||
|
const { transaction, user, onSave } = this.props;
|
||||||
|
const { selectedKreditorId } = this.state;
|
||||||
|
|
||||||
|
if (!selectedKreditorId) {
|
||||||
|
this.setState({ error: 'Bitte wählen Sie einen Kreditor aus' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.setState({ saving: true, error: null });
|
||||||
|
|
||||||
|
try {
|
||||||
|
let response;
|
||||||
|
|
||||||
|
if (transaction.id) {
|
||||||
|
// Check for existing assignment first
|
||||||
|
const checkResponse = await this.authService.apiCall(
|
||||||
|
`/data/banking-transactions/${transaction.id}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (checkResponse && checkResponse.ok) {
|
||||||
|
const existingAssignments = await checkResponse.json();
|
||||||
|
|
||||||
|
if (existingAssignments.length > 0) {
|
||||||
|
// Update existing assignment
|
||||||
|
response = await this.authService.apiCall(
|
||||||
|
`/data/banking-transactions/${existingAssignments[0].id}`,
|
||||||
|
{
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({
|
||||||
|
assigned_kreditor_id: parseInt(selectedKreditorId),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Create new assignment
|
||||||
|
response = await this.authService.apiCall(
|
||||||
|
'/data/banking-transactions',
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
transaction_id: transaction.isFromCSV ? null : transaction.id,
|
||||||
|
csv_transaction_id: transaction.isFromCSV ? transaction.id : null,
|
||||||
|
banking_iban: transaction['Kontonummer/IBAN'] || transaction.kontonummer_iban,
|
||||||
|
assigned_kreditor_id: parseInt(selectedKreditorId),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.setState({
|
||||||
|
error: 'Transaktion hat keine gültige ID',
|
||||||
|
saving: false
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response && response.ok) {
|
||||||
|
this.setState({ saving: false });
|
||||||
|
if (onSave) {
|
||||||
|
// Find the assigned kreditor from the list to pass to callback
|
||||||
|
const assignedKreditor = this.state.assignableKreditors.find(
|
||||||
|
k => k.id === parseInt(selectedKreditorId)
|
||||||
|
);
|
||||||
|
onSave(assignedKreditor);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const errorData = await response.json();
|
||||||
|
this.setState({
|
||||||
|
error: errorData.error || 'Fehler beim Speichern der Zuordnung',
|
||||||
|
saving: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving kreditor assignment:', error);
|
||||||
|
this.setState({
|
||||||
|
error: 'Fehler beim Speichern der Zuordnung',
|
||||||
|
saving: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const {
|
||||||
|
assignableKreditors,
|
||||||
|
selectedKreditorId,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
saving,
|
||||||
|
showCreateKreditor,
|
||||||
|
newKreditor,
|
||||||
|
creating,
|
||||||
|
validationErrors
|
||||||
|
} = this.state;
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Box display="flex" justifyContent="center" py={2}>
|
||||||
|
<CircularProgress size={20} />
|
||||||
|
<Typography variant="caption" sx={{ ml: 1 }}>
|
||||||
|
Lade Kreditoren...
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box>
|
||||||
|
{error && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FormControl fullWidth sx={{ mb: 2 }} size="small">
|
||||||
|
<InputLabel id="kreditor-select-label">
|
||||||
|
Kreditor auswählen *
|
||||||
|
</InputLabel>
|
||||||
|
<Select
|
||||||
|
labelId="kreditor-select-label"
|
||||||
|
value={selectedKreditorId}
|
||||||
|
onChange={this.handleKreditorChange}
|
||||||
|
label="Kreditor auswählen *"
|
||||||
|
>
|
||||||
|
{assignableKreditors.map((kreditor) => (
|
||||||
|
<MenuItem key={kreditor.id} value={kreditor.id}>
|
||||||
|
{kreditor.name} ({kreditor.kreditorId})
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
<MenuItem value="create_new" sx={{ color: 'primary.main', fontWeight: 'bold' }}>
|
||||||
|
<AddIcon sx={{ mr: 1 }} />
|
||||||
|
Neuen Kreditor erstellen
|
||||||
|
</MenuItem>
|
||||||
|
</Select>
|
||||||
|
</FormControl>
|
||||||
|
|
||||||
|
{showCreateKreditor && (
|
||||||
|
<Box sx={{ mt: 2, p: 2, bgcolor: '#f5f5f5', borderRadius: 1 }}>
|
||||||
|
<Typography variant="body2" sx={{ mb: 2, fontWeight: 'bold' }}>
|
||||||
|
Neuen Kreditor erstellen:
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{validationErrors.length > 0 && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
<ul style={{ margin: 0, paddingLeft: '20px' }}>
|
||||||
|
{validationErrors.map((error, index) => (
|
||||||
|
<li key={index}>{error}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
label="Name *"
|
||||||
|
value={newKreditor.name}
|
||||||
|
onChange={(e) => this.handleNewKreditorChange('name', e.target.value)}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
placeholder="Name des Kreditors"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-end', mb: 2 }}>
|
||||||
|
<TextField
|
||||||
|
label="Kreditor-ID *"
|
||||||
|
value={newKreditor.kreditorId}
|
||||||
|
onChange={(e) => this.handleNewKreditorChange('kreditorId', e.target.value)}
|
||||||
|
size="small"
|
||||||
|
placeholder="70001"
|
||||||
|
sx={{ flexGrow: 1 }}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
onClick={this.generateKreditorId}
|
||||||
|
variant="outlined"
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
Generieren
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Typography variant="caption" color="textSecondary" sx={{ display: 'block', mb: 2 }}>
|
||||||
|
Die Kreditor-ID muss mit "70" beginnen, gefolgt von mindestens 3 Ziffern.
|
||||||
|
Keine IBAN erforderlich, da diese Transaktion über ein Banking-Konto abgewickelt wurde.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Box sx={{ display: 'flex', gap: 1 }}>
|
||||||
|
<Button
|
||||||
|
onClick={this.handleCreateKreditor}
|
||||||
|
variant="contained"
|
||||||
|
size="small"
|
||||||
|
disabled={creating}
|
||||||
|
startIcon={creating ? <CircularProgress size={16} /> : null}
|
||||||
|
>
|
||||||
|
{creating ? 'Erstellen...' : 'Kreditor erstellen'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => this.setState({ showCreateKreditor: false, validationErrors: [] })}
|
||||||
|
variant="outlined"
|
||||||
|
size="small"
|
||||||
|
disabled={creating}
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
onClick={this.handleSave}
|
||||||
|
variant="contained"
|
||||||
|
disabled={!selectedKreditorId || saving}
|
||||||
|
size="small"
|
||||||
|
sx={{
|
||||||
|
bgcolor: '#ff5722',
|
||||||
|
'&:hover': { bgcolor: '#e64a19' }
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{saving ? (
|
||||||
|
<>
|
||||||
|
<CircularProgress size={16} sx={{ mr: 1 }} />
|
||||||
|
Speichern...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'Kreditor zuordnen'
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default BankingKreditorSelector;
|
||||||
502
client/src/components/CSVImportDialog.js
Normal file
502
client/src/components/CSVImportDialog.js
Normal file
@@ -0,0 +1,502 @@
|
|||||||
|
import React, { Component } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Typography,
|
||||||
|
Box,
|
||||||
|
Alert,
|
||||||
|
CircularProgress,
|
||||||
|
LinearProgress,
|
||||||
|
Chip,
|
||||||
|
Tabs,
|
||||||
|
Tab,
|
||||||
|
Divider,
|
||||||
|
Paper,
|
||||||
|
} from '@mui/material';
|
||||||
|
import {
|
||||||
|
CloudUpload as UploadIcon,
|
||||||
|
CheckCircle as SuccessIcon,
|
||||||
|
Error as ErrorIcon,
|
||||||
|
Link as LinkIcon,
|
||||||
|
AccountBalance as AccountIcon,
|
||||||
|
InfoOutlined as InfoIcon,
|
||||||
|
} from '@mui/icons-material';
|
||||||
|
import AuthService from '../services/AuthService';
|
||||||
|
|
||||||
|
const IMPORT_TYPES = {
|
||||||
|
BANKING: 'BANKING',
|
||||||
|
DATEV_LINKS: 'DATEV_LINKS',
|
||||||
|
};
|
||||||
|
|
||||||
|
class CSVImportPanel extends Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
this.state = {
|
||||||
|
// common
|
||||||
|
activeTab: IMPORT_TYPES.BANKING,
|
||||||
|
importing: false,
|
||||||
|
imported: false,
|
||||||
|
importResult: null,
|
||||||
|
error: null,
|
||||||
|
|
||||||
|
// drag/drop visual
|
||||||
|
dragOver: false,
|
||||||
|
|
||||||
|
// banking state
|
||||||
|
file: null,
|
||||||
|
csvData: null,
|
||||||
|
headers: null,
|
||||||
|
|
||||||
|
// datev links state
|
||||||
|
datevFile: null,
|
||||||
|
datevCsvData: null,
|
||||||
|
datevHeaders: null,
|
||||||
|
};
|
||||||
|
this.authService = new AuthService();
|
||||||
|
this.fileInputRef = React.createRef();
|
||||||
|
this.datevFileInputRef = React.createRef();
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
// Check if we should navigate to a specific tab
|
||||||
|
if (this.props.targetTab) {
|
||||||
|
this.setState({ activeTab: this.props.targetTab });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps) {
|
||||||
|
// Handle targetTab changes
|
||||||
|
if (this.props.targetTab !== prevProps.targetTab && this.props.targetTab) {
|
||||||
|
this.setState({ activeTab: this.props.targetTab });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tab switch resets type-specific state but keeps success state as-is
|
||||||
|
handleTabChange = (_e, value) => {
|
||||||
|
this.setState({
|
||||||
|
activeTab: value,
|
||||||
|
// clear type-specific selections and errors
|
||||||
|
file: null,
|
||||||
|
csvData: null,
|
||||||
|
headers: null,
|
||||||
|
datevFile: null,
|
||||||
|
datevCsvData: null,
|
||||||
|
datevHeaders: null,
|
||||||
|
error: null,
|
||||||
|
dragOver: false,
|
||||||
|
// keep importing false when switching
|
||||||
|
importing: false,
|
||||||
|
// keep imported/result to show success for last action regardless of tab
|
||||||
|
// Alternatively, uncomment next two lines to reset success on tab change:
|
||||||
|
// imported: false,
|
||||||
|
// importResult: null,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Generic CSV parser (semicolon with quotes)
|
||||||
|
parseCSV = (text) => {
|
||||||
|
const lines = text.split('\n').filter(line => line.trim());
|
||||||
|
if (lines.length < 2) {
|
||||||
|
throw new Error('CSV-Datei muss mindestens eine Kopfzeile und eine Datenzeile enthalten');
|
||||||
|
}
|
||||||
|
const parseCSVLine = (line) => {
|
||||||
|
const result = [];
|
||||||
|
let current = '';
|
||||||
|
let inQuotes = false;
|
||||||
|
for (let i = 0; i < line.length; i++) {
|
||||||
|
const char = line[i];
|
||||||
|
if (char === '"') {
|
||||||
|
inQuotes = !inQuotes;
|
||||||
|
} else if (char === ';' && !inQuotes) {
|
||||||
|
result.push(current.trim());
|
||||||
|
current = '';
|
||||||
|
} else {
|
||||||
|
current += char;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.push(current.trim());
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
const headers = parseCSVLine(lines[0]);
|
||||||
|
const dataRows = lines.slice(1).map(line => {
|
||||||
|
const values = parseCSVLine(line);
|
||||||
|
const row = {};
|
||||||
|
headers.forEach((header, index) => {
|
||||||
|
row[header] = values[index] || '';
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
});
|
||||||
|
return { headers, dataRows };
|
||||||
|
};
|
||||||
|
|
||||||
|
// Banking file handlers
|
||||||
|
handleFileSelect = (event) => {
|
||||||
|
const file = event.target.files[0];
|
||||||
|
if (file) {
|
||||||
|
this.processFile(file, IMPORT_TYPES.BANKING);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// DATEV file handlers
|
||||||
|
handleDatevFileSelect = (event) => {
|
||||||
|
const file = event.target.files[0];
|
||||||
|
if (file) {
|
||||||
|
this.processFile(file, IMPORT_TYPES.DATEV_LINKS);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleDrop = (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
this.setState({ dragOver: false });
|
||||||
|
const file = event.dataTransfer.files[0];
|
||||||
|
if (file) {
|
||||||
|
// route to active tab
|
||||||
|
this.processFile(file, this.state.activeTab);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleDragOver = (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
this.setState({ dragOver: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
handleDragLeave = () => {
|
||||||
|
this.setState({ dragOver: false });
|
||||||
|
};
|
||||||
|
|
||||||
|
processFile = (file, type) => {
|
||||||
|
if (!file.name.toLowerCase().endsWith('.csv')) {
|
||||||
|
this.setState({ error: 'Bitte wählen Sie eine CSV-Datei aus' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (e) => {
|
||||||
|
try {
|
||||||
|
const text = e.target.result;
|
||||||
|
const { headers, dataRows } = this.parseCSV(text);
|
||||||
|
if (type === IMPORT_TYPES.BANKING) {
|
||||||
|
this.setState({
|
||||||
|
file,
|
||||||
|
csvData: dataRows,
|
||||||
|
headers,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.setState({
|
||||||
|
datevFile: file,
|
||||||
|
datevCsvData: dataRows,
|
||||||
|
datevHeaders: headers,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error parsing CSV:', err);
|
||||||
|
this.setState({ error: err.message || 'Fehler beim Lesen der CSV-Datei' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsText(file, 'UTF-8');
|
||||||
|
};
|
||||||
|
|
||||||
|
handleImport = async () => {
|
||||||
|
const {
|
||||||
|
activeTab,
|
||||||
|
file, csvData, headers,
|
||||||
|
datevFile, datevCsvData, datevHeaders,
|
||||||
|
} = this.state;
|
||||||
|
|
||||||
|
const isBanking = activeTab === IMPORT_TYPES.BANKING;
|
||||||
|
const hasData = isBanking ? (csvData && csvData.length > 0) : (datevCsvData && datevCsvData.length > 0);
|
||||||
|
if (!hasData) {
|
||||||
|
this.setState({ error: 'Keine Daten zum Importieren gefunden' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.setState({ importing: true, error: null });
|
||||||
|
|
||||||
|
try {
|
||||||
|
let endpoint = '';
|
||||||
|
let payload = {};
|
||||||
|
if (isBanking) {
|
||||||
|
endpoint = '/data/import-csv-transactions';
|
||||||
|
payload = {
|
||||||
|
transactions: csvData,
|
||||||
|
headers: headers,
|
||||||
|
filename: file.name,
|
||||||
|
batchId: `import_${Date.now()}_${file.name}`,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// Placeholder endpoint for DATEV Beleglinks (adjust when backend is available)
|
||||||
|
endpoint = '/data/import-datev-beleglinks';
|
||||||
|
payload = {
|
||||||
|
beleglinks: datevCsvData,
|
||||||
|
headers: datevHeaders,
|
||||||
|
filename: datevFile.name,
|
||||||
|
batchId: `datev_${Date.now()}_${datevFile.name}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await this.authService.apiCall(endpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response && response.ok) {
|
||||||
|
const result = await response.json();
|
||||||
|
this.setState({
|
||||||
|
importing: false,
|
||||||
|
imported: true,
|
||||||
|
importResult: result,
|
||||||
|
});
|
||||||
|
if (this.props.onImportSuccess) {
|
||||||
|
this.props.onImportSuccess(result);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let errorText = 'Import fehlgeschlagen';
|
||||||
|
try {
|
||||||
|
const errorData = await response.json();
|
||||||
|
errorText = errorData.error || errorText;
|
||||||
|
} catch (_) {}
|
||||||
|
this.setState({
|
||||||
|
importing: false,
|
||||||
|
error: errorText,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Import error:', error);
|
||||||
|
this.setState({
|
||||||
|
importing: false,
|
||||||
|
error: 'Netzwerkfehler beim Import',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleClose = () => {
|
||||||
|
this.setState({
|
||||||
|
// common
|
||||||
|
importing: false,
|
||||||
|
imported: false,
|
||||||
|
importResult: null,
|
||||||
|
error: null,
|
||||||
|
dragOver: false,
|
||||||
|
|
||||||
|
// banking
|
||||||
|
file: null,
|
||||||
|
csvData: null,
|
||||||
|
headers: null,
|
||||||
|
|
||||||
|
// datev
|
||||||
|
datevFile: null,
|
||||||
|
datevCsvData: null,
|
||||||
|
datevHeaders: null,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
renderUploadPanel = ({ isBanking }) => {
|
||||||
|
const {
|
||||||
|
dragOver,
|
||||||
|
file, csvData, headers,
|
||||||
|
datevFile, datevCsvData, datevHeaders,
|
||||||
|
} = this.state;
|
||||||
|
|
||||||
|
const currentFile = isBanking ? file : datevFile;
|
||||||
|
const currentHeaders = isBanking ? headers : datevHeaders;
|
||||||
|
const currentData = isBanking ? csvData : datevCsvData;
|
||||||
|
|
||||||
|
const onClickPick = () => {
|
||||||
|
if (isBanking) {
|
||||||
|
this.fileInputRef.current?.click();
|
||||||
|
} else {
|
||||||
|
this.datevFileInputRef.current?.click();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
border: '2px dashed',
|
||||||
|
borderColor: dragOver ? 'primary.main' : 'grey.300',
|
||||||
|
borderRadius: 2,
|
||||||
|
p: 4,
|
||||||
|
textAlign: 'center',
|
||||||
|
bgcolor: dragOver ? 'action.hover' : 'background.paper',
|
||||||
|
cursor: 'pointer',
|
||||||
|
mb: 2,
|
||||||
|
}}
|
||||||
|
onDrop={this.handleDrop}
|
||||||
|
onDragOver={this.handleDragOver}
|
||||||
|
onDragLeave={this.handleDragLeave}
|
||||||
|
onClick={onClickPick}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept=".csv"
|
||||||
|
onChange={isBanking ? this.handleFileSelect : this.handleDatevFileSelect}
|
||||||
|
ref={isBanking ? this.fileInputRef : this.datevFileInputRef}
|
||||||
|
style={{ display: 'none' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{isBanking ? (
|
||||||
|
<AccountIcon sx={{ fontSize: 48, color: 'grey.400', mb: 2 }} />
|
||||||
|
) : (
|
||||||
|
<LinkIcon sx={{ fontSize: 48, color: 'grey.400', mb: 2 }} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
{isBanking ? 'Bankkontoumsätze CSV hier ablegen oder klicken zum Auswählen' : 'DATEV Beleglinks CSV hier ablegen oder klicken zum Auswählen'}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="textSecondary">
|
||||||
|
Unterstützte Formate: .csv (Semikolon-getrennt)
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{currentFile && (
|
||||||
|
<Box sx={{ mb: 2 }}>
|
||||||
|
<Typography variant="subtitle2" gutterBottom>
|
||||||
|
Ausgewählte Datei:
|
||||||
|
</Typography>
|
||||||
|
<Chip label={currentFile.name} color="primary" />
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{currentHeaders && (
|
||||||
|
|
||||||
|
<Box sx={{ mb: 2 }}>
|
||||||
|
<Typography variant="subtitle2" gutterBottom>
|
||||||
|
Erkannte Spalten ({currentHeaders.length}):
|
||||||
|
</Typography>
|
||||||
|
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
||||||
|
{currentHeaders.slice(0, 10).map((header, index) => (
|
||||||
|
<Chip key={index} label={header} size="small" variant="outlined" />
|
||||||
|
))}
|
||||||
|
{currentHeaders.length > 10 && (
|
||||||
|
<Chip label={`+${currentHeaders.length - 10} weitere`} size="small" />
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{currentData && (
|
||||||
|
<Box sx={{ mb: 2 }}>
|
||||||
|
<Typography variant="subtitle2" gutterBottom>
|
||||||
|
{isBanking ? 'Gefundene Transaktionen' : 'Gefundene Beleglinks'}: {currentData.length}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="textSecondary">
|
||||||
|
Die Daten werden validiert und in die Datenbank importiert.
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const {
|
||||||
|
activeTab,
|
||||||
|
importing,
|
||||||
|
imported,
|
||||||
|
importResult,
|
||||||
|
error,
|
||||||
|
csvData,
|
||||||
|
datevCsvData,
|
||||||
|
} = this.state;
|
||||||
|
|
||||||
|
const isBanking = activeTab === IMPORT_TYPES.BANKING;
|
||||||
|
const hasData = isBanking ? csvData : datevCsvData;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Paper sx={{ p: 3 }}>
|
||||||
|
<Typography variant="h5" gutterBottom>
|
||||||
|
CSV Import
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Tabs
|
||||||
|
value={activeTab}
|
||||||
|
onChange={this.handleTabChange}
|
||||||
|
variant="fullWidth"
|
||||||
|
sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}
|
||||||
|
>
|
||||||
|
<Tab value={IMPORT_TYPES.BANKING} iconPosition="start" icon={<AccountIcon />} label="Banking Umsätze" />
|
||||||
|
<Tab value={IMPORT_TYPES.DATEV_LINKS} iconPosition="start" icon={<LinkIcon />} label="DATEV Beleglinks" />
|
||||||
|
</Tabs>
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
{!imported ? (
|
||||||
|
<>
|
||||||
|
{this.renderUploadPanel({ isBanking })}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{importing && (
|
||||||
|
<Box sx={{ mb: 2 }}>
|
||||||
|
<LinearProgress />
|
||||||
|
<Typography variant="body2" sx={{ mt: 1, textAlign: 'center' }}>
|
||||||
|
{isBanking ? 'Importiere Transaktionen...' : 'Importiere DATEV Beleglinks...'}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Box sx={{ textAlign: 'center', py: 2 }}>
|
||||||
|
<SuccessIcon sx={{ fontSize: 64, color: 'success.main', mb: 2 }} />
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Import erfolgreich abgeschlossen!
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{importResult && (
|
||||||
|
<Box sx={{ mt: 2 }}>
|
||||||
|
<Typography variant="body1" gutterBottom>
|
||||||
|
<strong>Hinzugefügt:</strong> {importResult.imported} {isBanking ? 'Transaktionen' : 'Datevlinks'}
|
||||||
|
</Typography>
|
||||||
|
{importResult.skipped > 0 && (
|
||||||
|
<Typography variant="body1" color="info.main">
|
||||||
|
<strong>Übersprungen:</strong> {importResult.skipped} Zeilen (bereits vorhanden, unbekanntes Format, etc.)
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{importResult.errors > 0 && (
|
||||||
|
<Typography variant="body1" color="warning.main">
|
||||||
|
<strong>Fehler:</strong> {importResult.errors} Zeilen konnten nicht verarbeitet werden.
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{importResult.message && (
|
||||||
|
<Typography variant="body2" color="textSecondary" sx={{ mt: 1 }}>
|
||||||
|
{importResult.message}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
<Typography variant="body2" color="textSecondary" sx={{ mt: 1 }}>
|
||||||
|
Batch-ID: {importResult.batchId}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
{!imported && hasData && (
|
||||||
|
<Box sx={{ mt: 3, textAlign: 'center' }}>
|
||||||
|
<Button
|
||||||
|
onClick={this.handleImport}
|
||||||
|
variant="contained"
|
||||||
|
size="large"
|
||||||
|
disabled={importing || !hasData}
|
||||||
|
startIcon={importing ? <CircularProgress size={16} /> : <UploadIcon />}
|
||||||
|
>
|
||||||
|
{importing ? 'Importiere...' : 'Importieren'}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{imported && (
|
||||||
|
<Box sx={{ mt: 3, textAlign: 'center' }}>
|
||||||
|
<Button onClick={this.handleClose} variant="outlined" size="large">
|
||||||
|
Neuer Import
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
</Paper>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CSVImportPanel;
|
||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
import AuthService from '../services/AuthService';
|
import AuthService from '../services/AuthService';
|
||||||
import SummaryHeader from './SummaryHeader';
|
import SummaryHeader from './SummaryHeader';
|
||||||
import TransactionsTable from './TransactionsTable';
|
import TransactionsTable from './TransactionsTable';
|
||||||
import Navigation from './Navigation';
|
|
||||||
import Dashboard from './Dashboard';
|
import Dashboard from './Dashboard';
|
||||||
import TableManagement from './TableManagement';
|
import TableManagement from './TableManagement';
|
||||||
|
|
||||||
@@ -21,7 +20,7 @@ class DataViewer extends Component {
|
|||||||
summary: null,
|
summary: null,
|
||||||
loading: true,
|
loading: true,
|
||||||
error: null,
|
error: null,
|
||||||
currentView: 'dashboard', // 'dashboard' or 'tables'
|
|
||||||
};
|
};
|
||||||
this.authService = new AuthService();
|
this.authService = new AuthService();
|
||||||
}
|
}
|
||||||
@@ -114,21 +113,17 @@ class DataViewer extends Component {
|
|||||||
if (this.props.onUpdateExportData) {
|
if (this.props.onUpdateExportData) {
|
||||||
this.props.onUpdateExportData({
|
this.props.onUpdateExportData({
|
||||||
selectedMonth,
|
selectedMonth,
|
||||||
canExport: !!selectedMonth && !this.state.loading && this.state.currentView === 'dashboard',
|
canExport: !!selectedMonth && !this.state.loading && this.props.currentView === 'dashboard',
|
||||||
onExport: this.downloadDatev
|
onExport: this.downloadDatev
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
handleViewChange = (event, newView) => {
|
|
||||||
this.setState({ currentView: newView });
|
|
||||||
// Update export data when view changes
|
|
||||||
this.updateExportData();
|
|
||||||
};
|
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { months, selectedMonth, transactions, summary, loading, error, currentView } = this.state;
|
const { months, selectedMonth, transactions, summary, loading, error } = this.state;
|
||||||
const { user } = this.props;
|
const { user, currentView } = this.props;
|
||||||
|
|
||||||
if (loading && !transactions.length) {
|
if (loading && !transactions.length) {
|
||||||
return (
|
return (
|
||||||
@@ -148,11 +143,6 @@ class DataViewer extends Component {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
|
<Box sx={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
|
||||||
<Navigation
|
|
||||||
currentView={currentView}
|
|
||||||
onViewChange={this.handleViewChange}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{currentView === 'dashboard' ? (
|
{currentView === 'dashboard' ? (
|
||||||
<>
|
<>
|
||||||
<Box sx={{ flexShrink: 0 }}>
|
<Box sx={{ flexShrink: 0 }}>
|
||||||
@@ -175,7 +165,7 @@ class DataViewer extends Component {
|
|||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Box sx={{ flex: 1, minHeight: 0, overflow: 'auto', p: 2 }}>
|
<Box sx={{ flex: 1, minHeight: 0, overflow: 'auto', p: 2 }}>
|
||||||
<TableManagement user={user} />
|
<TableManagement user={user} targetTab={this.props.targetTab} />
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -41,12 +41,48 @@ class KreditorSelector extends Component {
|
|||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
this.loadKreditors();
|
this.loadKreditors();
|
||||||
|
|
||||||
|
// If prefilled data is provided, set it in the newKreditor state
|
||||||
|
const updates = {};
|
||||||
|
if (this.props.prefilledIban) {
|
||||||
|
updates.iban = this.props.prefilledIban;
|
||||||
|
}
|
||||||
|
if (this.props.prefilledName) {
|
||||||
|
updates.name = this.props.prefilledName;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(updates).length > 0) {
|
||||||
|
this.setState({
|
||||||
|
newKreditor: {
|
||||||
|
...this.state.newKreditor,
|
||||||
|
...updates
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidUpdate(prevProps) {
|
componentDidUpdate(prevProps) {
|
||||||
if (prevProps.selectedKreditorId !== this.props.selectedKreditorId) {
|
if (prevProps.selectedKreditorId !== this.props.selectedKreditorId) {
|
||||||
this.setState({ selectedKreditorId: this.props.selectedKreditorId || '' });
|
this.setState({ selectedKreditorId: this.props.selectedKreditorId || '' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If prefilled props change, update the newKreditor state
|
||||||
|
const updates = {};
|
||||||
|
if (prevProps.prefilledIban !== this.props.prefilledIban && this.props.prefilledIban) {
|
||||||
|
updates.iban = this.props.prefilledIban;
|
||||||
|
}
|
||||||
|
if (prevProps.prefilledName !== this.props.prefilledName && this.props.prefilledName) {
|
||||||
|
updates.name = this.props.prefilledName;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(updates).length > 0) {
|
||||||
|
this.setState({
|
||||||
|
newKreditor: {
|
||||||
|
...this.state.newKreditor,
|
||||||
|
...updates
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
loadKreditors = async () => {
|
loadKreditors = async () => {
|
||||||
@@ -83,7 +119,11 @@ class KreditorSelector extends Component {
|
|||||||
handleCreateDialogClose = () => {
|
handleCreateDialogClose = () => {
|
||||||
this.setState({
|
this.setState({
|
||||||
createDialogOpen: false,
|
createDialogOpen: false,
|
||||||
newKreditor: { iban: '', name: '', kreditorId: '' },
|
newKreditor: {
|
||||||
|
iban: this.props.prefilledIban || '',
|
||||||
|
name: this.props.prefilledName || '',
|
||||||
|
kreditorId: ''
|
||||||
|
},
|
||||||
validationErrors: [],
|
validationErrors: [],
|
||||||
error: null
|
error: null
|
||||||
});
|
});
|
||||||
@@ -115,8 +155,15 @@ class KreditorSelector extends Component {
|
|||||||
handleCreateKreditor = async () => {
|
handleCreateKreditor = async () => {
|
||||||
const { newKreditor } = this.state;
|
const { newKreditor } = this.state;
|
||||||
|
|
||||||
|
// For banking kreditors (when allowEmptyIban is true), mark as banking if IBAN is empty
|
||||||
|
const kreditorDataToValidate = {
|
||||||
|
...newKreditor,
|
||||||
|
is_banking: this.props.allowEmptyIban && (!newKreditor.iban || newKreditor.iban.trim() === ''),
|
||||||
|
iban: newKreditor.iban || null // Convert empty string to null
|
||||||
|
};
|
||||||
|
|
||||||
// Validate the data
|
// Validate the data
|
||||||
const validationErrors = this.kreditorService.validateKreditorData(newKreditor);
|
const validationErrors = this.kreditorService.validateKreditorData(kreditorDataToValidate);
|
||||||
if (validationErrors.length > 0) {
|
if (validationErrors.length > 0) {
|
||||||
this.setState({ validationErrors });
|
this.setState({ validationErrors });
|
||||||
return;
|
return;
|
||||||
@@ -125,7 +172,7 @@ class KreditorSelector extends Component {
|
|||||||
this.setState({ creating: true, error: null });
|
this.setState({ creating: true, error: null });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const createdKreditor = await this.kreditorService.createKreditor(newKreditor);
|
const createdKreditor = await this.kreditorService.createKreditor(kreditorDataToValidate);
|
||||||
|
|
||||||
// Add the new kreditor to the list and select it
|
// Add the new kreditor to the list and select it
|
||||||
const updatedKreditors = [...this.state.kreditors, createdKreditor];
|
const updatedKreditors = [...this.state.kreditors, createdKreditor];
|
||||||
@@ -181,10 +228,12 @@ class KreditorSelector extends Component {
|
|||||||
{kreditor.name} ({kreditor.kreditorId}) - {kreditor.iban}
|
{kreditor.name} ({kreditor.kreditorId}) - {kreditor.iban}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
<MenuItem value="create_new" sx={{ color: 'primary.main', fontWeight: 'bold' }}>
|
{(this.props.allowCreate !== false) && (
|
||||||
<AddIcon sx={{ mr: 1 }} />
|
<MenuItem value="create_new" sx={{ color: 'primary.main', fontWeight: 'bold' }}>
|
||||||
Neuen Kreditor erstellen
|
<AddIcon sx={{ mr: 1 }} />
|
||||||
</MenuItem>
|
Neuen Kreditor erstellen
|
||||||
|
</MenuItem>
|
||||||
|
)}
|
||||||
</Select>
|
</Select>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
|
||||||
@@ -201,9 +250,16 @@ class KreditorSelector extends Component {
|
|||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
fullWidth
|
fullWidth
|
||||||
>
|
>
|
||||||
<DialogTitle>Neuen Kreditor erstellen</DialogTitle>
|
<DialogTitle>
|
||||||
|
{this.props.allowEmptyIban ? 'Neuen Banking-Kreditor erstellen' : 'Neuen Kreditor erstellen'}
|
||||||
|
</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<Box sx={{ pt: 1 }}>
|
<Box sx={{ pt: 1 }}>
|
||||||
|
{this.props.allowEmptyIban && (
|
||||||
|
<Alert severity="info" sx={{ mb: 2 }}>
|
||||||
|
Sie erstellen einen Kreditor für eine Banking-Transaktion. Die IBAN kann leer bleiben, da diese Transaktion über ein Banking-Konto (z.B. PayPal) abgewickelt wurde.
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
{validationErrors.length > 0 && (
|
{validationErrors.length > 0 && (
|
||||||
<Alert severity="error" sx={{ mb: 2 }}>
|
<Alert severity="error" sx={{ mb: 2 }}>
|
||||||
<ul style={{ margin: 0, paddingLeft: '20px' }}>
|
<ul style={{ margin: 0, paddingLeft: '20px' }}>
|
||||||
@@ -235,8 +291,9 @@ class KreditorSelector extends Component {
|
|||||||
onChange={(e) => this.handleNewKreditorChange('iban', e.target.value.toUpperCase())}
|
onChange={(e) => this.handleNewKreditorChange('iban', e.target.value.toUpperCase())}
|
||||||
fullWidth
|
fullWidth
|
||||||
margin="normal"
|
margin="normal"
|
||||||
required
|
required={!this.props.allowEmptyIban}
|
||||||
placeholder="DE89 3704 0044 0532 0130 00"
|
placeholder={this.props.allowEmptyIban ? "Leer lassen für Banking-Kreditor" : "DE89 3704 0044 0532 0130 00"}
|
||||||
|
helperText={this.props.allowEmptyIban ? "Für Banking-Transaktionen kann die IBAN leer bleiben" : ""}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-end' }}>
|
<Box sx={{ display: 'flex', gap: 1, alignItems: 'flex-end' }}>
|
||||||
|
|||||||
@@ -9,6 +9,10 @@ class Login extends Component {
|
|||||||
error: null,
|
error: null,
|
||||||
loading: false,
|
loading: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Flags to track FedCM attempts and success
|
||||||
|
this.fedcmAttempted = false;
|
||||||
|
this.fedcmSucceeded = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
@@ -34,11 +38,17 @@ class Login extends Component {
|
|||||||
initializeGoogleSignIn = () => {
|
initializeGoogleSignIn = () => {
|
||||||
if (window.google && window.google.accounts) {
|
if (window.google && window.google.accounts) {
|
||||||
try {
|
try {
|
||||||
|
// Note: Removed debug logging to avoid deprecated method warnings
|
||||||
|
|
||||||
|
console.log('REACT_APP_GOOGLE_CLIENT_ID', process.env.REACT_APP_GOOGLE_CLIENT_ID);
|
||||||
|
console.log('Current origin for Google auth:', window.location.origin);
|
||||||
|
console.log('User agent:', navigator.userAgent);
|
||||||
|
|
||||||
window.google.accounts.id.initialize({
|
window.google.accounts.id.initialize({
|
||||||
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID || 'your_google_client_id_here',
|
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
|
||||||
callback: this.handleGoogleResponse,
|
callback: this.handleGoogleResponse,
|
||||||
auto_select: false,
|
auto_select: false,
|
||||||
cancel_on_tap_outside: true,
|
cancel_on_tap_outside: false,
|
||||||
});
|
});
|
||||||
console.log('✅ Google Sign-In initialized');
|
console.log('✅ Google Sign-In initialized');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -48,6 +58,9 @@ class Login extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
handleGoogleResponse = (response) => {
|
handleGoogleResponse = (response) => {
|
||||||
|
// Mark FedCM as successful if we get here
|
||||||
|
this.fedcmSucceeded = true;
|
||||||
|
|
||||||
this.setState({ loading: true, error: null });
|
this.setState({ loading: true, error: null });
|
||||||
this.props.onLogin(response)
|
this.props.onLogin(response)
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -70,6 +83,11 @@ class Login extends Component {
|
|||||||
errorMessage = '🚫 Zugriff verweigert: Ihre E-Mail-Adresse ist nicht autorisiert. Versuchen Sie, sich mit einem anderen Google-Konto anzumelden.';
|
errorMessage = '🚫 Zugriff verweigert: Ihre E-Mail-Adresse ist nicht autorisiert. Versuchen Sie, sich mit einem anderen Google-Konto anzumelden.';
|
||||||
} else if (error.message.includes('No authorized users configured')) {
|
} else if (error.message.includes('No authorized users configured')) {
|
||||||
errorMessage = '🔒 Kein Zugriff: Derzeit sind keine Benutzer autorisiert. Wenden Sie sich an den Administrator.';
|
errorMessage = '🔒 Kein Zugriff: Derzeit sind keine Benutzer autorisiert. Wenden Sie sich an den Administrator.';
|
||||||
|
} else if (error.message.includes('Not signed in with the identity provider') ||
|
||||||
|
error.message.includes('NetworkError') ||
|
||||||
|
error.message.includes('FedCM')) {
|
||||||
|
// FedCM failed, offer redirect option
|
||||||
|
errorMessage = '🔄 Schnelle Anmeldung nicht verfügbar. Versuchen Sie die Standard-Anmeldung.';
|
||||||
} else {
|
} else {
|
||||||
// Show the actual error message from the server
|
// Show the actual error message from the server
|
||||||
errorMessage = `❌ Anmeldefehler: ${error.message}`;
|
errorMessage = `❌ Anmeldefehler: ${error.message}`;
|
||||||
@@ -92,29 +110,105 @@ class Login extends Component {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear any previous error
|
// Clear any previous error and start loading
|
||||||
this.setState({ error: null, loading: false });
|
this.setState({ error: null, loading: true });
|
||||||
|
|
||||||
|
// Try FedCM first (seamless for users already signed in to Google)
|
||||||
|
console.log('🎯 Trying FedCM first for optimal UX...');
|
||||||
|
this.tryFedCMFirst();
|
||||||
|
};
|
||||||
|
|
||||||
|
tryFedCMFirst = () => {
|
||||||
if (window.google && window.google.accounts && window.google.accounts.id) {
|
if (window.google && window.google.accounts && window.google.accounts.id) {
|
||||||
try {
|
try {
|
||||||
window.google.accounts.id.prompt();
|
console.log('✅ Trying FedCM for seamless sign-in...');
|
||||||
} catch (error) {
|
|
||||||
console.error('Google prompt error:', error);
|
// Listen for the specific FedCM errors that indicate no Google session
|
||||||
this.setState({
|
const originalConsoleError = console.error;
|
||||||
error: 'Google-Anmeldung konnte nicht geladen werden. Die Seite wird aktualisiert, um es erneut zu versuchen.',
|
let errorIntercepted = false;
|
||||||
loading: true
|
|
||||||
|
console.error = (...args) => {
|
||||||
|
const errorMessage = args.join(' ');
|
||||||
|
if (!errorIntercepted && (
|
||||||
|
errorMessage.includes('Not signed in with the identity provider') ||
|
||||||
|
errorMessage.includes('FedCM get() rejects with NetworkError') ||
|
||||||
|
errorMessage.includes('Error retrieving a token')
|
||||||
|
)) {
|
||||||
|
errorIntercepted = true;
|
||||||
|
console.error = originalConsoleError; // Restore immediately
|
||||||
|
console.log('🔄 FedCM failed (user not signed in to Google), using redirect...');
|
||||||
|
this.redirectToGoogleOAuth();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
originalConsoleError.apply(console, args);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Try FedCM
|
||||||
|
window.google.accounts.id.prompt((notification) => {
|
||||||
|
console.log('🔍 FedCM notification:', notification);
|
||||||
|
console.error = originalConsoleError; // Restore console.error
|
||||||
|
// If we get here without error, FedCM is working
|
||||||
});
|
});
|
||||||
setTimeout(() => window.location.reload(), 2000);
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('FedCM initialization error, falling back to redirect:', error);
|
||||||
|
this.redirectToGoogleOAuth();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.setState({
|
// Google Identity Services not loaded, go straight to redirect
|
||||||
error: 'Google-Anmeldung nicht geladen. Die Seite wird aktualisiert, um es erneut zu versuchen.',
|
console.log('📋 GSI not loaded, using redirect flow...');
|
||||||
loading: true
|
this.redirectToGoogleOAuth();
|
||||||
});
|
|
||||||
setTimeout(() => window.location.reload(), 2000);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
redirectToGoogleOAuth = () => {
|
||||||
|
try {
|
||||||
|
// Generate a random state parameter for security
|
||||||
|
const state = this.generateRandomString(32);
|
||||||
|
sessionStorage.setItem('oauth_state', state);
|
||||||
|
|
||||||
|
// Build the Google OAuth2 authorization URL
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
|
||||||
|
redirect_uri: window.location.origin + '/auth/callback',
|
||||||
|
response_type: 'code',
|
||||||
|
scope: 'openid email profile',
|
||||||
|
state: state,
|
||||||
|
access_type: 'online',
|
||||||
|
prompt: 'select_account'
|
||||||
|
});
|
||||||
|
|
||||||
|
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
|
||||||
|
|
||||||
|
console.log('🔗 Redirecting to Google OAuth:', authUrl);
|
||||||
|
|
||||||
|
// Redirect to Google OAuth
|
||||||
|
window.location.href = authUrl;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Redirect OAuth error:', error);
|
||||||
|
this.setState({
|
||||||
|
error: 'Google-Anmeldung konnte nicht gestartet werden.',
|
||||||
|
loading: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
generateRandomString = (length) => {
|
||||||
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||||
|
let result = '';
|
||||||
|
for (let i = 0; i < length; i++) {
|
||||||
|
result += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
handleUseRedirect = () => {
|
||||||
|
console.log('🔄 User chose redirect flow');
|
||||||
|
this.setState({ error: null, loading: true });
|
||||||
|
this.redirectToGoogleOAuth();
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -157,6 +251,20 @@ class Login extends Component {
|
|||||||
{loading ? 'Anmeldung läuft...' : 'Mit Google anmelden'}
|
{loading ? 'Anmeldung läuft...' : 'Mit Google anmelden'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{error && error.includes('Standard-Anmeldung') && (
|
||||||
|
<Button
|
||||||
|
fullWidth
|
||||||
|
variant="outlined"
|
||||||
|
size="large"
|
||||||
|
startIcon={<GoogleIcon />}
|
||||||
|
onClick={this.handleUseRedirect}
|
||||||
|
disabled={loading}
|
||||||
|
sx={{ py: 1.5, mt: 2 }}
|
||||||
|
>
|
||||||
|
Standard Google-Anmeldung verwenden
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<Typography variant="caption" display="block" textAlign="center" sx={{ mt: 2 }}>
|
<Typography variant="caption" display="block" textAlign="center" sx={{ mt: 2 }}>
|
||||||
|
|||||||
133
client/src/components/OAuthCallback.js
Normal file
133
client/src/components/OAuthCallback.js
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
import React, { Component } from 'react';
|
||||||
|
import { Box, CircularProgress, Typography, Alert } from '@mui/material';
|
||||||
|
|
||||||
|
class OAuthCallback extends Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
this.state = {
|
||||||
|
loading: true,
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
this.handleOAuthCallback();
|
||||||
|
}
|
||||||
|
|
||||||
|
handleOAuthCallback = async () => {
|
||||||
|
try {
|
||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
const code = urlParams.get('code');
|
||||||
|
const state = urlParams.get('state');
|
||||||
|
const error = urlParams.get('error');
|
||||||
|
|
||||||
|
// Check for OAuth errors
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`OAuth error: ${error}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify state parameter for security
|
||||||
|
const storedState = sessionStorage.getItem('oauth_state');
|
||||||
|
if (!state || state !== storedState) {
|
||||||
|
throw new Error('Invalid state parameter - possible CSRF attack');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear stored state
|
||||||
|
sessionStorage.removeItem('oauth_state');
|
||||||
|
|
||||||
|
if (!code) {
|
||||||
|
throw new Error('No authorization code received');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('🔑 Authorization code received, exchanging for tokens...');
|
||||||
|
|
||||||
|
// Exchange authorization code for tokens via our backend
|
||||||
|
const response = await fetch('/api/auth/google/callback', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
code: code,
|
||||||
|
redirect_uri: window.location.origin + '/auth/callback'
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json().catch(() => ({}));
|
||||||
|
throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success && data.token) {
|
||||||
|
console.log('✅ OAuth callback successful');
|
||||||
|
|
||||||
|
// Store the JWT token
|
||||||
|
localStorage.setItem('token', data.token);
|
||||||
|
|
||||||
|
// Redirect to main app
|
||||||
|
window.location.href = '/';
|
||||||
|
} else {
|
||||||
|
throw new Error(data.message || 'Authentication failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('OAuth callback error:', error);
|
||||||
|
this.setState({
|
||||||
|
loading: false,
|
||||||
|
error: error.message || 'Authentication failed'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const { loading, error } = this.state;
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
display="flex"
|
||||||
|
justifyContent="center"
|
||||||
|
alignItems="center"
|
||||||
|
minHeight="60vh"
|
||||||
|
flexDirection="column"
|
||||||
|
>
|
||||||
|
<Alert severity="error" sx={{ mb: 2, maxWidth: 400 }}>
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Anmeldung fehlgeschlagen
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2">
|
||||||
|
{error}
|
||||||
|
</Typography>
|
||||||
|
</Alert>
|
||||||
|
<Typography variant="body2" color="textSecondary">
|
||||||
|
<a href="/" style={{ color: 'inherit' }}>
|
||||||
|
Zurück zur Anmeldung
|
||||||
|
</a>
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
display="flex"
|
||||||
|
justifyContent="center"
|
||||||
|
alignItems="center"
|
||||||
|
minHeight="60vh"
|
||||||
|
flexDirection="column"
|
||||||
|
>
|
||||||
|
<CircularProgress size={60} sx={{ mb: 2 }} />
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Anmeldung wird verarbeitet...
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="textSecondary">
|
||||||
|
Sie werden automatisch weitergeleitet.
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default OAuthCallback;
|
||||||
@@ -10,23 +10,49 @@ import {
|
|||||||
AccountBalance as KreditorIcon,
|
AccountBalance as KreditorIcon,
|
||||||
AccountBalanceWallet as KontoIcon,
|
AccountBalanceWallet as KontoIcon,
|
||||||
Receipt as BUIcon,
|
Receipt as BUIcon,
|
||||||
|
CloudUpload as ImportIcon,
|
||||||
} from '@mui/icons-material';
|
} from '@mui/icons-material';
|
||||||
import KreditorTable from './admin/KreditorTable';
|
import KreditorTable from './admin/KreditorTable';
|
||||||
import KontoTable from './admin/KontoTable';
|
import KontoTable from './admin/KontoTable';
|
||||||
import BUTable from './admin/BUTable';
|
import BUTable from './admin/BUTable';
|
||||||
|
import CSVImportPanel from './CSVImportDialog';
|
||||||
|
|
||||||
class TableManagement extends Component {
|
class TableManagement extends Component {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
this.state = {
|
this.state = {
|
||||||
activeTab: 0,
|
activeTab: 0,
|
||||||
|
csvImportOpen: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
componentDidMount() {
|
||||||
|
// Check if we should navigate to a specific tab
|
||||||
|
if (this.props.targetTab?.level1 !== undefined) {
|
||||||
|
this.setState({ activeTab: this.props.targetTab.level1 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidUpdate(prevProps) {
|
||||||
|
// Handle targetTab changes
|
||||||
|
if (this.props.targetTab?.level1 !== prevProps.targetTab?.level1 &&
|
||||||
|
this.props.targetTab?.level1 !== undefined) {
|
||||||
|
this.setState({ activeTab: this.props.targetTab.level1 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
handleTabChange = (event, newValue) => {
|
handleTabChange = (event, newValue) => {
|
||||||
this.setState({ activeTab: newValue });
|
this.setState({ activeTab: newValue });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
handleOpenCSVImport = () => {
|
||||||
|
this.setState({ csvImportOpen: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
handleCloseCSVImport = () => {
|
||||||
|
this.setState({ csvImportOpen: false });
|
||||||
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { activeTab } = this.state;
|
const { activeTab } = this.state;
|
||||||
const { user } = this.props;
|
const { user } = this.props;
|
||||||
@@ -59,6 +85,11 @@ class TableManagement extends Component {
|
|||||||
label="Buchungsschlüssel"
|
label="Buchungsschlüssel"
|
||||||
sx={{ minHeight: 64 }}
|
sx={{ minHeight: 64 }}
|
||||||
/>
|
/>
|
||||||
|
<Tab
|
||||||
|
icon={<ImportIcon />}
|
||||||
|
label="CSV Import"
|
||||||
|
sx={{ minHeight: 64 }}
|
||||||
|
/>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
@@ -66,6 +97,20 @@ class TableManagement extends Component {
|
|||||||
{activeTab === 0 && <KreditorTable user={user} />}
|
{activeTab === 0 && <KreditorTable user={user} />}
|
||||||
{activeTab === 1 && <KontoTable user={user} />}
|
{activeTab === 1 && <KontoTable user={user} />}
|
||||||
{activeTab === 2 && <BUTable user={user} />}
|
{activeTab === 2 && <BUTable user={user} />}
|
||||||
|
{activeTab === 3 && (
|
||||||
|
<Box>
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
CSV Transaktionen importieren
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" color="text.secondary" paragraph>
|
||||||
|
Hier können Sie CSV-Dateien von Ihrer Bank importieren. Die Daten werden in die Datenbank gespeichert und können dann Banking-Konten zugeordnet werden.
|
||||||
|
</Typography>
|
||||||
|
<CSVImportPanel
|
||||||
|
user={user}
|
||||||
|
targetTab={this.props.targetTab?.level2}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
</Paper>
|
</Paper>
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { Clear as ClearIcon } from '@mui/icons-material';
|
|||||||
import { getColumnDefs, defaultColDef, gridOptions } from './config/gridConfig';
|
import { getColumnDefs, defaultColDef, gridOptions } from './config/gridConfig';
|
||||||
import { processTransactionData, getRowStyle, getRowClass, getSelectedDisplayName } from './utils/dataUtils';
|
import { processTransactionData, getRowStyle, getRowClass, getSelectedDisplayName } from './utils/dataUtils';
|
||||||
|
|
||||||
|
|
||||||
class TransactionsTable extends Component {
|
class TransactionsTable extends Component {
|
||||||
constructor(props) {
|
constructor(props) {
|
||||||
super(props);
|
super(props);
|
||||||
@@ -51,6 +52,31 @@ class TransactionsTable extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener('resize', this.handleResize);
|
window.addEventListener('resize', this.handleResize);
|
||||||
|
|
||||||
|
// Add dialog open listener to blur grid focus
|
||||||
|
this.handleDialogOpen = () => {
|
||||||
|
if (this.gridApi) {
|
||||||
|
// Clear any focused cells to prevent aria-hidden conflicts
|
||||||
|
this.gridApi.clearFocusedCell();
|
||||||
|
// Also blur any focused elements within the grid
|
||||||
|
const gridElement = document.querySelector('.ag-root-wrapper');
|
||||||
|
if (gridElement) {
|
||||||
|
const focusedElement = gridElement.querySelector(':focus');
|
||||||
|
if (focusedElement) {
|
||||||
|
focusedElement.blur();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Listen for dialog open events (Material-UI dialogs)
|
||||||
|
this.handleFocusIn = (event) => {
|
||||||
|
// If focus moves to a dialog, blur the grid
|
||||||
|
if (event.target.closest('[role="dialog"]')) {
|
||||||
|
this.handleDialogOpen();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('focusin', this.handleFocusIn);
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillUnmount() {
|
componentWillUnmount() {
|
||||||
@@ -59,7 +85,13 @@ class TransactionsTable extends Component {
|
|||||||
window.removeEventListener('resize', this.handleResize);
|
window.removeEventListener('resize', this.handleResize);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.gridApi) {
|
// Clean up dialog focus listener
|
||||||
|
if (this.handleFocusIn) {
|
||||||
|
document.removeEventListener('focusin', this.handleFocusIn);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if grid API is still valid before removing listeners
|
||||||
|
if (this.gridApi && !this.gridApi.isDestroyed()) {
|
||||||
this.gridApi.removeEventListener('modelUpdated', this.onModelUpdated);
|
this.gridApi.removeEventListener('modelUpdated', this.onModelUpdated);
|
||||||
this.gridApi.removeEventListener('filterChanged', this.onFilterChanged);
|
this.gridApi.removeEventListener('filterChanged', this.onFilterChanged);
|
||||||
}
|
}
|
||||||
@@ -251,7 +283,7 @@ class TransactionsTable extends Component {
|
|||||||
console.log('Selected rows:', Array.from(selectedRows));
|
console.log('Selected rows:', Array.from(selectedRows));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { selectedMonth, loading } = this.props;
|
const { selectedMonth, loading } = this.props;
|
||||||
@@ -303,6 +335,7 @@ class TransactionsTable extends Component {
|
|||||||
selectedRows: this.state.selectedRows,
|
selectedRows: this.state.selectedRows,
|
||||||
onSelectionChange: this.onSelectionChange,
|
onSelectionChange: this.onSelectionChange,
|
||||||
onSelectAll: this.onSelectAll,
|
onSelectAll: this.onSelectAll,
|
||||||
|
|
||||||
totalRows: this.state.totalRows,
|
totalRows: this.state.totalRows,
|
||||||
displayedRows: this.state.displayedRows
|
displayedRows: this.state.displayedRows
|
||||||
}}
|
}}
|
||||||
@@ -317,7 +350,6 @@ class TransactionsTable extends Component {
|
|||||||
animateRows={true}
|
animateRows={true}
|
||||||
// Maintain state across data updates
|
// Maintain state across data updates
|
||||||
maintainColumnOrder={true}
|
maintainColumnOrder={true}
|
||||||
suppressColumnStateEvents={false}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</Box>
|
</Box>
|
||||||
@@ -449,6 +481,8 @@ class TransactionsTable extends Component {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
|
||||||
</Paper>
|
</Paper>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,11 @@ class BUTable extends Component {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
this.authService = new AuthService();
|
this.authService = new AuthService();
|
||||||
|
|
||||||
|
// Focus management refs
|
||||||
|
this.triggerRef = React.createRef();
|
||||||
|
this.dialogRef = React.createRef();
|
||||||
|
this.confirmDialogRef = React.createRef();
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
@@ -66,13 +71,16 @@ class BUTable extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
handleOpenDialog = (bu = null) => {
|
handleOpenDialog = (bu = null) => {
|
||||||
|
// Store reference to the trigger element for focus restoration
|
||||||
|
this.triggerRef.current = document.activeElement;
|
||||||
|
|
||||||
this.setState({
|
this.setState({
|
||||||
dialogOpen: true,
|
dialogOpen: true,
|
||||||
editingBU: bu,
|
editingBU: bu,
|
||||||
formData: bu ? {
|
formData: bu ? {
|
||||||
bu: bu.bu,
|
bu: bu.bu,
|
||||||
name: bu.name,
|
name: bu.name,
|
||||||
vst: bu.vst || '',
|
vst: bu.vst !== null && bu.vst !== undefined ? bu.vst.toString() : '',
|
||||||
} : {
|
} : {
|
||||||
bu: '',
|
bu: '',
|
||||||
name: '',
|
name: '',
|
||||||
@@ -91,6 +99,13 @@ class BUTable extends Component {
|
|||||||
vst: '',
|
vst: '',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
handleInputChange = (field) => (event) => {
|
handleInputChange = (field) => (event) => {
|
||||||
@@ -102,13 +117,20 @@ class BUTable extends Component {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
isFormValid = () => {
|
||||||
|
const { formData } = this.state;
|
||||||
|
return formData.bu.trim() !== '' &&
|
||||||
|
formData.name.trim() !== '' &&
|
||||||
|
formData.vst !== '';
|
||||||
|
};
|
||||||
|
|
||||||
handleSave = async () => {
|
handleSave = async () => {
|
||||||
const { editingBU, formData } = this.state;
|
const { editingBU, formData } = this.state;
|
||||||
|
|
||||||
// Convert vst to number or null
|
// Convert vst to number or null
|
||||||
const payload = {
|
const payload = {
|
||||||
...formData,
|
...formData,
|
||||||
vst: formData.vst ? parseFloat(formData.vst) : null,
|
vst: formData.vst !== '' ? parseFloat(formData.vst) : null,
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -138,6 +160,9 @@ class BUTable extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
handleDeleteClick = (bu) => {
|
handleDeleteClick = (bu) => {
|
||||||
|
// Store reference to the trigger element for focus restoration
|
||||||
|
this.triggerRef.current = document.activeElement;
|
||||||
|
|
||||||
this.setState({
|
this.setState({
|
||||||
confirmDialogOpen: true,
|
confirmDialogOpen: true,
|
||||||
itemToDelete: bu,
|
itemToDelete: bu,
|
||||||
@@ -149,6 +174,13 @@ class BUTable extends Component {
|
|||||||
if (!itemToDelete) return;
|
if (!itemToDelete) return;
|
||||||
|
|
||||||
this.setState({ confirmDialogOpen: false, itemToDelete: null });
|
this.setState({ confirmDialogOpen: false, itemToDelete: null });
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.authService.apiCall(`/admin/buchungsschluessel/${itemToDelete.id}`, {
|
const response = await this.authService.apiCall(`/admin/buchungsschluessel/${itemToDelete.id}`, {
|
||||||
@@ -172,6 +204,13 @@ class BUTable extends Component {
|
|||||||
confirmDialogOpen: false,
|
confirmDialogOpen: false,
|
||||||
itemToDelete: null,
|
itemToDelete: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
@@ -220,7 +259,7 @@ class BUTable extends Component {
|
|||||||
<TableCell>{bu.bu}</TableCell>
|
<TableCell>{bu.bu}</TableCell>
|
||||||
<TableCell>{bu.name}</TableCell>
|
<TableCell>{bu.name}</TableCell>
|
||||||
<TableCell align="right">
|
<TableCell align="right">
|
||||||
{bu.vst ? `${bu.vst}%` : '-'}
|
{bu.vst !== null && bu.vst !== undefined ? `${bu.vst}%` : '-'}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell align="right">
|
<TableCell align="right">
|
||||||
<IconButton
|
<IconButton
|
||||||
@@ -243,11 +282,22 @@ class BUTable extends Component {
|
|||||||
</Table>
|
</Table>
|
||||||
</TableContainer>
|
</TableContainer>
|
||||||
|
|
||||||
<Dialog open={dialogOpen} onClose={this.handleCloseDialog} maxWidth="sm" fullWidth>
|
<Dialog
|
||||||
<DialogTitle>
|
open={dialogOpen}
|
||||||
|
onClose={this.handleCloseDialog}
|
||||||
|
maxWidth="sm"
|
||||||
|
fullWidth
|
||||||
|
ref={this.dialogRef}
|
||||||
|
disableAutoFocus={false}
|
||||||
|
disableEnforceFocus={false}
|
||||||
|
disableRestoreFocus={true}
|
||||||
|
aria-labelledby="bu-dialog-title"
|
||||||
|
aria-describedby="bu-dialog-content"
|
||||||
|
>
|
||||||
|
<DialogTitle id="bu-dialog-title">
|
||||||
{editingBU ? 'Buchungsschlüssel bearbeiten' : 'Neuer Buchungsschlüssel'}
|
{editingBU ? 'Buchungsschlüssel bearbeiten' : 'Neuer Buchungsschlüssel'}
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent id="bu-dialog-content">
|
||||||
<TextField
|
<TextField
|
||||||
autoFocus
|
autoFocus
|
||||||
margin="dense"
|
margin="dense"
|
||||||
@@ -287,7 +337,11 @@ class BUTable extends Component {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={this.handleCloseDialog}>Abbrechen</Button>
|
<Button onClick={this.handleCloseDialog}>Abbrechen</Button>
|
||||||
<Button onClick={this.handleSave} variant="contained">
|
<Button
|
||||||
|
onClick={this.handleSave}
|
||||||
|
variant="contained"
|
||||||
|
disabled={!this.isFormValid()}
|
||||||
|
>
|
||||||
Speichern
|
Speichern
|
||||||
</Button>
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
@@ -299,9 +353,15 @@ class BUTable extends Component {
|
|||||||
onClose={this.handleDeleteCancel}
|
onClose={this.handleDeleteCancel}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
fullWidth
|
fullWidth
|
||||||
|
ref={this.confirmDialogRef}
|
||||||
|
disableAutoFocus={false}
|
||||||
|
disableEnforceFocus={false}
|
||||||
|
disableRestoreFocus={true}
|
||||||
|
aria-labelledby="confirm-dialog-title"
|
||||||
|
aria-describedby="confirm-dialog-content"
|
||||||
>
|
>
|
||||||
<DialogTitle>Löschen bestätigen</DialogTitle>
|
<DialogTitle id="confirm-dialog-title">Löschen bestätigen</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent id="confirm-dialog-content">
|
||||||
<Typography>
|
<Typography>
|
||||||
{this.state.itemToDelete &&
|
{this.state.itemToDelete &&
|
||||||
`Buchungsschlüssel "${this.state.itemToDelete.bu} - ${this.state.itemToDelete.name}" wirklich löschen?`
|
`Buchungsschlüssel "${this.state.itemToDelete.bu} - ${this.state.itemToDelete.name}" wirklich löschen?`
|
||||||
|
|||||||
@@ -43,6 +43,11 @@ class KontoTable extends Component {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
this.authService = new AuthService();
|
this.authService = new AuthService();
|
||||||
|
|
||||||
|
// Focus management refs
|
||||||
|
this.triggerRef = React.createRef();
|
||||||
|
this.dialogRef = React.createRef();
|
||||||
|
this.confirmDialogRef = React.createRef();
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
@@ -65,6 +70,9 @@ class KontoTable extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
handleOpenDialog = (konto = null) => {
|
handleOpenDialog = (konto = null) => {
|
||||||
|
// Store reference to the trigger element for focus restoration
|
||||||
|
this.triggerRef.current = document.activeElement;
|
||||||
|
|
||||||
this.setState({
|
this.setState({
|
||||||
dialogOpen: true,
|
dialogOpen: true,
|
||||||
editingKonto: konto,
|
editingKonto: konto,
|
||||||
@@ -87,6 +95,13 @@ class KontoTable extends Component {
|
|||||||
name: '',
|
name: '',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
handleInputChange = (field) => (event) => {
|
handleInputChange = (field) => (event) => {
|
||||||
@@ -98,6 +113,12 @@ class KontoTable extends Component {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
isFormValid = () => {
|
||||||
|
const { formData } = this.state;
|
||||||
|
return formData.konto.trim() !== '' &&
|
||||||
|
formData.name.trim() !== '';
|
||||||
|
};
|
||||||
|
|
||||||
handleSave = async () => {
|
handleSave = async () => {
|
||||||
const { editingKonto, formData } = this.state;
|
const { editingKonto, formData } = this.state;
|
||||||
|
|
||||||
@@ -128,6 +149,9 @@ class KontoTable extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
handleDeleteClick = (konto) => {
|
handleDeleteClick = (konto) => {
|
||||||
|
// Store reference to the trigger element for focus restoration
|
||||||
|
this.triggerRef.current = document.activeElement;
|
||||||
|
|
||||||
this.setState({
|
this.setState({
|
||||||
confirmDialogOpen: true,
|
confirmDialogOpen: true,
|
||||||
itemToDelete: konto,
|
itemToDelete: konto,
|
||||||
@@ -139,6 +163,13 @@ class KontoTable extends Component {
|
|||||||
if (!itemToDelete) return;
|
if (!itemToDelete) return;
|
||||||
|
|
||||||
this.setState({ confirmDialogOpen: false, itemToDelete: null });
|
this.setState({ confirmDialogOpen: false, itemToDelete: null });
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.authService.apiCall(`/admin/konten/${konto.id}`, {
|
const response = await this.authService.apiCall(`/admin/konten/${konto.id}`, {
|
||||||
@@ -162,6 +193,13 @@ class KontoTable extends Component {
|
|||||||
confirmDialogOpen: false,
|
confirmDialogOpen: false,
|
||||||
itemToDelete: null,
|
itemToDelete: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
@@ -229,11 +267,22 @@ class KontoTable extends Component {
|
|||||||
</Table>
|
</Table>
|
||||||
</TableContainer>
|
</TableContainer>
|
||||||
|
|
||||||
<Dialog open={dialogOpen} onClose={this.handleCloseDialog} maxWidth="sm" fullWidth>
|
<Dialog
|
||||||
<DialogTitle>
|
open={dialogOpen}
|
||||||
|
onClose={this.handleCloseDialog}
|
||||||
|
maxWidth="sm"
|
||||||
|
fullWidth
|
||||||
|
ref={this.dialogRef}
|
||||||
|
disableAutoFocus={false}
|
||||||
|
disableEnforceFocus={false}
|
||||||
|
disableRestoreFocus={true}
|
||||||
|
aria-labelledby="konto-dialog-title"
|
||||||
|
aria-describedby="konto-dialog-content"
|
||||||
|
>
|
||||||
|
<DialogTitle id="konto-dialog-title">
|
||||||
{editingKonto ? 'Konto bearbeiten' : 'Neues Konto'}
|
{editingKonto ? 'Konto bearbeiten' : 'Neues Konto'}
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent id="konto-dialog-content">
|
||||||
<TextField
|
<TextField
|
||||||
autoFocus
|
autoFocus
|
||||||
margin="dense"
|
margin="dense"
|
||||||
@@ -257,7 +306,11 @@ class KontoTable extends Component {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={this.handleCloseDialog}>Abbrechen</Button>
|
<Button onClick={this.handleCloseDialog}>Abbrechen</Button>
|
||||||
<Button onClick={this.handleSave} variant="contained">
|
<Button
|
||||||
|
onClick={this.handleSave}
|
||||||
|
variant="contained"
|
||||||
|
disabled={!this.isFormValid()}
|
||||||
|
>
|
||||||
Speichern
|
Speichern
|
||||||
</Button>
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
@@ -269,9 +322,15 @@ class KontoTable extends Component {
|
|||||||
onClose={this.handleDeleteCancel}
|
onClose={this.handleDeleteCancel}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
fullWidth
|
fullWidth
|
||||||
|
ref={this.confirmDialogRef}
|
||||||
|
disableAutoFocus={false}
|
||||||
|
disableEnforceFocus={false}
|
||||||
|
disableRestoreFocus={true}
|
||||||
|
aria-labelledby="konto-confirm-dialog-title"
|
||||||
|
aria-describedby="konto-confirm-dialog-content"
|
||||||
>
|
>
|
||||||
<DialogTitle>Löschen bestätigen</DialogTitle>
|
<DialogTitle id="konto-confirm-dialog-title">Löschen bestätigen</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent id="konto-confirm-dialog-content">
|
||||||
<Typography>
|
<Typography>
|
||||||
{this.state.itemToDelete &&
|
{this.state.itemToDelete &&
|
||||||
`Konto "${this.state.itemToDelete.konto} - ${this.state.itemToDelete.name}" wirklich löschen?`
|
`Konto "${this.state.itemToDelete.konto} - ${this.state.itemToDelete.name}" wirklich löschen?`
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import {
|
|||||||
Typography,
|
Typography,
|
||||||
Alert,
|
Alert,
|
||||||
CircularProgress,
|
CircularProgress,
|
||||||
|
Checkbox,
|
||||||
|
FormControlLabel,
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
import {
|
import {
|
||||||
Add as AddIcon,
|
Add as AddIcon,
|
||||||
@@ -41,9 +43,15 @@ class KreditorTable extends Component {
|
|||||||
iban: '',
|
iban: '',
|
||||||
name: '',
|
name: '',
|
||||||
kreditorId: '',
|
kreditorId: '',
|
||||||
|
is_banking: false,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
this.authService = new AuthService();
|
this.authService = new AuthService();
|
||||||
|
|
||||||
|
// Focus management refs
|
||||||
|
this.triggerRef = React.createRef();
|
||||||
|
this.dialogRef = React.createRef();
|
||||||
|
this.confirmDialogRef = React.createRef();
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
@@ -66,17 +74,22 @@ class KreditorTable extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
handleOpenDialog = (kreditor = null) => {
|
handleOpenDialog = (kreditor = null) => {
|
||||||
|
// Store reference to the trigger element for focus restoration
|
||||||
|
this.triggerRef.current = document.activeElement;
|
||||||
|
|
||||||
this.setState({
|
this.setState({
|
||||||
dialogOpen: true,
|
dialogOpen: true,
|
||||||
editingKreditor: kreditor,
|
editingKreditor: kreditor,
|
||||||
formData: kreditor ? {
|
formData: kreditor ? {
|
||||||
iban: kreditor.iban,
|
iban: kreditor.iban || '',
|
||||||
name: kreditor.name,
|
name: kreditor.name,
|
||||||
kreditorId: kreditor.kreditorId,
|
kreditorId: kreditor.kreditorId,
|
||||||
|
is_banking: Boolean(kreditor.is_banking),
|
||||||
} : {
|
} : {
|
||||||
iban: '',
|
iban: '',
|
||||||
name: '',
|
name: '',
|
||||||
kreditorId: '',
|
kreditorId: '',
|
||||||
|
is_banking: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -89,8 +102,16 @@ class KreditorTable extends Component {
|
|||||||
iban: '',
|
iban: '',
|
||||||
name: '',
|
name: '',
|
||||||
kreditorId: '',
|
kreditorId: '',
|
||||||
|
is_banking: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
handleInputChange = (field) => (event) => {
|
handleInputChange = (field) => (event) => {
|
||||||
@@ -102,6 +123,26 @@ class KreditorTable extends Component {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
handleCheckboxChange = (field) => (event) => {
|
||||||
|
this.setState({
|
||||||
|
formData: {
|
||||||
|
...this.state.formData,
|
||||||
|
[field]: event.target.checked,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
isFormValid = () => {
|
||||||
|
const { formData } = this.state;
|
||||||
|
// Name and kreditorId are always required
|
||||||
|
const basicFieldsValid = formData.name.trim() !== '' && formData.kreditorId.trim() !== '';
|
||||||
|
|
||||||
|
// IBAN is optional for banking accounts, required for regular kreditors
|
||||||
|
const ibanValid = formData.is_banking || formData.iban.trim() !== '';
|
||||||
|
|
||||||
|
return basicFieldsValid && ibanValid;
|
||||||
|
};
|
||||||
|
|
||||||
handleSave = async () => {
|
handleSave = async () => {
|
||||||
const { editingKreditor, formData } = this.state;
|
const { editingKreditor, formData } = this.state;
|
||||||
|
|
||||||
@@ -132,6 +173,9 @@ class KreditorTable extends Component {
|
|||||||
};
|
};
|
||||||
|
|
||||||
handleDeleteClick = (kreditor) => {
|
handleDeleteClick = (kreditor) => {
|
||||||
|
// Store reference to the trigger element for focus restoration
|
||||||
|
this.triggerRef.current = document.activeElement;
|
||||||
|
|
||||||
this.setState({
|
this.setState({
|
||||||
confirmDialogOpen: true,
|
confirmDialogOpen: true,
|
||||||
itemToDelete: kreditor,
|
itemToDelete: kreditor,
|
||||||
@@ -143,9 +187,16 @@ class KreditorTable extends Component {
|
|||||||
if (!itemToDelete) return;
|
if (!itemToDelete) return;
|
||||||
|
|
||||||
this.setState({ confirmDialogOpen: false, itemToDelete: null });
|
this.setState({ confirmDialogOpen: false, itemToDelete: null });
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.authService.apiCall(`/admin/kreditoren/${kreditor.id}`, {
|
const response = await this.authService.apiCall(`/admin/kreditoren/${itemToDelete.id}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -166,6 +217,13 @@ class KreditorTable extends Component {
|
|||||||
confirmDialogOpen: false,
|
confirmDialogOpen: false,
|
||||||
itemToDelete: null,
|
itemToDelete: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.triggerRef.current && this.triggerRef.current.focus) {
|
||||||
|
this.triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
@@ -205,6 +263,7 @@ class KreditorTable extends Component {
|
|||||||
<TableCell>Kreditor ID</TableCell>
|
<TableCell>Kreditor ID</TableCell>
|
||||||
<TableCell>Name</TableCell>
|
<TableCell>Name</TableCell>
|
||||||
<TableCell>IBAN</TableCell>
|
<TableCell>IBAN</TableCell>
|
||||||
|
<TableCell>Typ</TableCell>
|
||||||
<TableCell align="right">Aktionen</TableCell>
|
<TableCell align="right">Aktionen</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
@@ -213,7 +272,18 @@ class KreditorTable extends Component {
|
|||||||
<TableRow key={kreditor.id}>
|
<TableRow key={kreditor.id}>
|
||||||
<TableCell>{kreditor.kreditorId}</TableCell>
|
<TableCell>{kreditor.kreditorId}</TableCell>
|
||||||
<TableCell>{kreditor.name}</TableCell>
|
<TableCell>{kreditor.name}</TableCell>
|
||||||
<TableCell>{kreditor.iban}</TableCell>
|
<TableCell style={{
|
||||||
|
color: kreditor.is_banking ? '#ff5722' : 'inherit',
|
||||||
|
fontWeight: kreditor.is_banking ? 'bold' : 'normal'
|
||||||
|
}}>
|
||||||
|
{kreditor.iban || 'Keine IBAN'}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{kreditor.is_banking ?
|
||||||
|
<span style={{ color: '#ff5722', fontWeight: 'bold' }}>Banking</span> :
|
||||||
|
'Kreditor'
|
||||||
|
}
|
||||||
|
</TableCell>
|
||||||
<TableCell align="right">
|
<TableCell align="right">
|
||||||
<IconButton
|
<IconButton
|
||||||
size="small"
|
size="small"
|
||||||
@@ -235,11 +305,22 @@ class KreditorTable extends Component {
|
|||||||
</Table>
|
</Table>
|
||||||
</TableContainer>
|
</TableContainer>
|
||||||
|
|
||||||
<Dialog open={dialogOpen} onClose={this.handleCloseDialog} maxWidth="sm" fullWidth>
|
<Dialog
|
||||||
<DialogTitle>
|
open={dialogOpen}
|
||||||
|
onClose={this.handleCloseDialog}
|
||||||
|
maxWidth="sm"
|
||||||
|
fullWidth
|
||||||
|
ref={this.dialogRef}
|
||||||
|
disableAutoFocus={false}
|
||||||
|
disableEnforceFocus={false}
|
||||||
|
disableRestoreFocus={true}
|
||||||
|
aria-labelledby="kreditor-dialog-title"
|
||||||
|
aria-describedby="kreditor-dialog-content"
|
||||||
|
>
|
||||||
|
<DialogTitle id="kreditor-dialog-title">
|
||||||
{editingKreditor ? 'Kreditor bearbeiten' : 'Neuer Kreditor'}
|
{editingKreditor ? 'Kreditor bearbeiten' : 'Neuer Kreditor'}
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent id="kreditor-dialog-content">
|
||||||
<TextField
|
<TextField
|
||||||
autoFocus
|
autoFocus
|
||||||
margin="dense"
|
margin="dense"
|
||||||
@@ -266,11 +347,27 @@ class KreditorTable extends Component {
|
|||||||
variant="outlined"
|
variant="outlined"
|
||||||
value={formData.iban}
|
value={formData.iban}
|
||||||
onChange={this.handleInputChange('iban')}
|
onChange={this.handleInputChange('iban')}
|
||||||
|
helperText={formData.is_banking ? "IBAN ist optional für Banking-Konten" : ""}
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
<FormControlLabel
|
||||||
|
control={
|
||||||
|
<Checkbox
|
||||||
|
checked={formData.is_banking}
|
||||||
|
onChange={this.handleCheckboxChange('is_banking')}
|
||||||
|
color="primary"
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
label="Banking-Konto (z.B. PayPal) - benötigt manuelle Kreditor-Zuordnung"
|
||||||
/>
|
/>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={this.handleCloseDialog}>Abbrechen</Button>
|
<Button onClick={this.handleCloseDialog}>Abbrechen</Button>
|
||||||
<Button onClick={this.handleSave} variant="contained">
|
<Button
|
||||||
|
onClick={this.handleSave}
|
||||||
|
variant="contained"
|
||||||
|
disabled={!this.isFormValid()}
|
||||||
|
>
|
||||||
Speichern
|
Speichern
|
||||||
</Button>
|
</Button>
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
@@ -282,9 +379,15 @@ class KreditorTable extends Component {
|
|||||||
onClose={this.handleDeleteCancel}
|
onClose={this.handleDeleteCancel}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
fullWidth
|
fullWidth
|
||||||
|
ref={this.confirmDialogRef}
|
||||||
|
disableAutoFocus={false}
|
||||||
|
disableEnforceFocus={false}
|
||||||
|
disableRestoreFocus={true}
|
||||||
|
aria-labelledby="kreditor-confirm-dialog-title"
|
||||||
|
aria-describedby="kreditor-confirm-dialog-content"
|
||||||
>
|
>
|
||||||
<DialogTitle>Löschen bestätigen</DialogTitle>
|
<DialogTitle id="kreditor-confirm-dialog-title">Löschen bestätigen</DialogTitle>
|
||||||
<DialogContent>
|
<DialogContent id="kreditor-confirm-dialog-content">
|
||||||
<Typography>
|
<Typography>
|
||||||
{this.state.itemToDelete &&
|
{this.state.itemToDelete &&
|
||||||
`Kreditor "${this.state.itemToDelete.name}" wirklich löschen?`
|
`Kreditor "${this.state.itemToDelete.name}" wirklich löschen?`
|
||||||
|
|||||||
@@ -15,7 +15,9 @@ import {
|
|||||||
Divider,
|
Divider,
|
||||||
Tabs,
|
Tabs,
|
||||||
Tab,
|
Tab,
|
||||||
Alert
|
Alert,
|
||||||
|
Chip,
|
||||||
|
Paper
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
import {
|
import {
|
||||||
PictureAsPdf as PdfIcon,
|
PictureAsPdf as PdfIcon,
|
||||||
@@ -26,6 +28,8 @@ import {
|
|||||||
} from '@mui/icons-material';
|
} from '@mui/icons-material';
|
||||||
import { AgGridReact } from 'ag-grid-react';
|
import { AgGridReact } from 'ag-grid-react';
|
||||||
import KreditorSelector from '../KreditorSelector';
|
import KreditorSelector from '../KreditorSelector';
|
||||||
|
import BankingKreditorSelector from '../BankingKreditorSelector';
|
||||||
|
import AccountingItemsManager from '../AccountingItemsManager';
|
||||||
|
|
||||||
const DocumentRenderer = (params) => {
|
const DocumentRenderer = (params) => {
|
||||||
// Check for pdfs and links regardless of transaction source
|
// Check for pdfs and links regardless of transaction source
|
||||||
@@ -35,6 +39,10 @@ const DocumentRenderer = (params) => {
|
|||||||
const [tabValue, setTabValue] = useState(0);
|
const [tabValue, setTabValue] = useState(0);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
|
|
||||||
|
// Focus management refs
|
||||||
|
const triggerRef = React.useRef(null);
|
||||||
|
const dialogRef = React.useRef(null);
|
||||||
|
|
||||||
// Always show something clickable, even if no documents
|
// Always show something clickable, even if no documents
|
||||||
const hasDocuments = pdfs.length > 0 || links.length > 0;
|
const hasDocuments = pdfs.length > 0 || links.length > 0;
|
||||||
|
|
||||||
@@ -47,6 +55,8 @@ const DocumentRenderer = (params) => {
|
|||||||
const totalCount = allDocuments.length;
|
const totalCount = allDocuments.length;
|
||||||
|
|
||||||
const handleClick = () => {
|
const handleClick = () => {
|
||||||
|
// Store reference to the trigger element for focus restoration
|
||||||
|
triggerRef.current = document.activeElement;
|
||||||
setDialogOpen(true);
|
setDialogOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -54,6 +64,13 @@ const DocumentRenderer = (params) => {
|
|||||||
setDialogOpen(false);
|
setDialogOpen(false);
|
||||||
setTabValue(0); // Reset to first tab when closing
|
setTabValue(0); // Reset to first tab when closing
|
||||||
setError(null); // Clear any errors when closing
|
setError(null); // Clear any errors when closing
|
||||||
|
|
||||||
|
// Restore focus to the trigger element after dialog closes
|
||||||
|
setTimeout(() => {
|
||||||
|
if (triggerRef.current && triggerRef.current.focus) {
|
||||||
|
triggerRef.current.focus();
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleTabChange = (event, newValue) => {
|
const handleTabChange = (event, newValue) => {
|
||||||
@@ -119,10 +136,10 @@ const DocumentRenderer = (params) => {
|
|||||||
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
|
setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error opening PDF:', error);
|
console.error('Error opening PDF:', error);
|
||||||
setError('Fehler beim Öffnen des PDFs. Bitte versuchen Sie es erneut.');
|
setError('Fehler beim Öffnen des PDFs. Bitte versuchen Sie es erneut.');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Extract line items from document extraction data
|
// Extract line items from document extraction data
|
||||||
@@ -321,11 +338,41 @@ const DocumentRenderer = (params) => {
|
|||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Dialog open={dialogOpen} onClose={handleClose} maxWidth="lg" fullWidth>
|
<Dialog
|
||||||
<DialogTitle>
|
open={dialogOpen}
|
||||||
|
onClose={handleClose}
|
||||||
|
maxWidth="lg"
|
||||||
|
fullWidth
|
||||||
|
ref={dialogRef}
|
||||||
|
disableAutoFocus={false}
|
||||||
|
disableEnforceFocus={false}
|
||||||
|
disableRestoreFocus={true}
|
||||||
|
aria-labelledby="document-dialog-title"
|
||||||
|
aria-describedby="document-dialog-content"
|
||||||
|
>
|
||||||
|
<DialogTitle id="document-dialog-title">
|
||||||
{hasDocuments ? `Dokumente (${totalCount})` : 'Dokumentinformationen'}
|
{hasDocuments ? `Dokumente (${totalCount})` : 'Dokumentinformationen'}
|
||||||
|
{!params.data['Kontonummer/IBAN'] && (
|
||||||
|
<Typography variant="caption" sx={{ display: 'block', color: '#ff5722', fontWeight: 'normal' }}>
|
||||||
|
Banking-Transaktion • Kreditor-Zuordnung erforderlich
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
|
{params.data.description && (
|
||||||
|
<Typography variant="body2" sx={{
|
||||||
|
display: 'block',
|
||||||
|
color: 'text.secondary',
|
||||||
|
fontWeight: 'normal',
|
||||||
|
mt: 1,
|
||||||
|
p: 1,
|
||||||
|
bgcolor: '#f5f5f5',
|
||||||
|
borderRadius: 1,
|
||||||
|
border: '1px solid #e0e0e0'
|
||||||
|
}}>
|
||||||
|
<strong>Beschreibung:</strong> {params.data.description}
|
||||||
|
</Typography>
|
||||||
|
)}
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogContent sx={{ p: 0 }}>
|
<DialogContent sx={{ p: 0 }} id="document-dialog-content">
|
||||||
{error && (
|
{error && (
|
||||||
<Alert severity="error" sx={{ m: 2 }} onClose={() => setError(null)}>
|
<Alert severity="error" sx={{ m: 2 }} onClose={() => setError(null)}>
|
||||||
{error}
|
{error}
|
||||||
@@ -335,6 +382,23 @@ const DocumentRenderer = (params) => {
|
|||||||
<Tabs value={tabValue} onChange={handleTabChange}>
|
<Tabs value={tabValue} onChange={handleTabChange}>
|
||||||
<Tab label="Dokumente" />
|
<Tab label="Dokumente" />
|
||||||
<Tab label={`Buchungen (${lineItems.length})`} />
|
<Tab label={`Buchungen (${lineItems.length})`} />
|
||||||
|
<Tab
|
||||||
|
label="Kreditor"
|
||||||
|
sx={{
|
||||||
|
color: !params.data['Kontonummer/IBAN']
|
||||||
|
? 'text.secondary'
|
||||||
|
: (params.data.hasKreditor && params.data.kreditor && !params.data.kreditor.is_banking) || params.data.assignedKreditor
|
||||||
|
? 'success.main'
|
||||||
|
: 'warning.main',
|
||||||
|
'&.Mui-selected': {
|
||||||
|
color: !params.data['Kontonummer/IBAN']
|
||||||
|
? 'text.secondary'
|
||||||
|
: (params.data.hasKreditor && params.data.kreditor && !params.data.kreditor.is_banking) || params.data.assignedKreditor
|
||||||
|
? 'success.main'
|
||||||
|
: 'warning.main',
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
@@ -403,34 +467,242 @@ const DocumentRenderer = (params) => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{tabValue === 1 && (
|
{tabValue === 1 && (
|
||||||
<Box sx={{ p: 2, height: 500 }}>
|
<Box sx={{ p: 2 }}>
|
||||||
{lineItems.length > 0 ? (
|
{/* Accounting Items Manager */}
|
||||||
<div style={{ height: '100%', width: '100%' }}>
|
<AccountingItemsManager transaction={params.data} />
|
||||||
<AgGridReact
|
|
||||||
columnDefs={columnDefs}
|
{/* Document Line Items (if any) */}
|
||||||
rowData={lineItems}
|
{lineItems.length > 0 && (
|
||||||
defaultColDef={defaultColDef}
|
<Box sx={{ mt: 3 }}>
|
||||||
suppressRowTransform={true}
|
<Typography variant="h6" gutterBottom>
|
||||||
rowHeight={50}
|
Erkannte Positionen aus Dokumenten
|
||||||
headerHeight={35}
|
|
||||||
domLayout="normal"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<Box sx={{ textAlign: 'center', py: 4 }}>
|
|
||||||
<Typography variant="h6" color="textSecondary" gutterBottom>
|
|
||||||
Keine Buchungsdaten verfügbar
|
|
||||||
</Typography>
|
|
||||||
<Typography variant="body2" color="textSecondary">
|
|
||||||
{hasDocuments
|
|
||||||
? 'In den vorhandenen Dokumenten wurden keine Buchungsdaten gefunden.'
|
|
||||||
: 'Keine Dokumente vorhanden, daher keine Buchungsdaten verfügbar.'
|
|
||||||
}
|
|
||||||
</Typography>
|
</Typography>
|
||||||
|
<div style={{ height: '300px', width: '100%' }}>
|
||||||
|
<AgGridReact
|
||||||
|
columnDefs={columnDefs}
|
||||||
|
rowData={lineItems}
|
||||||
|
defaultColDef={defaultColDef}
|
||||||
|
suppressRowTransform={true}
|
||||||
|
rowHeight={50}
|
||||||
|
headerHeight={35}
|
||||||
|
domLayout="normal"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{tabValue === 2 && (
|
||||||
|
<Box sx={{ p: 2 }}>
|
||||||
|
<Typography variant="h6" gutterBottom>
|
||||||
|
Kreditor Information
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Paper sx={{ p: 2, mb: 2 }}>
|
||||||
|
<Typography variant="subtitle2" gutterBottom>
|
||||||
|
IBAN
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body1" sx={{ mb: 2 }}>
|
||||||
|
{params.data['Kontonummer/IBAN'] || 'Keine IBAN verfügbar'}
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{/* Show different content based on IBAN availability and Kreditor status */}
|
||||||
|
{!params.data['Kontonummer/IBAN'] ? (
|
||||||
|
<Box>
|
||||||
|
<Chip
|
||||||
|
label="Banking-Transaktion"
|
||||||
|
color="warning"
|
||||||
|
size="small"
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
<Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
|
||||||
|
Diese Transaktion wurde über ein Banking-Konto (z.B. PayPal) abgewickelt und benötigt eine Kreditor-Zuordnung.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{/* Show current assignment or assignment form for banking transactions */}
|
||||||
|
{params.data.assignedKreditor ? (
|
||||||
|
<Box sx={{ p: 2, bgcolor: '#e8f5e8', borderRadius: 1, mb: 2 }}>
|
||||||
|
<Typography variant="body2" sx={{ color: '#2e7d32', fontWeight: 'bold' }}>
|
||||||
|
✅ Zugeordnet zu: {params.data.assignedKreditor.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" sx={{ color: '#666' }}>
|
||||||
|
Kreditor ID: {params.data.assignedKreditor.kreditorId}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Box>
|
||||||
|
<Typography variant="body2" sx={{ mb: 2, color: '#ff5722', fontWeight: 'bold' }}>
|
||||||
|
⚠️ Keine Zuordnung - Bitte Kreditor zuweisen
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" sx={{ color: '#666', mb: 2, display: 'block' }}>
|
||||||
|
Wählen Sie einen bestehenden Kreditor aus oder erstellen Sie einen neuen Kreditor:
|
||||||
|
</Typography>
|
||||||
|
<BankingKreditorSelector
|
||||||
|
transaction={params.data}
|
||||||
|
user={params.context?.user}
|
||||||
|
onSave={async (assignedKreditor) => {
|
||||||
|
// Update the transaction data with the new assignment
|
||||||
|
if (assignedKreditor) {
|
||||||
|
params.data.assignedKreditor = assignedKreditor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the entire row to update colors and content
|
||||||
|
if (params.api) {
|
||||||
|
params.api.refreshCells({
|
||||||
|
rowNodes: [params.node],
|
||||||
|
force: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Force dialog re-render by updating state
|
||||||
|
this.forceUpdate();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
) : params.data.hasKreditor ? (
|
||||||
|
<Box>
|
||||||
|
{!params.data.kreditor?.is_banking && (
|
||||||
|
<Chip
|
||||||
|
label="Kreditor gefunden"
|
||||||
|
color="success"
|
||||||
|
size="small"
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{params.data.kreditor?.is_banking && (
|
||||||
|
<Chip
|
||||||
|
label="Banking-Konto erkannt"
|
||||||
|
color="warning"
|
||||||
|
size="small"
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Box sx={{ mt: 2 }}>
|
||||||
|
<Typography variant="subtitle2" gutterBottom>
|
||||||
|
Kreditor Details
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2">
|
||||||
|
<strong>Name:</strong> {params.data.kreditor.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2">
|
||||||
|
<strong>Kreditor ID:</strong> {params.data.kreditor.kreditorId}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2">
|
||||||
|
<strong>Typ:</strong> {params.data.kreditor.is_banking ? 'Banking-Konto' : 'Kreditor'}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{/* Banking Account Assignment Section */}
|
||||||
|
{params.data.kreditor.is_banking && (
|
||||||
|
<Box sx={{ mt: 3, p: 2, bgcolor: '#fff3e0', borderRadius: 1, border: '1px solid #ff9800' }}>
|
||||||
|
<Typography variant="subtitle2" gutterBottom sx={{ color: '#ff5722', fontWeight: 'bold' }}>
|
||||||
|
🏦 Banking-Konto Zuordnung
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="body2" sx={{ mb: 2, color: '#666' }}>
|
||||||
|
Dieses IBAN ist ein Banking-Konto (z.B. PayPal). Transaktionen müssen einem echten Kreditor zugeordnet werden.
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
{/* Show current assignment or assignment form */}
|
||||||
|
{params.data.assignedKreditor ? (
|
||||||
|
<Box sx={{ p: 2, bgcolor: '#e8f5e8', borderRadius: 1, mb: 2 }}>
|
||||||
|
<Typography variant="body2" sx={{ color: '#2e7d32', fontWeight: 'bold' }}>
|
||||||
|
✅ Zugeordnet zu: {params.data.assignedKreditor.name}
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" sx={{ color: '#666' }}>
|
||||||
|
Kreditor ID: {params.data.assignedKreditor.kreditorId}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Box>
|
||||||
|
<Typography variant="body2" sx={{ mb: 2, color: '#ff5722', fontWeight: 'bold' }}>
|
||||||
|
⚠️ Keine Zuordnung - Bitte Kreditor zuweisen
|
||||||
|
</Typography>
|
||||||
|
<Typography variant="caption" sx={{ color: '#666', mb: 2, display: 'block' }}>
|
||||||
|
Wählen Sie den echten Kreditor für diese Banking-Transaktion aus:
|
||||||
|
</Typography>
|
||||||
|
<BankingKreditorSelector
|
||||||
|
transaction={params.data}
|
||||||
|
user={params.context?.user}
|
||||||
|
onSave={async (assignedKreditor) => {
|
||||||
|
// Update the transaction data with the new assignment
|
||||||
|
if (assignedKreditor) {
|
||||||
|
params.data.assignedKreditor = assignedKreditor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the entire row to update colors and content
|
||||||
|
if (params.api) {
|
||||||
|
params.api.refreshCells({
|
||||||
|
rowNodes: [params.node],
|
||||||
|
force: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Force dialog re-render by updating state
|
||||||
|
this.forceUpdate();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
) : (
|
||||||
|
<Box>
|
||||||
|
<Chip
|
||||||
|
label="Kein Kreditor gefunden"
|
||||||
|
color="warning"
|
||||||
|
size="small"
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
<Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
|
||||||
|
Sie können einen neuen Kreditor für diese IBAN erstellen:
|
||||||
|
</Typography>
|
||||||
|
<KreditorSelector
|
||||||
|
selectedKreditorId=""
|
||||||
|
onKreditorChange={(kreditor) => {
|
||||||
|
console.log('Kreditor selected/created:', kreditor);
|
||||||
|
if (kreditor) {
|
||||||
|
// Update the transaction data to reflect the new kreditor
|
||||||
|
params.data.kreditor = kreditor;
|
||||||
|
params.data.hasKreditor = true;
|
||||||
|
|
||||||
|
// Update all transactions with the same IBAN in the grid
|
||||||
|
if (params.api && kreditor.iban) {
|
||||||
|
const nodesToRefresh = [];
|
||||||
|
params.api.forEachNode((node) => {
|
||||||
|
if (node.data && node.data['Kontonummer/IBAN'] === kreditor.iban) {
|
||||||
|
node.data.kreditor = kreditor;
|
||||||
|
node.data.hasKreditor = true;
|
||||||
|
nodesToRefresh.push(node);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Refresh specific cells to show updated colors and data
|
||||||
|
if (nodesToRefresh.length > 0) {
|
||||||
|
params.api.refreshCells({
|
||||||
|
rowNodes: nodesToRefresh,
|
||||||
|
columns: ['Kontonummer/IBAN'],
|
||||||
|
force: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close and reopen dialog to show updated status
|
||||||
|
setDialogOpen(false);
|
||||||
|
setTimeout(() => setDialogOpen(true), 100);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
prefilledIban={params.data['Kontonummer/IBAN']}
|
||||||
|
prefilledName={params.data['Beguenstigter/Zahlungspflichtiger']}
|
||||||
|
allowCreate={true}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Paper>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
<DialogActions>
|
<DialogActions>
|
||||||
<Button onClick={handleClose}>Schließen</Button>
|
<Button onClick={handleClose}>Schließen</Button>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ const RecipientRenderer = (params) => {
|
|||||||
// Stop event propagation to prevent row selection
|
// Stop event propagation to prevent row selection
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
|
||||||
// Apply filter to IBAN column using the custom IbanSelectionFilter format
|
// Default behavior: Apply filter to IBAN column
|
||||||
const currentFilterModel = params.api.getFilterModel();
|
const currentFilterModel = params.api.getFilterModel();
|
||||||
params.api.setFilterModel({
|
params.api.setFilterModel({
|
||||||
...currentFilterModel,
|
...currentFilterModel,
|
||||||
@@ -21,17 +21,63 @@ const RecipientRenderer = (params) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Determine color based on Kreditor status for IBAN column
|
||||||
|
const getIbanColor = () => {
|
||||||
|
if (!isIbanColumn || !value) return 'inherit';
|
||||||
|
|
||||||
|
|
||||||
|
// Check if this transaction has Kreditor information
|
||||||
|
if (params.data && params.data.hasKreditor) {
|
||||||
|
// Check if the kreditor is a banking account
|
||||||
|
if (params.data.kreditor?.is_banking) {
|
||||||
|
// Check if banking transaction has assigned kreditor
|
||||||
|
if (params.data.assignedKreditor) {
|
||||||
|
return '#00e676'; // Bright neon green for banking account with assigned kreditor
|
||||||
|
} else {
|
||||||
|
return '#ff5722'; // Red-orange for banking account needing assignment
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return '#2e7d32'; // Dark green for regular kreditor
|
||||||
|
}
|
||||||
|
} else if (params.data && value) {
|
||||||
|
return '#ed6c02'; // Orange for IBAN without Kreditor
|
||||||
|
}
|
||||||
|
|
||||||
|
return '#1976d2'; // Default blue for clickable IBAN
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTitle = () => {
|
||||||
|
if (!isIbanColumn || !value) return undefined;
|
||||||
|
|
||||||
|
if (params.data && params.data.hasKreditor) {
|
||||||
|
if (params.data.kreditor?.is_banking) {
|
||||||
|
if (params.data.assignedKreditor) {
|
||||||
|
return `Banking-IBAN "${value}" - Zugeordnet zu: ${params.data.assignedKreditor.name} (zum Filtern klicken)`;
|
||||||
|
} else {
|
||||||
|
return `Banking-IBAN "${value}" - BENÖTIGT KREDITOR-ZUORDNUNG (zum Filtern klicken)`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return `IBAN "${value}" - Kreditor: ${params.data.kreditor?.name || 'Unbekannt'} (zum Filtern klicken)`;
|
||||||
|
}
|
||||||
|
} else if (params.data && value) {
|
||||||
|
return `IBAN "${value}" - Kein Kreditor gefunden (zum Filtern klicken)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `Nach IBAN "${value}" filtern`;
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
style={{
|
style={{
|
||||||
fontSize: '0.7rem',
|
fontSize: '0.7rem',
|
||||||
lineHeight: '1.2',
|
lineHeight: '1.2',
|
||||||
cursor: isIbanColumn && value ? 'pointer' : 'default',
|
cursor: isIbanColumn && value ? 'pointer' : 'default',
|
||||||
color: isIbanColumn && value ? '#1976d2' : 'inherit',
|
color: getIbanColor(),
|
||||||
textDecoration: isIbanColumn && value ? 'underline' : 'none'
|
textDecoration: isIbanColumn && value ? 'underline' : 'none',
|
||||||
|
fontWeight: isIbanColumn && params.data && params.data.hasKreditor ? 'bold' : 'normal'
|
||||||
}}
|
}}
|
||||||
onClick={isIbanColumn && value ? handleClick : undefined}
|
onClick={isIbanColumn && value ? handleClick : undefined}
|
||||||
title={isIbanColumn && value ? `Nach IBAN "${value}" filtern` : undefined}
|
title={getTitle()}
|
||||||
>
|
>
|
||||||
{value}
|
{value}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ export const getColumnDefs = () => [
|
|||||||
sortable: false,
|
sortable: false,
|
||||||
filter: false,
|
filter: false,
|
||||||
resizable: false,
|
resizable: false,
|
||||||
suppressMenu: true,
|
suppressHeaderMenuButton: true,
|
||||||
cellRenderer: SelectionRenderer,
|
cellRenderer: SelectionRenderer,
|
||||||
headerComponent: SelectionHeader,
|
headerComponent: SelectionHeader,
|
||||||
headerComponentParams: {
|
headerComponentParams: {
|
||||||
@@ -101,7 +101,6 @@ export const getColumnDefs = () => [
|
|||||||
width: 70,
|
width: 70,
|
||||||
cellRenderer: TypeRenderer,
|
cellRenderer: TypeRenderer,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
suppressSorting: true,
|
|
||||||
filter: CheckboxFilter,
|
filter: CheckboxFilter,
|
||||||
filterParams: {
|
filterParams: {
|
||||||
filterOptions: [
|
filterOptions: [
|
||||||
@@ -138,7 +137,6 @@ export const getColumnDefs = () => [
|
|||||||
width: 70,
|
width: 70,
|
||||||
cellRenderer: JtlRenderer,
|
cellRenderer: JtlRenderer,
|
||||||
sortable: false,
|
sortable: false,
|
||||||
suppressSorting: true,
|
|
||||||
filter: CheckboxFilter,
|
filter: CheckboxFilter,
|
||||||
filterParams: {
|
filterParams: {
|
||||||
filterOptions: [
|
filterOptions: [
|
||||||
@@ -212,7 +210,10 @@ export const defaultColDef = {
|
|||||||
|
|
||||||
export const gridOptions = {
|
export const gridOptions = {
|
||||||
animateRows: true,
|
animateRows: true,
|
||||||
rowSelection: false,
|
rowSelection: {
|
||||||
|
mode: 'multiRow',
|
||||||
|
enableClickSelection: false
|
||||||
|
},
|
||||||
rowBuffer: 10,
|
rowBuffer: 10,
|
||||||
// Enable virtualization (default behavior)
|
// Enable virtualization (default behavior)
|
||||||
suppressRowVirtualisation: false,
|
suppressRowVirtualisation: false,
|
||||||
@@ -225,8 +226,7 @@ export const gridOptions = {
|
|||||||
// Pagination (optional - can be removed for infinite scrolling)
|
// Pagination (optional - can be removed for infinite scrolling)
|
||||||
pagination: false,
|
pagination: false,
|
||||||
paginationPageSize: 100,
|
paginationPageSize: 100,
|
||||||
// Disable cell selection
|
// Disable cell selection and focus
|
||||||
suppressCellSelection: true,
|
cellSelection: false,
|
||||||
suppressRowClickSelection: true,
|
|
||||||
suppressCellFocus: true
|
suppressCellFocus: true
|
||||||
};
|
};
|
||||||
@@ -103,9 +103,13 @@ export default class CheckboxFilter {
|
|||||||
};
|
};
|
||||||
|
|
||||||
destroy() {
|
destroy() {
|
||||||
if (this.reactRoot) {
|
// Use setTimeout to avoid unmounting during render
|
||||||
this.reactRoot.unmount();
|
setTimeout(() => {
|
||||||
}
|
if (this.reactRoot) {
|
||||||
|
this.reactRoot.unmount();
|
||||||
|
this.reactRoot = null;
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
renderReactComponent() {
|
renderReactComponent() {
|
||||||
@@ -172,10 +176,13 @@ export default class CheckboxFilter {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Recreate React root every time to avoid state corruption
|
// Recreate React root every time to avoid state corruption
|
||||||
if (this.reactRoot) {
|
// Use setTimeout to avoid unmounting during render
|
||||||
this.reactRoot.unmount();
|
setTimeout(() => {
|
||||||
}
|
if (this.reactRoot) {
|
||||||
this.reactRoot = createRoot(this.eGui);
|
this.reactRoot.unmount();
|
||||||
this.reactRoot.render(<FilterComponent />);
|
}
|
||||||
|
this.reactRoot = createRoot(this.eGui);
|
||||||
|
this.reactRoot.render(<FilterComponent />);
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,20 +8,27 @@ import {
|
|||||||
ListItemText,
|
ListItemText,
|
||||||
Box,
|
Box,
|
||||||
Chip,
|
Chip,
|
||||||
Button
|
Button,
|
||||||
|
TextField,
|
||||||
|
Typography,
|
||||||
|
Divider
|
||||||
} from '@mui/material';
|
} from '@mui/material';
|
||||||
|
|
||||||
export default class IbanSelectionFilter {
|
export default class IbanSelectionFilter {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.state = {
|
this.state = {
|
||||||
selectedValues: [],
|
selectedValues: [],
|
||||||
availableValues: []
|
availableValues: [],
|
||||||
|
partialIban: ''
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create the DOM element that AG Grid expects
|
// Create the DOM element that AG Grid expects
|
||||||
this.eGui = document.createElement('div');
|
this.eGui = document.createElement('div');
|
||||||
this.eGui.style.minWidth = '250px';
|
this.eGui.style.minWidth = '250px';
|
||||||
this.eGui.style.padding = '8px';
|
this.eGui.style.padding = '8px';
|
||||||
|
|
||||||
|
// Create a ref for the text input
|
||||||
|
this.textInputRef = React.createRef();
|
||||||
}
|
}
|
||||||
|
|
||||||
init(params) {
|
init(params) {
|
||||||
@@ -35,10 +42,13 @@ export default class IbanSelectionFilter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
destroy() {
|
destroy() {
|
||||||
if (this.reactRoot) {
|
// Use setTimeout to avoid unmounting during render
|
||||||
this.reactRoot.unmount();
|
setTimeout(() => {
|
||||||
this.reactRoot = null;
|
if (this.reactRoot) {
|
||||||
}
|
this.reactRoot.unmount();
|
||||||
|
this.reactRoot = null;
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateAvailableValues() {
|
updateAvailableValues() {
|
||||||
@@ -72,15 +82,27 @@ export default class IbanSelectionFilter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isFilterActive() {
|
isFilterActive() {
|
||||||
return this.state.selectedValues.length > 0;
|
return this.state.selectedValues.length > 0 || this.state.partialIban.trim() !== '';
|
||||||
}
|
}
|
||||||
|
|
||||||
doesFilterPass(params) {
|
doesFilterPass(params) {
|
||||||
const { selectedValues } = this.state;
|
const { selectedValues, partialIban } = this.state;
|
||||||
if (selectedValues.length === 0) return true;
|
|
||||||
|
|
||||||
const value = params.data['Kontonummer/IBAN'];
|
const value = params.data['Kontonummer/IBAN'];
|
||||||
return selectedValues.includes(value);
|
|
||||||
|
// If no filters are active, show all rows
|
||||||
|
if (selectedValues.length === 0 && partialIban.trim() === '') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if row matches selected IBANs
|
||||||
|
const matchesSelected = selectedValues.length === 0 || selectedValues.includes(value);
|
||||||
|
|
||||||
|
// Check if row matches partial IBAN (case-insensitive)
|
||||||
|
const matchesPartial = partialIban.trim() === '' ||
|
||||||
|
(value && value.toLowerCase().includes(partialIban.toLowerCase()));
|
||||||
|
|
||||||
|
// Both conditions must be true (AND logic)
|
||||||
|
return matchesSelected && matchesPartial;
|
||||||
}
|
}
|
||||||
|
|
||||||
getModel() {
|
getModel() {
|
||||||
@@ -88,16 +110,28 @@ export default class IbanSelectionFilter {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
filterType: 'iban-selection',
|
filterType: 'iban-selection',
|
||||||
values: this.state.selectedValues
|
values: this.state.selectedValues,
|
||||||
|
partialIban: this.state.partialIban
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
setModel(model) {
|
setModel(model) {
|
||||||
if (!model) {
|
if (!model) {
|
||||||
this.state.selectedValues = [];
|
this.state.selectedValues = [];
|
||||||
|
this.state.partialIban = '';
|
||||||
} else {
|
} else {
|
||||||
this.state.selectedValues = model.values || [];
|
this.state.selectedValues = model.values || [];
|
||||||
|
this.state.partialIban = model.partialIban || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update the text field value directly if it exists
|
||||||
|
if (this.textInputRef.current) {
|
||||||
|
const inputElement = this.textInputRef.current.querySelector('input');
|
||||||
|
if (inputElement) {
|
||||||
|
inputElement.value = this.state.partialIban;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.renderReactComponent();
|
this.renderReactComponent();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,8 +145,39 @@ export default class IbanSelectionFilter {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
handlePartialIbanChange = (partialIban) => {
|
||||||
|
this.state.partialIban = partialIban;
|
||||||
|
|
||||||
|
// Update the clear button visibility without full re-render
|
||||||
|
this.updateClearButtonVisibility();
|
||||||
|
|
||||||
|
// Notify AG Grid that filter changed
|
||||||
|
if (this.params && this.params.filterChangedCallback) {
|
||||||
|
this.params.filterChangedCallback();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
updateClearButtonVisibility = () => {
|
||||||
|
// Find the clear button container and update its visibility
|
||||||
|
const clearButtonContainer = this.eGui.querySelector('.clear-button-container');
|
||||||
|
if (clearButtonContainer) {
|
||||||
|
const shouldShow = this.state.selectedValues.length > 0 || this.state.partialIban.trim() !== '';
|
||||||
|
clearButtonContainer.style.display = shouldShow ? 'block' : 'none';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
clearFilter = () => {
|
clearFilter = () => {
|
||||||
this.state.selectedValues = [];
|
this.state.selectedValues = [];
|
||||||
|
this.state.partialIban = '';
|
||||||
|
|
||||||
|
// Clear the text field directly using the ref
|
||||||
|
if (this.textInputRef.current) {
|
||||||
|
const inputElement = this.textInputRef.current.querySelector('input');
|
||||||
|
if (inputElement) {
|
||||||
|
inputElement.value = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.renderReactComponent();
|
this.renderReactComponent();
|
||||||
|
|
||||||
if (this.params && this.params.filterChangedCallback) {
|
if (this.params && this.params.filterChangedCallback) {
|
||||||
@@ -127,6 +192,27 @@ export default class IbanSelectionFilter {
|
|||||||
|
|
||||||
const FilterComponent = () => (
|
const FilterComponent = () => (
|
||||||
<Box sx={{ minWidth: 250 }} className="ag-filter-custom">
|
<Box sx={{ minWidth: 250 }} className="ag-filter-custom">
|
||||||
|
<Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 'bold' }}>
|
||||||
|
IBAN Filter
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
ref={this.textInputRef}
|
||||||
|
fullWidth
|
||||||
|
size="small"
|
||||||
|
label="IBAN eingeben"
|
||||||
|
placeholder="z.B. DE89, 1234..."
|
||||||
|
defaultValue={this.state.partialIban}
|
||||||
|
onChange={(event) => this.handlePartialIbanChange(event.target.value)}
|
||||||
|
sx={{ mb: 2 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Divider sx={{ mb: 2 }} />
|
||||||
|
|
||||||
|
<Typography variant="body2" sx={{ mb: 1, color: 'text.secondary' }}>
|
||||||
|
Oder aus der Liste auswählen:
|
||||||
|
</Typography>
|
||||||
|
|
||||||
<FormControl fullWidth size="small">
|
<FormControl fullWidth size="small">
|
||||||
<Select
|
<Select
|
||||||
multiple
|
multiple
|
||||||
@@ -138,7 +224,7 @@ export default class IbanSelectionFilter {
|
|||||||
return <em>Alle IBANs</em>;
|
return <em>Alle IBANs</em>;
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
||||||
{selected.slice(0, 2).map((value) => {
|
{selected.slice(0, 2).map((value) => {
|
||||||
const ibanData = this.availableValues.find(item => item.iban === value);
|
const ibanData = this.availableValues.find(item => item.iban === value);
|
||||||
return (
|
return (
|
||||||
@@ -170,7 +256,7 @@ export default class IbanSelectionFilter {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{this.availableValues.map((item) => (
|
{this.availableValues.map((item) => (
|
||||||
<MenuItem key={item.iban} value={item.iban}>
|
<MenuItem key={item.iban} value={item.iban}>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
@@ -188,19 +274,21 @@ export default class IbanSelectionFilter {
|
|||||||
</Select>
|
</Select>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
|
||||||
{this.state.selectedValues.length > 0 && (
|
<Box
|
||||||
<Box sx={{ mt: 1, textAlign: 'right' }}>
|
className="clear-button-container"
|
||||||
<Button
|
sx={{ mt: 1, textAlign: 'right' }}
|
||||||
onClick={this.clearFilter}
|
style={{ display: (this.state.selectedValues.length > 0 || this.state.partialIban.trim() !== '') ? 'block' : 'none' }}
|
||||||
size="small"
|
>
|
||||||
variant="text"
|
<Button
|
||||||
color="primary"
|
onClick={this.clearFilter}
|
||||||
sx={{ fontSize: '0.75rem' }}
|
size="small"
|
||||||
>
|
variant="text"
|
||||||
Filter löschen
|
color="primary"
|
||||||
</Button>
|
sx={{ fontSize: '0.75rem' }}
|
||||||
</Box>
|
>
|
||||||
)}
|
Alle Filter löschen
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,10 @@ const SortHeader = (params) => {
|
|||||||
if (params.api) {
|
if (params.api) {
|
||||||
params.api.addEventListener('sortChanged', updateSortState);
|
params.api.addEventListener('sortChanged', updateSortState);
|
||||||
return () => {
|
return () => {
|
||||||
params.api.removeEventListener('sortChanged', updateSortState);
|
// Check if grid API is still valid before removing listener
|
||||||
|
if (params.api && !params.api.isDestroyed()) {
|
||||||
|
params.api.removeEventListener('sortChanged', updateSortState);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}, [params.api, params.column]);
|
}, [params.api, params.column]);
|
||||||
|
|||||||
@@ -36,8 +36,8 @@ class HeaderComponent extends Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
componentWillUnmount() {
|
componentWillUnmount() {
|
||||||
// Clean up event listener
|
// Clean up event listener - check if grid API is still valid
|
||||||
if (this.props.params && this.props.params.api) {
|
if (this.props.params && this.props.params.api && !this.props.params.api.isDestroyed()) {
|
||||||
this.props.params.api.removeEventListener('filterChanged', this.onFilterChanged);
|
this.props.params.api.removeEventListener('filterChanged', this.onFilterChanged);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,7 +147,7 @@ class HeaderComponent extends Component {
|
|||||||
const showTextFilter = isTextColumn;
|
const showTextFilter = isTextColumn;
|
||||||
|
|
||||||
// Check if sorting is disabled for this column
|
// Check if sorting is disabled for this column
|
||||||
const isSortingDisabled = column.colDef.sortable === false || column.colDef.suppressSorting === true;
|
const isSortingDisabled = column.colDef.sortable === false;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box sx={{
|
<Box sx={{
|
||||||
@@ -290,21 +290,19 @@ export default class TextHeaderWithFilter {
|
|||||||
this.eGui.style.height = '100%';
|
this.eGui.style.height = '100%';
|
||||||
this.eGui.style.display = 'flex';
|
this.eGui.style.display = 'flex';
|
||||||
this.eGui.style.flexDirection = 'column';
|
this.eGui.style.flexDirection = 'column';
|
||||||
|
|
||||||
console.log('TextHeaderWithFilter constructor');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
init(params) {
|
init(params) {
|
||||||
this.params = params;
|
this.params = params;
|
||||||
console.log('TextHeaderWithFilter init params:', params);
|
|
||||||
|
|
||||||
// Listen for menu close events to keep state in sync
|
// Listen for menu close events to keep state in sync
|
||||||
if (params.api) {
|
if (params.api) {
|
||||||
params.api.addEventListener('popupMenuVisibleChanged', (event) => {
|
this.popupMenuListener = (event) => {
|
||||||
if (!event.visible && this.headerComponent) {
|
if (!event.visible && this.headerComponent) {
|
||||||
this.headerComponent.setState({ menuOpen: false });
|
this.headerComponent.setState({ menuOpen: false });
|
||||||
}
|
}
|
||||||
});
|
};
|
||||||
|
params.api.addEventListener('popupMenuVisibleChanged', this.popupMenuListener);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render React component into the DOM element
|
// Render React component into the DOM element
|
||||||
@@ -312,11 +310,15 @@ export default class TextHeaderWithFilter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getGui() {
|
getGui() {
|
||||||
console.log('TextHeaderWithFilter getGui called');
|
|
||||||
return this.eGui;
|
return this.eGui;
|
||||||
}
|
}
|
||||||
|
|
||||||
destroy() {
|
destroy() {
|
||||||
|
// Clean up event listener if grid API is still valid
|
||||||
|
if (this.params && this.params.api && !this.params.api.isDestroyed() && this.popupMenuListener) {
|
||||||
|
this.params.api.removeEventListener('popupMenuVisibleChanged', this.popupMenuListener);
|
||||||
|
}
|
||||||
|
|
||||||
// Use setTimeout to avoid unmounting during render
|
// Use setTimeout to avoid unmounting during render
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (this.reactRoot) {
|
if (this.reactRoot) {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
export const processTransactionData = (transactions) => {
|
export const processTransactionData = (transactions) => {
|
||||||
return transactions.map((transaction, index) => ({
|
return transactions.map((transaction, index) => ({
|
||||||
...transaction,
|
...transaction,
|
||||||
id: `row-${index}-${transaction.Buchungstag}-${transaction.numericAmount}`, // Unique ID
|
// Use actual database ID, no fake ID generation
|
||||||
description: transaction['Verwendungszweck'] || transaction['Buchungstext'],
|
description: transaction['Verwendungszweck'] || transaction['Buchungstext'],
|
||||||
type: transaction.numericAmount >= 0 ? 'Income' : 'Expense',
|
type: transaction.numericAmount >= 0 ? 'Income' : 'Expense',
|
||||||
isIncome: transaction.numericAmount >= 0,
|
isIncome: transaction.numericAmount >= 0,
|
||||||
@@ -12,9 +12,7 @@ export const processTransactionData = (transactions) => {
|
|||||||
export const getRowStyle = (params, selectedRows) => {
|
export const getRowStyle = (params, selectedRows) => {
|
||||||
const rowId = params.data?.id || params.rowIndex;
|
const rowId = params.data?.id || params.rowIndex;
|
||||||
const isSelected = selectedRows && selectedRows.has && selectedRows.has(rowId);
|
const isSelected = selectedRows && selectedRows.has && selectedRows.has(rowId);
|
||||||
|
|
||||||
console.log('getRowStyle called for row:', rowId, 'isSelected:', isSelected, 'selectedRows size:', selectedRows?.size);
|
|
||||||
|
|
||||||
if (params.data.isJTLOnly) {
|
if (params.data.isJTLOnly) {
|
||||||
return {
|
return {
|
||||||
backgroundColor: isSelected ? '#e3f2fd' : '#ffebee',
|
backgroundColor: isSelected ? '#e3f2fd' : '#ffebee',
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
class KreditorService {
|
class KreditorService {
|
||||||
constructor() {
|
constructor() {
|
||||||
|
// API is mounted under /api (see src/index.js). Keep consistent with AuthService.
|
||||||
this.baseURL = '/api';
|
this.baseURL = '/api';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +46,8 @@ class KreditorService {
|
|||||||
|
|
||||||
async getAllKreditors() {
|
async getAllKreditors() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${this.baseURL}/data/kreditors`, {
|
const url = `${this.baseURL}/data/kreditors`;
|
||||||
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: await this.getAuthHeaders(),
|
headers: await this.getAuthHeaders(),
|
||||||
});
|
});
|
||||||
@@ -53,19 +55,23 @@ class KreditorService {
|
|||||||
return await this.handleResponse(response);
|
return await this.handleResponse(response);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching kreditors:', error);
|
console.error('Error fetching kreditors:', error);
|
||||||
|
|
||||||
// Handle network errors
|
|
||||||
if (error instanceof TypeError && error.message.includes('fetch')) {
|
if (error instanceof TypeError && error.message.includes('fetch')) {
|
||||||
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
||||||
}
|
}
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Convenience: find kreditor by kreditorId (string compare)
|
||||||
|
async findKreditorByCode(kreditorId) {
|
||||||
|
const all = await this.getAllKreditors();
|
||||||
|
return (all || []).find(k => String(k.kreditorId).trim() === String(kreditorId).trim());
|
||||||
|
}
|
||||||
|
|
||||||
async getKreditorById(id) {
|
async getKreditorById(id) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${this.baseURL}/data/kreditors/${id}`, {
|
const url = `${this.baseURL}/data/kreditors/${id}`;
|
||||||
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: await this.getAuthHeaders(),
|
headers: await this.getAuthHeaders(),
|
||||||
});
|
});
|
||||||
@@ -73,19 +79,18 @@ class KreditorService {
|
|||||||
return await this.handleResponse(response);
|
return await this.handleResponse(response);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching kreditor:', error);
|
console.error('Error fetching kreditor:', error);
|
||||||
|
|
||||||
// Handle network errors
|
|
||||||
if (error instanceof TypeError && error.message.includes('fetch')) {
|
if (error instanceof TypeError && error.message.includes('fetch')) {
|
||||||
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
||||||
}
|
}
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async createKreditor(kreditorData) {
|
async createKreditor(kreditorData) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${this.baseURL}/data/kreditors`, {
|
const url = `${this.baseURL}/data/kreditors`;
|
||||||
|
console.debug('[KreditorService] POST', url, kreditorData);
|
||||||
|
const response = await fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: await this.getAuthHeaders(),
|
headers: await this.getAuthHeaders(),
|
||||||
body: JSON.stringify(kreditorData),
|
body: JSON.stringify(kreditorData),
|
||||||
@@ -93,20 +98,23 @@ class KreditorService {
|
|||||||
|
|
||||||
return await this.handleResponse(response);
|
return await this.handleResponse(response);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
// Map unique constraint errors to a clearer duplicate message when possible
|
||||||
|
const msg = (error && error.message) || '';
|
||||||
|
if (/unique|bereits vorhanden|already exists|kreditor/i.test(msg)) {
|
||||||
|
throw new Error('Kreditor bereits vorhanden');
|
||||||
|
}
|
||||||
console.error('Error creating kreditor:', error);
|
console.error('Error creating kreditor:', error);
|
||||||
|
|
||||||
// Handle network errors
|
|
||||||
if (error instanceof TypeError && error.message.includes('fetch')) {
|
if (error instanceof TypeError && error.message.includes('fetch')) {
|
||||||
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
||||||
}
|
}
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateKreditor(id, kreditorData) {
|
async updateKreditor(id, kreditorData) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${this.baseURL}/data/kreditors/${id}`, {
|
const url = `${this.baseURL}/data/kreditors/${id}`;
|
||||||
|
const response = await fetch(url, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: await this.getAuthHeaders(),
|
headers: await this.getAuthHeaders(),
|
||||||
body: JSON.stringify(kreditorData),
|
body: JSON.stringify(kreditorData),
|
||||||
@@ -115,19 +123,17 @@ class KreditorService {
|
|||||||
return await this.handleResponse(response);
|
return await this.handleResponse(response);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error updating kreditor:', error);
|
console.error('Error updating kreditor:', error);
|
||||||
|
|
||||||
// Handle network errors
|
|
||||||
if (error instanceof TypeError && error.message.includes('fetch')) {
|
if (error instanceof TypeError && error.message.includes('fetch')) {
|
||||||
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
||||||
}
|
}
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteKreditor(id) {
|
async deleteKreditor(id) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${this.baseURL}/data/kreditors/${id}`, {
|
const url = `${this.baseURL}/data/kreditors/${id}`;
|
||||||
|
const response = await fetch(url, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: await this.getAuthHeaders(),
|
headers: await this.getAuthHeaders(),
|
||||||
});
|
});
|
||||||
@@ -135,12 +141,9 @@ class KreditorService {
|
|||||||
return await this.handleResponse(response);
|
return await this.handleResponse(response);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error deleting kreditor:', error);
|
console.error('Error deleting kreditor:', error);
|
||||||
|
|
||||||
// Handle network errors
|
|
||||||
if (error instanceof TypeError && error.message.includes('fetch')) {
|
if (error instanceof TypeError && error.message.includes('fetch')) {
|
||||||
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
throw new Error('FibDash Service nicht erreichbar - Prüfen Sie Ihre Internetverbindung oder versuchen Sie es später erneut');
|
||||||
}
|
}
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,8 +152,13 @@ class KreditorService {
|
|||||||
validateKreditorData(kreditorData) {
|
validateKreditorData(kreditorData) {
|
||||||
const errors = [];
|
const errors = [];
|
||||||
|
|
||||||
if (!kreditorData.iban || kreditorData.iban.trim() === '') {
|
// IBAN is only required for non-banking accounts that are not manual assignments
|
||||||
errors.push('IBAN ist erforderlich');
|
const isBanking = kreditorData.is_banking || false;
|
||||||
|
const hasIban = kreditorData.iban && kreditorData.iban.trim() !== '';
|
||||||
|
const isManualAssignment = kreditorData.is_manual_assignment || false;
|
||||||
|
|
||||||
|
if (!isBanking && !hasIban && !isManualAssignment) {
|
||||||
|
errors.push('IBAN ist erforderlich (außer für Banking-Konten oder manuelle Zuordnungen)');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!kreditorData.name || kreditorData.name.trim() === '') {
|
if (!kreditorData.name || kreditorData.name.trim() === '') {
|
||||||
@@ -161,14 +169,20 @@ class KreditorService {
|
|||||||
errors.push('Kreditor-ID ist erforderlich');
|
errors.push('Kreditor-ID ist erforderlich');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Basic IBAN format validation (simplified)
|
// Basic IBAN format validation (simplified) - only if IBAN is provided
|
||||||
if (kreditorData.iban && !/^[A-Z]{2}[0-9]{2}[A-Z0-9]{4}[0-9]{7}([A-Z0-9]?){0,16}$/i.test(kreditorData.iban.replace(/\s/g, ''))) {
|
if (hasIban && !/^[A-Z]{2}[0-9]{2}[A-Z0-9]{4}[0-9]{7}([A-Z0-9]?){0,16}$/i.test(kreditorData.iban.replace(/\s/g, ''))) {
|
||||||
errors.push('IBAN Format ist ungültig');
|
errors.push('IBAN Format ist ungültig');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate kreditorId format (should start with 70xxx)
|
// Validate kreditorId format (should start with 70xxx for regular kreditors)
|
||||||
if (kreditorData.kreditorId && !/^70\d{3,}$/.test(kreditorData.kreditorId)) {
|
if (kreditorData.kreditorId && !isBanking && !/^70\d{3,}$/.test(kreditorData.kreditorId)) {
|
||||||
errors.push('Kreditor-ID muss mit 70 beginnen gefolgt von mindestens 3 Ziffern');
|
errors.push('Kreditor-ID muss mit 70 beginnen gefolgt von mindestens 3 Ziffern (außer für Banking-Konten)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// For banking accounts, warn about special handling
|
||||||
|
if (isBanking && hasIban) {
|
||||||
|
// This is just informational, not an error
|
||||||
|
console.info('Banking-Konto erkannt: Transaktionen benötigen manuelle Kreditor-Zuordnung');
|
||||||
}
|
}
|
||||||
|
|
||||||
return errors;
|
return errors;
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
|
||||||
nginx:
|
|
||||||
image: nginx:alpine
|
|
||||||
ports:
|
|
||||||
- "80:80"
|
|
||||||
volumes:
|
|
||||||
- ./nginx.dev.conf:/etc/nginx/conf.d/default.conf
|
|
||||||
- ./logs/nginx:/var/log/nginx
|
|
||||||
depends_on:
|
|
||||||
- frontend
|
|
||||||
- backend
|
|
||||||
restart: unless-stopped
|
|
||||||
networks:
|
|
||||||
- fibdash-network
|
|
||||||
|
|
||||||
frontend:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: Dockerfile.dev.frontend
|
|
||||||
ports:
|
|
||||||
- "5001:5001"
|
|
||||||
volumes:
|
|
||||||
- ./client:/app/client
|
|
||||||
- /app/node_modules
|
|
||||||
environment:
|
|
||||||
- NODE_ENV=development
|
|
||||||
- CHOKIDAR_USEPOLLING=true
|
|
||||||
networks:
|
|
||||||
- fibdash-network
|
|
||||||
command: npm run dev:frontend
|
|
||||||
|
|
||||||
backend:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
dockerfile: Dockerfile.dev.backend
|
|
||||||
ports:
|
|
||||||
- "5000:5000"
|
|
||||||
volumes:
|
|
||||||
- ./src:/app/src
|
|
||||||
- /app/node_modules
|
|
||||||
environment:
|
|
||||||
- NODE_ENV=development
|
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
networks:
|
|
||||||
- fibdash-network
|
|
||||||
command: npm run dev:backend
|
|
||||||
|
|
||||||
networks:
|
|
||||||
fibdash-network:
|
|
||||||
driver: bridge
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
node_modules:
|
|
||||||
34
package-lock.json
generated
34
package-lock.json
generated
@@ -21,6 +21,8 @@
|
|||||||
"google-auth-library": "^9.0.0",
|
"google-auth-library": "^9.0.0",
|
||||||
"jsonwebtoken": "^9.0.0",
|
"jsonwebtoken": "^9.0.0",
|
||||||
"mssql": "^9.1.0",
|
"mssql": "^9.1.0",
|
||||||
|
"nodemailer": "^7.0.5",
|
||||||
|
"openai": "^5.12.0",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0"
|
"react-dom": "^18.2.0"
|
||||||
},
|
},
|
||||||
@@ -7142,6 +7144,15 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/nodemailer": {
|
||||||
|
"version": "7.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.5.tgz",
|
||||||
|
"integrity": "sha512-nsrh2lO3j4GkLLXoeEksAMgAOqxOv6QumNRVQTJwKH4nuiww6iC2y7GyANs9kRAxCexg3+lTWM3PZ91iLlVjfg==",
|
||||||
|
"license": "MIT-0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/nodemon": {
|
"node_modules/nodemon": {
|
||||||
"version": "3.1.10",
|
"version": "3.1.10",
|
||||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz",
|
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz",
|
||||||
@@ -7365,6 +7376,27 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/openai": {
|
||||||
|
"version": "5.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/openai/-/openai-5.12.0.tgz",
|
||||||
|
"integrity": "sha512-vUdt02xiWgOHiYUmW0Hj1Qu9OKAiVQu5Bd547ktVCiMKC1BkB5L3ImeEnCyq3WpRKR6ZTaPgekzqdozwdPs7Lg==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"openai": "bin/cli"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"ws": "^8.18.0",
|
||||||
|
"zod": "^3.23.8"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"ws": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"zod": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/own-keys": {
|
"node_modules/own-keys": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz",
|
||||||
@@ -9827,7 +9859,7 @@
|
|||||||
"version": "8.18.3",
|
"version": "8.18.3",
|
||||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
||||||
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
|
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
|
||||||
"dev": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "concurrently \"npm run dev:frontend\" \"npm run dev:backend\"",
|
"dev": "concurrently \"npm run dev:frontend\" \"npm run dev:backend\"",
|
||||||
"dev:frontend": "webpack serve --mode development --config webpack.config.js",
|
"dev:frontend": "webpack serve --mode development --config webpack.config.js",
|
||||||
"dev:backend": "nodemon src/index.js",
|
"dev:backend": "nodemon --exitcrash src/index.js",
|
||||||
"build": "webpack --config webpack.prod.config.js",
|
"build": "webpack --config webpack.prod.config.js",
|
||||||
"build:prod": "npm run build && npm run start:prod",
|
"build:prod": "npm run build && npm run start:prod",
|
||||||
"start": "npm run build && node src/index.js",
|
"start": "npm run build && node src/index.js",
|
||||||
@@ -32,6 +32,8 @@
|
|||||||
"google-auth-library": "^9.0.0",
|
"google-auth-library": "^9.0.0",
|
||||||
"jsonwebtoken": "^9.0.0",
|
"jsonwebtoken": "^9.0.0",
|
||||||
"mssql": "^9.1.0",
|
"mssql": "^9.1.0",
|
||||||
|
"nodemailer": "^7.0.5",
|
||||||
|
"openai": "^5.12.0",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0"
|
"react-dom": "^18.2.0"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -73,10 +73,42 @@ const executeQuery = async (query, params = {}) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const executeTransaction = async (callback) => {
|
||||||
|
if (!process.env.DB_SERVER) {
|
||||||
|
throw new Error('Database not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
let pool;
|
||||||
|
let transaction;
|
||||||
|
|
||||||
|
try {
|
||||||
|
pool = await getPool();
|
||||||
|
transaction = new sql.Transaction(pool);
|
||||||
|
|
||||||
|
await transaction.begin();
|
||||||
|
|
||||||
|
const result = await callback(transaction);
|
||||||
|
|
||||||
|
await transaction.commit();
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
if (transaction) {
|
||||||
|
try {
|
||||||
|
await transaction.rollback();
|
||||||
|
} catch (rollbackError) {
|
||||||
|
console.error('Transaction rollback failed:', rollbackError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.error('Transaction error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
config,
|
config,
|
||||||
getPool,
|
getPool,
|
||||||
testConnection,
|
testConnection,
|
||||||
executeQuery,
|
executeQuery,
|
||||||
|
executeTransaction,
|
||||||
sql,
|
sql,
|
||||||
};
|
};
|
||||||
124
src/database/csv_transactions_schema.sql
Normal file
124
src/database/csv_transactions_schema.sql
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
-- CSV Transactions Import Schema
|
||||||
|
-- This script creates a table to store imported CSV transaction data
|
||||||
|
|
||||||
|
-- Create CSVTransactions table to store imported CSV data
|
||||||
|
CREATE TABLE fibdash.CSVTransactions (
|
||||||
|
id INT IDENTITY(1,1) PRIMARY KEY,
|
||||||
|
|
||||||
|
-- Original CSV columns (German names as they appear in CSV)
|
||||||
|
buchungstag NVARCHAR(50), -- "Buchungstag"
|
||||||
|
wertstellung NVARCHAR(50), -- "Wertstellung"
|
||||||
|
umsatzart NVARCHAR(100), -- "Umsatzart"
|
||||||
|
betrag DECIMAL(15,2), -- "Betrag" (numeric value)
|
||||||
|
betrag_original NVARCHAR(50), -- Original string from CSV
|
||||||
|
waehrung NVARCHAR(10), -- "Waehrung"
|
||||||
|
beguenstigter_zahlungspflichtiger NVARCHAR(500), -- "Beguenstigter/Zahlungspflichtiger"
|
||||||
|
kontonummer_iban NVARCHAR(50), -- "Kontonummer/IBAN"
|
||||||
|
bic NVARCHAR(20), -- "BIC"
|
||||||
|
verwendungszweck NVARCHAR(1000), -- "Verwendungszweck"
|
||||||
|
|
||||||
|
-- Processed/computed fields
|
||||||
|
parsed_date DATE, -- Parsed buchungstag
|
||||||
|
numeric_amount DECIMAL(15,2), -- Processed amount
|
||||||
|
|
||||||
|
-- Import metadata
|
||||||
|
import_date DATETIME2 NOT NULL DEFAULT GETDATE(),
|
||||||
|
import_batch_id NVARCHAR(100), -- To group imports from same file
|
||||||
|
source_filename NVARCHAR(255), -- Original CSV filename
|
||||||
|
source_row_number INT, -- Row number in original CSV
|
||||||
|
|
||||||
|
-- Processing status
|
||||||
|
is_processed BIT NOT NULL DEFAULT 0, -- Whether this transaction has been processed
|
||||||
|
processing_notes NVARCHAR(500), -- Any processing notes or errors
|
||||||
|
|
||||||
|
-- Create indexes for performance
|
||||||
|
INDEX IX_CSVTransactions_IBAN (kontonummer_iban),
|
||||||
|
INDEX IX_CSVTransactions_Date (parsed_date),
|
||||||
|
INDEX IX_CSVTransactions_Amount (numeric_amount),
|
||||||
|
INDEX IX_CSVTransactions_ImportBatch (import_batch_id),
|
||||||
|
INDEX IX_CSVTransactions_Processed (is_processed)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Update BankingAccountTransactions to reference CSVTransactions
|
||||||
|
-- Add a new column to support both AccountingItems and CSVTransactions
|
||||||
|
ALTER TABLE fibdash.BankingAccountTransactions
|
||||||
|
ADD csv_transaction_id INT NULL;
|
||||||
|
|
||||||
|
-- Add foreign key constraint
|
||||||
|
ALTER TABLE fibdash.BankingAccountTransactions
|
||||||
|
ADD CONSTRAINT FK_BankingAccountTransactions_CSVTransactions
|
||||||
|
FOREIGN KEY (csv_transaction_id) REFERENCES fibdash.CSVTransactions(id);
|
||||||
|
|
||||||
|
-- Create index for the new column
|
||||||
|
CREATE INDEX IX_BankingAccountTransactions_CSVTransactionId
|
||||||
|
ON fibdash.BankingAccountTransactions(csv_transaction_id);
|
||||||
|
|
||||||
|
-- Update the view to include CSV transactions
|
||||||
|
DROP VIEW IF EXISTS fibdash.vw_TransactionsWithKreditors;
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE VIEW fibdash.vw_TransactionsWithKreditors AS
|
||||||
|
-- AccountingItems transactions
|
||||||
|
SELECT
|
||||||
|
'AccountingItems' as source_table,
|
||||||
|
ai.id as transaction_id,
|
||||||
|
NULL as csv_transaction_id,
|
||||||
|
ai.umsatz_brutto as amount,
|
||||||
|
ai.buchungsdatum as transaction_date,
|
||||||
|
NULL as kontonummer_iban, -- AccountingItems uses gegenkonto
|
||||||
|
ai.buchungstext as description,
|
||||||
|
k.name as kreditor_name,
|
||||||
|
k.kreditorId as kreditor_id,
|
||||||
|
k.is_banking as kreditor_is_banking,
|
||||||
|
bat.assigned_kreditor_id,
|
||||||
|
ak.name as assigned_kreditor_name,
|
||||||
|
ak.kreditorId as assigned_kreditor_id_code,
|
||||||
|
bat.assigned_date,
|
||||||
|
bat.notes as assignment_notes,
|
||||||
|
CASE
|
||||||
|
WHEN k.is_banking = 1 AND bat.assigned_kreditor_id IS NOT NULL THEN 'banking_assigned'
|
||||||
|
WHEN k.is_banking = 1 AND bat.assigned_kreditor_id IS NULL THEN 'banking_unassigned'
|
||||||
|
WHEN k.is_banking = 0 THEN 'regular_kreditor'
|
||||||
|
ELSE 'no_kreditor'
|
||||||
|
END as transaction_type
|
||||||
|
FROM fibdash.AccountingItems ai
|
||||||
|
LEFT JOIN fibdash.Kreditor k ON ai.gegenkonto = k.kreditorId
|
||||||
|
LEFT JOIN fibdash.BankingAccountTransactions bat ON ai.id = bat.transaction_id
|
||||||
|
LEFT JOIN fibdash.Kreditor ak ON bat.assigned_kreditor_id = ak.id
|
||||||
|
|
||||||
|
UNION ALL
|
||||||
|
|
||||||
|
-- CSV transactions
|
||||||
|
SELECT
|
||||||
|
'CSVTransactions' as source_table,
|
||||||
|
NULL as transaction_id,
|
||||||
|
csv.id as csv_transaction_id,
|
||||||
|
csv.numeric_amount as amount,
|
||||||
|
csv.parsed_date as transaction_date,
|
||||||
|
csv.kontonummer_iban,
|
||||||
|
csv.verwendungszweck as description,
|
||||||
|
k.name as kreditor_name,
|
||||||
|
k.kreditorId as kreditor_id,
|
||||||
|
k.is_banking as kreditor_is_banking,
|
||||||
|
bat.assigned_kreditor_id,
|
||||||
|
ak.name as assigned_kreditor_name,
|
||||||
|
ak.kreditorId as assigned_kreditor_id_code,
|
||||||
|
bat.assigned_date,
|
||||||
|
bat.notes as assignment_notes,
|
||||||
|
CASE
|
||||||
|
WHEN k.is_banking = 1 AND bat.assigned_kreditor_id IS NOT NULL THEN 'banking_assigned'
|
||||||
|
WHEN k.is_banking = 1 AND bat.assigned_kreditor_id IS NULL THEN 'banking_unassigned'
|
||||||
|
WHEN k.is_banking = 0 THEN 'regular_kreditor'
|
||||||
|
ELSE 'no_kreditor'
|
||||||
|
END as transaction_type
|
||||||
|
FROM fibdash.CSVTransactions csv
|
||||||
|
LEFT JOIN fibdash.Kreditor k ON csv.kontonummer_iban = k.iban
|
||||||
|
LEFT JOIN fibdash.BankingAccountTransactions bat ON csv.id = bat.csv_transaction_id
|
||||||
|
LEFT JOIN fibdash.Kreditor ak ON bat.assigned_kreditor_id = ak.id;
|
||||||
|
|
||||||
|
GO
|
||||||
|
|
||||||
|
PRINT 'CSV Transactions schema created successfully!';
|
||||||
|
PRINT 'Created CSVTransactions table';
|
||||||
|
PRINT 'Updated BankingAccountTransactions table';
|
||||||
|
PRINT 'Updated vw_TransactionsWithKreditors view';
|
||||||
@@ -8,16 +8,21 @@ GO
|
|||||||
|
|
||||||
|
|
||||||
-- Create Kreditor table
|
-- Create Kreditor table
|
||||||
|
-- Multiple IBANs can have the same kreditor name and kreditorId
|
||||||
|
-- IBAN can be NULL for Kreditors that don't have an IBAN (for banking account assignments)
|
||||||
|
-- is_banking flag indicates if this IBAN represents a banking account (like PayPal) rather than a direct creditor
|
||||||
CREATE TABLE fibdash.Kreditor (
|
CREATE TABLE fibdash.Kreditor (
|
||||||
id INT IDENTITY(1,1) PRIMARY KEY,
|
id INT IDENTITY(1,1) PRIMARY KEY,
|
||||||
iban NVARCHAR(34) NOT NULL,
|
iban NVARCHAR(34) NULL, -- Nullable to allow Kreditors without IBAN
|
||||||
name NVARCHAR(255) NOT NULL,
|
name NVARCHAR(255) NOT NULL,
|
||||||
kreditorId NVARCHAR(50) NOT NULL
|
kreditorId NVARCHAR(50) NOT NULL,
|
||||||
|
is_banking BIT NOT NULL DEFAULT 0 -- 1 = banking account, 0 = regular creditor
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Ensure kreditorId is unique to support FK references
|
-- Create unique index on IBAN to prevent duplicate IBANs (allows NULL values)
|
||||||
ALTER TABLE fibdash.Kreditor
|
CREATE UNIQUE INDEX UQ_Kreditor_IBAN_NotNull
|
||||||
ADD CONSTRAINT UQ_Kreditor_kreditorId UNIQUE (kreditorId);
|
ON fibdash.Kreditor(iban)
|
||||||
|
WHERE iban IS NOT NULL;
|
||||||
|
|
||||||
-- Create AccountingItems table
|
-- Create AccountingItems table
|
||||||
-- Based on CSV structure: umsatz brutto, soll/haben kz, konto, gegenkonto, bu, buchungsdatum, rechnungsnummer, buchungstext, beleglink
|
-- Based on CSV structure: umsatz brutto, soll/haben kz, konto, gegenkonto, bu, buchungsdatum, rechnungsnummer, buchungstext, beleglink
|
||||||
@@ -84,10 +89,14 @@ CSV
|
|||||||
-- Create indexes for better performance
|
-- Create indexes for better performance
|
||||||
CREATE INDEX IX_Kreditor_IBAN ON fibdash.Kreditor(iban);
|
CREATE INDEX IX_Kreditor_IBAN ON fibdash.Kreditor(iban);
|
||||||
CREATE INDEX IX_Kreditor_KreditorId ON fibdash.Kreditor(kreditorId);
|
CREATE INDEX IX_Kreditor_KreditorId ON fibdash.Kreditor(kreditorId);
|
||||||
|
CREATE INDEX IX_Kreditor_IsBanking ON fibdash.Kreditor(is_banking);
|
||||||
CREATE INDEX IX_AccountingItems_Buchungsdatum ON fibdash.AccountingItems(buchungsdatum);
|
CREATE INDEX IX_AccountingItems_Buchungsdatum ON fibdash.AccountingItems(buchungsdatum);
|
||||||
CREATE INDEX IX_AccountingItems_Konto ON fibdash.AccountingItems(konto);
|
CREATE INDEX IX_AccountingItems_Konto ON fibdash.AccountingItems(konto);
|
||||||
CREATE INDEX IX_AccountingItems_Rechnungsnummer ON fibdash.AccountingItems(rechnungsnummer);
|
CREATE INDEX IX_AccountingItems_Rechnungsnummer ON fibdash.AccountingItems(rechnungsnummer);
|
||||||
CREATE INDEX IX_AccountingItems_SollHabenKz ON fibdash.AccountingItems(soll_haben_kz);
|
CREATE INDEX IX_AccountingItems_SollHabenKz ON fibdash.AccountingItems(soll_haben_kz);
|
||||||
|
CREATE INDEX IX_BankingAccountTransactions_TransactionId ON fibdash.BankingAccountTransactions(transaction_id);
|
||||||
|
CREATE INDEX IX_BankingAccountTransactions_BankingIban ON fibdash.BankingAccountTransactions(banking_iban);
|
||||||
|
CREATE INDEX IX_BankingAccountTransactions_AssignedKreditorId ON fibdash.BankingAccountTransactions(assigned_kreditor_id);
|
||||||
|
|
||||||
-- Add FK from AccountingItems.bu -> BU(bu)
|
-- Add FK from AccountingItems.bu -> BU(bu)
|
||||||
ALTER TABLE fibdash.AccountingItems
|
ALTER TABLE fibdash.AccountingItems
|
||||||
@@ -104,6 +113,25 @@ ALTER TABLE fibdash.AccountingItems
|
|||||||
ADD CONSTRAINT FK_AccountingItems_Konto_Konto
|
ADD CONSTRAINT FK_AccountingItems_Konto_Konto
|
||||||
FOREIGN KEY (konto) REFERENCES fibdash.Konto(konto);
|
FOREIGN KEY (konto) REFERENCES fibdash.Konto(konto);
|
||||||
|
|
||||||
|
-- Create BankingAccountTransactions table to map banking account transactions to Kreditors
|
||||||
|
-- This table handles cases where an IBAN is a banking account (like PayPal) and needs
|
||||||
|
-- to be mapped to the actual creditor for accounting purposes
|
||||||
|
CREATE TABLE fibdash.BankingAccountTransactions (
|
||||||
|
id INT IDENTITY(1,1) PRIMARY KEY,
|
||||||
|
transaction_id INT NOT NULL, -- References AccountingItems.id
|
||||||
|
banking_iban NVARCHAR(34) NOT NULL, -- The banking account IBAN (e.g., PayPal)
|
||||||
|
assigned_kreditor_id INT NOT NULL, -- References Kreditor.id for the actual creditor
|
||||||
|
assigned_date DATETIME2 NOT NULL DEFAULT GETDATE(),
|
||||||
|
assigned_by NVARCHAR(100), -- User who made the assignment
|
||||||
|
notes NVARCHAR(500), -- Optional notes about the assignment
|
||||||
|
|
||||||
|
-- Foreign key constraints
|
||||||
|
CONSTRAINT FK_BankingAccountTransactions_AccountingItems
|
||||||
|
FOREIGN KEY (transaction_id) REFERENCES fibdash.AccountingItems(id),
|
||||||
|
CONSTRAINT FK_BankingAccountTransactions_Kreditor
|
||||||
|
FOREIGN KEY (assigned_kreditor_id) REFERENCES fibdash.Kreditor(id)
|
||||||
|
);
|
||||||
|
|
||||||
-- Add vst column to existing BU table (for databases created before this update)
|
-- Add vst column to existing BU table (for databases created before this update)
|
||||||
-- IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('fibdash.BU') AND name = 'vst')
|
-- IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('fibdash.BU') AND name = 'vst')
|
||||||
-- BEGIN
|
-- BEGIN
|
||||||
@@ -122,4 +150,28 @@ FOREIGN KEY (konto) REFERENCES fibdash.Konto(konto);
|
|||||||
-- ('9', '19% VST', 19.00),
|
-- ('9', '19% VST', 19.00),
|
||||||
-- ('8', '7% VST', 7.00),
|
-- ('8', '7% VST', 7.00),
|
||||||
-- ('506', 'Dienstleistung aus EU', NULL),
|
-- ('506', 'Dienstleistung aus EU', NULL),
|
||||||
-- ('511', 'Dienstleistung außerhalb EU', NULL);
|
-- ('511', 'Dienstleistung außerhalb EU', NULL);
|
||||||
|
|
||||||
|
-- Create view to easily query transactions with their assigned Kreditors
|
||||||
|
-- This view combines regular transactions with banking account assignments
|
||||||
|
CREATE VIEW fibdash.vw_TransactionsWithKreditors AS
|
||||||
|
SELECT
|
||||||
|
ai.*,
|
||||||
|
k.name as kreditor_name,
|
||||||
|
k.kreditorId as kreditor_id,
|
||||||
|
k.is_banking as kreditor_is_banking,
|
||||||
|
bat.assigned_kreditor_id,
|
||||||
|
ak.name as assigned_kreditor_name,
|
||||||
|
ak.kreditorId as assigned_kreditor_id_code,
|
||||||
|
bat.assigned_date,
|
||||||
|
bat.notes as assignment_notes,
|
||||||
|
CASE
|
||||||
|
WHEN k.is_banking = 1 AND bat.assigned_kreditor_id IS NOT NULL THEN 'banking_assigned'
|
||||||
|
WHEN k.is_banking = 1 AND bat.assigned_kreditor_id IS NULL THEN 'banking_unassigned'
|
||||||
|
WHEN k.is_banking = 0 THEN 'regular_kreditor'
|
||||||
|
ELSE 'no_kreditor'
|
||||||
|
END as transaction_type
|
||||||
|
FROM fibdash.AccountingItems ai
|
||||||
|
LEFT JOIN fibdash.Kreditor k ON ai.gegenkonto = k.kreditorId
|
||||||
|
LEFT JOIN fibdash.BankingAccountTransactions bat ON ai.id = bat.transaction_id
|
||||||
|
LEFT JOIN fibdash.Kreditor ak ON bat.assigned_kreditor_id = ak.id;
|
||||||
@@ -10,11 +10,11 @@ const dataRoutes = require('./routes/data');
|
|||||||
const dbConfig = require('./config/database');
|
const dbConfig = require('./config/database');
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const PORT = process.env.PORT || 5000;
|
const PORT = process.env.PORT || 5500;
|
||||||
|
|
||||||
// Middleware
|
// Middleware
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.use(express.json());
|
app.use(express.json({ limit: '10mb' })); // Increased limit for CSV imports
|
||||||
|
|
||||||
// Routes
|
// Routes
|
||||||
app.use('/api/auth', authRoutes);
|
app.use('/api/auth', authRoutes);
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ router.get('/system-info', authenticateToken, (req, res) => {
|
|||||||
// Get all kreditoren
|
// Get all kreditoren
|
||||||
router.get('/kreditoren', authenticateToken, async (req, res) => {
|
router.get('/kreditoren', authenticateToken, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const result = await executeQuery('SELECT * FROM fibdash.Kreditor ORDER BY name');
|
const result = await executeQuery('SELECT id, iban, name, kreditorId, is_banking FROM fibdash.Kreditor ORDER BY name, iban');
|
||||||
res.json({ kreditoren: result.recordset });
|
res.json({ kreditoren: result.recordset });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching kreditoren:', error);
|
console.error('Error fetching kreditoren:', error);
|
||||||
@@ -32,22 +32,30 @@ router.get('/kreditoren', authenticateToken, async (req, res) => {
|
|||||||
|
|
||||||
// Create new kreditor
|
// Create new kreditor
|
||||||
router.post('/kreditoren', authenticateToken, async (req, res) => {
|
router.post('/kreditoren', authenticateToken, async (req, res) => {
|
||||||
const { iban, name, kreditorId } = req.body;
|
const { iban, name, kreditorId, is_banking } = req.body;
|
||||||
|
|
||||||
if (!iban || !name || !kreditorId) {
|
// IBAN is optional for banking accounts or manual kreditor assignments
|
||||||
return res.status(400).json({ error: 'IBAN, Name und Kreditor ID sind erforderlich' });
|
const isBanking = is_banking || false;
|
||||||
|
|
||||||
|
if (!name || !kreditorId) {
|
||||||
|
return res.status(400).json({ error: 'Name und Kreditor ID sind erforderlich' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// IBAN validation - required for non-banking accounts
|
||||||
|
if (!isBanking && (!iban || iban.trim() === '')) {
|
||||||
|
return res.status(400).json({ error: 'IBAN ist erforderlich (außer für Banking-Konten)' });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await executeQuery(
|
await executeQuery(
|
||||||
'INSERT INTO fibdash.Kreditor (iban, name, kreditorId) VALUES (@iban, @name, @kreditorId)',
|
'INSERT INTO fibdash.Kreditor (iban, name, kreditorId, is_banking) VALUES (@iban, @name, @kreditorId, @is_banking)',
|
||||||
{ iban, name, kreditorId }
|
{ iban: iban || null, name, kreditorId, is_banking: isBanking }
|
||||||
);
|
);
|
||||||
res.json({ message: 'Kreditor erfolgreich erstellt' });
|
res.json({ message: 'Kreditor erfolgreich erstellt' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating kreditor:', error);
|
console.error('Error creating kreditor:', error);
|
||||||
if (error.number === 2627) { // Unique constraint violation
|
if (error.number === 2627) { // Unique constraint violation
|
||||||
res.status(400).json({ error: 'Kreditor ID bereits vorhanden' });
|
res.status(400).json({ error: 'IBAN oder Kreditor ID bereits vorhanden' });
|
||||||
} else {
|
} else {
|
||||||
res.status(500).json({ error: 'Fehler beim Erstellen des Kreditors' });
|
res.status(500).json({ error: 'Fehler beim Erstellen des Kreditors' });
|
||||||
}
|
}
|
||||||
@@ -57,22 +65,30 @@ router.post('/kreditoren', authenticateToken, async (req, res) => {
|
|||||||
// Update kreditor
|
// Update kreditor
|
||||||
router.put('/kreditoren/:id', authenticateToken, async (req, res) => {
|
router.put('/kreditoren/:id', authenticateToken, async (req, res) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const { iban, name, kreditorId } = req.body;
|
const { iban, name, kreditorId, is_banking } = req.body;
|
||||||
|
|
||||||
if (!iban || !name || !kreditorId) {
|
// IBAN is optional for banking accounts or manual kreditor assignments
|
||||||
return res.status(400).json({ error: 'IBAN, Name und Kreditor ID sind erforderlich' });
|
const isBanking = is_banking || false;
|
||||||
|
|
||||||
|
if (!name || !kreditorId) {
|
||||||
|
return res.status(400).json({ error: 'Name und Kreditor ID sind erforderlich' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// IBAN validation - required for non-banking accounts
|
||||||
|
if (!isBanking && (!iban || iban.trim() === '')) {
|
||||||
|
return res.status(400).json({ error: 'IBAN ist erforderlich (außer für Banking-Konten)' });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await executeQuery(
|
await executeQuery(
|
||||||
'UPDATE fibdash.Kreditor SET iban = @iban, name = @name, kreditorId = @kreditorId WHERE id = @id',
|
'UPDATE fibdash.Kreditor SET iban = @iban, name = @name, kreditorId = @kreditorId, is_banking = @is_banking WHERE id = @id',
|
||||||
{ iban, name, kreditorId, id }
|
{ iban: iban || null, name, kreditorId, is_banking: isBanking, id }
|
||||||
);
|
);
|
||||||
res.json({ message: 'Kreditor erfolgreich aktualisiert' });
|
res.json({ message: 'Kreditor erfolgreich aktualisiert' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error updating kreditor:', error);
|
console.error('Error updating kreditor:', error);
|
||||||
if (error.number === 2627) { // Unique constraint violation
|
if (error.number === 2627) { // Unique constraint violation
|
||||||
res.status(400).json({ error: 'Kreditor ID bereits vorhanden' });
|
res.status(400).json({ error: 'IBAN oder Kreditor ID bereits vorhanden' });
|
||||||
} else {
|
} else {
|
||||||
res.status(500).json({ error: 'Fehler beim Aktualisieren des Kreditors' });
|
res.status(500).json({ error: 'Fehler beim Aktualisieren des Kreditors' });
|
||||||
}
|
}
|
||||||
@@ -199,7 +215,7 @@ router.post('/buchungsschluessel', authenticateToken, async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
await executeQuery(
|
await executeQuery(
|
||||||
'INSERT INTO fibdash.BU (bu, name, vst) VALUES (@bu, @name, @vst)',
|
'INSERT INTO fibdash.BU (bu, name, vst) VALUES (@bu, @name, @vst)',
|
||||||
{ bu, name, vst: vst || null }
|
{ bu, name, vst: vst !== undefined && vst !== '' ? vst : null }
|
||||||
);
|
);
|
||||||
res.json({ message: 'Buchungsschlüssel erfolgreich erstellt' });
|
res.json({ message: 'Buchungsschlüssel erfolgreich erstellt' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -224,7 +240,7 @@ router.put('/buchungsschluessel/:id', authenticateToken, async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
await executeQuery(
|
await executeQuery(
|
||||||
'UPDATE fibdash.BU SET bu = @bu, name = @name, vst = @vst WHERE id = @id',
|
'UPDATE fibdash.BU SET bu = @bu, name = @name, vst = @vst WHERE id = @id',
|
||||||
{ bu, name, vst: vst || null, id }
|
{ bu, name, vst: vst !== undefined && vst !== '' ? vst : null, id }
|
||||||
);
|
);
|
||||||
res.json({ message: 'Buchungsschlüssel erfolgreich aktualisiert' });
|
res.json({ message: 'Buchungsschlüssel erfolgreich aktualisiert' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -254,4 +270,4 @@ router.delete('/buchungsschluessel/:id', authenticateToken, async (req, res) =>
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
@@ -76,6 +76,98 @@ router.post('/google', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Google OAuth callback (redirect flow)
|
||||||
|
router.post('/google/callback', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { code, redirect_uri } = req.body;
|
||||||
|
|
||||||
|
console.log('🔄 Processing OAuth callback with authorization code');
|
||||||
|
|
||||||
|
if (!code) {
|
||||||
|
console.log('❌ No authorization code provided');
|
||||||
|
return res.status(400).json({ error: 'Authorization code is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exchange authorization code for tokens
|
||||||
|
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
body: new URLSearchParams({
|
||||||
|
client_id: process.env.GOOGLE_CLIENT_ID,
|
||||||
|
client_secret: process.env.GOOGLE_CLIENT_SECRET,
|
||||||
|
code: code,
|
||||||
|
grant_type: 'authorization_code',
|
||||||
|
redirect_uri: redirect_uri,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!tokenResponse.ok) {
|
||||||
|
const errorData = await tokenResponse.text();
|
||||||
|
console.log('❌ Token exchange failed:', errorData);
|
||||||
|
return res.status(400).json({ error: 'Failed to exchange authorization code' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokens = await tokenResponse.json();
|
||||||
|
console.log('🎯 Received tokens from Google');
|
||||||
|
|
||||||
|
// Use the ID token to get user info
|
||||||
|
const ticket = await client.verifyIdToken({
|
||||||
|
idToken: tokens.id_token,
|
||||||
|
audience: process.env.GOOGLE_CLIENT_ID,
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = ticket.getPayload();
|
||||||
|
const googleId = payload['sub'];
|
||||||
|
const email = payload['email'];
|
||||||
|
const name = payload['name'];
|
||||||
|
const picture = payload['picture'];
|
||||||
|
|
||||||
|
console.log(`👤 OAuth callback verified for: ${email}`);
|
||||||
|
|
||||||
|
// Check if email is authorized
|
||||||
|
const authorized = await isEmailAuthorized(email);
|
||||||
|
console.log(`🔒 Email authorization check for ${email}: ${authorized ? 'ALLOWED' : 'DENIED'}`);
|
||||||
|
|
||||||
|
if (!authorized) {
|
||||||
|
console.log(`❌ Access denied for ${email}`);
|
||||||
|
return res.status(403).json({
|
||||||
|
error: 'Access denied',
|
||||||
|
message: 'Your email address is not authorized to access this application'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create user object
|
||||||
|
const user = {
|
||||||
|
id: googleId,
|
||||||
|
email,
|
||||||
|
name,
|
||||||
|
picture,
|
||||||
|
google_id: googleId,
|
||||||
|
};
|
||||||
|
console.log('✅ User object created from OAuth callback');
|
||||||
|
|
||||||
|
// Generate JWT token
|
||||||
|
const jwtToken = generateToken(user);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
token: jwtToken,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
name: user.name,
|
||||||
|
picture: user.picture,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('OAuth callback error:', error);
|
||||||
|
res.status(401).json({ error: 'OAuth authentication failed' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Verify JWT token
|
// Verify JWT token
|
||||||
router.get('/verify', authenticateToken, async (req, res) => {
|
router.get('/verify', authenticateToken, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,740 +1,10 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const fs = require('fs');
|
|
||||||
const path = require('path');
|
// Explicitly require the index file to avoid resolving a non-router object.
|
||||||
const { authenticateToken } = require('../middleware/auth');
|
const dataRouter = require('./data/index.js');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
// Parse CSV data
|
router.use('/', dataRouter);
|
||||||
const parseCSV = () => {
|
|
||||||
try {
|
|
||||||
const csvPath = path.join(__dirname, '../../data.csv');
|
|
||||||
const csvData = fs.readFileSync(csvPath, 'utf8');
|
|
||||||
const lines = csvData.split('\n');
|
|
||||||
const headers = lines[0].split(';').map(h => h.replace(/"/g, ''));
|
|
||||||
|
|
||||||
const transactions = [];
|
|
||||||
for (let i = 1; i < lines.length; i++) {
|
|
||||||
const line = lines[i];
|
|
||||||
if (!line.trim()) continue;
|
|
||||||
|
|
||||||
// Parse CSV line (handle semicolon-separated values with quotes)
|
|
||||||
const values = [];
|
|
||||||
let current = '';
|
|
||||||
let inQuotes = false;
|
|
||||||
|
|
||||||
for (let j = 0; j < line.length; j++) {
|
|
||||||
const char = line[j];
|
|
||||||
if (char === '"') {
|
|
||||||
inQuotes = !inQuotes;
|
|
||||||
} else if (char === ';' && !inQuotes) {
|
|
||||||
values.push(current);
|
|
||||||
current = '';
|
|
||||||
} else {
|
|
||||||
current += char;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
values.push(current); // Add last value
|
|
||||||
|
|
||||||
if (values.length >= headers.length) {
|
|
||||||
const transaction = {};
|
|
||||||
headers.forEach((header, index) => {
|
|
||||||
transaction[header] = values[index] || '';
|
|
||||||
});
|
|
||||||
|
|
||||||
// Parse date and amount
|
|
||||||
if (transaction['Buchungstag']) {
|
|
||||||
const dateParts = transaction['Buchungstag'].split('.');
|
|
||||||
if (dateParts.length === 3) {
|
|
||||||
// Convert DD.MM.YY to proper date
|
|
||||||
const day = dateParts[0];
|
|
||||||
const month = dateParts[1];
|
|
||||||
const year = '20' + dateParts[2]; // Assuming 20xx
|
|
||||||
transaction.parsedDate = new Date(year, month - 1, day);
|
|
||||||
transaction.monthYear = `${year}-${month.padStart(2, '0')}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse amount
|
|
||||||
if (transaction['Betrag']) {
|
|
||||||
const amount = transaction['Betrag'].replace(',', '.').replace(/[^-0-9.]/g, '');
|
|
||||||
transaction.numericAmount = parseFloat(amount) || 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
transactions.push(transaction);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return transactions;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error parsing CSV:', error);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get available months
|
module.exports = router;
|
||||||
router.get('/months', authenticateToken, (req, res) => {
|
|
||||||
try {
|
|
||||||
const transactions = parseCSV();
|
|
||||||
const months = [...new Set(transactions
|
|
||||||
.filter(t => t.monthYear)
|
|
||||||
.map(t => t.monthYear)
|
|
||||||
)].sort().reverse(); // Newest first
|
|
||||||
|
|
||||||
res.json({ months });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error getting months:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to load months' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get database transactions for JTL comparison
|
|
||||||
const getJTLTransactions = async () => {
|
|
||||||
try {
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
const query = `
|
|
||||||
SELECT
|
|
||||||
cKonto, cKontozusatz, cName, dBuchungsdatum,
|
|
||||||
tZahlungsabgleichUmsatz.kZahlungsabgleichUmsatz,
|
|
||||||
cVerwendungszweck, fBetrag, tUmsatzKontierung.data
|
|
||||||
FROM [eazybusiness].[dbo].[tZahlungsabgleichUmsatz]
|
|
||||||
LEFT JOIN tUmsatzKontierung ON (tUmsatzKontierung.kZahlungsabgleichUmsatz = tZahlungsabgleichUmsatz.kZahlungsabgleichUmsatz)
|
|
||||||
ORDER BY dBuchungsdatum desc, tZahlungsabgleichUmsatz.kZahlungsabgleichUmsatz desc
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(query);
|
|
||||||
const transactions = result.recordset || [];
|
|
||||||
|
|
||||||
// Get PDF documents for each transaction
|
|
||||||
const pdfQuery = `SELECT kUmsatzBeleg, kZahlungsabgleichUmsatz, textContent, markDown, extraction, datevlink FROM tUmsatzBeleg`;
|
|
||||||
const pdfResult = await executeQuery(pdfQuery);
|
|
||||||
|
|
||||||
for(const item of pdfResult.recordset){
|
|
||||||
for(const transaction of transactions){
|
|
||||||
if(item.kZahlungsabgleichUmsatz == transaction.kZahlungsabgleichUmsatz){
|
|
||||||
if(!transaction.pdfs) transaction.pdfs = [];
|
|
||||||
transaction.pdfs.push({
|
|
||||||
kUmsatzBeleg: item.kUmsatzBeleg,
|
|
||||||
content: item.textContent,
|
|
||||||
markDown: item.markDown,
|
|
||||||
extraction: item.extraction,
|
|
||||||
datevlink: item.datevlink
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get links for each transaction
|
|
||||||
const linksQuery = `
|
|
||||||
SELECT kZahlungsabgleichUmsatzLink, kZahlungsabgleichUmsatz, linktarget, linktype, note,
|
|
||||||
tPdfObjekt.kPdfObjekt, tPdfObjekt.textContent, tPdfObjekt.markDown,
|
|
||||||
tPdfObjekt.extraction
|
|
||||||
FROM tZahlungsabgleichUmsatzLink
|
|
||||||
LEFT JOIN tPdfObjekt ON (tZahlungsabgleichUmsatzLink.linktarget = tPdfObjekt.kLieferantenbestellung)
|
|
||||||
WHERE linktype = 'kLieferantenBestellung'
|
|
||||||
`;
|
|
||||||
const linksResult = await executeQuery(linksQuery);
|
|
||||||
|
|
||||||
for(const item of linksResult.recordset){
|
|
||||||
for(const transaction of transactions){
|
|
||||||
if(item.kZahlungsabgleichUmsatz == transaction.kZahlungsabgleichUmsatz){
|
|
||||||
if(!transaction.links) transaction.links = [];
|
|
||||||
transaction.links.push(item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return transactions;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching JTL transactions:', error);
|
|
||||||
throw error; // Re-throw the error so the caller knows the database is unavailable
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get transactions for a specific time period (month, quarter, or year)
|
|
||||||
router.get('/transactions/:timeRange', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { timeRange } = req.params;
|
|
||||||
const transactions = parseCSV();
|
|
||||||
|
|
||||||
let filteredTransactions = [];
|
|
||||||
let periodDescription = '';
|
|
||||||
|
|
||||||
if (timeRange.includes('-Q')) {
|
|
||||||
// Quarter format: YYYY-Q1, YYYY-Q2, etc.
|
|
||||||
const [year, quarterPart] = timeRange.split('-Q');
|
|
||||||
const quarter = parseInt(quarterPart);
|
|
||||||
const startMonth = (quarter - 1) * 3 + 1;
|
|
||||||
const endMonth = startMonth + 2;
|
|
||||||
|
|
||||||
filteredTransactions = transactions.filter(t => {
|
|
||||||
if (!t.monthYear) return false;
|
|
||||||
const [tYear, tMonth] = t.monthYear.split('-');
|
|
||||||
const monthNum = parseInt(tMonth);
|
|
||||||
return tYear === year && monthNum >= startMonth && monthNum <= endMonth;
|
|
||||||
});
|
|
||||||
|
|
||||||
periodDescription = `Q${quarter} ${year}`;
|
|
||||||
} else if (timeRange.length === 4) {
|
|
||||||
// Year format: YYYY
|
|
||||||
filteredTransactions = transactions.filter(t => {
|
|
||||||
if (!t.monthYear) return false;
|
|
||||||
const [tYear] = t.monthYear.split('-');
|
|
||||||
return tYear === timeRange;
|
|
||||||
});
|
|
||||||
|
|
||||||
periodDescription = `Jahr ${timeRange}`;
|
|
||||||
} else {
|
|
||||||
// Month format: YYYY-MM
|
|
||||||
filteredTransactions = transactions.filter(t => t.monthYear === timeRange);
|
|
||||||
const [year, month] = timeRange.split('-');
|
|
||||||
const date = new Date(year, month - 1);
|
|
||||||
periodDescription = date.toLocaleDateString('de-DE', { month: 'long', year: 'numeric' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const monthTransactions = filteredTransactions
|
|
||||||
.sort((a, b) => b.parsedDate - a.parsedDate); // Newest first
|
|
||||||
|
|
||||||
// Get JTL transactions for comparison
|
|
||||||
let jtlTransactions = [];
|
|
||||||
let jtlDatabaseAvailable = false;
|
|
||||||
try {
|
|
||||||
jtlTransactions = await getJTLTransactions();
|
|
||||||
jtlDatabaseAvailable = true;
|
|
||||||
} catch (error) {
|
|
||||||
console.log('JTL database not available, continuing without JTL data');
|
|
||||||
jtlDatabaseAvailable = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Filter JTL transactions for the selected time period
|
|
||||||
let jtlMonthTransactions = [];
|
|
||||||
|
|
||||||
if (timeRange.includes('-Q')) {
|
|
||||||
const [year, quarterPart] = timeRange.split('-Q');
|
|
||||||
const quarter = parseInt(quarterPart);
|
|
||||||
const startMonth = (quarter - 1) * 3 + 1;
|
|
||||||
const endMonth = startMonth + 2;
|
|
||||||
|
|
||||||
jtlMonthTransactions = jtlTransactions.filter(jtl => {
|
|
||||||
const jtlDate = new Date(jtl.dBuchungsdatum);
|
|
||||||
const jtlMonth = jtlDate.getMonth() + 1; // 0-based to 1-based
|
|
||||||
return jtlDate.getFullYear() === parseInt(year) &&
|
|
||||||
jtlMonth >= startMonth && jtlMonth <= endMonth;
|
|
||||||
});
|
|
||||||
} else if (timeRange.length === 4) {
|
|
||||||
jtlMonthTransactions = jtlTransactions.filter(jtl => {
|
|
||||||
const jtlDate = new Date(jtl.dBuchungsdatum);
|
|
||||||
return jtlDate.getFullYear() === parseInt(timeRange);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
const [year, month] = timeRange.split('-');
|
|
||||||
jtlMonthTransactions = jtlTransactions.filter(jtl => {
|
|
||||||
const jtlDate = new Date(jtl.dBuchungsdatum);
|
|
||||||
return jtlDate.getFullYear() === parseInt(year) &&
|
|
||||||
jtlDate.getMonth() === parseInt(month) - 1;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add JTL status to each CSV transaction
|
|
||||||
const transactionsWithJTL = monthTransactions.map(transaction => {
|
|
||||||
// Try to match by amount and date (approximate matching)
|
|
||||||
const amount = transaction.numericAmount;
|
|
||||||
const transactionDate = transaction.parsedDate;
|
|
||||||
|
|
||||||
const jtlMatch = jtlMonthTransactions.find(jtl => {
|
|
||||||
const jtlAmount = parseFloat(jtl.fBetrag) || 0;
|
|
||||||
const jtlDate = new Date(jtl.dBuchungsdatum);
|
|
||||||
|
|
||||||
// Match by amount (exact) and date (same day)
|
|
||||||
const amountMatch = Math.abs(amount - jtlAmount) < 0.01;
|
|
||||||
const dateMatch = transactionDate && jtlDate &&
|
|
||||||
transactionDate.getFullYear() === jtlDate.getFullYear() &&
|
|
||||||
transactionDate.getMonth() === jtlDate.getMonth() &&
|
|
||||||
transactionDate.getDate() === jtlDate.getDate();
|
|
||||||
|
|
||||||
return amountMatch && dateMatch;
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
...transaction,
|
|
||||||
hasJTL: jtlDatabaseAvailable ? !!jtlMatch : undefined,
|
|
||||||
jtlId: jtlMatch ? jtlMatch.kZahlungsabgleichUmsatz : null,
|
|
||||||
isFromCSV: true,
|
|
||||||
jtlDatabaseAvailable,
|
|
||||||
// Include document data from JTL match
|
|
||||||
pdfs: jtlMatch ? jtlMatch.pdfs || [] : [],
|
|
||||||
links: jtlMatch ? jtlMatch.links || [] : []
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// Find JTL transactions that don't have CSV matches (red rows)
|
|
||||||
const unmatchedJTLTransactions = jtlMonthTransactions
|
|
||||||
.filter(jtl => {
|
|
||||||
const jtlAmount = parseFloat(jtl.fBetrag) || 0;
|
|
||||||
const jtlDate = new Date(jtl.dBuchungsdatum);
|
|
||||||
|
|
||||||
// Check if this JTL transaction has a CSV match
|
|
||||||
const hasCSVMatch = monthTransactions.some(transaction => {
|
|
||||||
const amount = transaction.numericAmount;
|
|
||||||
const transactionDate = transaction.parsedDate;
|
|
||||||
|
|
||||||
const amountMatch = Math.abs(amount - jtlAmount) < 0.01;
|
|
||||||
const dateMatch = transactionDate && jtlDate &&
|
|
||||||
transactionDate.getFullYear() === jtlDate.getFullYear() &&
|
|
||||||
transactionDate.getMonth() === jtlDate.getMonth() &&
|
|
||||||
transactionDate.getDate() === jtlDate.getDate();
|
|
||||||
|
|
||||||
return amountMatch && dateMatch;
|
|
||||||
});
|
|
||||||
|
|
||||||
return !hasCSVMatch;
|
|
||||||
})
|
|
||||||
.map(jtl => ({
|
|
||||||
// Convert JTL format to CSV-like format for display
|
|
||||||
'Buchungstag': new Date(jtl.dBuchungsdatum).toLocaleDateString('de-DE', {
|
|
||||||
day: '2-digit',
|
|
||||||
month: '2-digit',
|
|
||||||
year: '2-digit'
|
|
||||||
}),
|
|
||||||
'Verwendungszweck': jtl.cVerwendungszweck || '',
|
|
||||||
'Buchungstext': 'JTL Transaction',
|
|
||||||
'Beguenstigter/Zahlungspflichtiger': jtl.cName || '',
|
|
||||||
'Betrag': jtl.fBetrag ? jtl.fBetrag.toString().replace('.', ',') : '0,00',
|
|
||||||
numericAmount: parseFloat(jtl.fBetrag) || 0,
|
|
||||||
parsedDate: new Date(jtl.dBuchungsdatum),
|
|
||||||
monthYear: timeRange,
|
|
||||||
hasJTL: true,
|
|
||||||
jtlId: jtl.kZahlungsabgleichUmsatz,
|
|
||||||
isFromCSV: false,
|
|
||||||
isJTLOnly: true,
|
|
||||||
// Include document data from JTL transaction
|
|
||||||
pdfs: jtl.pdfs || [],
|
|
||||||
links: jtl.links || []
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Combine CSV and JTL-only transactions
|
|
||||||
const allTransactions = [...transactionsWithJTL, ...unmatchedJTLTransactions]
|
|
||||||
.sort((a, b) => b.parsedDate - a.parsedDate);
|
|
||||||
|
|
||||||
// Calculate summary
|
|
||||||
const summary = {
|
|
||||||
totalTransactions: allTransactions.length,
|
|
||||||
totalIncome: allTransactions
|
|
||||||
.filter(t => t.numericAmount > 0)
|
|
||||||
.reduce((sum, t) => sum + t.numericAmount, 0),
|
|
||||||
totalExpenses: allTransactions
|
|
||||||
.filter(t => t.numericAmount < 0)
|
|
||||||
.reduce((sum, t) => sum + Math.abs(t.numericAmount), 0),
|
|
||||||
netAmount: allTransactions.reduce((sum, t) => sum + t.numericAmount, 0),
|
|
||||||
jtlMatches: jtlDatabaseAvailable ? allTransactions.filter(t => t.hasJTL === true && t.isFromCSV).length : undefined,
|
|
||||||
jtlMissing: jtlDatabaseAvailable ? allTransactions.filter(t => t.hasJTL === false && t.isFromCSV).length : undefined,
|
|
||||||
jtlOnly: jtlDatabaseAvailable ? allTransactions.filter(t => t.isJTLOnly).length : undefined,
|
|
||||||
csvOnly: jtlDatabaseAvailable ? allTransactions.filter(t => t.hasJTL === false && t.isFromCSV).length : undefined,
|
|
||||||
jtlDatabaseAvailable
|
|
||||||
};
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
transactions: allTransactions,
|
|
||||||
summary,
|
|
||||||
timeRange,
|
|
||||||
periodDescription
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error getting transactions:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to load transactions' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// DATEV export functionality
|
|
||||||
const buildDatevHeader = (periodStart, periodEnd) => {
|
|
||||||
const ts = new Date().toISOString().replace(/[-T:\.Z]/g, '').slice(0, 17); // yyyymmddHHMMSSfff
|
|
||||||
const meta = {
|
|
||||||
consultant: 1001,
|
|
||||||
client: 10001,
|
|
||||||
fyStart: periodStart.slice(0, 4) + '0101', // fiscal year start
|
|
||||||
accLength: 4,
|
|
||||||
description: 'Bank Statement Export',
|
|
||||||
currency: 'EUR'
|
|
||||||
};
|
|
||||||
|
|
||||||
return [
|
|
||||||
'"EXTF"', 700, 21, '"Buchungsstapel"', 12, ts,
|
|
||||||
'', '', '', '', // 7‑10 spare
|
|
||||||
meta.consultant, meta.client, // 11, 12
|
|
||||||
meta.fyStart, meta.accLength, // 13, 14
|
|
||||||
periodStart, periodEnd, // 15, 16
|
|
||||||
'"' + meta.description + '"',
|
|
||||||
'AM', 1, 0, 1, meta.currency
|
|
||||||
].join(';');
|
|
||||||
};
|
|
||||||
|
|
||||||
const DATEV_COLS = [
|
|
||||||
'Umsatz (ohne Soll/Haben-Kz)', 'Soll/Haben-Kennzeichen', 'WKZ Umsatz',
|
|
||||||
'Kurs', 'Basis-Umsatz', 'WKZ Basis-Umsatz', 'Konto',
|
|
||||||
'Gegenkonto (ohne BU-Schlüssel)', 'BU-Schlüssel', 'Belegdatum',
|
|
||||||
'Belegfeld 1', 'Belegfeld 2', 'Skonto', 'Buchungstext',
|
|
||||||
'Postensperre', 'Diverse Adressnummer', 'Geschäftspartnerbank',
|
|
||||||
'Sachverhalt', 'Zinssperre', 'Beleglink'
|
|
||||||
].join(';');
|
|
||||||
|
|
||||||
const formatDatevAmount = (amount) => {
|
|
||||||
return Math.abs(amount).toFixed(2).replace('.', ',');
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatDatevDate = (dateString) => {
|
|
||||||
if (!dateString) return '';
|
|
||||||
const parts = dateString.split('.');
|
|
||||||
if (parts.length === 3) {
|
|
||||||
const day = parts[0].padStart(2, '0');
|
|
||||||
const month = parts[1].padStart(2, '0');
|
|
||||||
return day + month;
|
|
||||||
}
|
|
||||||
return '';
|
|
||||||
};
|
|
||||||
|
|
||||||
const quote = (str, maxLen = 60) => {
|
|
||||||
if (!str) return '""';
|
|
||||||
return '"' + str.slice(0, maxLen).replace(/"/g, '""') + '"';
|
|
||||||
};
|
|
||||||
|
|
||||||
// DATEV export endpoint
|
|
||||||
router.get('/datev/:timeRange', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { timeRange } = req.params;
|
|
||||||
|
|
||||||
// Get transactions for the time period
|
|
||||||
const transactions = parseCSV();
|
|
||||||
let filteredTransactions = [];
|
|
||||||
let periodStart, periodEnd, filename;
|
|
||||||
|
|
||||||
if (timeRange.includes('-Q')) {
|
|
||||||
// Quarter format: YYYY-Q1, YYYY-Q2, etc.
|
|
||||||
const [year, quarterPart] = timeRange.split('-Q');
|
|
||||||
const quarter = parseInt(quarterPart);
|
|
||||||
const startMonth = (quarter - 1) * 3 + 1;
|
|
||||||
const endMonth = startMonth + 2;
|
|
||||||
|
|
||||||
filteredTransactions = transactions.filter(t => {
|
|
||||||
if (!t.monthYear) return false;
|
|
||||||
const [tYear, tMonth] = t.monthYear.split('-');
|
|
||||||
const monthNum = parseInt(tMonth);
|
|
||||||
return tYear === year && monthNum >= startMonth && monthNum <= endMonth;
|
|
||||||
});
|
|
||||||
|
|
||||||
periodStart = `${year}${startMonth.toString().padStart(2, '0')}01`;
|
|
||||||
periodEnd = new Date(year, endMonth, 0).toISOString().slice(0, 10).replace(/-/g, '');
|
|
||||||
filename = `DATEV_${year}_Q${quarter}.csv`;
|
|
||||||
} else if (timeRange.length === 4) {
|
|
||||||
// Year format: YYYY
|
|
||||||
filteredTransactions = transactions.filter(t => {
|
|
||||||
if (!t.monthYear) return false;
|
|
||||||
const [tYear] = t.monthYear.split('-');
|
|
||||||
return tYear === timeRange;
|
|
||||||
});
|
|
||||||
|
|
||||||
periodStart = `${timeRange}0101`;
|
|
||||||
periodEnd = `${timeRange}1231`;
|
|
||||||
filename = `DATEV_${timeRange}.csv`;
|
|
||||||
} else {
|
|
||||||
// Month format: YYYY-MM
|
|
||||||
const [year, month] = timeRange.split('-');
|
|
||||||
filteredTransactions = transactions.filter(t => t.monthYear === timeRange);
|
|
||||||
|
|
||||||
periodStart = `${year}${month.padStart(2, '0')}01`;
|
|
||||||
periodEnd = new Date(year, month, 0).toISOString().slice(0, 10).replace(/-/g, '');
|
|
||||||
filename = `DATEV_${year}_${month.padStart(2, '0')}.csv`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const monthTransactions = filteredTransactions
|
|
||||||
.sort((a, b) => a.parsedDate - b.parsedDate); // Oldest first for DATEV
|
|
||||||
|
|
||||||
if (!monthTransactions.length) {
|
|
||||||
return res.status(404).json({ error: 'No transactions found for this time period' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build DATEV format
|
|
||||||
const header = buildDatevHeader(periodStart, periodEnd);
|
|
||||||
|
|
||||||
const rows = monthTransactions.map((transaction, index) => {
|
|
||||||
const amount = Math.abs(transaction.numericAmount);
|
|
||||||
const isDebit = transaction.numericAmount < 0 ? 'S' : 'H'; // S = Soll (debit), H = Haben (credit)
|
|
||||||
|
|
||||||
return [
|
|
||||||
formatDatevAmount(amount), // #1 Umsatz
|
|
||||||
isDebit, // #2 Soll/Haben
|
|
||||||
quote('EUR', 3), // #3 WKZ Umsatz
|
|
||||||
'', '', '', // #4-6 (no FX)
|
|
||||||
'1200', // #7 Konto (Bank account)
|
|
||||||
transaction.numericAmount < 0 ? '4000' : '8400', // #8 Gegenkonto (expense/income)
|
|
||||||
'', // #9 BU-Schlüssel
|
|
||||||
formatDatevDate(transaction['Buchungstag']), // #10 Belegdatum
|
|
||||||
quote((index + 1).toString(), 36), // #11 Belegfeld 1 (sequential number)
|
|
||||||
'', '', // #12, #13
|
|
||||||
quote(transaction['Verwendungszweck'] || transaction['Buchungstext'], 60), // #14 Buchungstext
|
|
||||||
'', '', '', '', '', // #15-19 unused
|
|
||||||
'' // #20 Beleglink
|
|
||||||
].join(';');
|
|
||||||
});
|
|
||||||
|
|
||||||
const csv = [header, DATEV_COLS, ...rows].join('\r\n');
|
|
||||||
|
|
||||||
// Set headers for file download
|
|
||||||
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
|
||||||
res.setHeader('Content-Type', 'text/csv; charset=latin1');
|
|
||||||
|
|
||||||
// Convert to latin1 encoding for DATEV compatibility
|
|
||||||
const buffer = Buffer.from(csv, 'utf8');
|
|
||||||
res.send(buffer);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error generating DATEV export:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to generate DATEV export' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get PDF from tUmsatzBeleg
|
|
||||||
router.get('/pdf/umsatzbeleg/:kUmsatzBeleg', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { kUmsatzBeleg } = req.params;
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
SELECT content, datevlink
|
|
||||||
FROM dbo.tUmsatzBeleg
|
|
||||||
WHERE kUmsatzBeleg = @kUmsatzBeleg AND content IS NOT NULL
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(query, {
|
|
||||||
kUmsatzBeleg: parseInt(kUmsatzBeleg)
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!result.recordset || result.recordset.length === 0) {
|
|
||||||
return res.status(404).json({ error: 'PDF not found' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const pdfData = result.recordset[0];
|
|
||||||
const filename = `Umsatzbeleg_${kUmsatzBeleg}_${pdfData.datevlink || 'document'}.pdf`;
|
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'application/pdf');
|
|
||||||
res.setHeader('Content-Disposition', `inline; filename="${filename}"`);
|
|
||||||
res.send(pdfData.content);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching PDF from tUmsatzBeleg:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to fetch PDF' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get PDF from tPdfObjekt
|
|
||||||
router.get('/pdf/pdfobject/:kPdfObjekt', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { kPdfObjekt } = req.params;
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
SELECT content, datevlink, kLieferantenbestellung
|
|
||||||
FROM dbo.tPdfObjekt
|
|
||||||
WHERE kPdfObjekt = @kPdfObjekt AND content IS NOT NULL
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(query, {
|
|
||||||
kPdfObjekt: parseInt(kPdfObjekt)
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!result.recordset || result.recordset.length === 0) {
|
|
||||||
return res.status(404).json({ error: 'PDF not found' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const pdfData = result.recordset[0];
|
|
||||||
const filename = `PdfObjekt_${kPdfObjekt}_LB${pdfData.kLieferantenbestellung}_${pdfData.datevlink || 'document'}.pdf`;
|
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'application/pdf');
|
|
||||||
res.setHeader('Content-Disposition', `inline; filename="${filename}"`);
|
|
||||||
res.send(pdfData.content);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching PDF from tPdfObjekt:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to fetch PDF' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Kreditor API endpoints
|
|
||||||
|
|
||||||
// Get all kreditors
|
|
||||||
router.get('/kreditors', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
const query = `
|
|
||||||
SELECT id, iban, name, kreditorId, created_at, updated_at
|
|
||||||
FROM Kreditor
|
|
||||||
WHERE is_active = 1
|
|
||||||
ORDER BY name ASC
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(query);
|
|
||||||
res.json(result.recordset || []);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching kreditors:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to fetch kreditors' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get kreditor by ID
|
|
||||||
router.get('/kreditors/:id', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
const { id } = req.params;
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
SELECT id, iban, name, kreditorId, created_at, updated_at
|
|
||||||
FROM Kreditor
|
|
||||||
WHERE id = @id AND is_active = 1
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(query, [
|
|
||||||
{ name: 'id', type: 'int', value: parseInt(id) }
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (result.recordset.length === 0) {
|
|
||||||
return res.status(404).json({ error: 'Kreditor not found' });
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json(result.recordset[0]);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching kreditor:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to fetch kreditor' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create new kreditor
|
|
||||||
router.post('/kreditors', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
const { iban, name, kreditorId } = req.body;
|
|
||||||
|
|
||||||
// Validate required fields
|
|
||||||
if (!iban || !name || !kreditorId) {
|
|
||||||
return res.status(400).json({ error: 'IBAN, name, and kreditorId are required' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if kreditor with same IBAN or kreditorId already exists
|
|
||||||
const checkQuery = `
|
|
||||||
SELECT id FROM Kreditor
|
|
||||||
WHERE (iban = @iban OR kreditorId = @kreditorId) AND is_active = 1
|
|
||||||
`;
|
|
||||||
|
|
||||||
const checkResult = await executeQuery(checkQuery, [
|
|
||||||
{ name: 'iban', type: 'nvarchar', value: iban },
|
|
||||||
{ name: 'kreditorId', type: 'nvarchar', value: kreditorId }
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (checkResult.recordset.length > 0) {
|
|
||||||
return res.status(409).json({ error: 'Kreditor with this IBAN or kreditorId already exists' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const insertQuery = `
|
|
||||||
INSERT INTO Kreditor (iban, name, kreditorId, created_at, updated_at)
|
|
||||||
OUTPUT INSERTED.id, INSERTED.iban, INSERTED.name, INSERTED.kreditorId, INSERTED.created_at, INSERTED.updated_at
|
|
||||||
VALUES (@iban, @name, @kreditorId, GETDATE(), GETDATE())
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(insertQuery, [
|
|
||||||
{ name: 'iban', type: 'nvarchar', value: iban },
|
|
||||||
{ name: 'name', type: 'nvarchar', value: name },
|
|
||||||
{ name: 'kreditorId', type: 'nvarchar', value: kreditorId }
|
|
||||||
]);
|
|
||||||
|
|
||||||
res.status(201).json(result.recordset[0]);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error creating kreditor:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to create kreditor' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update kreditor
|
|
||||||
router.put('/kreditors/:id', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
const { id } = req.params;
|
|
||||||
const { iban, name, kreditorId } = req.body;
|
|
||||||
|
|
||||||
// Validate required fields
|
|
||||||
if (!iban || !name || !kreditorId) {
|
|
||||||
return res.status(400).json({ error: 'IBAN, name, and kreditorId are required' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if kreditor exists
|
|
||||||
const checkQuery = `SELECT id FROM Kreditor WHERE id = @id AND is_active = 1`;
|
|
||||||
const checkResult = await executeQuery(checkQuery, [
|
|
||||||
{ name: 'id', type: 'int', value: parseInt(id) }
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (checkResult.recordset.length === 0) {
|
|
||||||
return res.status(404).json({ error: 'Kreditor not found' });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for conflicts with other kreditors
|
|
||||||
const conflictQuery = `
|
|
||||||
SELECT id FROM Kreditor
|
|
||||||
WHERE (iban = @iban OR kreditorId = @kreditorId) AND id != @id AND is_active = 1
|
|
||||||
`;
|
|
||||||
|
|
||||||
const conflictResult = await executeQuery(conflictQuery, [
|
|
||||||
{ name: 'iban', type: 'nvarchar', value: iban },
|
|
||||||
{ name: 'kreditorId', type: 'nvarchar', value: kreditorId },
|
|
||||||
{ name: 'id', type: 'int', value: parseInt(id) }
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (conflictResult.recordset.length > 0) {
|
|
||||||
return res.status(409).json({ error: 'Another kreditor with this IBAN or kreditorId already exists' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const updateQuery = `
|
|
||||||
UPDATE Kreditor
|
|
||||||
SET iban = @iban, name = @name, kreditorId = @kreditorId, updated_at = GETDATE()
|
|
||||||
OUTPUT INSERTED.id, INSERTED.iban, INSERTED.name, INSERTED.kreditorId, INSERTED.created_at, INSERTED.updated_at
|
|
||||||
WHERE id = @id
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(updateQuery, [
|
|
||||||
{ name: 'iban', type: 'nvarchar', value: iban },
|
|
||||||
{ name: 'name', type: 'nvarchar', value: name },
|
|
||||||
{ name: 'kreditorId', type: 'nvarchar', value: kreditorId },
|
|
||||||
{ name: 'id', type: 'int', value: parseInt(id) }
|
|
||||||
]);
|
|
||||||
|
|
||||||
res.json(result.recordset[0]);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error updating kreditor:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to update kreditor' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Delete kreditor (soft delete)
|
|
||||||
router.delete('/kreditors/:id', authenticateToken, async (req, res) => {
|
|
||||||
try {
|
|
||||||
const { executeQuery } = require('../config/database');
|
|
||||||
const { id } = req.params;
|
|
||||||
|
|
||||||
const query = `
|
|
||||||
UPDATE Kreditor
|
|
||||||
SET is_active = 0, updated_at = GETDATE()
|
|
||||||
WHERE id = @id AND is_active = 1
|
|
||||||
`;
|
|
||||||
|
|
||||||
const result = await executeQuery(query, [
|
|
||||||
{ name: 'id', type: 'int', value: parseInt(id) }
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (result.rowsAffected[0] === 0) {
|
|
||||||
return res.status(404).json({ error: 'Kreditor not found' });
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({ message: 'Kreditor deleted successfully' });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error deleting kreditor:', error);
|
|
||||||
res.status(500).json({ error: 'Failed to delete kreditor' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
|
||||||
273
src/routes/data/accountingItems.js
Normal file
273
src/routes/data/accountingItems.js
Normal file
@@ -0,0 +1,273 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Debug: Get JTL Kontierung data for a specific JTL Umsatz (by kZahlungsabgleichUmsatz)
|
||||||
|
router.get('/jtl-kontierung/:jtlId', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { jtlId } = req.params;
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT
|
||||||
|
uk.data
|
||||||
|
FROM eazybusiness.dbo.tZahlungsabgleichUmsatz z
|
||||||
|
LEFT JOIN eazybusiness.dbo.tUmsatzKontierung uk
|
||||||
|
ON uk.kZahlungsabgleichUmsatz = z.kZahlungsabgleichUmsatz
|
||||||
|
WHERE z.kZahlungsabgleichUmsatz = @jtlId
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query, { jtlId: parseInt(jtlId, 10) });
|
||||||
|
// Return undefined when no data found (do not lie with empty array/string)
|
||||||
|
if (!result.recordset || result.recordset.length === 0) {
|
||||||
|
return res.json({ data: undefined });
|
||||||
|
}
|
||||||
|
|
||||||
|
// If multiple rows exist, return all; otherwise single object
|
||||||
|
const rows = result.recordset.map(r => ({ data: r.data }));
|
||||||
|
if (rows.length === 1) {
|
||||||
|
return res.json(rows[0]);
|
||||||
|
}
|
||||||
|
return res.json(rows);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching JTL Kontierung data:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch JTL Kontierung data' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get accounting items for a specific transaction
|
||||||
|
router.get('/accounting-items/:transactionId', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { transactionId } = req.params;
|
||||||
|
|
||||||
|
// Try both numeric and string format (similar to banking transactions)
|
||||||
|
let query, params;
|
||||||
|
const numericId = parseInt(transactionId, 10);
|
||||||
|
|
||||||
|
if (!isNaN(numericId) && numericId.toString() === transactionId) {
|
||||||
|
// It's a numeric ID - check transaction_id column
|
||||||
|
query = `
|
||||||
|
SELECT
|
||||||
|
ai.*,
|
||||||
|
k.name as konto_name,
|
||||||
|
bu.name as bu_name,
|
||||||
|
bu.vst as bu_vst
|
||||||
|
FROM fibdash.AccountingItems ai
|
||||||
|
LEFT JOIN fibdash.Konto k ON ai.konto = k.konto
|
||||||
|
LEFT JOIN fibdash.BU bu ON ai.bu = bu.bu
|
||||||
|
WHERE ai.transaction_id = @transactionId
|
||||||
|
ORDER BY ai.id
|
||||||
|
`;
|
||||||
|
params = { transactionId: numericId };
|
||||||
|
} else {
|
||||||
|
// It's a string ID - check csv_transaction_id column
|
||||||
|
query = `
|
||||||
|
SELECT
|
||||||
|
ai.*,
|
||||||
|
k.name as konto_name,
|
||||||
|
bu.name as bu_name,
|
||||||
|
bu.vst as bu_vst
|
||||||
|
FROM fibdash.AccountingItems ai
|
||||||
|
LEFT JOIN fibdash.Konto k ON ai.konto = k.konto
|
||||||
|
LEFT JOIN fibdash.BU bu ON ai.bu = bu.bu
|
||||||
|
WHERE ai.csv_transaction_id = @transactionId
|
||||||
|
ORDER BY ai.id
|
||||||
|
`;
|
||||||
|
params = { transactionId };
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await executeQuery(query, params);
|
||||||
|
res.json(result.recordset);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching accounting items:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch accounting items' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create accounting item for a transaction
|
||||||
|
router.post('/accounting-items', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const {
|
||||||
|
transaction_id,
|
||||||
|
csv_transaction_id,
|
||||||
|
umsatz_brutto,
|
||||||
|
soll_haben_kz,
|
||||||
|
konto,
|
||||||
|
bu,
|
||||||
|
buchungsdatum,
|
||||||
|
rechnungsnummer,
|
||||||
|
buchungstext
|
||||||
|
} = req.body;
|
||||||
|
|
||||||
|
if ((!transaction_id && !csv_transaction_id) || !umsatz_brutto || !soll_haben_kz || !konto || !buchungsdatum) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error: 'Transaction ID, amount, debit/credit indicator, account, and booking date are required'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let insertQuery, queryParams;
|
||||||
|
|
||||||
|
if (csv_transaction_id) {
|
||||||
|
// For CSV transactions, use placeholder transaction_id
|
||||||
|
insertQuery = `
|
||||||
|
INSERT INTO fibdash.AccountingItems
|
||||||
|
(transaction_id, csv_transaction_id, umsatz_brutto, soll_haben_kz, konto, gegenkonto, bu, buchungsdatum, rechnungsnummer, buchungstext)
|
||||||
|
OUTPUT INSERTED.*
|
||||||
|
VALUES (-1, @csv_transaction_id, @umsatz_brutto, @soll_haben_kz, @konto, '', @bu, @buchungsdatum, @rechnungsnummer, @buchungstext)
|
||||||
|
`;
|
||||||
|
queryParams = {
|
||||||
|
csv_transaction_id,
|
||||||
|
umsatz_brutto,
|
||||||
|
soll_haben_kz,
|
||||||
|
konto,
|
||||||
|
bu: bu || null,
|
||||||
|
buchungsdatum,
|
||||||
|
rechnungsnummer: rechnungsnummer || null,
|
||||||
|
buchungstext: buchungstext || null
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// For regular transactions
|
||||||
|
insertQuery = `
|
||||||
|
INSERT INTO fibdash.AccountingItems
|
||||||
|
(transaction_id, csv_transaction_id, umsatz_brutto, soll_haben_kz, konto, gegenkonto, bu, buchungsdatum, rechnungsnummer, buchungstext)
|
||||||
|
OUTPUT INSERTED.*
|
||||||
|
VALUES (@transaction_id, NULL, @umsatz_brutto, @soll_haben_kz, @konto, '', @bu, @buchungsdatum, @rechnungsnummer, @buchungstext)
|
||||||
|
`;
|
||||||
|
queryParams = {
|
||||||
|
transaction_id,
|
||||||
|
umsatz_brutto,
|
||||||
|
soll_haben_kz,
|
||||||
|
konto,
|
||||||
|
bu: bu || null,
|
||||||
|
buchungsdatum,
|
||||||
|
rechnungsnummer: rechnungsnummer || null,
|
||||||
|
buchungstext: buchungstext || null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await executeQuery(insertQuery, queryParams);
|
||||||
|
res.status(201).json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating accounting item:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to create accounting item' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update accounting item
|
||||||
|
router.put('/accounting-items/:id', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { id } = req.params;
|
||||||
|
const { umsatz_brutto, soll_haben_kz, konto, bu, rechnungsnummer, buchungstext } = req.body;
|
||||||
|
|
||||||
|
if (!umsatz_brutto || !soll_haben_kz || !konto) {
|
||||||
|
return res.status(400).json({ error: 'Amount, debit/credit indicator, and account are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateQuery = `
|
||||||
|
UPDATE fibdash.AccountingItems
|
||||||
|
SET umsatz_brutto = @umsatz_brutto,
|
||||||
|
soll_haben_kz = @soll_haben_kz,
|
||||||
|
konto = @konto,
|
||||||
|
bu = @bu,
|
||||||
|
rechnungsnummer = @rechnungsnummer,
|
||||||
|
buchungstext = @buchungstext
|
||||||
|
OUTPUT INSERTED.*
|
||||||
|
WHERE id = @id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(updateQuery, {
|
||||||
|
umsatz_brutto,
|
||||||
|
soll_haben_kz,
|
||||||
|
konto,
|
||||||
|
bu: bu || null,
|
||||||
|
rechnungsnummer: rechnungsnummer || null,
|
||||||
|
buchungstext: buchungstext || null,
|
||||||
|
id: parseInt(id, 10)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.recordset.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'Accounting item not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating accounting item:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to update accounting item' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete accounting item
|
||||||
|
router.delete('/accounting-items/:id', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const deleteQuery = `DELETE FROM fibdash.AccountingItems WHERE id = @id`;
|
||||||
|
await executeQuery(deleteQuery, { id: parseInt(id, 10) });
|
||||||
|
|
||||||
|
res.json({ message: 'Accounting item deleted successfully' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting accounting item:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to delete accounting item' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get all Konto options
|
||||||
|
router.get('/kontos', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
const query = `SELECT * FROM fibdash.Konto ORDER BY konto`;
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
|
||||||
|
res.json(result.recordset);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching kontos:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch kontos' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create new Konto
|
||||||
|
router.post('/kontos', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { konto, name } = req.body;
|
||||||
|
|
||||||
|
if (!konto || !name) {
|
||||||
|
return res.status(400).json({ error: 'Konto and name are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertQuery = `
|
||||||
|
INSERT INTO fibdash.Konto (konto, name)
|
||||||
|
OUTPUT INSERTED.*
|
||||||
|
VALUES (@konto, @name)
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(insertQuery, { konto, name });
|
||||||
|
res.status(201).json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating konto:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to create konto' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get all BU options
|
||||||
|
router.get('/bus', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
const query = `SELECT * FROM fibdash.BU ORDER BY bu`;
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
|
||||||
|
res.json(result.recordset);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching BUs:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch BUs' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
198
src/routes/data/bankingTransactions.js
Normal file
198
src/routes/data/bankingTransactions.js
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Get banking account transactions for a specific transaction
|
||||||
|
router.get('/banking-transactions/:transactionId', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { transactionId } = req.params;
|
||||||
|
|
||||||
|
// Try both numeric and string format
|
||||||
|
let query, params;
|
||||||
|
const numericId = parseInt(transactionId, 10);
|
||||||
|
|
||||||
|
if (!isNaN(numericId) && numericId.toString() === transactionId) {
|
||||||
|
// It's a numeric ID - check transaction_id column
|
||||||
|
query = `
|
||||||
|
SELECT
|
||||||
|
bat.*,
|
||||||
|
k.name as assigned_kreditor_name,
|
||||||
|
k.kreditorId as assigned_kreditor_id_code
|
||||||
|
FROM fibdash.BankingAccountTransactions bat
|
||||||
|
LEFT JOIN fibdash.Kreditor k ON bat.assigned_kreditor_id = k.id
|
||||||
|
WHERE bat.transaction_id = @transactionId
|
||||||
|
`;
|
||||||
|
params = { transactionId: numericId };
|
||||||
|
} else {
|
||||||
|
// It's a string ID - check csv_transaction_id column
|
||||||
|
query = `
|
||||||
|
SELECT
|
||||||
|
bat.*,
|
||||||
|
k.name as assigned_kreditor_name,
|
||||||
|
k.kreditorId as assigned_kreditor_id_code
|
||||||
|
FROM fibdash.BankingAccountTransactions bat
|
||||||
|
LEFT JOIN fibdash.Kreditor k ON bat.assigned_kreditor_id = k.id
|
||||||
|
WHERE bat.csv_transaction_id = @transactionId
|
||||||
|
`;
|
||||||
|
params = { transactionId };
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await executeQuery(query, params);
|
||||||
|
|
||||||
|
res.json(result.recordset);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching banking account transactions:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch banking account transactions' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create banking account transaction assignment
|
||||||
|
router.post('/banking-transactions', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { transaction_id, csv_transaction_id, banking_iban, assigned_kreditor_id, notes } = req.body;
|
||||||
|
|
||||||
|
if ((!transaction_id && !csv_transaction_id) || !banking_iban || !assigned_kreditor_id) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error: 'Transaction ID (or CSV Transaction ID), banking IBAN, and assigned kreditor ID are required'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let checkQuery, checkParams;
|
||||||
|
|
||||||
|
if (csv_transaction_id) {
|
||||||
|
checkQuery = `SELECT id FROM fibdash.BankingAccountTransactions WHERE csv_transaction_id = @csv_transaction_id`;
|
||||||
|
checkParams = { csv_transaction_id };
|
||||||
|
} else {
|
||||||
|
checkQuery = `SELECT id FROM fibdash.BankingAccountTransactions WHERE transaction_id = @transaction_id`;
|
||||||
|
checkParams = { transaction_id };
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkResult = await executeQuery(checkQuery, checkParams);
|
||||||
|
|
||||||
|
if (checkResult.recordset.length > 0) {
|
||||||
|
return res.status(409).json({ error: 'Banking transaction assignment already exists' });
|
||||||
|
}
|
||||||
|
|
||||||
|
let insertQuery, queryParams;
|
||||||
|
|
||||||
|
if (csv_transaction_id) {
|
||||||
|
// For CSV transactions, use a placeholder transaction_id since it's NOT NULL
|
||||||
|
insertQuery = `
|
||||||
|
INSERT INTO fibdash.BankingAccountTransactions
|
||||||
|
(transaction_id, csv_transaction_id, banking_iban, assigned_kreditor_id, notes)
|
||||||
|
OUTPUT INSERTED.*
|
||||||
|
VALUES (-1, @csv_transaction_id, @banking_iban, @assigned_kreditor_id, @notes)
|
||||||
|
`;
|
||||||
|
queryParams = {
|
||||||
|
csv_transaction_id,
|
||||||
|
banking_iban,
|
||||||
|
assigned_kreditor_id,
|
||||||
|
notes: notes || null
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// For regular transactions
|
||||||
|
insertQuery = `
|
||||||
|
INSERT INTO fibdash.BankingAccountTransactions
|
||||||
|
(transaction_id, csv_transaction_id, banking_iban, assigned_kreditor_id, notes)
|
||||||
|
OUTPUT INSERTED.*
|
||||||
|
VALUES (@transaction_id, NULL, @banking_iban, @assigned_kreditor_id, @notes)
|
||||||
|
`;
|
||||||
|
queryParams = {
|
||||||
|
transaction_id,
|
||||||
|
banking_iban,
|
||||||
|
assigned_kreditor_id,
|
||||||
|
notes: notes || null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await executeQuery(insertQuery, queryParams);
|
||||||
|
|
||||||
|
res.status(201).json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating banking account transaction:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to create banking account transaction' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update banking account transaction assignment
|
||||||
|
router.put('/banking-transactions/:id', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { id } = req.params;
|
||||||
|
const { assigned_kreditor_id, notes } = req.body;
|
||||||
|
|
||||||
|
if (!assigned_kreditor_id) {
|
||||||
|
return res.status(400).json({ error: 'Assigned kreditor ID is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateQuery = `
|
||||||
|
UPDATE fibdash.BankingAccountTransactions
|
||||||
|
SET assigned_kreditor_id = @assigned_kreditor_id,
|
||||||
|
notes = @notes,
|
||||||
|
assigned_date = GETDATE()
|
||||||
|
OUTPUT INSERTED.*
|
||||||
|
WHERE id = @id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(updateQuery, {
|
||||||
|
assigned_kreditor_id,
|
||||||
|
notes: notes || null,
|
||||||
|
id: parseInt(id, 10)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.recordset.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'Banking transaction assignment not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating banking account transaction:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to update banking account transaction' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete banking account transaction assignment
|
||||||
|
router.delete('/banking-transactions/:id', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const deleteQuery = `
|
||||||
|
DELETE FROM fibdash.BankingAccountTransactions
|
||||||
|
WHERE id = @id
|
||||||
|
`;
|
||||||
|
|
||||||
|
await executeQuery(deleteQuery, { id: parseInt(id, 10) });
|
||||||
|
|
||||||
|
res.json({ message: 'Banking transaction assignment deleted successfully' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting banking account transaction:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to delete banking account transaction' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get all kreditors that can be assigned to banking transactions (non-banking kreditors)
|
||||||
|
router.get('/assignable-kreditors', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT id, name, kreditorId
|
||||||
|
FROM fibdash.Kreditor
|
||||||
|
WHERE (is_banking = 0 OR is_banking IS NULL)
|
||||||
|
ORDER BY name
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
|
||||||
|
res.json(result.recordset);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching assignable kreditors:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch assignable kreditors' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
635
src/routes/data/csvImport.js
Normal file
635
src/routes/data/csvImport.js
Normal file
@@ -0,0 +1,635 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Test CSV import endpoint (no auth for testing) - ACTUALLY IMPORTS TO DATABASE
|
||||||
|
router.post('/test-csv-import', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { transactions, filename, batchId } = req.body;
|
||||||
|
|
||||||
|
if (!transactions || !Array.isArray(transactions)) {
|
||||||
|
return res.status(400).json({ error: 'Transactions array is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const importBatchId = batchId || 'test_import_' + Date.now();
|
||||||
|
let successCount = 0;
|
||||||
|
let errorCount = 0;
|
||||||
|
const errors = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < transactions.length; i++) {
|
||||||
|
const transaction = transactions[i];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const validationErrors = [];
|
||||||
|
|
||||||
|
if (!transaction['Buchungstag'] || transaction['Buchungstag'].trim() === '') {
|
||||||
|
validationErrors.push('Buchungstag is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!transaction['Betrag'] || transaction['Betrag'].toString().trim() === '') {
|
||||||
|
validationErrors.push('Betrag is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (validationErrors.length > 0) {
|
||||||
|
errors.push({
|
||||||
|
row: i + 1,
|
||||||
|
error: 'Validation failed: ' + validationErrors.join(', '),
|
||||||
|
transaction: transaction
|
||||||
|
});
|
||||||
|
errorCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsedDate = null;
|
||||||
|
if (transaction['Buchungstag']) {
|
||||||
|
const dateStr = transaction['Buchungstag'].trim();
|
||||||
|
const dateParts = dateStr.split(/[.\/\-]/);
|
||||||
|
if (dateParts.length === 3) {
|
||||||
|
const day = parseInt(dateParts[0], 10);
|
||||||
|
const month = parseInt(dateParts[1], 10) - 1;
|
||||||
|
let year = parseInt(dateParts[2], 10);
|
||||||
|
|
||||||
|
if (year < 100) {
|
||||||
|
year += (year < 50) ? 2000 : 1900;
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedDate = new Date(year, month, day);
|
||||||
|
|
||||||
|
if (isNaN(parsedDate.getTime())) {
|
||||||
|
parsedDate = null;
|
||||||
|
validationErrors.push('Invalid date format: ' + dateStr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let numericAmount = 0;
|
||||||
|
if (transaction['Betrag']) {
|
||||||
|
const amountStr = transaction['Betrag'].toString().replace(/[^\d,.-]/g, '');
|
||||||
|
const normalizedAmount = amountStr.replace(',', '.');
|
||||||
|
numericAmount = parseFloat(normalizedAmount) || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for existing transaction to prevent duplicates
|
||||||
|
const duplicateCheckQuery = `
|
||||||
|
SELECT COUNT(*) as count FROM fibdash.CSVTransactions
|
||||||
|
WHERE buchungstag = @buchungstag
|
||||||
|
AND wertstellung = @wertstellung
|
||||||
|
AND umsatzart = @umsatzart
|
||||||
|
AND betrag = @betrag
|
||||||
|
AND beguenstigter_zahlungspflichtiger = @beguenstigter_zahlungspflichtiger
|
||||||
|
AND verwendungszweck = @verwendungszweck
|
||||||
|
`;
|
||||||
|
|
||||||
|
const duplicateCheckResult = await executeQuery(duplicateCheckQuery, {
|
||||||
|
buchungstag: transaction['Buchungstag'] || null,
|
||||||
|
wertstellung: transaction['Valutadatum'] || null,
|
||||||
|
umsatzart: transaction['Buchungstext'] || null,
|
||||||
|
betrag: numericAmount,
|
||||||
|
beguenstigter_zahlungspflichtiger: transaction['Beguenstigter/Zahlungspflichtiger'] || null,
|
||||||
|
verwendungszweck: transaction['Verwendungszweck'] || null
|
||||||
|
});
|
||||||
|
|
||||||
|
if (duplicateCheckResult.recordset[0].count > 0) {
|
||||||
|
console.log(`Skipping duplicate transaction at row ${i + 1}: ${transaction['Buchungstag']} - ${numericAmount}`);
|
||||||
|
errors.push({
|
||||||
|
row: i + 1,
|
||||||
|
error: 'Duplicate transaction (already exists in database)',
|
||||||
|
transaction: transaction
|
||||||
|
});
|
||||||
|
errorCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertQuery = `
|
||||||
|
INSERT INTO fibdash.CSVTransactions
|
||||||
|
(buchungstag, wertstellung, umsatzart, betrag, betrag_original, waehrung,
|
||||||
|
beguenstigter_zahlungspflichtiger, kontonummer_iban, bic, verwendungszweck,
|
||||||
|
parsed_date, numeric_amount, import_batch_id, source_filename, source_row_number)
|
||||||
|
VALUES
|
||||||
|
(@buchungstag, @wertstellung, @umsatzart, @betrag, @betrag_original, @waehrung,
|
||||||
|
@beguenstigter_zahlungspflichtiger, @kontonummer_iban, @bic, @verwendungszweck,
|
||||||
|
@parsed_date, @numeric_amount, @import_batch_id, @source_filename, @source_row_number)
|
||||||
|
`;
|
||||||
|
|
||||||
|
await executeQuery(insertQuery, {
|
||||||
|
buchungstag: transaction['Buchungstag'] || null,
|
||||||
|
wertstellung: transaction['Valutadatum'] || null,
|
||||||
|
umsatzart: transaction['Buchungstext'] || null,
|
||||||
|
betrag: numericAmount,
|
||||||
|
betrag_original: transaction['Betrag'] || null,
|
||||||
|
waehrung: transaction['Waehrung'] || null,
|
||||||
|
beguenstigter_zahlungspflichtiger: transaction['Beguenstigter/Zahlungspflichtiger'] || null,
|
||||||
|
kontonummer_iban: transaction['Kontonummer/IBAN'] || null,
|
||||||
|
bic: transaction['BIC (SWIFT-Code)'] || null,
|
||||||
|
verwendungszweck: transaction['Verwendungszweck'] || null,
|
||||||
|
parsed_date: parsedDate,
|
||||||
|
numeric_amount: numericAmount,
|
||||||
|
import_batch_id: importBatchId,
|
||||||
|
source_filename: filename || 'test_import',
|
||||||
|
source_row_number: i + 1
|
||||||
|
});
|
||||||
|
|
||||||
|
successCount++;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error importing transaction ' + (i + 1) + ':', error);
|
||||||
|
errors.push({
|
||||||
|
row: i + 1,
|
||||||
|
error: error.message,
|
||||||
|
transaction: transaction
|
||||||
|
});
|
||||||
|
errorCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
batchId: importBatchId,
|
||||||
|
imported: successCount,
|
||||||
|
errors: errorCount,
|
||||||
|
details: errors.length > 0 ? errors : undefined,
|
||||||
|
paypalTransaction: transactions.find(t => t['Kontonummer/IBAN'] === 'LU89751000135104200E')
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Test import error:', error);
|
||||||
|
res.status(500).json({ error: 'Test import failed' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Import CSV transactions to database
|
||||||
|
router.post('/import-csv-transactions', authenticateToken, async (req, res) => {
|
||||||
|
console.log('Importing CSV transactions');
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { transactions, filename, batchId, headers } = req.body;
|
||||||
|
|
||||||
|
if (!transactions || !Array.isArray(transactions)) {
|
||||||
|
return res.status(400).json({ error: 'Transactions array is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedHeaders = [
|
||||||
|
'Auftragskonto',
|
||||||
|
'Buchungstag',
|
||||||
|
'Valutadatum',
|
||||||
|
'Buchungstext',
|
||||||
|
'Verwendungszweck',
|
||||||
|
'Glaeubiger ID',
|
||||||
|
'Mandatsreferenz',
|
||||||
|
'Kundenreferenz (End-to-End)',
|
||||||
|
'Sammlerreferenz',
|
||||||
|
'Lastschrift Ursprungsbetrag',
|
||||||
|
'Auslagenersatz Ruecklastschrift',
|
||||||
|
'Beguenstigter/Zahlungspflichtiger',
|
||||||
|
'Kontonummer/IBAN',
|
||||||
|
'BIC (SWIFT-Code)',
|
||||||
|
'Betrag',
|
||||||
|
'Waehrung',
|
||||||
|
'Info'
|
||||||
|
];
|
||||||
|
|
||||||
|
if (headers && Array.isArray(headers)) {
|
||||||
|
const missingHeaders = expectedHeaders.filter(expected =>
|
||||||
|
!headers.some(header => header.trim() === expected)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (missingHeaders.length > 0) {
|
||||||
|
return res.status(400).json({
|
||||||
|
error: 'Invalid CSV format - missing required headers',
|
||||||
|
missing: missingHeaders,
|
||||||
|
expected: expectedHeaders,
|
||||||
|
received: headers
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (transactions.length === 0) {
|
||||||
|
return res.status(400).json({ error: 'No transaction data found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const importBatchId = batchId || 'import_' + Date.now();
|
||||||
|
let successCount = 0;
|
||||||
|
let errorCount = 0;
|
||||||
|
const errors = [];
|
||||||
|
console.log('precheck done');
|
||||||
|
|
||||||
|
for (let i = 0; i < transactions.length; i++) {
|
||||||
|
const transaction = transactions[i];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const validationErrors = [];
|
||||||
|
|
||||||
|
if (!transaction['Buchungstag'] || transaction['Buchungstag'].trim() === '') {
|
||||||
|
validationErrors.push('Buchungstag is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!transaction['Betrag'] || transaction['Betrag'].toString().trim() === '') {
|
||||||
|
validationErrors.push('Betrag is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (validationErrors.length > 2) {
|
||||||
|
console.log('Skipping invalid row ' + (i + 1) + ':', validationErrors);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (validationErrors.length > 0) {
|
||||||
|
errors.push({
|
||||||
|
row: i + 1,
|
||||||
|
error: 'Validation failed: ' + validationErrors.join(', '),
|
||||||
|
transaction: transaction
|
||||||
|
});
|
||||||
|
errorCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let parsedDate = null;
|
||||||
|
if (transaction['Buchungstag']) {
|
||||||
|
const dateStr = transaction['Buchungstag'].trim();
|
||||||
|
const dateParts = dateStr.split(/[.\/\-]/);
|
||||||
|
if (dateParts.length === 3) {
|
||||||
|
const day = parseInt(dateParts[0], 10);
|
||||||
|
const month = parseInt(dateParts[1], 10) - 1;
|
||||||
|
let year = parseInt(dateParts[2], 10);
|
||||||
|
|
||||||
|
if (year < 100) {
|
||||||
|
year += (year < 50) ? 2000 : 1900;
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedDate = new Date(year, month, day);
|
||||||
|
|
||||||
|
if (isNaN(parsedDate.getTime()) ||
|
||||||
|
parsedDate.getDate() !== day ||
|
||||||
|
parsedDate.getMonth() !== month ||
|
||||||
|
parsedDate.getFullYear() !== year) {
|
||||||
|
parsedDate = null;
|
||||||
|
validationErrors.push('Invalid date format: ' + dateStr);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
validationErrors.push('Invalid date format: ' + dateStr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let numericAmount = 0;
|
||||||
|
if (transaction['Betrag']) {
|
||||||
|
const amountStr = transaction['Betrag'].toString().replace(/[^\d,.-]/g, '');
|
||||||
|
const normalizedAmount = amountStr.replace(',', '.');
|
||||||
|
numericAmount = parseFloat(normalizedAmount) || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for existing transaction to prevent duplicates
|
||||||
|
const duplicateCheckQuery = `
|
||||||
|
SELECT COUNT(*) as count FROM fibdash.CSVTransactions
|
||||||
|
WHERE buchungstag = @buchungstag
|
||||||
|
AND wertstellung = @wertstellung
|
||||||
|
AND umsatzart = @umsatzart
|
||||||
|
AND betrag = @betrag
|
||||||
|
AND beguenstigter_zahlungspflichtiger = @beguenstigter_zahlungspflichtiger
|
||||||
|
AND verwendungszweck = @verwendungszweck
|
||||||
|
`;
|
||||||
|
|
||||||
|
const duplicateCheckResult = await executeQuery(duplicateCheckQuery, {
|
||||||
|
buchungstag: transaction['Buchungstag'] || null,
|
||||||
|
wertstellung: transaction['Valutadatum'] || null,
|
||||||
|
umsatzart: transaction['Buchungstext'] || null,
|
||||||
|
betrag: numericAmount,
|
||||||
|
beguenstigter_zahlungspflichtiger: transaction['Beguenstigter/Zahlungspflichtiger'] || null,
|
||||||
|
verwendungszweck: transaction['Verwendungszweck'] || null
|
||||||
|
});
|
||||||
|
|
||||||
|
if (duplicateCheckResult.recordset[0].count > 0) {
|
||||||
|
console.log(`Skipping duplicate transaction at row ${i + 1}: ${transaction['Buchungstag']} - ${numericAmount}`);
|
||||||
|
errors.push({
|
||||||
|
row: i + 1,
|
||||||
|
error: 'Duplicate transaction (already exists in database)',
|
||||||
|
transaction: transaction
|
||||||
|
});
|
||||||
|
errorCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertQuery = `
|
||||||
|
INSERT INTO fibdash.CSVTransactions
|
||||||
|
(buchungstag, wertstellung, umsatzart, betrag, betrag_original, waehrung,
|
||||||
|
beguenstigter_zahlungspflichtiger, kontonummer_iban, bic, verwendungszweck,
|
||||||
|
parsed_date, numeric_amount, import_batch_id, source_filename, source_row_number)
|
||||||
|
VALUES
|
||||||
|
(@buchungstag, @wertstellung, @umsatzart, @betrag, @betrag_original, @waehrung,
|
||||||
|
@beguenstigter_zahlungspflichtiger, @kontonummer_iban, @bic, @verwendungszweck,
|
||||||
|
@parsed_date, @numeric_amount, @import_batch_id, @source_filename, @source_row_number)
|
||||||
|
`;
|
||||||
|
|
||||||
|
await executeQuery(insertQuery, {
|
||||||
|
buchungstag: transaction['Buchungstag'] || null,
|
||||||
|
wertstellung: transaction['Valutadatum'] || null,
|
||||||
|
umsatzart: transaction['Buchungstext'] || null,
|
||||||
|
betrag: numericAmount,
|
||||||
|
betrag_original: transaction['Betrag'] || null,
|
||||||
|
waehrung: transaction['Waehrung'] || null,
|
||||||
|
beguenstigter_zahlungspflichtiger: transaction['Beguenstigter/Zahlungspflichtiger'] || null,
|
||||||
|
kontonummer_iban: transaction['Kontonummer/IBAN'] || null,
|
||||||
|
bic: transaction['BIC (SWIFT-Code)'] || null,
|
||||||
|
verwendungszweck: transaction['Verwendungszweck'] || null,
|
||||||
|
parsed_date: parsedDate,
|
||||||
|
numeric_amount: numericAmount,
|
||||||
|
import_batch_id: importBatchId,
|
||||||
|
source_filename: filename || null,
|
||||||
|
source_row_number: i + 1
|
||||||
|
});
|
||||||
|
|
||||||
|
successCount++;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error importing transaction ' + (i + 1) + ':', error);
|
||||||
|
errors.push({
|
||||||
|
row: i + 1,
|
||||||
|
error: error.message,
|
||||||
|
transaction: transaction
|
||||||
|
});
|
||||||
|
errorCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('import done',errors);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
batchId: importBatchId,
|
||||||
|
imported: successCount,
|
||||||
|
errors: errorCount,
|
||||||
|
details: errors.length > 0 ? errors : undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error importing CSV transactions:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to import CSV transactions' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get imported CSV transactions
|
||||||
|
router.get('/csv-transactions', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { batchId, limit = 100, offset = 0 } = req.query;
|
||||||
|
|
||||||
|
let query = `
|
||||||
|
SELECT
|
||||||
|
csv.*,
|
||||||
|
k.name as kreditor_name,
|
||||||
|
k.kreditorId as kreditor_id,
|
||||||
|
k.is_banking as kreditor_is_banking,
|
||||||
|
bat.assigned_kreditor_id,
|
||||||
|
ak.name as assigned_kreditor_name
|
||||||
|
FROM fibdash.CSVTransactions csv
|
||||||
|
LEFT JOIN fibdash.Kreditor k ON csv.kontonummer_iban = k.iban
|
||||||
|
LEFT JOIN fibdash.BankingAccountTransactions bat ON csv.id = bat.csv_transaction_id
|
||||||
|
LEFT JOIN fibdash.Kreditor ak ON bat.assigned_kreditor_id = ak.id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const params = {};
|
||||||
|
|
||||||
|
if (batchId) {
|
||||||
|
query += ' WHERE csv.import_batch_id = @batchId';
|
||||||
|
params.batchId = batchId;
|
||||||
|
}
|
||||||
|
|
||||||
|
query += ' ORDER BY csv.parsed_date DESC, csv.id DESC';
|
||||||
|
query += ' OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY';
|
||||||
|
|
||||||
|
params.offset = parseInt(offset, 10);
|
||||||
|
params.limit = parseInt(limit, 10);
|
||||||
|
|
||||||
|
const result = await executeQuery(query, params);
|
||||||
|
|
||||||
|
res.json(result.recordset);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching CSV transactions:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch CSV transactions' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get CSV import batches
|
||||||
|
router.get('/csv-import-batches', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT
|
||||||
|
import_batch_id,
|
||||||
|
source_filename,
|
||||||
|
MIN(import_date) as import_date,
|
||||||
|
COUNT(*) as transaction_count,
|
||||||
|
SUM(CASE WHEN is_processed = 1 THEN 1 ELSE 0 END) as processed_count
|
||||||
|
FROM fibdash.CSVTransactions
|
||||||
|
GROUP BY import_batch_id, source_filename
|
||||||
|
ORDER BY MIN(import_date) DESC
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
|
||||||
|
res.json(result.recordset);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching import batches:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch import batches' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Import DATEV Beleglinks to database
|
||||||
|
router.post('/import-datev-beleglinks', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { beleglinks, filename, batchId, headers } = req.body;
|
||||||
|
|
||||||
|
if (!beleglinks || !Array.isArray(beleglinks)) {
|
||||||
|
return res.status(400).json({ error: 'Beleglinks array is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expected DATEV CSV headers from the example
|
||||||
|
const expectedHeaders = [
|
||||||
|
'Belegart', 'Geschäftspartner-Name', 'Geschäftspartner-Konto', 'Rechnungsbetrag', 'WKZ',
|
||||||
|
'Rechnungs-Nr.', 'Interne Re.-Nr.', 'Rechnungsdatum', 'BU', 'Konto', 'Konto-Bezeichnung',
|
||||||
|
'Ware/Leistung', 'Zahlungszuordnung', 'Kontoumsatzzuordnung', 'Gebucht', 'Festgeschrieben',
|
||||||
|
'Kopie', 'Eingangsdatum', 'Bezahlt', 'BezahltAm', 'Geschäftspartner-Ort', 'Skonto-Betrag 1',
|
||||||
|
'Fällig mit Skonto 1', 'Skonto 1 in %', 'Skonto-Betrag 2', 'Fällig mit Skonto 2',
|
||||||
|
'Skonto 2 in %', 'Fällig ohne Skonto', 'Steuer in %', 'USt-IdNr.', 'Kunden-Nr.',
|
||||||
|
'KOST 1', 'KOST 2', 'KOST-Menge', 'Kurs', 'Nachricht', 'Freier Text', 'IBAN', 'BIC',
|
||||||
|
'Bankkonto-Nr.', 'BLZ', 'Notiz', 'Land', 'Personalnummer', 'Nachname', 'Vorname',
|
||||||
|
'Belegkategorie', 'Bezeichnung', 'Abrechnungsmonat', 'Gültig bis', 'Prüfungsrelevant',
|
||||||
|
'Ablageort', 'Belegtyp', 'Herkunft', 'Leistungsdatum', 'Buchungstext', 'Beleg-ID',
|
||||||
|
'Zahlungsbedingung', 'Geheftet', 'Gegenkonto', 'keine Überweisung/Lastschrift erstellen',
|
||||||
|
'Aufgeteilt', 'Bereitgestellt', 'Freigegeben', 'FreigegebenAm', 'Erweiterte Belegdaten fehlen',
|
||||||
|
'Periode fehlt', 'Rechnungsdaten beim Import fehlen'
|
||||||
|
];
|
||||||
|
|
||||||
|
if (beleglinks.length === 0) {
|
||||||
|
return res.status(400).json({ error: 'No beleglink data found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const importBatchId = batchId || 'datev_import_' + Date.now();
|
||||||
|
let successCount = 0;
|
||||||
|
let errorCount = 0;
|
||||||
|
let updateCount = 0;
|
||||||
|
let insertCount = 0;
|
||||||
|
let skippedCount = 0;
|
||||||
|
const errors = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < beleglinks.length; i++) {
|
||||||
|
const beleglink = beleglinks[i];
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Skip empty rows or rows without Beleg-ID
|
||||||
|
const belegId = beleglink['Beleg-ID'];
|
||||||
|
if (!belegId || belegId.trim() === '') {
|
||||||
|
console.log(`Skipping row ${i + 1}: No Beleg-ID found`);
|
||||||
|
skippedCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const validationErrors = [];
|
||||||
|
|
||||||
|
// Parse amount if available
|
||||||
|
let numericAmount = null;
|
||||||
|
if (beleglink['Rechnungsbetrag']) {
|
||||||
|
const amountStr = beleglink['Rechnungsbetrag'].toString().replace(/[^\d,.-]/g, '');
|
||||||
|
const normalizedAmount = amountStr.replace(',', '.');
|
||||||
|
numericAmount = parseFloat(normalizedAmount) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse date if available
|
||||||
|
let parsedDate = null;
|
||||||
|
if (beleglink['Rechnungsdatum']) {
|
||||||
|
const dateStr = beleglink['Rechnungsdatum'].trim();
|
||||||
|
const dateParts = dateStr.split(/[.\/\-]/);
|
||||||
|
if (dateParts.length === 3) {
|
||||||
|
const day = parseInt(dateParts[0], 10);
|
||||||
|
const month = parseInt(dateParts[1], 10) - 1;
|
||||||
|
let year = parseInt(dateParts[2], 10);
|
||||||
|
|
||||||
|
if (year < 100) {
|
||||||
|
year += (year < 50) ? 2000 : 1900;
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedDate = new Date(year, month, day);
|
||||||
|
|
||||||
|
if (isNaN(parsedDate.getTime())) {
|
||||||
|
parsedDate = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// First, check if a record with this datevlink already exists
|
||||||
|
const checkExistingDatevLink = `
|
||||||
|
SELECT kUmsatzBeleg FROM eazybusiness.dbo.tUmsatzBeleg WHERE datevlink = @datevlink
|
||||||
|
`;
|
||||||
|
|
||||||
|
const existingDatevLink = await executeQuery(checkExistingDatevLink, { datevlink: belegId });
|
||||||
|
|
||||||
|
if (existingDatevLink.recordset.length > 0) {
|
||||||
|
// Record with this datevlink already exists - skip
|
||||||
|
console.log(`Datevlink already exists, skipping: ${belegId}`);
|
||||||
|
skippedCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract key from filename in 'Herkunft' column
|
||||||
|
// Examples: "Rechnung146.pdf" -> key 146 for tRechnung
|
||||||
|
// "UmsatzBeleg192.pdf" -> key 192 for tUmsatzBeleg
|
||||||
|
const herkunft = beleglink['Herkunft'];
|
||||||
|
if (!herkunft || herkunft.trim() === '') {
|
||||||
|
console.log(`Skipping row ${i + 1}: No filename in Herkunft column`);
|
||||||
|
skippedCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract the key from filename patterns
|
||||||
|
let matchFound = false;
|
||||||
|
|
||||||
|
// Pattern: UmsatzBeleg{key}.pdf -> match with tUmsatzBeleg.kUmsatzBeleg
|
||||||
|
const umsatzBelegMatch = herkunft.match(/UmsatzBeleg(\d+)\.pdf/i);
|
||||||
|
if (umsatzBelegMatch) {
|
||||||
|
const kUmsatzBeleg = parseInt(umsatzBelegMatch[1], 10);
|
||||||
|
|
||||||
|
const updateQuery = `
|
||||||
|
UPDATE eazybusiness.dbo.tUmsatzBeleg
|
||||||
|
SET datevlink = @datevlink
|
||||||
|
WHERE kUmsatzBeleg = @kUmsatzBeleg AND (datevlink IS NULL OR datevlink = '' OR datevlink = 'pending')
|
||||||
|
`;
|
||||||
|
|
||||||
|
const updateResult = await executeQuery(updateQuery, {
|
||||||
|
datevlink: belegId,
|
||||||
|
kUmsatzBeleg: kUmsatzBeleg
|
||||||
|
});
|
||||||
|
|
||||||
|
if (updateResult.rowsAffected && updateResult.rowsAffected[0] > 0) {
|
||||||
|
updateCount++;
|
||||||
|
console.log(`Added datevlink ${belegId} to tUmsatzBeleg.kUmsatzBeleg: ${kUmsatzBeleg}`);
|
||||||
|
matchFound = true;
|
||||||
|
} else {
|
||||||
|
console.log(`Skipping row ${i + 1}: UmsatzBeleg ${kUmsatzBeleg} nicht gefunden oder datevlink bereits gesetzt`);
|
||||||
|
skippedCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pattern: Rechnung{key}.pdf -> match with tPdfObjekt.kPdfObjekt
|
||||||
|
const rechnungMatch = herkunft.match(/Rechnung(\d+)\.pdf/i);
|
||||||
|
if (!matchFound && rechnungMatch) {
|
||||||
|
const kPdfObjekt = parseInt(rechnungMatch[1], 10);
|
||||||
|
|
||||||
|
const updateQuery = `
|
||||||
|
UPDATE eazybusiness.dbo.tPdfObjekt
|
||||||
|
SET datevlink = @datevlink
|
||||||
|
WHERE kPdfObjekt = @kPdfObjekt AND (datevlink IS NULL OR datevlink = '' OR datevlink = 'pending')
|
||||||
|
`;
|
||||||
|
|
||||||
|
const updateResult = await executeQuery(updateQuery, {
|
||||||
|
datevlink: belegId,
|
||||||
|
kPdfObjekt: kPdfObjekt
|
||||||
|
});
|
||||||
|
|
||||||
|
if (updateResult.rowsAffected && updateResult.rowsAffected[0] > 0) {
|
||||||
|
updateCount++;
|
||||||
|
console.log(`Added datevlink ${belegId} to tPdfObjekt.kPdfObjekt: ${kPdfObjekt}`);
|
||||||
|
matchFound = true;
|
||||||
|
} else {
|
||||||
|
console.log(`Skipping row ${i + 1}: PdfObjekt ${kPdfObjekt} nicht gefunden oder datevlink bereits gesetzt`);
|
||||||
|
skippedCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!matchFound) {
|
||||||
|
console.log(`Skipping row ${i + 1}: Unbekanntes Dateiformat '${herkunft}' (erwartet: UmsatzBeleg{key}.pdf oder Rechnung{key}.pdf)`);
|
||||||
|
skippedCount++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
successCount++;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing beleglink ' + (i + 1) + ':', error);
|
||||||
|
errors.push({
|
||||||
|
row: i + 1,
|
||||||
|
error: error.message,
|
||||||
|
beleglink: beleglink
|
||||||
|
});
|
||||||
|
errorCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
batchId: importBatchId,
|
||||||
|
imported: updateCount, // Number of datevlinks actually added/updated
|
||||||
|
processed: successCount,
|
||||||
|
updated: updateCount,
|
||||||
|
inserted: insertCount,
|
||||||
|
skipped: skippedCount, // Records skipped (existing datevlinks)
|
||||||
|
errors: errorCount, // Only actual errors, not skipped records
|
||||||
|
details: errors.length > 0 ? errors : undefined,
|
||||||
|
message: `${updateCount} datevlinks hinzugefügt, ${skippedCount} bereits vorhanden, ${errorCount} Fehler`
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error importing DATEV beleglinks:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to import DATEV beleglinks' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
296
src/routes/data/datev.js
Normal file
296
src/routes/data/datev.js
Normal file
@@ -0,0 +1,296 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// DATEV helpers (ported from original file)
|
||||||
|
const buildDatevHeader = (periodStart, periodEnd) => {
|
||||||
|
const ts = new Date().toISOString().replace(/[-T:\.Z]/g, '').slice(0, 17); // yyyymmddHHMMSSfff
|
||||||
|
const meta = {
|
||||||
|
consultant: 1001,
|
||||||
|
client: 10001,
|
||||||
|
fyStart: periodStart.slice(0, 4) + '0101', // fiscal year start
|
||||||
|
accLength: 4,
|
||||||
|
description: 'Bank Statement Export',
|
||||||
|
currency: 'EUR'
|
||||||
|
};
|
||||||
|
|
||||||
|
return [
|
||||||
|
'"EXTF"', 700, 21, '"Buchungsstapel"', 12, ts,
|
||||||
|
'', '', '', '', // 7‑10 spare
|
||||||
|
meta.consultant, meta.client, // 11, 12
|
||||||
|
meta.fyStart, meta.accLength, // 13, 14
|
||||||
|
periodStart, periodEnd, // 15, 16
|
||||||
|
'"' + meta.description + '"',
|
||||||
|
'AM', 1, 0, 1, meta.currency
|
||||||
|
].join(';');
|
||||||
|
};
|
||||||
|
|
||||||
|
const DATEV_COLS = [
|
||||||
|
'Umsatz (ohne Soll/Haben-Kz)', 'Soll/Haben-Kennzeichen', 'WKZ Umsatz',
|
||||||
|
'Kurs', 'Basis-Umsatz', 'WKZ Basis-Umsatz', 'Konto',
|
||||||
|
'Gegenkonto (ohne BU-Schlüssel)', 'BU-Schlüssel', 'Belegdatum',
|
||||||
|
'Belegfeld 1', 'Belegfeld 2', 'Skonto', 'Buchungstext',
|
||||||
|
'Postensperre', 'Diverse Adressnummer', 'Geschäftspartnerbank',
|
||||||
|
'Sachverhalt', 'Zinssperre', 'Beleglink'
|
||||||
|
].join(';');
|
||||||
|
|
||||||
|
const formatDatevAmount = (amount) => {
|
||||||
|
return Math.abs(amount).toFixed(2).replace('.', ',');
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDatevDate = (date) => {
|
||||||
|
if (!date) return '';
|
||||||
|
|
||||||
|
// Handle Date object
|
||||||
|
if (date instanceof Date) {
|
||||||
|
const day = date.getDate().toString().padStart(2, '0');
|
||||||
|
const month = (date.getMonth() + 1).toString().padStart(2, '0');
|
||||||
|
return day + month;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle string date
|
||||||
|
const dateStr = date.toString();
|
||||||
|
const parts = dateStr.split('.');
|
||||||
|
if (parts.length === 3) {
|
||||||
|
const day = parts[0].padStart(2, '0');
|
||||||
|
const month = parts[1].padStart(2, '0');
|
||||||
|
return day + month;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to parse as date string
|
||||||
|
const parsedDate = new Date(dateStr);
|
||||||
|
if (!isNaN(parsedDate)) {
|
||||||
|
const day = parsedDate.getDate().toString().padStart(2, '0');
|
||||||
|
const month = (parsedDate.getMonth() + 1).toString().padStart(2, '0');
|
||||||
|
return day + month;
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const quote = (str, maxLen = 60) => {
|
||||||
|
if (!str) return '""';
|
||||||
|
return '"' + str.slice(0, maxLen).replace(/"/g, '""') + '"';
|
||||||
|
};
|
||||||
|
|
||||||
|
// Parse konto field which might contain multiple accounts like "5400+5300"
|
||||||
|
const parseKonto = (konto) => {
|
||||||
|
if (!konto) return '';
|
||||||
|
// Take the first account number if multiple are present
|
||||||
|
const parts = konto.split('+');
|
||||||
|
return parts[0].trim();
|
||||||
|
};
|
||||||
|
|
||||||
|
// DATEV export endpoint
|
||||||
|
router.get('/datev/:timeRange', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { timeRange } = req.params;
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
// Parse the time range to get start and end dates
|
||||||
|
let startDate, endDate;
|
||||||
|
|
||||||
|
if (timeRange.includes('-Q')) {
|
||||||
|
// Quarter format: 2025-Q1
|
||||||
|
const [year, quarterPart] = timeRange.split('-Q');
|
||||||
|
const quarter = parseInt(quarterPart, 10);
|
||||||
|
const startMonth = (quarter - 1) * 3 + 1;
|
||||||
|
const endMonth = startMonth + 2;
|
||||||
|
|
||||||
|
startDate = new Date(year, startMonth - 1, 1);
|
||||||
|
endDate = new Date(year, endMonth - 1, new Date(year, endMonth, 0).getDate());
|
||||||
|
} else if (timeRange.length === 4) {
|
||||||
|
// Year format: 2025
|
||||||
|
startDate = new Date(timeRange, 0, 1);
|
||||||
|
endDate = new Date(timeRange, 11, 31);
|
||||||
|
} else {
|
||||||
|
// Month format: 2025-03
|
||||||
|
const [year, month] = timeRange.split('-');
|
||||||
|
startDate = new Date(year, parseInt(month) - 1, 1);
|
||||||
|
endDate = new Date(year, parseInt(month), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format dates for SQL query
|
||||||
|
const sqlStartDate = startDate.toISOString().split('T')[0];
|
||||||
|
const sqlEndDate = endDate.toISOString().split('T')[0];
|
||||||
|
|
||||||
|
// Query to get all DATEV data with proper joins
|
||||||
|
// This handles multiple documents per transaction by creating separate rows
|
||||||
|
const query = `
|
||||||
|
WITH DatevDocuments AS (
|
||||||
|
-- Get documents from tUmsatzBeleg
|
||||||
|
SELECT
|
||||||
|
uk.kZahlungsabgleichUmsatz,
|
||||||
|
zu.fBetrag as umsatz_brutto,
|
||||||
|
CASE WHEN zu.fBetrag < 0 THEN 'H' ELSE 'S' END as soll_haben_kz,
|
||||||
|
JSON_VALUE(uk.data, '$.konto1') as konto,
|
||||||
|
'' as gegenkonto, -- No creditorID in tUmsatzBeleg
|
||||||
|
-- BU determination based on amount and konto type
|
||||||
|
CASE
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') IN ('3720', '3740', '2100', '1460', '1462') THEN ''
|
||||||
|
WHEN zu.fBetrag > 0 THEN ''
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') LIKE '5%' THEN '9' -- 19% for purchases
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') LIKE '6%' THEN '9' -- 19% for expenses
|
||||||
|
ELSE ''
|
||||||
|
END as bu,
|
||||||
|
FORMAT(zu.dBuchungsdatum, 'Mdd') as buchungsdatum_mdd,
|
||||||
|
zu.dBuchungsdatum,
|
||||||
|
'' as rechnungsnummer, -- No invoice number in tUmsatzBeleg
|
||||||
|
zu.cVerwendungszweck as buchungstext,
|
||||||
|
ub.datevlink as beleglink,
|
||||||
|
1 as priority -- tUmsatzBeleg has priority
|
||||||
|
FROM tUmsatzKontierung uk
|
||||||
|
INNER JOIN tZahlungsabgleichUmsatz zu ON uk.kZahlungsabgleichUmsatz = zu.kZahlungsabgleichUmsatz
|
||||||
|
INNER JOIN tUmsatzBeleg ub ON ub.kZahlungsabgleichUmsatz = zu.kZahlungsabgleichUmsatz
|
||||||
|
WHERE ub.datevlink IS NOT NULL
|
||||||
|
AND zu.dBuchungsdatum >= @startDate
|
||||||
|
AND zu.dBuchungsdatum <= @endDate
|
||||||
|
|
||||||
|
UNION ALL
|
||||||
|
|
||||||
|
-- Get documents from tPdfObjekt via tZahlungsabgleichUmsatzLink
|
||||||
|
SELECT
|
||||||
|
uk.kZahlungsabgleichUmsatz,
|
||||||
|
zu.fBetrag as umsatz_brutto,
|
||||||
|
CASE WHEN zu.fBetrag < 0 THEN 'H' ELSE 'S' END as soll_haben_kz,
|
||||||
|
JSON_VALUE(uk.data, '$.konto1') as konto,
|
||||||
|
COALESCE(JSON_VALUE(po.extraction, '$.creditorID'), '') as gegenkonto,
|
||||||
|
-- BU determination based on amount and konto type
|
||||||
|
CASE
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') IN ('3720', '3740', '2100', '1460', '1462') THEN ''
|
||||||
|
WHEN zu.fBetrag > 0 THEN ''
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') LIKE '5%' THEN '9' -- 19% for purchases
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') LIKE '6%' THEN '9' -- 19% for expenses
|
||||||
|
ELSE ''
|
||||||
|
END as bu,
|
||||||
|
FORMAT(zu.dBuchungsdatum, 'Mdd') as buchungsdatum_mdd,
|
||||||
|
zu.dBuchungsdatum,
|
||||||
|
COALESCE(JSON_VALUE(po.extraction, '$.invoice_number'), '') as rechnungsnummer,
|
||||||
|
zu.cVerwendungszweck as buchungstext,
|
||||||
|
po.datevlink as beleglink,
|
||||||
|
2 as priority -- tPdfObjekt has lower priority
|
||||||
|
FROM tUmsatzKontierung uk
|
||||||
|
INNER JOIN tZahlungsabgleichUmsatz zu ON uk.kZahlungsabgleichUmsatz = zu.kZahlungsabgleichUmsatz
|
||||||
|
INNER JOIN tZahlungsabgleichUmsatzLink zul ON zu.kZahlungsabgleichUmsatz = zul.kZahlungsabgleichUmsatz
|
||||||
|
AND zul.linktype = 'kLieferantenBestellung'
|
||||||
|
INNER JOIN tPdfObjekt po ON zul.linktarget = po.kLieferantenbestellung
|
||||||
|
WHERE po.datevlink IS NOT NULL
|
||||||
|
AND zu.dBuchungsdatum >= @startDate
|
||||||
|
AND zu.dBuchungsdatum <= @endDate
|
||||||
|
|
||||||
|
UNION ALL
|
||||||
|
|
||||||
|
-- Get transactions without documents
|
||||||
|
SELECT
|
||||||
|
uk.kZahlungsabgleichUmsatz,
|
||||||
|
zu.fBetrag as umsatz_brutto,
|
||||||
|
CASE WHEN zu.fBetrag < 0 THEN 'H' ELSE 'S' END as soll_haben_kz,
|
||||||
|
JSON_VALUE(uk.data, '$.konto1') as konto,
|
||||||
|
'' as gegenkonto,
|
||||||
|
-- BU determination based on amount and konto type
|
||||||
|
CASE
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') IN ('3720', '3740', '2100', '1460', '1462') THEN ''
|
||||||
|
WHEN zu.fBetrag > 0 THEN ''
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') LIKE '5%' THEN '9' -- 19% for purchases
|
||||||
|
WHEN JSON_VALUE(uk.data, '$.konto1') LIKE '6%' THEN '9' -- 19% for expenses
|
||||||
|
ELSE ''
|
||||||
|
END as bu,
|
||||||
|
FORMAT(zu.dBuchungsdatum, 'Mdd') as buchungsdatum_mdd,
|
||||||
|
zu.dBuchungsdatum,
|
||||||
|
'' as rechnungsnummer,
|
||||||
|
zu.cVerwendungszweck as buchungstext,
|
||||||
|
'' as beleglink,
|
||||||
|
3 as priority -- No documents has lowest priority
|
||||||
|
FROM tUmsatzKontierung uk
|
||||||
|
INNER JOIN tZahlungsabgleichUmsatz zu ON uk.kZahlungsabgleichUmsatz = zu.kZahlungsabgleichUmsatz
|
||||||
|
WHERE zu.dBuchungsdatum >= @startDate
|
||||||
|
AND zu.dBuchungsdatum <= @endDate
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM tUmsatzBeleg ub2
|
||||||
|
WHERE ub2.kZahlungsabgleichUmsatz = zu.kZahlungsabgleichUmsatz
|
||||||
|
AND ub2.datevlink IS NOT NULL
|
||||||
|
)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM tZahlungsabgleichUmsatzLink zul2
|
||||||
|
INNER JOIN tPdfObjekt po2 ON zul2.linktarget = po2.kLieferantenbestellung
|
||||||
|
WHERE zul2.kZahlungsabgleichUmsatz = zu.kZahlungsabgleichUmsatz
|
||||||
|
AND zul2.linktype = 'kLieferantenBestellung'
|
||||||
|
AND po2.datevlink IS NOT NULL
|
||||||
|
)
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
*,
|
||||||
|
ROW_NUMBER() OVER (PARTITION BY kZahlungsabgleichUmsatz, beleglink ORDER BY priority) as rn
|
||||||
|
FROM DatevDocuments
|
||||||
|
ORDER BY dBuchungsdatum DESC, kZahlungsabgleichUmsatz, priority
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query, {
|
||||||
|
startDate: sqlStartDate,
|
||||||
|
endDate: sqlEndDate
|
||||||
|
});
|
||||||
|
|
||||||
|
// Format data for DATEV CSV
|
||||||
|
const datevRows = [];
|
||||||
|
|
||||||
|
// Build header
|
||||||
|
const periodStart = startDate.getFullYear() +
|
||||||
|
('0' + (startDate.getMonth() + 1)).slice(-2) +
|
||||||
|
('0' + startDate.getDate()).slice(-2);
|
||||||
|
const periodEnd = endDate.getFullYear() +
|
||||||
|
('0' + (endDate.getMonth() + 1)).slice(-2) +
|
||||||
|
('0' + endDate.getDate()).slice(-2);
|
||||||
|
|
||||||
|
datevRows.push(buildDatevHeader(periodStart, periodEnd));
|
||||||
|
datevRows.push(DATEV_COLS);
|
||||||
|
|
||||||
|
// Process each transaction
|
||||||
|
result.recordset.forEach(row => {
|
||||||
|
// Skip duplicate rows (keep only the first occurrence of each transaction+beleglink combination)
|
||||||
|
if (row.rn > 1) return;
|
||||||
|
|
||||||
|
const datevRow = [
|
||||||
|
formatDatevAmount(row.umsatz_brutto), // Umsatz (ohne Soll/Haben-Kz)
|
||||||
|
row.soll_haben_kz, // Soll/Haben-Kennzeichen
|
||||||
|
'', // WKZ Umsatz
|
||||||
|
'', // Kurs
|
||||||
|
'', // Basis-Umsatz
|
||||||
|
'', // WKZ Basis-Umsatz
|
||||||
|
parseKonto(row.konto), // Konto (parsed)
|
||||||
|
row.gegenkonto || '', // Gegenkonto (ohne BU-Schlüssel)
|
||||||
|
row.bu || '', // BU-Schlüssel
|
||||||
|
row.buchungsdatum_mdd || '', // Belegdatum (MDD format)
|
||||||
|
quote(row.rechnungsnummer || ''), // Belegfeld 1 (invoice number)
|
||||||
|
'', // Belegfeld 2
|
||||||
|
'', // Skonto
|
||||||
|
quote(row.buchungstext || ''), // Buchungstext
|
||||||
|
'', // Postensperre
|
||||||
|
'', // Diverse Adressnummer
|
||||||
|
'', // Geschäftspartnerbank
|
||||||
|
'', // Sachverhalt
|
||||||
|
'', // Zinssperre
|
||||||
|
row.beleglink || '' // Beleglink
|
||||||
|
].join(';');
|
||||||
|
|
||||||
|
datevRows.push(datevRow);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate CSV content
|
||||||
|
const csvContent = datevRows.join('\n');
|
||||||
|
|
||||||
|
// Set headers for CSV download
|
||||||
|
const filename = `EXTF_${timeRange.replace('-', '_')}.csv`;
|
||||||
|
res.setHeader('Content-Type', 'text/csv; charset=windows-1252');
|
||||||
|
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
||||||
|
|
||||||
|
// Send CSV content
|
||||||
|
res.send(csvContent);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating DATEV export:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to generate DATEV export' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
416
src/routes/data/documentProcessing.js
Normal file
416
src/routes/data/documentProcessing.js
Normal file
@@ -0,0 +1,416 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
const { executeQuery, executeTransaction } = require('../../config/database');
|
||||||
|
const sql = require('mssql');
|
||||||
|
const nodemailer = require('nodemailer');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Get document processing status
|
||||||
|
router.get('/document-status', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
console.log('Document status endpoint called');
|
||||||
|
const queries = {
|
||||||
|
needMarkdownUmsatz: "SELECT COUNT(*) as count FROM tUmsatzBeleg WHERE markDown is null",
|
||||||
|
needMarkdownPdf: "SELECT COUNT(*) as count FROM tPdfObjekt WHERE markDown is null",
|
||||||
|
needExtractionUmsatz: "SELECT COUNT(*) as count FROM tUmsatzBeleg WHERE markDown is not null and extraction is null",
|
||||||
|
needExtractionPdf: "SELECT COUNT(*) as count FROM tPdfObjekt WHERE markDown is not null and extraction is null",
|
||||||
|
needDatevSyncUmsatz: "SELECT COUNT(*) as count FROM tUmsatzBeleg WHERE markDown is not null and datevlink is null",
|
||||||
|
needDatevSyncPdf: "SELECT COUNT(*) as count FROM tPdfObjekt WHERE markDown is not null and datevlink is null",
|
||||||
|
needDatevUploadUmsatz: "SELECT COUNT(*) as count FROM tUmsatzBeleg WHERE datevlink = 'pending'",
|
||||||
|
needDatevUploadPdf: "SELECT COUNT(*) as count FROM tPdfObjekt WHERE datevlink = 'pending'"
|
||||||
|
};
|
||||||
|
|
||||||
|
const results = {};
|
||||||
|
for (const [key, query] of Object.entries(queries)) {
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
results[key] = result.recordset[0].count;
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = {
|
||||||
|
needMarkdown: results.needMarkdownUmsatz + results.needMarkdownPdf,
|
||||||
|
needExtraction: results.needExtractionUmsatz + results.needExtractionPdf,
|
||||||
|
needDatevSync: results.needDatevSyncUmsatz + results.needDatevSyncPdf,
|
||||||
|
needDatevUpload: results.needDatevUploadUmsatz + results.needDatevUploadPdf,
|
||||||
|
details: {
|
||||||
|
markdown: {
|
||||||
|
umsatzBeleg: results.needMarkdownUmsatz,
|
||||||
|
pdfObjekt: results.needMarkdownPdf
|
||||||
|
},
|
||||||
|
extraction: {
|
||||||
|
umsatzBeleg: results.needExtractionUmsatz,
|
||||||
|
pdfObjekt: results.needExtractionPdf
|
||||||
|
},
|
||||||
|
datevSync: {
|
||||||
|
umsatzBeleg: results.needDatevSyncUmsatz,
|
||||||
|
pdfObjekt: results.needDatevSyncPdf
|
||||||
|
},
|
||||||
|
datevUpload: {
|
||||||
|
umsatzBeleg: results.needDatevUploadUmsatz,
|
||||||
|
pdfObjekt: results.needDatevUploadPdf
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('Document status computed:', status);
|
||||||
|
res.json(status);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching document processing status:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch document processing status' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Process markdown conversion
|
||||||
|
router.post('/process-markdown', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { OpenAI } = require('openai');
|
||||||
|
|
||||||
|
// Check environment for OpenAI API key
|
||||||
|
if (!process.env.OPENAI_API_KEY) {
|
||||||
|
return res.status(500).json({ error: 'OpenAI API key not configured' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const openai = new OpenAI({
|
||||||
|
apiKey: process.env.OPENAI_API_KEY,
|
||||||
|
});
|
||||||
|
|
||||||
|
await executeTransaction(async (transaction) => {
|
||||||
|
// Process UmsatzBeleg documents
|
||||||
|
const umsatzResult = await new sql.Request(transaction).query(
|
||||||
|
"SELECT TOP 1 kUmsatzBeleg, content FROM tUmsatzBeleg WHERE markDown is null"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (umsatzResult.recordset.length > 0) {
|
||||||
|
const { kUmsatzBeleg, content } = umsatzResult.recordset[0];
|
||||||
|
|
||||||
|
const response = await openai.responses.create({
|
||||||
|
model: "gpt-4o",
|
||||||
|
input: [
|
||||||
|
{ "role": "developer", "content": [{ "type": "input_text", "text": "Convert to Markdown" }] },
|
||||||
|
{ "role": "user", "content": [{ "type": "input_file", "filename": "invoice.pdf", "file_data": "data:application/pdf;base64," + content.toString('base64') }] }
|
||||||
|
],
|
||||||
|
text: {
|
||||||
|
"format": {
|
||||||
|
"type": "json_schema", "name": "markdown", "strict": true, "schema": { "type": "object", "properties": {
|
||||||
|
"output": { "type": "string", "description": "Input converted to Markdown" }
|
||||||
|
}, "required": ["output"], "additionalProperties": false }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
tools: [],
|
||||||
|
store: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const markdown = JSON.parse(response.output_text);
|
||||||
|
|
||||||
|
await new sql.Request(transaction)
|
||||||
|
.input('kUmsatzBeleg', kUmsatzBeleg)
|
||||||
|
.input('markDown', markdown.output)
|
||||||
|
.query("UPDATE tUmsatzBeleg SET markDown = @markDown WHERE kUmsatzBeleg = @kUmsatzBeleg");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process PdfObjekt documents
|
||||||
|
const pdfResult = await new sql.Request(transaction).query(
|
||||||
|
"SELECT TOP 1 kPdfObjekt, content FROM tPdfObjekt WHERE markDown is null"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (pdfResult.recordset.length > 0) {
|
||||||
|
const { kPdfObjekt, content } = pdfResult.recordset[0];
|
||||||
|
|
||||||
|
const response = await openai.responses.create({
|
||||||
|
model: "gpt-4o",
|
||||||
|
input: [
|
||||||
|
{ "role": "developer", "content": [{ "type": "input_text", "text": "Convert to Markdown" }] },
|
||||||
|
{ "role": "user", "content": [{ "type": "input_file", "filename": "invoice.pdf", "file_data": "data:application/pdf;base64," + content.toString('base64') }] }
|
||||||
|
],
|
||||||
|
text: {
|
||||||
|
"format": {
|
||||||
|
"type": "json_schema", "name": "markdown", "strict": true, "schema": { "type": "object", "properties": {
|
||||||
|
"output": { "type": "string", "description": "Input converted to Markdown" }
|
||||||
|
}, "required": ["output"], "additionalProperties": false }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
tools: [],
|
||||||
|
store: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const markdown = JSON.parse(response.output_text);
|
||||||
|
|
||||||
|
await new sql.Request(transaction)
|
||||||
|
.input('kPdfObjekt', kPdfObjekt)
|
||||||
|
.input('markDown', markdown.output)
|
||||||
|
.query("UPDATE tPdfObjekt SET markDown = @markDown WHERE kPdfObjekt = @kPdfObjekt");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({ success: true, message: 'Markdown processing completed' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing markdown:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to process markdown: ' + error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Process data extraction
|
||||||
|
router.post('/process-extraction', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { OpenAI } = require('openai');
|
||||||
|
|
||||||
|
if (!process.env.OPENAI_API_KEY) {
|
||||||
|
return res.status(500).json({ error: 'OpenAI API key not configured' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const openai = new OpenAI({
|
||||||
|
apiKey: process.env.OPENAI_API_KEY,
|
||||||
|
});
|
||||||
|
|
||||||
|
await executeTransaction(async (transaction) => {
|
||||||
|
// Get creditor IDs for extraction
|
||||||
|
const creditorResult = await new sql.Request(transaction).query(
|
||||||
|
"SELECT kreditorId FROM fibdash.Kreditor ORDER BY kreditorId"
|
||||||
|
);
|
||||||
|
const creditorIDs = creditorResult.recordset.map(r => r.kreditorId).join(', ');
|
||||||
|
|
||||||
|
// Process UmsatzBeleg documents
|
||||||
|
const umsatzResult = await new sql.Request(transaction).query(
|
||||||
|
"SELECT TOP 1 kUmsatzBeleg, markDown FROM tUmsatzBeleg WHERE markDown is not null and extraction is null"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (umsatzResult.recordset.length > 0) {
|
||||||
|
const { kUmsatzBeleg, markDown } = umsatzResult.recordset[0];
|
||||||
|
|
||||||
|
const response = await openai.responses.create({
|
||||||
|
model: "gpt-5-mini",
|
||||||
|
input: [
|
||||||
|
{ "role": "developer", "content": [{ "type": "input_text", "text": `Extract specified information from provided input and structure it in a JSON format.
|
||||||
|
|
||||||
|
The aim is to accurately identify and capture the following elements:
|
||||||
|
- Rechnungsdatum/Belegdatum (Invoice Date/Document Date),
|
||||||
|
- Rechnungsnummer/Belegnummer (Invoice Number/Document Number),
|
||||||
|
- Netto Betrag (Net Amount),
|
||||||
|
- Brutto Betrag (Gross Amount),
|
||||||
|
- and Absender (Sender).
|
||||||
|
|
||||||
|
# Steps
|
||||||
|
|
||||||
|
1. **Identify Dates**: Find and extract the invoice or document date (Rechnungsdatum/Belegdatum) from the input text.
|
||||||
|
2. **Extract Numbers**: Locate and pull out the invoice or document number (Rechnungsnummer/Belegnummer).
|
||||||
|
3. **Determine Amounts**: Identify the net amount (Netto Betrag) and the gross amount (Brutto Betrag) and the currency in the text.
|
||||||
|
4. **Source the Sender**: Extract the sender's information (Absender, Country).
|
||||||
|
5. **Structure Data**: Organize the extracted information into a JSON format following the specified schema.
|
||||||
|
|
||||||
|
# Notes
|
||||||
|
|
||||||
|
- Ensure that dates are formatted consistently.
|
||||||
|
- Be mindful of various numerical representations (e.g., with commas or periods).
|
||||||
|
- The sender's information might include company names, so recognize various formats.
|
||||||
|
- Prioritize accuracy in identifying the correct fields, as there can be similar text elements present.
|
||||||
|
|
||||||
|
Also select the CreditorID, from that List: ${creditorIDs}` }] },
|
||||||
|
{ "role": "user", "content": [{ "type": "input_text", "text": markDown }] }
|
||||||
|
],
|
||||||
|
text: {
|
||||||
|
"format": {
|
||||||
|
"type": "json_schema", "name": "invoice", "strict": true, "schema": { "type": "object", "properties": {
|
||||||
|
"date": { "type": "string", "description": "Rechungsdatum / Belegdatum in ISO 8601" },
|
||||||
|
"invoice_number": { "type": "string", "description": "Rechnungsnummer / Belegnummer / Invoicenr" },
|
||||||
|
"net_amounts_and_tax": {
|
||||||
|
"type": "array", "description": "Liste von Nettobeträgen mit jeweiligem Steuersatz und Steuerbetrag, ein Listeneintrag pro Steuersatz",
|
||||||
|
"items": { "type": "object", "properties": {
|
||||||
|
"net_amount": { "type": "number", "description": "Netto Betrag" },
|
||||||
|
"tax_rate": { "type": "number", "description": "Steuersatz in Prozent" },
|
||||||
|
"tax_amount": { "type": "number", "description": "Steuerbetrag" }
|
||||||
|
}, "required": ["net_amount", "tax_rate", "tax_amount"], "additionalProperties": false }
|
||||||
|
},
|
||||||
|
"gross_amount": { "type": "number", "description": "Brutto Betrag (muss der Summe aller net_amount + tax_amount entsprechen)" },
|
||||||
|
"currency": { "type": "string", "description": "currency code in ISO 4217" },
|
||||||
|
"country": { "type": "string", "description": "country of origin in ISO 3166" },
|
||||||
|
"sender": { "type": "string", "description": "Absender" },
|
||||||
|
"creditorID": { "type": "string", "description": "CreditorID or empty if unknown" }
|
||||||
|
}, "required": ["date", "invoice_number", "net_amounts_and_tax", "gross_amount", "currency", "country", "sender", "creditorID"], "additionalProperties": false }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
tools: [],
|
||||||
|
store: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const extraction = JSON.parse(response.output_text);
|
||||||
|
|
||||||
|
await new sql.Request(transaction)
|
||||||
|
.input('kUmsatzBeleg', kUmsatzBeleg)
|
||||||
|
.input('extraction', JSON.stringify(extraction))
|
||||||
|
.query("UPDATE tUmsatzBeleg SET extraction = @extraction WHERE kUmsatzBeleg = @kUmsatzBeleg");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process PdfObjekt documents
|
||||||
|
const pdfResult = await new sql.Request(transaction).query(
|
||||||
|
"SELECT TOP 1 kPdfObjekt, markDown FROM tPdfObjekt WHERE markDown is not null and extraction is null"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (pdfResult.recordset.length > 0) {
|
||||||
|
const { kPdfObjekt, markDown } = pdfResult.recordset[0];
|
||||||
|
|
||||||
|
const response = await openai.responses.create({
|
||||||
|
model: "gpt-5-mini",
|
||||||
|
input: [
|
||||||
|
{ "role": "developer", "content": [{ "type": "input_text", "text": `Extract specified information from provided input and structure it in a JSON format.
|
||||||
|
|
||||||
|
The aim is to accurately identify and capture the following elements:
|
||||||
|
- Rechnungsdatum/Belegdatum (Invoice Date/Document Date),
|
||||||
|
- Rechnungsnummer/Belegnummer (Invoice Number/Document Number),
|
||||||
|
- Netto Betrag (Net Amount),
|
||||||
|
- Brutto Betrag (Gross Amount),
|
||||||
|
- and Absender (Sender).
|
||||||
|
|
||||||
|
# Steps
|
||||||
|
|
||||||
|
1. **Identify Dates**: Find and extract the invoice or document date (Rechnungsdatum/Belegdatum) from the input text.
|
||||||
|
2. **Extract Numbers**: Locate and pull out the invoice or document number (Rechnungsnummer/Belegnummer).
|
||||||
|
3. **Determine Amounts**: Identify the net amount (Netto Betrag) and the gross amount (Brutto Betrag) and the currency in the text.
|
||||||
|
4. **Source the Sender**: Extract the sender's information (Absender, Country).
|
||||||
|
5. **Structure Data**: Organize the extracted information into a JSON format following the specified schema.
|
||||||
|
|
||||||
|
# Notes
|
||||||
|
|
||||||
|
- Ensure that dates are formatted consistently.
|
||||||
|
- Be mindful of various numerical representations (e.g., with commas or periods).
|
||||||
|
- The sender's information might include company names, so recognize various formats.
|
||||||
|
- Prioritize accuracy in identifying the correct fields, as there can be similar text elements present.
|
||||||
|
|
||||||
|
Also select the CreditorID, from that List: ${creditorIDs}` }] },
|
||||||
|
{ "role": "user", "content": [{ "type": "input_text", "text": markDown }] }
|
||||||
|
],
|
||||||
|
text: {
|
||||||
|
"format": {
|
||||||
|
"type": "json_schema", "name": "invoice", "strict": true, "schema": { "type": "object", "properties": {
|
||||||
|
"date": { "type": "string", "description": "Rechungsdatum / Belegdatum in ISO 8601" },
|
||||||
|
"invoice_number": { "type": "string", "description": "Rechnungsnummer / Belegnummer / Invoicenr" },
|
||||||
|
"net_amounts_and_tax": {
|
||||||
|
"type": "array", "description": "Liste von Nettobeträgen mit jeweiligem Steuersatz und Steuerbetrag, ein Listeneintrag pro Steuersatz",
|
||||||
|
"items": { "type": "object", "properties": {
|
||||||
|
"net_amount": { "type": "number", "description": "Netto Betrag" },
|
||||||
|
"tax_rate": { "type": "number", "description": "Steuersatz in Prozent" },
|
||||||
|
"tax_amount": { "type": "number", "description": "Steuerbetrag" }
|
||||||
|
}, "required": ["net_amount", "tax_rate", "tax_amount"], "additionalProperties": false }
|
||||||
|
},
|
||||||
|
"gross_amount": { "type": "number", "description": "Brutto Betrag (muss der Summe aller net_amount + tax_amount entsprechen)" },
|
||||||
|
"currency": { "type": "string", "description": "currency code in ISO 4217" },
|
||||||
|
"country": { "type": "string", "description": "country of origin in ISO 3166" },
|
||||||
|
"sender": { "type": "string", "description": "Absender" },
|
||||||
|
"creditorID": { "type": "string", "description": "CreditorID or empty if unknown" }
|
||||||
|
}, "required": ["date", "invoice_number", "net_amounts_and_tax", "gross_amount", "currency", "country", "sender", "creditorID"], "additionalProperties": false }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
tools: [],
|
||||||
|
store: false
|
||||||
|
});
|
||||||
|
|
||||||
|
const extraction = JSON.parse(response.output_text);
|
||||||
|
|
||||||
|
await new sql.Request(transaction)
|
||||||
|
.input('kPdfObjekt', kPdfObjekt)
|
||||||
|
.input('extraction', JSON.stringify(extraction))
|
||||||
|
.query("UPDATE tPdfObjekt SET extraction = @extraction WHERE kPdfObjekt = @kPdfObjekt");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({ success: true, message: 'Extraction processing completed' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing extraction:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to process extraction: ' + error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Process Datev sync
|
||||||
|
router.post('/process-datev-sync', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: "smtp.gmail.com",
|
||||||
|
port: 587,
|
||||||
|
secure: false, // true for 465, false for other ports
|
||||||
|
auth: {
|
||||||
|
user: "sebgreenbus@gmail.com",
|
||||||
|
pass: "abrp idub thbi kdws", // For Gmail, you might need an app-specific password
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await executeTransaction(async (transaction) => {
|
||||||
|
// Process UmsatzBeleg documents
|
||||||
|
const umsatzResult = await new sql.Request(transaction).query(
|
||||||
|
"SELECT TOP 1 kUmsatzBeleg, content FROM tUmsatzBeleg WHERE markDown is not null and datevlink is null"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (umsatzResult.recordset.length > 0) {
|
||||||
|
const { kUmsatzBeleg, content } = umsatzResult.recordset[0];
|
||||||
|
|
||||||
|
const mailOptions = {
|
||||||
|
from: '"Growheads" <sebgreenbus@gmail.com>',
|
||||||
|
to: "97bfd9eb-770f-481a-accb-e69649d36a9e@uploadmail.datev.de",
|
||||||
|
subject: `Beleg ${kUmsatzBeleg} für Datev`,
|
||||||
|
text: "", // No body text as requested
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
filename: `UmsatzBeleg${kUmsatzBeleg}.pdf`,
|
||||||
|
content: content,
|
||||||
|
contentType: "application/pdf",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
let info = await transporter.sendMail(mailOptions);
|
||||||
|
console.log("Message sent: %s", info.messageId);
|
||||||
|
|
||||||
|
await new sql.Request(transaction)
|
||||||
|
.input('kUmsatzBeleg', kUmsatzBeleg)
|
||||||
|
.input('datevlink', 'pending')
|
||||||
|
.query("UPDATE tUmsatzBeleg SET datevlink = @datevlink WHERE kUmsatzBeleg = @kUmsatzBeleg");
|
||||||
|
} catch (emailError) {
|
||||||
|
console.error("Error sending email:", emailError);
|
||||||
|
throw emailError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process PdfObjekt documents
|
||||||
|
const pdfResult = await new sql.Request(transaction).query(
|
||||||
|
"SELECT TOP 1 kPdfObjekt, content FROM tPdfObjekt WHERE markDown is not null and datevlink is null"
|
||||||
|
);
|
||||||
|
|
||||||
|
if (pdfResult.recordset.length > 0) {
|
||||||
|
const { kPdfObjekt, content } = pdfResult.recordset[0];
|
||||||
|
|
||||||
|
const mailOptions = {
|
||||||
|
from: '"Growheads" <sebgreenbus@gmail.com>',
|
||||||
|
to: "97bfd9eb-770f-481a-accb-e69649d36a9e@uploadmail.datev.de",
|
||||||
|
subject: `Rechnung ${kPdfObjekt} für Datev`,
|
||||||
|
text: "", // No body text as requested
|
||||||
|
attachments: [
|
||||||
|
{
|
||||||
|
filename: `Rechnung${kPdfObjekt}.pdf`,
|
||||||
|
content: content,
|
||||||
|
contentType: "application/pdf",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
let info = await transporter.sendMail(mailOptions);
|
||||||
|
console.log("Message sent: %s", info.messageId);
|
||||||
|
|
||||||
|
await new sql.Request(transaction)
|
||||||
|
.input('kPdfObjekt', kPdfObjekt)
|
||||||
|
.input('datevlink', 'pending')
|
||||||
|
.query("UPDATE tPdfObjekt SET datevlink = @datevlink WHERE kPdfObjekt = @kPdfObjekt");
|
||||||
|
} catch (emailError) {
|
||||||
|
console.error("Error sending email:", emailError);
|
||||||
|
throw emailError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({ success: true, message: 'Datev sync processing completed' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing Datev sync:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to process Datev sync: ' + error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
67
src/routes/data/helpers/jtl.js
Normal file
67
src/routes/data/helpers/jtl.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
const { executeQuery } = require('../../../config/database');
|
||||||
|
|
||||||
|
// Get database transactions for JTL comparison
|
||||||
|
async function getJTLTransactions() {
|
||||||
|
try {
|
||||||
|
const query = `
|
||||||
|
SELECT
|
||||||
|
cKonto, cKontozusatz, cName, dBuchungsdatum,
|
||||||
|
tZahlungsabgleichUmsatz.kZahlungsabgleichUmsatz,
|
||||||
|
cVerwendungszweck, fBetrag, tUmsatzKontierung.data
|
||||||
|
FROM [eazybusiness].[dbo].[tZahlungsabgleichUmsatz]
|
||||||
|
LEFT JOIN tUmsatzKontierung ON (tUmsatzKontierung.kZahlungsabgleichUmsatz = tZahlungsabgleichUmsatz.kZahlungsabgleichUmsatz)
|
||||||
|
ORDER BY dBuchungsdatum desc, tZahlungsabgleichUmsatz.kZahlungsabgleichUmsatz desc
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
const transactions = result.recordset || [];
|
||||||
|
|
||||||
|
// Get PDF documents for each transaction
|
||||||
|
const pdfQuery = `SELECT kUmsatzBeleg, kZahlungsabgleichUmsatz, textContent, markDown, extraction, datevlink FROM tUmsatzBeleg`;
|
||||||
|
const pdfResult = await executeQuery(pdfQuery);
|
||||||
|
|
||||||
|
for (const item of pdfResult.recordset) {
|
||||||
|
for (const transaction of transactions) {
|
||||||
|
if (item.kZahlungsabgleichUmsatz == transaction.kZahlungsabgleichUmsatz) {
|
||||||
|
if (!transaction.pdfs) transaction.pdfs = [];
|
||||||
|
transaction.pdfs.push({
|
||||||
|
kUmsatzBeleg: item.kUmsatzBeleg,
|
||||||
|
content: item.textContent,
|
||||||
|
markDown: item.markDown,
|
||||||
|
extraction: item.extraction,
|
||||||
|
datevlink: item.datevlink
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get links for each transaction
|
||||||
|
const linksQuery = `
|
||||||
|
SELECT kZahlungsabgleichUmsatzLink, kZahlungsabgleichUmsatz, linktarget, linktype, note,
|
||||||
|
tPdfObjekt.kPdfObjekt, tPdfObjekt.textContent, tPdfObjekt.markDown,
|
||||||
|
tPdfObjekt.extraction
|
||||||
|
FROM tZahlungsabgleichUmsatzLink
|
||||||
|
LEFT JOIN tPdfObjekt ON (tZahlungsabgleichUmsatzLink.linktarget = tPdfObjekt.kLieferantenbestellung)
|
||||||
|
WHERE linktype = 'kLieferantenBestellung'
|
||||||
|
`;
|
||||||
|
const linksResult = await executeQuery(linksQuery);
|
||||||
|
|
||||||
|
for (const item of linksResult.recordset) {
|
||||||
|
for (const transaction of transactions) {
|
||||||
|
if (item.kZahlungsabgleichUmsatz == transaction.kZahlungsabgleichUmsatz) {
|
||||||
|
if (!transaction.links) transaction.links = [];
|
||||||
|
transaction.links.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return transactions;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching JTL transactions:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getJTLTransactions
|
||||||
|
};
|
||||||
26
src/routes/data/index.js
Normal file
26
src/routes/data/index.js
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
const express = require('express');
|
||||||
|
|
||||||
|
const months = require('./months');
|
||||||
|
const transactions = require('./transactions');
|
||||||
|
const datev = require('./datev');
|
||||||
|
const pdf = require('./pdf');
|
||||||
|
const kreditors = require('./kreditors');
|
||||||
|
const bankingTransactions = require('./bankingTransactions');
|
||||||
|
const accountingItems = require('./accountingItems');
|
||||||
|
const csvImport = require('./csvImport');
|
||||||
|
const documentProcessing = require('./documentProcessing');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Mount sub-routers preserving original paths
|
||||||
|
router.use(months);
|
||||||
|
router.use(transactions);
|
||||||
|
router.use(datev);
|
||||||
|
router.use(pdf);
|
||||||
|
router.use(kreditors);
|
||||||
|
router.use(bankingTransactions);
|
||||||
|
router.use(accountingItems);
|
||||||
|
router.use(csvImport);
|
||||||
|
router.use(documentProcessing);
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
183
src/routes/data/kreditors.js
Normal file
183
src/routes/data/kreditors.js
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Get all kreditors
|
||||||
|
router.get('/kreditors', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const query = `
|
||||||
|
SELECT id, iban, name, kreditorId
|
||||||
|
FROM fibdash.Kreditor
|
||||||
|
ORDER BY name ASC, iban ASC
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
res.json(result.recordset || []);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching kreditors:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch kreditors' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get kreditor by ID
|
||||||
|
router.get('/kreditors/:id', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT id, iban, name, kreditorId, is_banking
|
||||||
|
FROM fibdash.Kreditor
|
||||||
|
WHERE id = @id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query, { id: parseInt(id, 10) });
|
||||||
|
|
||||||
|
if (result.recordset.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'Kreditor not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching kreditor:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch kreditor' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create new kreditor
|
||||||
|
router.post('/kreditors', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { iban, name, kreditorId, is_banking } = req.body;
|
||||||
|
|
||||||
|
const isBanking = is_banking || false;
|
||||||
|
|
||||||
|
if (!name || !kreditorId) {
|
||||||
|
return res.status(400).json({ error: 'Name and kreditorId are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Business rule: IBAN is required for banking kreditors (proxies), not required for real kreditors
|
||||||
|
if (isBanking && (!iban || iban.trim() === '')) {
|
||||||
|
return res.status(400).json({ error: 'IBAN is required for banking kreditors' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (iban && iban.trim() !== '') {
|
||||||
|
const checkQuery = `
|
||||||
|
SELECT id FROM fibdash.Kreditor
|
||||||
|
WHERE iban = @iban
|
||||||
|
`;
|
||||||
|
|
||||||
|
const checkResult = await executeQuery(checkQuery, { iban });
|
||||||
|
|
||||||
|
if (checkResult.recordset.length > 0) {
|
||||||
|
return res.status(409).json({ error: 'Kreditor with this IBAN already exists' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertQuery = `
|
||||||
|
INSERT INTO fibdash.Kreditor (iban, name, kreditorId, is_banking)
|
||||||
|
OUTPUT INSERTED.id, INSERTED.iban, INSERTED.name, INSERTED.kreditorId, INSERTED.is_banking
|
||||||
|
VALUES (@iban, @name, @kreditorId, @is_banking)
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(insertQuery, {
|
||||||
|
iban: iban || null,
|
||||||
|
name,
|
||||||
|
kreditorId,
|
||||||
|
is_banking: isBanking
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating kreditor:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to create kreditor' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update kreditor
|
||||||
|
router.put('/kreditors/:id', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { id } = req.params;
|
||||||
|
const { iban, name, kreditorId, is_banking } = req.body;
|
||||||
|
|
||||||
|
const isBanking = is_banking || false;
|
||||||
|
|
||||||
|
if (!name || !kreditorId) {
|
||||||
|
return res.status(400).json({ error: 'Name and kreditorId are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Business rule: IBAN is required for banking kreditors (proxies), not required for real kreditors
|
||||||
|
if (isBanking && (!iban || iban.trim() === '')) {
|
||||||
|
return res.status(400).json({ error: 'IBAN is required for banking kreditors' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkQuery = `SELECT id FROM fibdash.Kreditor WHERE id = @id`;
|
||||||
|
const checkResult = await executeQuery(checkQuery, { id: parseInt(id, 10) });
|
||||||
|
|
||||||
|
if (checkResult.recordset.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'Kreditor not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (iban && iban.trim() !== '') {
|
||||||
|
const conflictQuery = `
|
||||||
|
SELECT id FROM fibdash.Kreditor
|
||||||
|
WHERE iban = @iban AND id != @id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const conflictResult = await executeQuery(conflictQuery, { iban, id: parseInt(id, 10) });
|
||||||
|
|
||||||
|
if (conflictResult.recordset.length > 0) {
|
||||||
|
return res.status(409).json({ error: 'Another kreditor with this IBAN already exists' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateQuery = `
|
||||||
|
UPDATE fibdash.Kreditor
|
||||||
|
SET iban = @iban, name = @name, kreditorId = @kreditorId, is_banking = @is_banking
|
||||||
|
OUTPUT INSERTED.id, INSERTED.iban, INSERTED.name, INSERTED.kreditorId, INSERTED.is_banking
|
||||||
|
WHERE id = @id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(updateQuery, {
|
||||||
|
iban: iban || null,
|
||||||
|
name,
|
||||||
|
kreditorId,
|
||||||
|
is_banking: isBanking,
|
||||||
|
id: parseInt(id, 10)
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json(result.recordset[0]);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating kreditor:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to update kreditor' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete kreditor (hard delete)
|
||||||
|
router.delete('/kreditors/:id', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
const { id } = req.params;
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
DELETE FROM fibdash.Kreditor
|
||||||
|
WHERE id = @id
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query, { id: parseInt(id, 10) });
|
||||||
|
|
||||||
|
if (result.rowsAffected[0] === 0) {
|
||||||
|
return res.status(404).json({ error: 'Kreditor not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ message: 'Kreditor deleted successfully' });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting kreditor:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to delete kreditor' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
33
src/routes/data/months.js
Normal file
33
src/routes/data/months.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Get available months from database
|
||||||
|
router.get('/months', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT DISTINCT
|
||||||
|
FORMAT(combined.date_col, 'yyyy-MM') as month_year
|
||||||
|
FROM (
|
||||||
|
SELECT buchungsdatum as date_col FROM fibdash.AccountingItems WHERE buchungsdatum IS NOT NULL
|
||||||
|
UNION ALL
|
||||||
|
SELECT parsed_date as date_col FROM fibdash.CSVTransactions WHERE parsed_date IS NOT NULL
|
||||||
|
) combined
|
||||||
|
WHERE combined.date_col IS NOT NULL
|
||||||
|
ORDER BY month_year DESC
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
const months = result.recordset.map(row => row.month_year);
|
||||||
|
|
||||||
|
res.json({ months });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting months:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to load months' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
72
src/routes/data/pdf.js
Normal file
72
src/routes/data/pdf.js
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Get PDF from tUmsatzBeleg
|
||||||
|
router.get('/pdf/umsatzbeleg/:kUmsatzBeleg', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { kUmsatzBeleg } = req.params;
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT content, datevlink
|
||||||
|
FROM dbo.tUmsatzBeleg
|
||||||
|
WHERE kUmsatzBeleg = @kUmsatzBeleg AND content IS NOT NULL
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query, {
|
||||||
|
kUmsatzBeleg: parseInt(kUmsatzBeleg, 10)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.recordset || result.recordset.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'PDF not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const pdfData = result.recordset[0];
|
||||||
|
const filename = 'Umsatzbeleg_' + kUmsatzBeleg + '_' + (pdfData.datevlink || 'document') + '.pdf';
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'application/pdf');
|
||||||
|
res.setHeader('Content-Disposition', 'inline; filename="' + filename + '"');
|
||||||
|
res.send(pdfData.content);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching PDF from tUmsatzBeleg:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch PDF' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get PDF from tPdfObjekt
|
||||||
|
router.get('/pdf/pdfobject/:kPdfObjekt', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { kPdfObjekt } = req.params;
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT content, datevlink, kLieferantenbestellung
|
||||||
|
FROM dbo.tPdfObjekt
|
||||||
|
WHERE kPdfObjekt = @kPdfObjekt AND content IS NOT NULL
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query, {
|
||||||
|
kPdfObjekt: parseInt(kPdfObjekt, 10)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.recordset || result.recordset.length === 0) {
|
||||||
|
return res.status(404).json({ error: 'PDF not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const pdfData = result.recordset[0];
|
||||||
|
const filename = 'PdfObjekt_' + kPdfObjekt + '_LB' + pdfData.kLieferantenbestellung + '_' + (pdfData.datevlink || 'document') + '.pdf';
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'application/pdf');
|
||||||
|
res.setHeader('Content-Disposition', 'inline; filename="' + filename + '"');
|
||||||
|
res.send(pdfData.content);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching PDF from tPdfObjekt:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to fetch PDF' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
226
src/routes/data/transactions.js
Normal file
226
src/routes/data/transactions.js
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { authenticateToken } = require('../../middleware/auth');
|
||||||
|
const { getJTLTransactions } = require('./helpers/jtl');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// Get transactions for a specific time period (month, quarter, or year)
|
||||||
|
router.get('/transactions/:timeRange', authenticateToken, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { timeRange } = req.params;
|
||||||
|
|
||||||
|
const { executeQuery } = require('../../config/database');
|
||||||
|
|
||||||
|
// Build WHERE clause based on timeRange format
|
||||||
|
let timeWhereClause = '';
|
||||||
|
if (timeRange.includes('-Q')) {
|
||||||
|
// Quarter format: 2025-Q2
|
||||||
|
const [year, quarterPart] = timeRange.split('-Q');
|
||||||
|
const quarter = parseInt(quarterPart, 10);
|
||||||
|
const startMonth = (quarter - 1) * 3 + 1;
|
||||||
|
const endMonth = startMonth + 2;
|
||||||
|
timeWhereClause = `WHERE YEAR(csv.parsed_date) = ${year} AND MONTH(csv.parsed_date) BETWEEN ${startMonth} AND ${endMonth}`;
|
||||||
|
} else if (timeRange.length === 4) {
|
||||||
|
// Year format: 2025
|
||||||
|
timeWhereClause = `WHERE YEAR(csv.parsed_date) = ${timeRange}`;
|
||||||
|
} else {
|
||||||
|
// Month format: 2025-07
|
||||||
|
const [year, month] = timeRange.split('-');
|
||||||
|
timeWhereClause = `WHERE YEAR(csv.parsed_date) = ${year} AND MONTH(csv.parsed_date) = ${parseInt(month, 10)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const query = `
|
||||||
|
SELECT
|
||||||
|
csv.id as id,
|
||||||
|
csv.buchungstag as 'Buchungstag',
|
||||||
|
csv.wertstellung as 'Valutadatum',
|
||||||
|
csv.umsatzart as 'Buchungstext',
|
||||||
|
csv.verwendungszweck as 'Verwendungszweck',
|
||||||
|
csv.beguenstigter_zahlungspflichtiger as 'Beguenstigter/Zahlungspflichtiger',
|
||||||
|
csv.kontonummer_iban as 'Kontonummer/IBAN',
|
||||||
|
csv.bic as 'BIC (SWIFT-Code)',
|
||||||
|
csv.betrag_original as 'Betrag',
|
||||||
|
csv.waehrung as 'Waehrung',
|
||||||
|
csv.numeric_amount as numericAmount,
|
||||||
|
csv.parsed_date,
|
||||||
|
FORMAT(csv.parsed_date, 'yyyy-MM') as monthYear,
|
||||||
|
jtl.kZahlungsabgleichUmsatz as jtlId,
|
||||||
|
CASE WHEN jtl.kZahlungsabgleichUmsatz IS NOT NULL THEN 1 ELSE 0 END as hasJTL,
|
||||||
|
k.name as kreditor_name,
|
||||||
|
k.kreditorId as kreditor_id,
|
||||||
|
k.is_banking as kreditor_is_banking,
|
||||||
|
bat.assigned_kreditor_id,
|
||||||
|
ak.name as assigned_kreditor_name,
|
||||||
|
ak.kreditorId as assigned_kreditor_kreditorId,
|
||||||
|
0 as isJTLOnly,
|
||||||
|
1 as isFromCSV,
|
||||||
|
ub.textContent as jtl_document_data,
|
||||||
|
ub.kUmsatzBeleg,
|
||||||
|
ub.datevlink
|
||||||
|
FROM fibdash.CSVTransactions csv
|
||||||
|
LEFT JOIN eazybusiness.dbo.tZahlungsabgleichUmsatz jtl ON (
|
||||||
|
ABS(csv.numeric_amount - jtl.fBetrag) < 0.01 AND
|
||||||
|
ABS(DATEDIFF(day, csv.parsed_date, jtl.dBuchungsdatum)) <= 1
|
||||||
|
)
|
||||||
|
LEFT JOIN eazybusiness.dbo.tUmsatzBeleg ub ON ub.kZahlungsabgleichUmsatz = jtl.kZahlungsabgleichUmsatz
|
||||||
|
LEFT JOIN fibdash.Kreditor k ON csv.kontonummer_iban = k.iban
|
||||||
|
LEFT JOIN fibdash.BankingAccountTransactions bat ON csv.id = bat.csv_transaction_id
|
||||||
|
LEFT JOIN fibdash.Kreditor ak ON bat.assigned_kreditor_id = ak.id
|
||||||
|
${timeWhereClause}
|
||||||
|
|
||||||
|
UNION ALL
|
||||||
|
|
||||||
|
SELECT
|
||||||
|
jtl.kZahlungsabgleichUmsatz as id,
|
||||||
|
FORMAT(jtl.dBuchungsdatum, 'dd.MM.yy') as 'Buchungstag',
|
||||||
|
FORMAT(jtl.dBuchungsdatum, 'dd.MM.yy') as 'Valutadatum',
|
||||||
|
'JTL Transaction' as 'Buchungstext',
|
||||||
|
jtl.cVerwendungszweck as 'Verwendungszweck',
|
||||||
|
jtl.cName as 'Beguenstigter/Zahlungspflichtiger',
|
||||||
|
'' as 'Kontonummer/IBAN',
|
||||||
|
'' as 'BIC (SWIFT-Code)',
|
||||||
|
FORMAT(jtl.fBetrag, 'N2', 'de-DE') as 'Betrag',
|
||||||
|
'' as 'Waehrung',
|
||||||
|
jtl.fBetrag as numericAmount,
|
||||||
|
jtl.dBuchungsdatum as parsed_date,
|
||||||
|
FORMAT(jtl.dBuchungsdatum, 'yyyy-MM') as monthYear,
|
||||||
|
jtl.kZahlungsabgleichUmsatz as jtlId,
|
||||||
|
1 as hasJTL,
|
||||||
|
NULL as kreditor_name,
|
||||||
|
NULL as kreditor_id,
|
||||||
|
NULL as kreditor_is_banking,
|
||||||
|
NULL as assigned_kreditor_id,
|
||||||
|
NULL as assigned_kreditor_name,
|
||||||
|
NULL as assigned_kreditor_kreditorId,
|
||||||
|
1 as isJTLOnly,
|
||||||
|
0 as isFromCSV,
|
||||||
|
ub.textContent as jtl_document_data,
|
||||||
|
ub.kUmsatzBeleg,
|
||||||
|
ub.datevlink
|
||||||
|
FROM eazybusiness.dbo.tZahlungsabgleichUmsatz jtl
|
||||||
|
LEFT JOIN eazybusiness.dbo.tUmsatzBeleg ub ON ub.kZahlungsabgleichUmsatz = jtl.kZahlungsabgleichUmsatz
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM fibdash.CSVTransactions csv
|
||||||
|
WHERE ABS(csv.numeric_amount - jtl.fBetrag) < 0.01
|
||||||
|
AND ABS(DATEDIFF(day, csv.parsed_date, jtl.dBuchungsdatum)) <= 1
|
||||||
|
)
|
||||||
|
${timeRange.includes('-Q') ?
|
||||||
|
`AND YEAR(jtl.dBuchungsdatum) = ${timeRange.split('-Q')[0]} AND MONTH(jtl.dBuchungsdatum) BETWEEN ${(parseInt(timeRange.split('-Q')[1], 10) - 1) * 3 + 1} AND ${(parseInt(timeRange.split('-Q')[1], 10) - 1) * 3 + 3}` :
|
||||||
|
timeRange.length === 4 ?
|
||||||
|
`AND YEAR(jtl.dBuchungsdatum) = ${timeRange}` :
|
||||||
|
`AND YEAR(jtl.dBuchungsdatum) = ${timeRange.split('-')[0]} AND MONTH(jtl.dBuchungsdatum) = ${parseInt(timeRange.split('-')[1], 10)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
ORDER BY parsed_date DESC
|
||||||
|
`;
|
||||||
|
|
||||||
|
const result = await executeQuery(query);
|
||||||
|
|
||||||
|
// Get links data separately to avoid duplicate rows
|
||||||
|
const linksQuery = `
|
||||||
|
SELECT
|
||||||
|
zul.kZahlungsabgleichUmsatz,
|
||||||
|
zul.linktarget,
|
||||||
|
zul.linktype,
|
||||||
|
zul.note,
|
||||||
|
po.kPdfObjekt,
|
||||||
|
po.textContent,
|
||||||
|
po.markDown,
|
||||||
|
po.extraction
|
||||||
|
FROM eazybusiness.dbo.tZahlungsabgleichUmsatzLink zul
|
||||||
|
LEFT JOIN eazybusiness.dbo.tPdfObjekt po ON zul.linktarget = po.kLieferantenbestellung
|
||||||
|
WHERE zul.linktype = 'kLieferantenBestellung'
|
||||||
|
`;
|
||||||
|
const linksResult = await executeQuery(linksQuery);
|
||||||
|
const linksData = linksResult.recordset || [];
|
||||||
|
|
||||||
|
// Group transactions by ID to handle multiple JTL matches
|
||||||
|
const transactionGroups = {};
|
||||||
|
result.recordset.forEach(row => {
|
||||||
|
const key = row.id;
|
||||||
|
if (!transactionGroups[key]) {
|
||||||
|
transactionGroups[key] = {
|
||||||
|
...row,
|
||||||
|
pdfs: [],
|
||||||
|
links: []
|
||||||
|
};
|
||||||
|
// Remove top-level kUmsatzBeleg and datevlink since they belong in pdfs array
|
||||||
|
delete transactionGroups[key].kUmsatzBeleg;
|
||||||
|
delete transactionGroups[key].datevlink;
|
||||||
|
delete transactionGroups[key].jtl_document_data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add PDF data if present
|
||||||
|
if (row.jtl_document_data) {
|
||||||
|
transactionGroups[key].pdfs.push({
|
||||||
|
content: row.jtl_document_data,
|
||||||
|
kUmsatzBeleg: row.kUmsatzBeleg,
|
||||||
|
datevlink: row.datevlink
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add links data if present
|
||||||
|
if (row.jtlId) {
|
||||||
|
const transactionLinks = linksData.filter(link =>
|
||||||
|
link.kZahlungsabgleichUmsatz === row.jtlId
|
||||||
|
);
|
||||||
|
transactionGroups[key].links.push(...transactionLinks);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const transactions = Object.values(transactionGroups).map(transaction => ({
|
||||||
|
...transaction,
|
||||||
|
parsedDate: new Date(transaction.parsed_date),
|
||||||
|
hasJTL: Boolean(transaction.hasJTL),
|
||||||
|
isFromCSV: Boolean(transaction.isFromCSV),
|
||||||
|
jtlDatabaseAvailable: true,
|
||||||
|
hasKreditor: !!transaction.kreditor_name,
|
||||||
|
kreditor: transaction.kreditor_name ? {
|
||||||
|
name: transaction.kreditor_name,
|
||||||
|
kreditorId: transaction.kreditor_id,
|
||||||
|
is_banking: Boolean(transaction.kreditor_is_banking)
|
||||||
|
} : null,
|
||||||
|
assignedKreditor: transaction.assigned_kreditor_name ? {
|
||||||
|
name: transaction.assigned_kreditor_name,
|
||||||
|
id: transaction.assigned_kreditor_id,
|
||||||
|
kreditorId: transaction.assigned_kreditor_kreditorId
|
||||||
|
} : null,
|
||||||
|
// Remove duplicate links
|
||||||
|
links: [...new Set(transaction.links.map(l => JSON.stringify(l)))].map(l => JSON.parse(l))
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Transactions are already filtered by the SQL query, so we just need to sort them
|
||||||
|
const monthTransactions = transactions
|
||||||
|
.sort((a, b) => b.parsedDate - a.parsedDate);
|
||||||
|
|
||||||
|
// Since transactions are already filtered and joined with JTL data in SQL,
|
||||||
|
// we don't need the complex post-processing logic anymore
|
||||||
|
|
||||||
|
const summary = {
|
||||||
|
totalTransactions: transactions.length,
|
||||||
|
totalIncome: transactions
|
||||||
|
.filter(t => t.numericAmount > 0)
|
||||||
|
.reduce((sum, t) => sum + t.numericAmount, 0),
|
||||||
|
totalExpenses: transactions
|
||||||
|
.filter(t => t.numericAmount < 0)
|
||||||
|
.reduce((sum, t) => sum + Math.abs(t.numericAmount), 0),
|
||||||
|
netAmount: transactions.reduce((sum, t) => sum + t.numericAmount, 0),
|
||||||
|
timeRange: timeRange,
|
||||||
|
jtlDatabaseAvailable: true,
|
||||||
|
jtlMatches: transactions.filter(t => t.hasJTL === true && t.isFromCSV).length,
|
||||||
|
jtlMissing: transactions.filter(t => t.hasJTL === false && t.isFromCSV).length,
|
||||||
|
jtlOnly: transactions.filter(t => t.isJTLOnly === true).length,
|
||||||
|
csvOnly: transactions.filter(t => t.hasJTL === false && t.isFromCSV).length
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
transactions: transactions,
|
||||||
|
summary
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error getting transactions:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to load transactions' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -5,12 +5,20 @@ const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'
|
|||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
mode: process.env.NODE_ENV || 'development',
|
||||||
entry: './client/src/index.js',
|
entry: './client/src/index.js',
|
||||||
output: {
|
output: {
|
||||||
path: path.resolve(__dirname, 'dist'),
|
path: path.resolve(__dirname, 'dist'),
|
||||||
filename: 'bundle.js',
|
filename: 'bundle.js',
|
||||||
publicPath: '/',
|
publicPath: '/',
|
||||||
},
|
},
|
||||||
|
cache: {
|
||||||
|
type: 'filesystem',
|
||||||
|
buildDependencies: {
|
||||||
|
config: [__filename],
|
||||||
|
},
|
||||||
|
cacheDirectory: path.resolve(__dirname, 'node_modules/.cache/webpack'),
|
||||||
|
},
|
||||||
module: {
|
module: {
|
||||||
rules: [
|
rules: [
|
||||||
{
|
{
|
||||||
@@ -36,7 +44,7 @@ module.exports = {
|
|||||||
new HtmlWebpackPlugin({
|
new HtmlWebpackPlugin({
|
||||||
template: './client/public/index.html',
|
template: './client/public/index.html',
|
||||||
templateParameters: {
|
templateParameters: {
|
||||||
REACT_APP_GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID || 'your_google_client_id_here',
|
REACT_APP_GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
new webpack.DefinePlugin({
|
new webpack.DefinePlugin({
|
||||||
@@ -67,11 +75,36 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api': {
|
'/api': {
|
||||||
target: 'http://localhost:5000',
|
target: 'http://localhost:5500',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
watchOptions: {
|
||||||
|
ignored: /node_modules/,
|
||||||
|
aggregateTimeout: 300,
|
||||||
|
poll: false,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
managedPaths: [path.resolve(__dirname, 'node_modules')],
|
||||||
|
immutablePaths: [],
|
||||||
|
buildDependencies: {
|
||||||
|
hash: true,
|
||||||
|
timestamp: true,
|
||||||
|
},
|
||||||
|
module: {
|
||||||
|
timestamp: true,
|
||||||
|
hash: true,
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
timestamp: true,
|
||||||
|
hash: true,
|
||||||
|
},
|
||||||
|
resolveBuildDependencies: {
|
||||||
|
timestamp: true,
|
||||||
|
hash: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
resolve: {
|
resolve: {
|
||||||
extensions: ['.js', '.jsx'],
|
extensions: ['.js', '.jsx'],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api': {
|
'/api': {
|
||||||
target: 'http://localhost:5000',
|
target: 'http://localhost:5500',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -94,4 +94,4 @@ module.exports = {
|
|||||||
maxAssetSize: 512000,
|
maxAssetSize: 512000,
|
||||||
maxEntrypointSize: 512000,
|
maxEntrypointSize: 512000,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user