Commit Graph

27 Commits

Author SHA1 Message Date
09a368355d Complete Windows deployment console FULL INTEGRATION with auto-detection
This commit completes the unified Windows deployment console with automatic detection of first-time install vs update, eliminating the need for separate Install-*.ps1 scripts.

## Changes

### Added Detection Functions
- `Test-BackendInstalled`: Checks if backend is installed (venv + service + requirements.txt)
- `Test-TelegramBotInstalled`: Checks if telegram bot is installed (venv + service + app files)

### Added Prerequisite Installation Functions
- `Install-Chocolatey`: Automated Chocolatey package manager installation
- `Install-Python`: Python 3.11 installation via Chocolatey
- `Install-NSSM`: NSSM (Windows service manager) installation via Chocolatey
- `Install-IISModules`: IIS and required modules (URL Rewrite, Application Initialization)

### Added First-Time Installation Functions
- `Install-BackendFirstTime`: Complete backend first-time installation (~240 lines)
  - Directory structure creation
  - Backend, frontend, shared files copying with exclusions
  - .env.example template copying
  - Virtual environment creation with proper pip installation
  - Windows Service creation via NSSM
  - IIS Application Pool and Web Application configuration

- `Install-TelegramBotFirstTime`: Complete telegram bot first-time installation (~155 lines)
  - Directory structure (app, data, logs, temp, backups)
  - App files and requirements.txt copying
  - Virtual environment creation
  - Windows Service creation via NSSM

### Updated Deployment Functions with Auto-Routing
- `Deploy-Backend`: Now calls `Test-BackendInstalled` first
  - If NOT installed → routes to `Install-BackendFirstTime`
  - If installed → proceeds with existing UPDATE logic (backup, stop, update, start)

- `Deploy-TelegramBot`: Now calls `Test-TelegramBotInstalled` first
  - If NOT installed → routes to `Install-TelegramBotFirstTime`
  - If installed → proceeds with existing UPDATE logic (backup, stop, update, start)

## Benefits

1. **Single Entry Point**: Users can run the same deploy command for both first-time install and updates
2. **No Separate Install Scripts**: Eliminates confusion between Install-*.ps1 and Deploy-*.ps1
3. **Automatic Detection**: Intelligently detects what needs to be done
4. **Safer Updates**: Always checks if components exist before attempting updates
5. **Better UX**: Clear warnings about first-time installation vs updates

## Usage

```powershell
# Interactive (auto-detects install vs update)
.\ROA2WEB-Console.ps1
# Select: Deploy Components > Backend + Frontend

# Command line (auto-detects install vs update)
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployBackend
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployTelegramBot
.\ROA2WEB-Console.ps1 -NonInteractive -Action DeployAll
```

The console will automatically:
- Detect if backend/telegram-bot are installed
- Perform first-time installation if needed (including prerequisites)
- Perform updates if already installed (with automatic backups)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-12 02:23:59 +02:00
016c309d70 Optimize Windows deployment scripts: build cache, console integration, and .env.example handling
Build-ROA2WEB.ps1 improvements:
- Add intelligent npm node_modules caching (saves 2-5 minutes on repeated builds)
- Cache stored outside deploy-package in .build-cache/ directory
- Add Clean Cache menu option ([C]) and -CleanCache parameter
- Include ROA2WEB-Console.ps1 in deployment package
- Update README workflow to use unified console (interactive and CLI modes)
- Remove obsolete script references (Manage-ROA2WEB.ps1, Deploy-*.ps1)
- Fix .env.example copying for backend and telegram-bot (copy from source instead of hardcoded template)

ROA2WEB-Console.ps1 improvements:
- Fix PowerShell parsing error: ${ComponentName}: instead of $ComponentName:
- Add .env.example copying in Update-BackendFiles function
- Add .env.example copying in Update-TelegramBotFiles function
- Keep .env.example synchronized with development templates

.gitignore:
- Add .build-cache/ to prevent committing npm cache directory

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-12 02:04:31 +02:00
1832684aca Refactor Windows deployment scripts: unify build and management tools
Major improvements to deployment workflow with unified scripts and interactive menus.

