# ROA2WEB Telegram Bot

> ⚠️ **ARCHITECTURE NOTE**
>
> This documentation partially references the old standalone bot architecture.
> The current architecture is an **ultrathin monolith** where the Telegram bot runs
> as a background task within the main backend (`backend/main.py`) on port 8000/8001.
> The `INTERNAL_API_PORT` variable is no longer used - internal API is at `/api/telegram/internal/*`.

> **Telegram Frontend for ROA2WEB ERP System** with Direct Command Interface

## Overview

ROA2WEB Telegram Bot provides a command-based interface to the ROA2WEB Financial ERP system through Telegram. Users can access dashboards, invoices, treasury data, and company information using simple slash commands.

### Key Features

- **Direct Command Interface**: Simple `/` commands for all operations
- **Simplified Authentication** 🆕: Multiple linking methods (Deep Link, QR Code, Manual) - 77% faster than before!
- **One-Click Connection**: Deep link automatically opens Telegram with pre-populated code
- **QR Code Support**: Scan from mobile to link instantly (cross-device)
- **Secure Authentication**: Account linking with Oracle backend and JWT token management
- **Financial Data Access**: Query dashboards, invoices, treasury data, and company information
- **Company Selection**: Set active company for all subsequent queries
- **Multi-language**: Romanian and English support
- **Session Management**: Active company persistence with SQLite database
- **Docker Ready**: Containerized deployment with Docker Compose

## Architecture

### System Components

```
telegram-bot/
├── app/
│   ├── agent/                # Session management
│   │   └── session.py       # Active company persistence
│   ├── api/                  # Backend API client
│   │   └── client.py        # HTTP client for ROA2WEB backend
│   ├── auth/                 # Authentication & linking
│   │   └── linking.py       # Account linking logic
│   ├── bot/                  # Telegram bot handlers
│   │   ├── handlers.py      # Command handlers
│   │   ├── helpers.py       # Helper functions
│   │   ├── formatters.py    # Response formatting
│   │   └── keyboards.py     # Inline keyboard helpers
│   ├── db/                   # SQLite database (standalone)
│   │   ├── database.py      # Connection & schema
│   │   └── operations.py    # CRUD operations
│   ├── internal_api.py       # FastAPI for backend communication
│   └── main.py               # Main entry point
├── data/                     # SQLite database storage (gitignored)
├── tests/                    # Unit & integration tests
├── Dockerfile                # Container configuration
├── requirements.txt          # Python dependencies
└── .env.example              # Environment variables template
```

### Data Flow

1. **User sends command** → Telegram → Bot Command Handlers
2. **Authentication check** → SQLite database → JWT validation
3. **API calls** → ROA2WEB Backend → Oracle database
4. **Response formatting** → Telegram user

### Database Schema (SQLite)

The bot uses a standalone SQLite database for:

- **telegram_users**: User accounts and Oracle account linking
- **telegram_auth_codes**: Temporary 8-character linking codes (15 min expiry)
- **telegram_sessions**: Active company selection and session state

## Installation & Setup

### Prerequisites

