# JIRA AI Fixer v2.0 - Installation Guide

## Overview

JIRA AI Fixer is an enterprise AI-powered platform that automatically analyzes issues from JIRA, ServiceNow, GitHub, GitLab and other platforms, generates root cause analysis, and creates Pull Requests with fixes.

## Architecture

```
┌─────────────┐     ┌──────────────┐     ┌────────────┐
│   Frontend   │────▶│   Backend    │────▶│ PostgreSQL │
│  (Nginx)     │     │  (FastAPI)   │     │            │
│  React SPA   │     │  Python 3.11 │     └────────────┘
└─────────────┘     └──────┬───────┘
                           │
                    ┌──────▼───────┐
                    │    Redis     │
                    │  (Queue)     │
                    └──────────────┘
```

### Tech Stack

**Backend:**
- Python 3.11 + FastAPI
- PostgreSQL (async via SQLAlchemy + asyncpg)
- Redis (job queue)
- JWT Authentication
- Resend (email notifications)

**Frontend:**
- React 18 + Vite
- TailwindCSS + shadcn/ui components
- React Query (data fetching)
- Recharts (analytics)
- React Router (SPA routing)

---

## Prerequisites

- Docker & Docker Compose (or Docker Swarm)
- PostgreSQL 14+ (or use existing instance)
- Redis (or use existing instance)
- A domain with SSL (recommended)

---

## Quick Start (Docker Compose)

### 1. Clone the repository

```bash
git clone https://gitea.startdata.com.br/startdata/jira-ai-fixer.git
cd jira-ai-fixer
```

### 2. Configure environment

```bash
cp .env.example .env
```

Edit `.env` with your settings:

```env
# Database
DATABASE_URL=postgresql+asyncpg://postgres:postgres@db:5432/jira_fixer

# Redis
REDIS_URL=redis://redis:6379/0

# Security (generate with: openssl rand -hex 32)
SECRET_KEY=your-secret-key-here
JWT_SECRET=your-jwt-secret-here

# Email (optional - Resend.com)
RESEND_API_KEY=re_xxxxx
EMAIL_FROM=JIRA AI Fixer <noreply@yourdomain.com>

# AI Analysis (optional - OpenRouter.ai)
OPENROUTER_API_KEY=sk-or-xxxxx

# Git Integration (optional - Gitea/GitHub)
GITEA_URL=https://gitea.yourdomain.com
GITEA_TOKEN=your-token

# OAuth Integrations (optional)
JIRA_CLIENT_ID=
JIRA_CLIENT_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
```

### 3. Start with Docker Compose

```bash
docker compose up -d
```

### 4. Access the application

- **Frontend:** http://localhost (or your domain)
- **API Docs:** http://localhost/api/docs
- **Health Check:** http://localhost/api/health

---

## Production Deployment (Docker Swarm + Traefik)

### 1. Create the stack file

```yaml
version: '3.8'

services:
  api:
    image: python:3.11-slim
    command: >
      bash -c "
        apt-get update && apt-get install -y curl &&
        pip install fastapi uvicorn[standard] sqlalchemy[asyncio] asyncpg
        pydantic[email] pydantic-settings python-jose[cryptography]
        passlib[bcrypt] httpx python-multipart email-validator &&
        mkdir -p /app && cd /app &&
        curl -sL 'https://gitea.yourdomain.com/org/jira-ai-fixer/archive/master.tar.gz' |
        tar xz --strip-components=1 &&
        uvicorn app.main:app --host 0.0.0.0 --port 8000
      "
    environment:
      - DATABASE_URL=postgresql+asyncpg://user:pass@db_host:5432/jira_fixer
      - REDIS_URL=redis://redis_host:6379
      - JWT_SECRET=your-jwt-secret
      - RESEND_API_KEY=re_xxxxx
      - APP_URL=https://jira-fixer.yourdomain.com
    networks:
      - internal
      - db_network
    deploy:
      replicas: 1
      restart_policy:
        condition: on-failure
        delay: 25s

  frontend:
    image: nginx:alpine
    command: >
      sh -c "apk add --no-cache curl &&
        mkdir -p /app && cd /app &&
        curl -sL 'https://gitea.yourdomain.com/org/jira-ai-fixer/archive/master.tar.gz' |
        tar xz --strip-components=1 &&
        cp -r frontend_build/* /usr/share/nginx/html/ &&
        echo 'c2VydmVyIHsKICBsaXN0ZW4gODA7...' | base64 -d > /etc/nginx/conf.d/default.conf &&
        nginx -g 'daemon off;'"
    networks:
      - proxy_network
      - internal
    deploy:
      labels:
        - traefik.enable=true
        - traefik.http.routers.jira-fixer.rule=Host(`jira-fixer.yourdomain.com`)
        - traefik.http.routers.jira-fixer.entrypoints=websecure
        - traefik.http.routers.jira-fixer.tls.certresolver=le
        - traefik.http.services.jira-fixer.loadbalancer.server.port=80

networks:
  proxy_network:
    external: true
  db_network:
    external: true
  internal:
    driver: overlay
```