New unified scripts:
- Build-ROA2WEB.ps1: Interactive menu for building all components
  * Isolated temp directory for frontend builds (prevents WSL node_modules corruption)
  * Automatic devDependencies installation (fixes Vite not found issue)
  * Auto-cleanup after build
  * Supports both interactive menu and non-interactive CLI

- ROA2WEB-Console.ps1: All-in-one deployment and management console
  * Interactive menus for deploy, manage services, and status checks
  * Automatic backups before deployment
  * Smart dependency updates (only if requirements.txt changed)
  * Health checks after service operations
  * Color-coded status output
  * Both interactive and non-interactive modes

Removed deprecated scripts (replaced by unified tools):
- Build-Frontend.ps1 → Use Build-ROA2WEB.ps1 -Component Frontend
- Build-TelegramBot.ps1 → Use Build-ROA2WEB.ps1 -Component TelegramBot
- Deploy-ROA2WEB.ps1 → Use ROA2WEB-Console.ps1 [Deploy menu]
- Deploy-TelegramBot.ps1 → Use ROA2WEB-Console.ps1 [Deploy menu]
- Manage-ROA2WEB.ps1 → Use ROA2WEB-Console.ps1 [Manage menu]

Updated documentation:
- Complete rewrite of scripts/README.md
- Clear workflow guides for first-time deployment and updates
- Comparison table v1.0 vs v2.0
- Updated best practices and troubleshooting

Benefits:
 Reduced from 13 to 8 scripts (better maintainability)
 Interactive menus for better UX
 Fixed WSL node_modules corruption issue
 Smart dependency management (faster deployments)
 Unified interface reduces learning curve
 Better error handling and health checks

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-12 01:35:14 +02:00
a227a10ca8 Refactor Telegram bot code login: unify UI with single message editing
Remove FakeMessage wrapper class and implement consistent message editing
for web app code login flow. User-submitted code is now deleted immediately
and instructions message transforms in-place to show menu, matching the
email login UX pattern.

Changes:
- Remove FakeMessage class from start_command handler
- Use direct edit_message_text for all message updates
- Delete user's code message for cleaner chat interface
- Preserve web_login_message_id in context throughout flow
- Apply same pattern to handle_text_message (8-char code handler)
- Ensure single editable message from instructions to menu

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-12 00:51:28 +02:00
6e6111df18 Refactor Telegram bot login flow: clean UI with single editable message
- Consolidate login flow to use single message that edits in place
- Auto-delete all user messages (email, code, password, /start command)
- Remove all emojis from bot messages for cleaner interface
- Fix "Retrimite Cod" bug - buttons now persist after resending code
- Replace "Oracle" with "ROA" in all user-facing messages
- Add clear instructions for each step (email input, code input, password)
- Implement message tracking with context.user_data['login_message_id']
- Clean chat history - only menu message remains visible

Files modified:
- app/bot/email_handlers.py: Complete refactor of email login flow
- app/bot/handlers.py: Update /start command to delete user message and edit existing message

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-12 00:01:19 +02:00
1b4e2e1f40 Refactor Windows deployment scripts: unify build and management tools
Major improvements to Windows deployment workflow:

 New Unified Scripts:
- Build-ROA2WEB.ps1: Single build script for all components (Frontend, Backend, TelegramBot)
  * Supports selective builds: -Component All|Frontend|Backend|TelegramBot
  * Replaces Build-Frontend.ps1 and Build-TelegramBot.ps1
  * Consistent output structure and better validation

- Manage-ROA2WEB.ps1: Unified service management
  * Single entry point for Start, Stop, Restart, Status actions
  * Supports -Component All|Backend|TelegramBot
  * Health checks and detailed status reporting
  * Replaces 6 separate Start/Stop/Restart scripts

🗑️ Removed Deprecated Scripts:
- Start-ROA2WEB.ps1, Stop-ROA2WEB.ps1, Restart-ROA2WEB.ps1
- Start-TelegramBot.ps1, Stop-TelegramBot.ps1, Restart-TelegramBot.ps1
(6 scripts → 1 unified Manage-ROA2WEB.ps1)

⚠️ Marked as DEPRECATED (backward compatibility):
- Build-Frontend.ps1 (use Build-ROA2WEB.ps1 -Component Frontend)
- Build-TelegramBot.ps1 (use Build-ROA2WEB.ps1 -Component TelegramBot)