- Python 3.11+
- Telegram account
- ROA2WEB backend API running (default: http://localhost:8001)

### Step 1: Create Telegram Bot

1. Open Telegram and search for `@BotFather`
2. Send `/newbot` command
3. Follow prompts to create bot
4. Save the bot token provided

### Step 2: Install Dependencies

```bash
# Navigate to telegram-bot directory
cd backend/modules/telegram

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate  # Linux/Mac
# or
venv\Scripts\activate     # Windows

# Install dependencies
pip install -r requirements.txt
```

### Step 3: Configure Environment

```bash
# Copy environment template
cp .env.example .env

# Edit .env file with your configuration
nano .env
```

Required configuration in `.env`:

```bash
# Required
TELEGRAM_BOT_TOKEN=your_bot_token_from_botfather
BACKEND_URL=http://localhost:8001

# Database
SQLITE_DB_PATH=./data/telegram_bot.db

# Internal API - DEPRECATED (now served via main backend at /api/telegram/internal/*)
# INTERNAL_API_PORT=8002

# Optional
LOG_LEVEL=INFO
SENTRY_DSN=https://your-sentry-dsn
ENVIRONMENT=production
```

### Step 4: Run the Bot

```bash
# Make sure backend is running first
# Backend should be at http://localhost:8001 (or configured BACKEND_URL)

# Run the bot
python -m app.main
```

## Usage

### Available Commands

| Command | Description |
|---------|-------------|
| `/start [code]` | Start bot or link account with 8-char code |
| `/help` | Show available commands and usage guide |
| `/companies` | View accessible companies/firms |
| `/selectcompany [name]` | Select or search for active company |
| `/dashboard` | View financial dashboard for active company |
| `/sold` | View balance (alias for `/dashboard`) |
| `/facturi [filter]` | View invoices (optional filters: neplatite, platite) |
| `/trezorerie` | View treasury/payment data |
| `/clear` | Clear active company selection |
| `/unlink` | Unlink Telegram account from Oracle |

### Authentication Flow (Updated 2025 - FAZA 1 Improvements)

The bot now supports **3 easy methods** for account linking:

#### Method 1: Deep Link (Recommended - One Click) 🚀

1. **Login** to ROA2WEB web application at http://localhost:3000
2. **Navigate** to `/telegram` (Settings → Telegram)
3. **Click** "Generează Cod" button
4. **Click** "🚀 Deschide în Telegram" button
5. **Telegram opens automatically** with code pre-populated
6. **Done!** Account linked in <30 seconds

**Benefits:**
- ⚡ **Zero manual copying** - code is pre-filled
- 🎯 **One click** - Telegram opens automatically
- ⏱️ **Super fast** - complete in ~30 seconds
- 📱 **Works on desktop and mobile** (same device)

#### Method 2: QR Code (Cross-Device) 📷

Perfect when working on desktop but have Telegram on mobile:

1. **Login** to ROA2WEB web app (desktop)
2. **Navigate** to `/telegram`
3. **Click** "Generează Cod"
4. **Scan QR Code** displayed on screen with Telegram on mobile
5. **Telegram opens** with code pre-populated
6. **Done!** Account linked

**Benefits:**
- 📱 **Cross-device** - desktop browser → mobile Telegram
- 📷 **Easy scanning** - just point camera at screen
- ✅ **No typing** - code automatically loaded

#### Method 3: Manual (Traditional Fallback) ⌨️

If deep link or QR code don't work:

1. **Login** to ROA2WEB web application
2. **Navigate** to `/telegram`
3. **Click** "Generează Cod"
4. **Click** copy button (📋) to copy code
5. **Open Telegram** manually
6. **Send code** to bot:
   - **Direct input**: `ABC123XY` (just paste)
   - **Classic format**: `/start ABC123XY`
7. **Done!** Account linked

**Technical Details:**
- Backend generates **8-character code** (valid 15 minutes)
- Backend saves code to telegram-bot via internal API (`POST /internal/save-code`)
- Bot verifies code and links accounts in SQLite database
- Bot receives **JWT token** from backend
- User can now use commands to query financial data

**Improvement Metrics:**
- ⏱️ Time: **3 minutes → 40 seconds** (77% reduction)
- 📉 Steps: **7 → 4** (43% reduction)
- ✅ Manual copying: **Eliminated** (with Method 1 or 2)

### Usage Examples

```
User: /companies
Bot: Lists all accessible companies with ID, name, and CUI

User: /selectcompany ACME
Bot: Shows selection keyboard for companies matching "ACME"
[User clicks company button]
Bot: Company selected: ACME SRL

User: /dashboard
Bot: Displays dashboard statistics for ACME SRL:
     - Total balance
     - Invoices issued/paid/unpaid
     - Total collections and payments

User: /facturi neplatite
Bot: Shows list of unpaid invoices for ACME SRL

User: /trezorerie
Bot: Displays treasury data (cash balance, bank accounts, etc.)

User: /clear
Bot: Active company cleared. Use /selectcompany to select another.
```

## Docker Deployment

### Build Image

```bash
# From telegram-bot directory
docker build -t roa-telegram-bot .
```

### Run Container

```bash
docker run -d \
  --name roa-telegram-bot \
  -e TELEGRAM_BOT_TOKEN=your_token \
  -e BACKEND_URL=http://backend:8001 \
  -v $(pwd)/data:/app/data \
  roa-telegram-bot
```

### Docker Compose

See `docker-compose.yml` in project root for full orchestration with backend and database.

## Development

### Project Structure

- **app/main.py**: Bot entry point and Telegram application setup
- **app/bot/handlers.py**: All command handlers (`/start`, `/dashboard`, etc.)
- **app/bot/helpers.py**: Helper functions for company selection and prompts
- **app/bot/formatters.py**: Response formatting utilities
- **app/auth/linking.py**: Account linking and JWT management
- **app/api/client.py**: HTTP client for backend API calls
- **app/agent/session.py**: Session management (active company persistence)
- **app/db/**: SQLite database operations
- **app/internal_api.py**: FastAPI for backend callbacks

### Running Tests

```bash
# Run all tests
pytest tests/ -v

# Run specific test suites
pytest tests/test_auth.py -v           # Authentication tests
pytest tests/test_session_company.py -v # Session & company tests
pytest tests/test_helpers.py -v        # Helper function tests
pytest tests/test_formatters.py -v     # Formatter tests

# Run with coverage
pytest tests/ --cov=app --cov-report=html
```

### Adding New Commands

1. Add handler function in `app/bot/handlers.py`:
```python
async def my_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # Implementation
    pass
```

2. Register handler in `app/main.py`:
```python
application.add_handler(CommandHandler("mycommand", my_command))
```

3. Add to `__all__` export in `handlers.py`

## User Experience Improvements (2025)

### FAZA 1: Authentication Simplification ✅

**Implemented:** January 2025
**Status:** Production Ready

**What Changed:**
- Added **Deep Link** button - one-click Telegram opening
- Added **QR Code** generation for cross-device linking
- Improved **Manual method** with copy button
- Reduced linking time by **77%** (3 min → 40 sec)
- Reduced steps by **43%** (7 → 4 steps)

**Documentation:**
- **Complete Plan:** [TELEGRAM_AUTH_IMPROVEMENT_PLAN.md](./TELEGRAM_AUTH_IMPROVEMENT_PLAN.md)
- **Testing Guide:** [TESTING_INSTRUCTIONS_FAZA1.md](./TESTING_INSTRUCTIONS_FAZA1.md)
- **Implementation Summary:** [FAZA1_IMPLEMENTATION_SUMMARY.md](./FAZA1_IMPLEMENTATION_SUMMARY.md)

**Frontend Changes:**
- `src/modules/reports/views/TelegramView.vue` - Complete UI refactor
- Added `qrcode.vue` dependency for QR generation
- Environment variable: `VITE_TELEGRAM_BOT_USERNAME`

### FAZA 2: Email Magic Link (Optional - Future)

**Status:** Planned
**Estimated:** 3.5 hours development

**What's Planned:**
- Email with magic link option
- Professional HTML email template
- Auto-detect SMTP configuration
- Checkbox "Send code via email"

**Prerequisites:**
- SMTP server configuration (Gmail, SendGrid, AWS SES)
- User email addresses in Oracle database

**Note:** FAZA 2 is completely optional. FAZA 1 provides excellent UX for most users.

## Troubleshooting

### Bot Not Responding

- Check bot is running: `ps aux | grep python.*main.py`
- Check logs: `tail -f logs/telegram-bot.log`
- Verify TELEGRAM_BOT_TOKEN is correct
- Ensure backend is accessible at BACKEND_URL

### Authentication Issues

- Check auth code expiry (15 minutes)
- Verify backend internal API is accessible (port 8002)
- Check SQLite database permissions
- **Deep Link not working?** Browser may block protocol handler - click "Allow" when prompted
- **QR Code not scanning?** Ensure good lighting and camera focus
- **Manual method always works** as fallback

### Database Issues

- Ensure `data/` directory exists and is writable
- Check database file: `sqlite3 data/telegram_bot.db ".schema"`
- Automatic cleanup runs hourly for expired data

### Deep Link Issues (FAZA 1)

**Problem:** Deep link button doesn't open Telegram

**Solutions:**
1. **Desktop:** Browser may ask permission - click "Allow" to open Telegram
2. **Mobile:** Ensure Telegram app is installed
3. **Fallback:** Use QR Code (Method 2) or Manual (Method 3)

**Browser Compatibility:**
- ✅ Chrome/Edge - Works perfectly
- ⚠️ Firefox - May show permission prompt
- ⚠️ Safari - May show permission prompt
- ✅ Mobile browsers - Works on all major browsers

**Problem:** QR Code doesn't display

**Solutions:**
1. Check browser console for errors (F12)
2. Ensure `qrcode.vue` package is installed: `npm list qrcode.vue`
3. Rebuild frontend: `cd frontend && npm run build`
4. **Fallback:** Use Manual method (always works)

## API Integration

The bot communicates with ROA2WEB backend via HTTP API:

- `POST /api/telegram/auth/verify-user` - Verify user_id
- `POST /api/telegram/auth/refresh-token` - Refresh JWT
- `GET /api/companies` - Get user companies
- `GET /api/dashboard/{company_id}` - Dashboard data
- `GET /api/invoices/{company_id}` - Invoice list
- `GET /api/treasury/{company_id}` - Treasury data

All requests include JWT token in Authorization header (except verify-user endpoint).

## Security

- JWT tokens are stored encrypted in SQLite
- Auth codes expire after 15 minutes
- Sessions are automatically cleaned up
- Environment variables never committed to git
- Rate limiting on authentication endpoints

## License

See main project LICENSE file.

## Support

For issues, questions, or contributions, see the main ROA2WEB project documentation.
