# Goa GEL Backend

**Blockchain Document Verification Platform for Government of Goa**

A production-ready NestJS backend for managing multi-department approval workflows with blockchain-backed verification using Hyperledger Besu and ERC-721 Soulbound NFTs.

## 🚀 Quick Start

### Prerequisites

- Node.js 18+
- Docker & Docker Compose
- PostgreSQL 15+ (or use Docker)
- Redis 7+ (or use Docker)

### Installation

```bash
# Clone and install
cd backend
npm install

# Copy environment file
cp .env.example .env

# Start infrastructure (PostgreSQL, Redis, MinIO, Besu)
docker-compose up -d postgres redis minio besu-node-1

# Run migrations
npm run migrate:latest

# Seed sample data
npm run seed:run

# Start development server
npm run start:dev
```

### Access Points

| Service | URL | Description |
|---------|-----|-------------|
| API | http://localhost:3001 | REST API |
| Swagger Docs | http://localhost:3001/api/docs | API Documentation |
| Health Check | http://localhost:3001/health | Service Health |
| MinIO Console | http://localhost:9001 | Object Storage UI |
| Besu RPC | http://localhost:8545 | Blockchain RPC |

## 📁 Project Structure

```
backend/
├── src/
│   ├── main.ts                    # Application entry point
│   ├── app.module.ts              # Root module
│   ├── config/                    # Configuration files
│   │   ├── app.config.ts
│   │   ├── database.config.ts
│   │   ├── blockchain.config.ts
│   │   ├── storage.config.ts
│   │   └── redis.config.ts
│   ├── common/                    # Shared utilities
│   │   ├── constants/
│   │   ├── decorators/
│   │   ├── enums/
│   │   ├── filters/
│   │   ├── guards/
│   │   ├── interceptors/
│   │   ├── interfaces/
│   │   ├── pipes/
│   │   └── utils/
│   ├── database/                  # Database layer (Knex + Objection.js)
│   │   ├── models/                # Objection.js models
│   │   ├── migrations/            # Knex migrations
│   │   ├── seeds/                 # Seed data
│   │   └── knexfile.ts
│   └── modules/                   # Feature modules
│       ├── auth/                  # Authentication
│       ├── applicants/            # Applicant management
│       ├── departments/           # Department management
│       ├── requests/              # License requests
│       ├── documents/             # Document management
│       ├── approvals/             # Approval workflow
│       ├── workflows/             # Workflow engine
│       ├── webhooks/              # Webhook delivery
│       ├── blockchain/            # Blockchain integration
│       ├── admin/                 # Admin operations
│       └── audit/                 # Audit logging
├── test/                          # Test suites
├── docker-compose.yml             # Docker services
├── Dockerfile                     # Production image
└── package.json
```

## 🔧 Configuration

### Environment Variables

```bash
# Application
NODE_ENV=development
PORT=3001
API_VERSION=v1

# Database (PostgreSQL)
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=goa_gel_platform
DATABASE_USER=postgres
DATABASE_PASSWORD=your_password

# Blockchain (Hyperledger Besu)
BESU_RPC_URL=http://localhost:8545
BESU_CHAIN_ID=1337
CONTRACT_ADDRESS_LICENSE_NFT=0x...
PLATFORM_WALLET_PRIVATE_KEY=0x...

# Storage (MinIO)
MINIO_ENDPOINT=localhost
MINIO_PORT=9000
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=minioadmin

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379

# Security
JWT_SECRET=your-32-char-secret-key
```

## 📚 API Documentation

### Authentication

**Department Login:**
```bash
curl -X POST http://localhost:3001/api/v1/auth/department/login \
  -H "Content-Type: application/json" \
  -d '{"apiKey": "fire_api_key_123", "departmentCode": "FIRE_DEPT"}'
```

**DigiLocker Login (Mock):**
```bash
curl -X POST http://localhost:3001/api/v1/auth/digilocker/login \
  -H "Content-Type: application/json" \
  -d '{"digilockerId": "DL-GOA-123456789", "name": "John Doe", "email": "john@example.com"}'
```

### Core Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/api/v1/requests` | Create license request |
| POST | `/api/v1/requests/:id/submit` | Submit for approval |
| GET | `/api/v1/requests/:id` | Get request details |
| GET | `/api/v1/requests/pending` | Get pending requests |
| POST | `/api/v1/requests/:id/documents` | Upload document |
| POST | `/api/v1/requests/:id/approve` | Approve request |
| POST | `/api/v1/requests/:id/reject` | Reject request |
| GET | `/api/v1/workflows` | List workflows |
| POST | `/api/v1/webhooks` | Register webhook |

## 🗄️ Database

### Using Knex Migrations

```bash
# Create new migration
npm run migrate:make -- create_new_table

# Run migrations
npm run migrate:latest

# Rollback last migration
npm run migrate:rollback

# Check migration status
npm run migrate:status

# Run seeds
npm run seed:run
```

### Models (Objection.js)

- `Applicant` - User profiles linked to DigiLocker
- `Department` - Government departments with API keys
- `LicenseRequest` - License/permit applications
- `Document` - Uploaded documents with versioning
- `Approval` - Department approval records
- `Workflow` - Approval workflow definitions
- `WorkflowState` - Workflow execution state
- `Webhook` - Webhook configurations
- `AuditLog` - Immutable audit trail
- `BlockchainTransaction` - Blockchain transaction records

## 🔗 Blockchain Integration

### Smart Contracts

| Contract | Purpose |
|----------|---------|
| LicenseRequestNFT | ERC-721 Soulbound NFTs for licenses |
| ApprovalManager | Records approvals on-chain |
| DepartmentRegistry | Department registration |
| WorkflowRegistry | Workflow definitions |

### Transaction Flow

1. Request created → Draft NFT minted
2. Document uploaded → Hash recorded on-chain
3. Department approves → Approval recorded on-chain
4. All approvals complete → NFT finalized

## 🧪 Testing

```bash
# Run unit tests
npm test

# Run with coverage
npm run test:cov

# Run e2e tests
npm run test:e2e

# Watch mode
npm run test:watch
```

## 🐳 Docker Deployment

### Development

```bash
# Start all services
docker-compose up -d

# View logs
docker-compose logs -f api

# Stop services
docker-compose down
```

### Production

```bash
# Build production image
docker build -t goa-gel-api:latest .

# Run with production compose
docker-compose -f docker-compose.prod.yml up -d
```

## 📊 Monitoring

### Health Check

```bash
curl http://localhost:3001/health
```

Response:
```json
{
  "status": "ok",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "uptime": 3600,
  "checks": {
    "database": "ok",
    "redis": "ok",
    "blockchain": "ok",
    "storage": "ok"
  }
}
```

## 🔐 Security

- API Key authentication for departments
- JWT tokens for applicants
- RBAC (Role-Based Access Control)
- Rate limiting (100 req/min global)
- Input validation with class-validator
- SQL injection prevention (parameterized queries)
- Helmet security headers
- CORS configuration

## 📝 License

Proprietary - Government of Goa

## 🤝 Support

For technical support, contact: support@goagel.gov.in