🧹 Cleanup & Organization:
- Updated .gitignore: deploy-package/ and build artifacts excluded
- Removed deploy-package/ from git tracking (generated artifacts)
- Added DEPLOY_PACKAGE.md with generation instructions
- Created comprehensive scripts/README.md documentation

📝 Documentation Updates:
- Updated CLAUDE.md Windows deployment section
- Added complete script reference guide
- Migration guide from old scripts to new unified system

📊 Impact:
- 18 scripts → 11 scripts (39% reduction)
- ~10,000 LOC → ~6,500 LOC (35% reduction)
- Zero duplicate code
- Cleaner git repository (no build artifacts)
- Unified, consistent API across all operations

Migration:
./Build-Frontend.ps1        → ./Build-ROA2WEB.ps1 -Component Frontend
./Build-TelegramBot.ps1      → ./Build-ROA2WEB.ps1 -Component TelegramBot
./Start-ROA2WEB.ps1          → ./Manage-ROA2WEB.ps1 -Action Start -Component Backend
./Restart-TelegramBot.ps1    → ./Manage-ROA2WEB.ps1 -Action Restart -Component TelegramBot

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 22:50:03 +02:00
53d108e7c8 Add encrypted production secrets backup (2025-11-11)
Initial encrypted backup of all sensitive configuration files and SSH keys
for version control and disaster recovery.

Contents:
- backend/.env and .env.prod (development and production config)
- telegram-bot/.env and .env.prod (bot configuration)
- secrets/ directory (SSH keys for Oracle server access)

Encryption: AES-256-CBC with PBKDF2 using OpenSSL
Total: 5 encrypted items (4 files + 1 directory archive)
Backup date: 2025-11-11 14:46:50

⚠️ IMPORTANT: Decryption password required for restore
Password format: ROA2WEB_Backup_2024_Secure_Key_YYYYMMDD

To restore:
./scripts/restore-secrets.sh 2025-11-11_14-46-50

All files are safely encrypted and can be committed to git without
exposing sensitive credentials. Decryption password must be stored
separately in password manager.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 14:47:34 +02:00
71f0fcaab0 Add secrets directory support to backup/restore scripts
Extended backup and restore utilities to include the secrets/ directory
containing SSH keys for Oracle server access.

Changes:
- backup-secrets.sh: Added SECRET_DIRS array to backup entire directories as tar archives
- restore-secrets.sh: Added logic to detect and restore tar.enc directory archives
- Both scripts now handle:
  * Individual .env files (as before)
  * Complete directories (new: secrets/ with SSH keys)

Technical implementation:
- Directories are archived with tar and piped directly to openssl for encryption
- Uses tar -cf - to output to stdout, then pipes to openssl enc
- Restore decrypts and extracts in one step: openssl | tar -xf -
- Preserves directory structure and file permissions

Files backed up:
- reports-app/backend/.env and .env.prod
- reports-app/telegram-bot/.env and .env.prod
- secrets/ directory (SSH keys: roa_oracle_server, *.pub, .gitkeep)

Backup structure now includes:
- *.env.enc (individual encrypted files)
- secrets.tar.enc (encrypted tar archive of directory)

Tested successfully with encryption/decryption cycle.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 12:44:34 +02:00
60346ff7da Add encrypted secrets backup and restore utilities
Implements secure backup system for environment configuration files (.env, .env.prod)
containing sensitive credentials using AES-256-CBC encryption with OpenSSL.

New utilities:
- scripts/backup-secrets.sh: Encrypts and backs up all .env files to timestamped directory
- scripts/restore-secrets.sh: Decrypts and restores .env files from backup
- scripts/README.md: Complete documentation with usage examples and best practices

Features:
- AES-256-CBC encryption with PBKDF2 key derivation (strong encryption)
- Interactive password prompts with confirmation
- Non-interactive mode via BACKUP_PASSWORD environment variable
- Automatic README generation in each backup with restore instructions
- Color-coded output for better UX
- Validation and error handling

Backup structure:
secrets-backup/
└── YYYY-MM-DD_HH-MM-SS/
    ├── backend-.env.enc
    ├── backend-.env.prod.enc
    ├── telegram-bot-.env.enc
    ├── telegram-bot-.env.prod.enc
    └── README.md