### 2. Nginx Config (base64 encoded in command)

```nginx
server {
  listen 80;
  root /usr/share/nginx/html;
  index index.html;
  location / {
    try_files $uri $uri/ /index.html;
  }
  location /api {
    proxy_pass http://api:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}
```

### 3. Deploy

```bash
docker stack deploy -c docker-compose.yml jira-fixer
```

---

## Local Development

### Backend

```bash
cd app
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt  # or install manually (see stack command)
uvicorn app.main:app --reload --port 8000
```

### Frontend

```bash
cd frontend
npm install
npm run dev
```

Frontend dev server runs on http://localhost:5173 with proxy to backend.

### Build Frontend

```bash
cd frontend
npm run build
cp -r dist/* ../frontend_build/
```

---

## API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/auth/register` | Register new user |
| POST | `/api/auth/login` | Login |
| GET | `/api/organizations` | List organizations |
| POST | `/api/organizations` | Create organization |
| GET | `/api/issues` | List issues |
| POST | `/api/issues` | Create issue |
| GET | `/api/issues/:id` | Get issue detail |
| PATCH | `/api/issues/:id` | Update issue |
| POST | `/api/webhooks/jira` | JIRA webhook |
| POST | `/api/webhooks/servicenow` | ServiceNow webhook |
| POST | `/api/webhooks/github` | GitHub webhook |
| GET | `/api/reports/summary` | Report summary |
| GET | `/api/health` | Health check |

Full API documentation available at `/api/docs` (Swagger UI).

---

## Integrations

### JIRA Cloud
1. Go to Settings > Integrations > JIRA
2. Enter your Atlassian domain, email, and API token
3. Configure webhook in JIRA to point to `https://your-domain/api/webhooks/jira`

### GitHub
1. Create a GitHub App or use personal access token
2. Configure in Settings > Integrations > GitHub
3. Set webhook URL: `https://your-domain/api/webhooks/github`

### ServiceNow
1. Configure REST integration in ServiceNow
2. Point to: `https://your-domain/api/webhooks/servicenow`

---

## Environment Variables Reference

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `DATABASE_URL` | Yes | - | PostgreSQL connection string |
| `REDIS_URL` | No | `redis://localhost:6379` | Redis connection string |
| `SECRET_KEY` | Yes | - | App secret key |
| `JWT_SECRET` | Yes | - | JWT signing key |
| `JWT_EXPIRE_MINUTES` | No | `1440` | Token expiry (24h) |
| `RESEND_API_KEY` | No | - | Email service API key |
| `OPENROUTER_API_KEY` | No | - | AI analysis API key |
| `GITEA_URL` | No | - | Git server URL |
| `GITEA_TOKEN` | No | - | Git server access token |
| `JIRA_CLIENT_ID` | No | - | JIRA OAuth client ID |
| `JIRA_CLIENT_SECRET` | No | - | JIRA OAuth client secret |
| `GITHUB_CLIENT_ID` | No | - | GitHub OAuth client ID |
| `GITHUB_CLIENT_SECRET` | No | - | GitHub OAuth client secret |

---

## License

MIT © StartData
