# CLAUDE.md - AI Coding Assistant Guidelines

## Core Principles
- **Structured Code First**: Write code that is well-organized from the start to avoid future refactoring
- **YAGNI (You Aren't Gonna Need It)**: Only implement what is currently needed, not what might be needed

## Project Structure
```
v2_adminpanel/
├── routes/          # Blueprint route handlers
├── templates/       # Jinja2 templates
├── utils/          # Utilities
├── leads/          # CRM module (service/repository pattern)
├── core/           # Error handling, logging, monitoring
└── middleware/     # Request processing
```

## Database Schema Reference

### Key Database Tables

Refer to `v2_adminpanel/init.sql` for complete schema. Important tables:
- `license_heartbeats` - Partitioned by month, NO response_time column
- `license_sessions` - Active sessions (UNIQUE per license_id)
- `session_history` - Audit trail with end_reason
- `client_configs` - API configuration for Account Forger
- `system_api_key` - Global API key management

Additional tables: customers, licenses, users, audit_log, lead_*, resource_pools, activations, feature_flags, rate_limits

## Template Parameter Contracts

### error.html
```python
render_template('error.html',
    error='Error message',        # NOT error_message!
    details='Optional details',   # Optional
    error_code=404,              # Optional
    request_id='uuid'            # Optional
)
```

### Common Template Parameters
- All templates expect `current_user` in session context
- Use `error` not `error_message` for error displays
- Flash messages use categories: 'success', 'error', 'warning', 'info'

## Pre-Implementation Checklist

### Pre-Implementation Checklist
- Check existing routes: `grep -r "route_name" .`
- Verify template parameters match expectations
- Confirm table/column exists in init.sql
- Use RealDictCursor and handle cleanup in finally blocks
- Check leads/ for existing repository methods

### Before Modifying Templates
- [ ] Check which routes use this template
- [ ] Verify all passed parameters are used
- [ ] Maintain consistent styling with existing templates

## Common Patterns

### Error Handling
```python
try:
    # operation
except Exception as e:
    logger.error(f"Error in operation: {str(e)}")
    return render_template('error.html', 
                         error='Specific error message',
                         details=str(e))
```

### Database Connections
```python
conn = get_db_connection()
cur = conn.cursor(cursor_factory=RealDictCursor)
try:
    # queries
    conn.commit()
finally:
    cur.close()
    conn.close()
```

### API Authentication
```python
# Check API key
api_key = request.headers.get('X-API-Key')
if not api_key or not verify_api_key(api_key):
    return jsonify({'error': 'Invalid API key'}), 401
```

### Session Management
```python
# For user sessions
if 'user_id' not in session:
    return redirect(url_for('auth.login'))

# For 2FA
if session.get('requires_2fa'):
    return redirect(url_for('auth.verify_2fa'))
```

## Testing & Verification

### Check Logs
```bash
docker-compose logs admin-panel | tail -50
```

### Verify Container Status
```bash
docker-compose ps
```

### Common Issues to Avoid
1. **Parameter Mismatches**: Verify template expectations (use `error` not `error_message`)
2. **Missing Columns**: Check schema before queries
3. **Creating Unnecessary Files**: Check if functionality exists first
4. **Missing Audit Logs**: Add audit_log entries for important actions
5. **Hardcoded Values**: Use config.py or environment variables

## Docker Environment
Container names: v2_admin_panel, v2_license_server, v2_postgres, v2_redis, v2_rabbitmq, v2_nginx
Public access: Port 80 via Nginx

## Code Style Rules
- NO comments unless explicitly requested
- Follow existing patterns in the codebase
- Use existing utilities before creating new ones
- Maintain consistent error handling
- Always use absolute paths for file operations

## YAGNI Reminders
- Don't add features "for the future"
- Don't create generic solutions for single use cases
- Don't add configuration options that aren't needed now
- Don't abstract code that's only used once
- Implement exactly what's requested, nothing more

## Recent Updates

### June 22, 2025 - 20:26
- Added Lead Management to main navigation (above Ressourcen Pool)
- Created Lead Management dashboard with:
  - Overview statistics (institutions, contacts, user attribution)
  - Recent activity feed showing who added/edited what
  - Quick actions (add institution, view all, export)
  - Shared information view between users rac00n and w@rh@mm3r
- Route: `/leads/management` accessible via navbar "Lead Management"

## Last Updated: June 22, 2025