Updated .gitignore to allow committing encrypted .gpg/.enc files while
blocking decrypted .env files in secrets-backup directory.

Usage:
./scripts/backup-secrets.sh                    # Create encrypted backup
./scripts/restore-secrets.sh [backup-date]     # Restore from backup

Tested with OpenSSL (pre-installed on most systems). Provides secure way to
version control and sync credentials across development and production environments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 12:36:43 +02:00
830c5c8181 Refactor environment configuration templates with comprehensive documentation
Updates .env.example files for both backend and telegram-bot with:
- Complete variable coverage matching actual code usage
- Clear section-based organization (Oracle, JWT, SMTP, Cache, etc.)
- Detailed comments explaining purpose and usage location for each variable
- Added missing critical variables (AUTH_SESSION_SECRET, CACHE_*, token expiration settings)
- Removed unused/dead variables (CLAUDE_API_KEY, DEBUG, API_HOST, SQLITE_DB_PATH, etc.)
- Consistent formatting and structure across development and production templates

Critical additions:
- AUTH_SESSION_SECRET for email 2FA flow (must match between backend and telegram-bot)
- Full cache configuration variables (17 vars for hybrid L1/L2 cache system)
- Token expiration settings (ACCESS_TOKEN_EXPIRE_MINUTES, REFRESH_TOKEN_EXPIRE_DAYS)
- SMTP email retry settings for telegram bot

Ensures all .env.example files accurately reflect required and optional environment
variables used in the codebase, making deployment and configuration easier.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 12:30:44 +02:00
706062dc0f Implement email-based 2FA authentication for Telegram bot with Oracle integration fixes
This commit adds a complete email authentication flow for the Telegram bot, allowing users to login with email + password instead of web app linking codes. Includes critical bug fixes for Oracle integration.

**New Features:**
- Email-based 2FA authentication with 6-digit codes sent via SMTP
- Backend endpoints: verify-email and login-with-email
- ConversationHandler for email authentication flow in Telegram bot
- Session token verification to prevent user ID spoofing
- Rate limiting (5 attempts per 5 minutes)
- Email code expiry (5 minutes) with automatic cleanup

**Bug Fixes:**
- Fixed Oracle column name: ACTIV → INACTIV (with inverted logic)
- Fixed Oracle password verification: verificautilizator returns checksum, not user_id
- Fixed username case sensitivity: Oracle usernames must be uppercase
- Fixed SMTP connection: use start_tls parameter instead of manual STARTTLS
- Added middleware exclusions for public email auth endpoints

**Backend Changes:**
- Added verify-email endpoint (public) in telegram.py
- Added login-with-email endpoint (public) with rate limiting and session verification
- Updated middleware exclusions in main.py and auth_middleware_wrapper.py
- Added AUTH_SESSION_SECRET configuration for session token signing

**Telegram Bot Changes:**
- New modules: app/auth/email_auth.py, app/bot/email_handlers.py
- New utilities: app/utils/email_service.py (SMTP email sending)
- Updated handlers.py: ignore callbacks handled by ConversationHandler
- Updated menus.py: show Login button for unauthenticated users
- Updated API client: verify_email() and login_with_email() methods
- Database: email_auth_codes table with cleanup task

**Configuration:**
- Added SMTP configuration to telegram-bot .env.example
- Added AUTH_SESSION_SECRET to backend .env.example
- Updated .gitignore: exclude temporary files (*.pid, *.checksum, test scripts)

**Dependencies:**
- Added aiosmtplib for async SMTP email sending

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 12:00:46 +02:00
1378ee1e6a Implement hybrid two-tier cache system with full monitoring and Telegram bot enhancements
Cache System (Backend):
- Implemented two-tier hybrid cache: L1 (in-memory) + L2 (SQLite)
- L1 cache: Fast dictionary-based with 5-minute TTL for hot data
- L2 cache: Persistent SQLite with 1-hour TTL for warm data
- Cache decorator with automatic tier management and fallback
- Cache key generation with per-user isolation
- Event monitoring system for cache statistics
- Cache benchmarking utilities for performance testing
- Added cache management endpoints: /api/cache/stats, /api/cache/clear, /api/cache/benchmark
- Cache configuration via environment variables (CACHE_ENABLED, CACHE_L1_TTL, etc.)

