# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## πŸš€ Project Overview **ROA2WEB** - Modern ERP Application with two main modules: 1. **Reports App** (`reports-app/`) - Read-only reports from Oracle (raportΔƒri) 2. **Data Entry App** (`data-entry-app/`) - Data input with approval workflow (introduceri date) **Main Branch**: `main` (use for PRs) **Working Directory**: Repository root **Quick Reference**: See `README.md` for complete setup, commands, deployment, and testing instructions. --- ## πŸ“ Application-Specific Instructions > **IMPORTANT**: When working on a specific application, ALWAYS read its dedicated CLAUDE.md first! | Application | CLAUDE.md Location | Description | |-------------|-------------------|-------------| | **Data Entry** | `data-entry-app/CLAUDE.md` | Bonuri fiscale, chitanΘ›e, workflow aprobare | | **Reports** | This file (below) | Rapoarte Oracle read-only | | **Telegram Bot** | `reports-app/telegram-bot/README.md` | Bot Telegram | ### When to Use Which Instructions **Working on `data-entry-app/`**: β†’ **FIRST read `data-entry-app/CLAUDE.md`** for: - SQLModel + Alembic patterns (NOT Oracle) - SQLite database (NOT Oracle pool) - Workflow states (DRAFT β†’ PENDING β†’ APPROVED) - Receipt/Attachment/AccountingEntry models - Expense types and auto-generation logic **Working on `reports-app/` or `shared/`**: β†’ Use instructions from this file (below) **Working on shared components** (`shared/auth/`, `shared/database/`, `shared/frontend/`): β†’ These are used by BOTH apps - be careful with changes! β†’ `shared/frontend/` contains: LoginView.vue, auth store factory, login styles --- ## πŸ—οΈ Architecture ### Microservices Structure ``` . β”œβ”€β”€ shared/ # Shared components (DB pool, auth, frontend) β”‚ β”œβ”€β”€ database/ # Oracle pool (used by both apps) β”‚ β”œβ”€β”€ auth/ # JWT auth (used by both apps) β”‚ └── frontend/ # Shared Vue components, stores, styles β”‚ β”œβ”€β”€ components/ # LoginView.vue β”‚ β”œβ”€β”€ stores/ # auth.js (Pinia store factory) β”‚ └── styles/ # login.css β”‚ β”œβ”€β”€ reports-app/ # READ-ONLY reports from Oracle β”‚ β”œβ”€β”€ backend/ # FastAPI API (port 8001) β”‚ β”œβ”€β”€ frontend/ # Vue.js 3 UI (port 3000-3005) β”‚ └── telegram-bot/ # Telegram bot (port 8002 internal) β”‚ β”œβ”€β”€ data-entry-app/ # DATA INPUT with approval workflow β”‚ β”œβ”€β”€ backend/ # FastAPI API (port 8003) - SQLite + SQLModel β”‚ β”œβ”€β”€ frontend/ # Vue.js 3 UI (port 3010) β”‚ └── CLAUDE.md # ⚠️ READ THIS for data-entry work! β”‚ β”œβ”€β”€ docs/ # Architecture & style guides β”œβ”€β”€ deployment/ # Production deployment scripts └── ssh-tunnel/ # SSH tunnel for Oracle DB access ``` ### Starting Services **Quick Start** (All services with parallel backend startup): ```bash ./start-dev.sh # Dev: Backend :8001, :8003, Bot :8002, Frontend :3000 (~11s) ./start-test.sh # Test: Same ports (~33s - Oracle pool init takes longer) ``` **Individual Service Control** (for quick development iterations): ```bash ./frontend.sh restart # Restart frontend only (~7s - fastest!) ./backend-reports.sh start # Start Reports backend :8001 ./backend-data-entry.sh stop # Stop Data Entry backend :8003 ./bot.sh status # Check Telegram bot :8002 status ./status.sh # Show all services status + health checks ``` **Infrastructure**: ```bash ./ssh_tunnel.sh start # Oracle DB tunnel (production: 10.0.20.36) ./ssh-tunnel-test.sh start # Oracle TEST tunnel (LXC: 10.0.20.121) ``` **Benefits**: - **87% faster frontend restart**: 7s vs 53s full restart - **38% faster full startup**: 33s vs 53s (test) via parallel backend init - **Granular control**: Restart individual services without affecting others ### Key Architectural Decisions - **Shared Database Pool**: Singleton `OraclePool` in `shared/database/oracle_pool.py` (python-oracledb with connection pooling) - **Centralized Auth**: JWT-based auth in `shared/auth/` with middleware auto-injecting `request.state.user` - **Two-Tier Cache System**: Hybrid L1 (Memory) + L2 (SQLite) cache in `backend/app/cache/` - **MANDATORY for all new endpoints** - **SSH Tunnel**: Required for Oracle DB connections (development/Linux) - see Database Setup - **FastAPI Structure**: Services in `backend/app/services/` with `@cached` decorator, routers in `backend/app/routers/`, models in `backend/app/models/` or `schemas/` - **Telegram Bot**: Standalone SQLite database for bot data, communicates with backend via HTTP API --- ## πŸ—„οΈ Database Setup **Schema**: `CONTAFIN_ORACLE` (authentication and user management) **Connection**: SSH tunnel required (Oracle on remote network) ### SSH Tunnel (Development/Linux) ```bash ./ssh_tunnel.sh start # localhost:1526 β†’ remote:1521 ./ssh_tunnel.sh status # Check tunnel ./ssh_tunnel.sh stop # Stop tunnel ``` **IMPORTANT**: Always ensure SSH tunnel is running before starting backend services. ### Environment Variables (`reports-app/backend/.env`) ```bash # Oracle Database (through SSH tunnel) ORACLE_USER=CONTAFIN_ORACLE ORACLE_PASSWORD=your_password ORACLE_HOST=localhost ORACLE_PORT=1526 ORACLE_SID=ROA # JWT Authentication JWT_SECRET_KEY=your_secret_key JWT_ALGORITHM=HS256 JWT_EXPIRE_MINUTES=30 # Telegram Bot Integration TELEGRAM_BOT_INTERNAL_API=http://localhost:8002 ``` **Windows Production**: Direct Oracle connection, no SSH tunnel required. Ensure `TELEGRAM_BOT_INTERNAL_API` is set for auth code management. --- ## πŸ”‘ Authentication Flow 1. **Login**: `POST /api/auth/login` β†’ calls `pack_drepturi.verificautilizator(username, password)` 2. **Token**: JWT includes `username`, `user_id`, `companies[]`, `permissions[]`, `exp`, `iat`, `type` 3. **Middleware**: `AuthenticationMiddleware` in `shared/auth/middleware.py` validates tokens, injects user 4. **Protected Routes**: All routes except `excluded_paths` require valid JWT **Key Files**: - `shared/auth/middleware.py` - FastAPI middleware with rate limiting (5 req/5 min) - `shared/auth/jwt_handler.py` - Token creation/validation - `reports-app/backend/app/main.py` - Auth router inline definition --- ## πŸ“ Common Development Tasks ### Adding a New API Endpoint **IMPORTANT**: Always use the cache system for database queries to improve performance. 1. Create **service** in `reports-app/backend/app/services/your_service.py` (NOT in router!) 2. Define Pydantic schemas in `app/schemas/` or `app/models/` 3. **Add caching** using `@cached` decorator in service methods 4. Create router in `reports-app/backend/app/routers/your_router.py` (calls service) 5. Register router in `app/main.py`: `app.include_router(your_router, prefix="/api/your_prefix")` **Service Example with Caching** (RECOMMENDED): ```python # app/services/your_service.py from app.cache.decorators import cached from database.oracle_pool import oracle_pool class YourService: @staticmethod @cached(cache_type='schema', key_params=['company_id']) async def _get_schema(company_id: int) -> str: """Get schema for company (CACHED 24h)""" async with oracle_pool.get_connection() as connection: with connection.cursor() as cursor: cursor.execute(""" SELECT schema FROM CONTAFIN_ORACLE.v_nom_firme WHERE id_firma = :company_id """, {'company_id': company_id}) result = cursor.fetchone() return result[0] if result else None @staticmethod @cached(cache_type='your_data', key_params=['filter_params', 'username']) async def get_your_data(filter_params: YourFilter, username: str) -> YourResponse: """ Get your data from Oracle (CACHED 10 min) Cache automatically: - Generates unique key from filter_params + username - Stores in L1 (memory) + L2 (SQLite) - Returns cached data on subsequent calls - Tracks performance metrics """ schema = await YourService._get_schema(filter_params.company_id) async with oracle_pool.get_connection() as connection: with connection.cursor() as cursor: cursor.execute(f""" SELECT * FROM {schema}.your_table WHERE your_condition = :param """, {'param': filter_params.param}) rows = cursor.fetchall() # Process results... return YourResponse(data=processed_data) ``` **Router Example** (calls service): ```python # app/routers/your_router.py from app.services.your_service import YourService @router.get("/", response_model=YourResponse) async def get_your_data( filter_params: YourFilter = Depends(), current_user: CurrentUser = Depends(get_current_user) ): """Get your data - delegated to service with caching""" return await YourService.get_your_data(filter_params, current_user.username) ``` **Cache Configuration** (add to `app/cache/config.py` if new cache type): ```python # Add TTL for your cache type ttl_your_data: int = int(os.getenv('CACHE_TTL_YOUR_DATA', '600')) # 10 min default # Add to get_ttl_for_type() method: 'your_data': self.ttl_your_data, ``` **Cache Best Practices**: - βœ… Use `@cached` decorator for ALL database queries - βœ… Place logic in services (NOT routers) - βœ… Cache schema lookups separately (long TTL: 24h) - βœ… Choose appropriate TTL (frequently changing data: 5-10 min, static data: 30 min - 24h) - βœ… Include `username` in `key_params` for user-specific data - βœ… Include filter parameters in `key_params` for query variations - ❌ Don't query Oracle directly in routers (use services with caching) - ❌ Don't skip caching for performance-critical endpoints ### Adding a New Frontend Page/Component **IMPORTANT**: Follow the established CSS architecture and design system. **Before writing ANY CSS**: Read **`docs/ONBOARDING_CSS.md`** (5-minute quick start) β†’ See "Documentation Index" below for complete guide list. **Golden Rules**: - βœ… Use global patterns first (`.roa-card`, `.roa-metric`, `.roa-badge-*`) - check `CSS_PATTERNS.md` - βœ… Use design tokens (`var(--color-primary)`) not hardcoded values (`#2563eb`) - βœ… **Use shared CSS** from `src/assets/css/` - NEVER create new CSS when shared classes exist - βœ… For inline stats/totals use `.summary-stats-inline`, `.stat-item`, `.stat-label`, `.stat-value` from `stats.css` - ❌ Never use `:deep()` in components (use `src/assets/css/vendor/` for PrimeVue overrides) - ❌ Never duplicate CSS (write once, use everywhere) - ❌ Never add new scoped CSS for patterns that already exist in shared CSS files **Tables - Unified Column Structure & Filter Buttons**: - βœ… **ALWAYS use separate columns** for related data (Debit | Credit, not Debit+Credit stacked) - βœ… **Use PrimeVue DataTable** with one value per `` component - βœ… **Add filter/action buttons** (clear, export Excel, export PDF, refresh) **on separate row below filters** - βœ… **PrimeVue Button** components with **icon + label** (not icon-only!) - βœ… **Export ALL data** from backend (page_size: 999999), not just current page - ❌ **Never group multiple values** vertically in a single column - ❌ **Never use HTML `