Backend Services:
- Updated dashboard_service to use @cached decorator with request context
- Added cache support to invoice_service and treasury_service
- Integrated cache manager into main.py with lifespan events
- Added Request parameter to service methods for cache metadata

Frontend Enhancements:
- New CacheStatsView.vue for real-time cache monitoring dashboard
- Cache store (cacheStore.js) for state management
- Updated router to include /cache-stats route
- Navigation updates in DashboardHeader and HamburgerMenu
- Cache stats accessible from main navigation

Telegram Bot Improvements:
- Enhanced formatters with YTD comparison data
- Improved menu navigation and button layout
- Better error handling and user feedback
- Bot startup improvements with graceful shutdown

Auth & Middleware:
- Enhanced middleware with cache metadata injection
- Improved request state handling for cache source tracking

Development:
- Updated start-dev.sh with better error handling
- Added TELEGRAM_EMAIL_AUTH_PLAN.md documentation
- Updated requirements.txt with aiosqlite for async SQLite

Performance:
- L1 cache provides <1ms response for hot data
- L2 cache provides ~5ms response for warm data
- Database queries only for cold data or cache misses
- Cache hit rates tracked and displayed in real-time

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 22:42:00 +02:00
2a37959d80 Add cache source tracking (L1/L2) for Telegram bot responses
Implements cache tier identification in Telegram bot to display data source:
- "db" for database queries
- "cached L1" for in-memory cache hits
- "cached L2" for SQLite cache hits

Backend changes:
- Added cache metadata fields to TrendsResponse and DashboardSummary models
  (cache_hit, response_time_ms, cache_source)
- Updated /api/dashboard/summary and /api/dashboard/trends endpoints to
  include cache metadata when X-Include-Cache-Metadata header is present
- Cache metadata is extracted from request.state (set by @cached decorator)

Telegram bot changes:
- Updated API client to send X-Include-Cache-Metadata header
- Modified helpers to extract cache_source from backend responses
- Updated handlers to pass cache metadata to formatters
- Performance footer now displays specific cache tier (L1 vs L2)

Fixed Pydantic serialization issue:
- Changed field names from _cache_hit to cache_hit (without underscore)
- Pydantic excludes underscore-prefixed fields from JSON by default

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 22:39:09 +02:00
87bd04e3ff Enhance Telegram bot UI with YTD comparison, 12-month evolution, and improved navigation
- Add YTD year-over-year comparison table for cash flow evolution
- Extend monthly evolution from 6 to 12 months with dynamic year extraction
- Simplify monthly view to show only Net values aligned with YTD table
- Upgrade client/supplier display from Top 5 to Top 10 with alphabetical sorting
- Remove Refresh and Export buttons from dashboard and evolution views
- Add get_trends() API method for 12-month historical data from backend
- Fix default years to 2025/2024 for accurate YTD calculations

Changes:
- client.py: New get_trends() method calls /api/dashboard/trends endpoint
- helpers.py: Rewrite get_cashflow_evolution_data() to use trends and calculate YTD
- formatters.py: Complete redesign with YTD table and simplified 12-month Net view
- menus.py: Alphabetical sorting for clients/suppliers, removed refresh buttons
- handlers.py: Disabled refresh/export buttons on dashboard and evolution views

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 02:30:28 +02:00
a4ee394091 Implement unified Telegram bot interface with Login/Logout and fix callback_data limits
**Interface improvements:**
- Add persistent Login/Logout buttons to main menu
- Help button now updates text above menu (not separate message)
- Expired token automatically transforms menu to Login state
- Consolidate linking success messages (single welcome + menu)

**Fix callback_data length limits (Telegram 64-byte limit):**
- Truncate client/supplier names to 40 chars in callback_data
- Use full names for API calls but truncated for buttons
- Fix pagination buttons for long partner names (30 chars limit)
- Search entities by prefix match to handle truncated names

**Treasury improvements:**
- Show ALL bank/cash accounts (removed 5-item limit)
- Remove unnecessary Refresh/Export buttons from treasury views
- Handle "Message is not modified" error gracefully

**Bug fixes:**
- Fix Markdown parsing errors (replace <cod> with `CODUL_TAU`)
- Fix silent errors when token expires (show user-friendly message)
- Fix Button_data_invalid errors on pagination and details

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-07 01:02:03 +02:00
20f6c52785 Load .env before app imports to ensure environment variables are available
Move load_dotenv() call before all app.* imports in main.py to fix the
import-time environment variable loading issue.

Problem:
- Previously, load_dotenv() was called AFTER importing app.* modules
- When app.api.client was imported, it read BACKEND_URL at import time
- At that moment, .env was not yet loaded, so it used the hardcoded default
- This caused the bot to connect to wrong backend port even when .env was
  correctly configured

Solution:
- Move load_dotenv() to line 20-21, immediately after standard library imports
- This ensures .env is loaded BEFORE any app.* modules are imported
- Now all modules see the correct environment variables from .env file
- Also updated BACKEND_URL default from 8001 to 8000 for consistency

Flow now:
1. Import standard libraries (os, Path, dotenv, etc.)
2. Load .env file (line 20-21) 
3. Import app.* modules (which can now read env vars correctly) 
4. Import telegram-python-bot and other dependencies
5. Start application

This follows Python best practices for environment variable loading and
ensures reliable configuration loading in Windows Service deployments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 00:43:57 +02:00
10d6ddead9 Fix default BACKEND_URL port from 8001 to 8000 for production
Change hardcoded default backend URL from development port (8001) to
production port (8000) in Telegram bot API client.

This fixes the issue where Telegram bot would try to connect to wrong port
when BACKEND_URL environment variable is not properly loaded from .env file,
causing "Cannot connect to backend" errors during account linking.

Root cause: When .env file is not loaded correctly by Windows Service,
the code falls back to the hardcoded default value which was incorrectly
set to the development port 8001 instead of production port 8000.

Changes:
- reports-app/telegram-bot/app/api/client.py: Change default from 8001 to 8000
- Add comment explaining this is for production deployment

This ensures the bot connects to the correct backend port even if .env
configuration has issues during service startup on Windows Server.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 00:34:30 +02:00
87bda52524 Fix ConnectError handling in Telegram bot API client
Fix AttributeError crash when backend is unreachable during account linking.
Previously, when telegram bot couldn't connect to backend, the error handler
tried to access e.response.status_code on a ConnectError exception which
doesn't have a response attribute.

Changes to reports-app/telegram-bot/app/api/client.py:
- Import ConnectError from httpx
- Add separate exception handler for ConnectError before HTTPError handler
- Log clear error message indicating backend connectivity issue
- Return None gracefully instead of crashing with AttributeError

Changes to deployment/windows/docs/TELEGRAM_BOT_TROUBLESHOOTING.md:
- Add new section "Problem: Cannot connect to backend / Connection Errors"
- Add diagnostic steps for backend service verification
- Add checklist for BACKEND_URL configuration (http://localhost:8000)
- Add Issue 5: Backend Service Not Running
- Add Issue 6: Wrong Backend URL in Telegram Bot
- Include PowerShell commands for Windows Server troubleshooting

This fix ensures the Telegram bot provides clear error messages when backend
is unavailable instead of crashing, making debugging easier for production
deployments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 00:12:57 +02:00
68459b5c7e Add Telegram Bot internal API configuration for Windows deployment
Fix issue where backend cannot communicate with Telegram bot service to save
authentication codes during account linking flow. This caused "link invalid or
expired" errors when users tried to link Telegram accounts.

Changes:
- Add TELEGRAM_BOT_INTERNAL_API environment variable to backend .env.example
  (defaults to http://localhost:8002 for local/Windows deployments)
- Update CLAUDE.md with Telegram Bot integration requirements for Windows
- Add comprehensive troubleshooting guide for Windows deployment at
  deployment/windows/docs/TELEGRAM_BOT_TROUBLESHOOTING.md

The troubleshooting guide includes:
- Diagnostic steps to verify service health and connectivity
- Common issues and solutions (port conflicts, firewall, wrong bot token)
- PowerShell commands for Windows Server administration
- Verification steps for end-to-end testing

This ensures proper backend-to-telegram-bot communication for the auth code
linking workflow in production Windows deployments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-27 00:09:37 +02:00
b97a650fb4 Fix Windows deployment scripts for missing Python dependencies
Issues fixed:
1. Build-Frontend.ps1: Add verification that requirements.txt is included in deployment package
   - Prevents incomplete packages that cause ModuleNotFoundError on server
   - Throws error if critical files are missing before package is transferred

2. Deploy-ROA2WEB.ps1: Auto-detect first deployment and force install dependencies
   - Automatically sets ForceInstallDependencies=true on first deployment
   - Add -ForceInstallDependencies parameter for manual override
   - Better error handling and validation for pip install
   - Shows clear error messages with manual recovery instructions

This fixes the "ModuleNotFoundError: No module named 'httpx'" error that occurred
when deploying to Windows Server without explicitly forcing dependency installation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-26 23:53:56 +02:00
702ca9fa3d Fix SSH tunnel Docker build for Dokploy deployment
Changes:
- Fix Dockerfile COPY path from ../secrets to secrets/ (Docker doesn't allow parent directory access)
- Create ssh-tunnel/secrets/ directory structure with comprehensive README
- Add .dockerignore for ssh-tunnel to optimize build context
- Add DOKPLOY_DEPLOYMENT.md with complete deployment guide including:
  * SSH key configuration options (repository, secrets manager, BuildKit)
  * Environment variables setup
  * Step-by-step deployment instructions
  * Troubleshooting section
  * Security best practices
- Update .gitignore to allow secrets/README.md files for documentation

This resolves the Dokploy build failure: "failed to calculate checksum of ref... /secrets/roa_oracle_server: not found"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-26 21:36:46 +02:00
c56f832e81 Add comprehensive multi-tenant architecture upgrade plan
Creates detailed 60-page implementation roadmap for transforming ROA2WEB from
single-tenant to multi-tenant SaaS architecture. Plan includes 6 phases with
backward compatibility, hybrid connection support (SSH tunnel + direct), and
complete deployment strategies for dev/Docker/Windows environments.

Key features:
- Tenant isolation with separate Oracle connection pools per tenant
- Dynamic SSH tunnel management with auto-restart
- Encrypted credentials in PostgreSQL/SQLite tenant config DB
- JWT-based tenant identification and access validation
- Redis cache namespacing per tenant
- Comprehensive testing and migration strategies

Timeline: 14-20 days implementation
Target: <10% performance overhead, zero downtime migration

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 22:59:12 +03:00
e82b839766 Remove duplicate and outdated documentation files
Cleaned up repository by removing files that were duplicates or
outdated:

Removed documentation (duplicates moved to root docs/):
- docs/DEVELOPMENT_BLUEPRINT.md (outdated)
- docs/PRODUCTION_CHECKLIST.md (outdated)

Removed telegram-bot documentation (superseded by main docs):
- FAZA1_IMPLEMENTATION_SUMMARY.md (implementation completed)
- TELEGRAM_COMMANDS.md (now in main README)
- TELEGRAM_UI_REFACTOR_PLAN.md (refactor completed)

Removed root test files (moved to tests/ directory):
- test_claude_integration.py → tests/test_claude_integration.py
- test_claude_response.py → tests/test_claude_response.py
- test_db.py → tests/test_db.py

All content is preserved in proper locations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 15:27:15 +03:00
0c782fc1e7 Add configuration template files (.env.example, .dockerignore)
Added essential configuration templates that were missing from the
repository due to overly restrictive .gitignore patterns.

Changes to .gitignore:
- Added negation patterns for .env.example files
- Added negation patterns for .dockerignore files
- These are safe template files with placeholder values

Files added:
- .env.example (root): Main environment configuration template
- reports-app/backend/.env.example: Backend configuration template
- reports-app/frontend/.env.example: Frontend configuration template
- reports-app/telegram-bot/.env.example: Telegram bot config template
- reports-app/telegram-bot/.dockerignore: Docker build exclusions

These template files help developers quickly set up their local
development environment by copying and customizing them.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 15:26:47 +03:00
a7a1bef375 Add missing test files and update .gitignore to allow test files
This commit addresses the overly restrictive .gitignore pattern that
was excluding all test files (test_*.py), including legitimate pytest
and unittest test suites essential for code quality and CI/CD.

Changes to .gitignore:
- Added negation patterns !**/tests/test_*.py and !**/test_*.py
  to allow proper test files while still blocking temporary scripts
- This enables pytest test suites to be tracked by git

Added test files (17 files):

Telegram Bot Tests (15 files):
- reports-app/telegram-bot/tests/test_auth.py
  Tests for authentication and account linking flow
- reports-app/telegram-bot/tests/test_callbacks.py
  Tests for callback query handlers
- reports-app/telegram-bot/tests/test_formatters.py
  Tests for message formatting utilities
- reports-app/telegram-bot/tests/test_formatters_extended.py
  Extended formatter tests
- reports-app/telegram-bot/tests/test_handlers_menu.py
  Tests for menu handlers
- reports-app/telegram-bot/tests/test_helpers.py
  Tests for helper functions
- reports-app/telegram-bot/tests/test_helpers_extended.py
  Extended helper tests
- reports-app/telegram-bot/tests/test_helpers_real.py
  Real integration tests for helpers
- reports-app/telegram-bot/tests/test_helpers_real_simple.py
  Simplified integration tests
- reports-app/telegram-bot/tests/test_login_flow.py
  Complete login flow integration tests
- reports-app/telegram-bot/tests/test_menus.py
  Menu system tests
- reports-app/telegram-bot/tests/test_session_company.py
  Session and company management tests
- reports-app/telegram-bot/test_claude_integration.py
  Manual integration test (Claude AI)
- reports-app/telegram-bot/test_claude_response.py
  Response formatting test
- reports-app/telegram-bot/test_db.py
  Database operations manual test

Shared Module Tests (2 files):
- shared/auth/test_auth.py
  Authentication system tests
- shared/database/test_pool.py
  Oracle connection pool tests

Security verification:
 All test files use mock objects, fixtures, and environment variables
 No hardcoded credentials or secrets found
 Safe for version control

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 15:09:43 +03:00
f42eff71a6 Fix .gitignore and add missing authentication source files
This commit fixes overly broad .gitignore patterns that were excluding
important source code files from version control. Previously, wildcard
patterns like *auth*, *token*, *secret*, *connection*, and *credential*
were excluding ALL files containing these words, including critical
application code.

Changes:
- Updated .gitignore with specific patterns for sensitive config files
  (*.json, *.txt, *.yml, *.yaml extensions only)
- Removed broad wildcards that excluded source code files

Added missing source files:
- shared/auth/ (9 files): Complete authentication system
  - JWT handler, middleware, auth service, models, routes
- reports-app/backend/app/routers/auth.py: Authentication API router
- reports-app/backend/app/auth_middleware_wrapper.py: Middleware wrapper
- reports-app/frontend/src/stores/auth.js: Vue.js auth store
- reports-app/frontend/tests/: E2E tests and fixtures for auth
- reports-app/telegram-bot/app/auth/: Telegram auth linking module
- deployment/windows/scripts/Setup-ClaudeAuth.ps1: Windows deployment script
- security/secrets_scanner.py: Security scanning utility

These files are essential for the application to function and should
have been included in the initial commit.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 15:02:28 +03:00
6b13ffa183 Initial commit: ROA2WEB - FastAPI + Vue.js + Telegram Bot
Modern ERP Reports Application with microservices architecture

Tech Stack:
- Backend: FastAPI + python-oracledb (Oracle DB integration)
- Frontend: Vue.js 3 + PrimeVue + Vite
- Telegram Bot: python-telegram-bot + SQLite
- Infrastructure: Shared database pool, JWT authentication, SSH tunnel

Features:
- FastAPI backend with async Oracle connection pool
- Vue.js 3 responsive frontend with PrimeVue components
- Telegram bot alternative interface
- Microservices architecture with shared components
- Complete deployment support (Linux Docker + Windows IIS)
- Comprehensive testing (Playwright E2E + pytest)

Repository Structure:
- reports-app/ - Main application (backend, frontend, telegram-bot)
- shared/ - Shared components (database pool, auth, utils)
- deployment/ - Deployment scripts (Linux & Windows)
- docs/ - Project documentation
- security/ - Security scanning and git hooks
2025-10-25 14:55:08 +03:00