# TranslatePressZone Backend Application

A production-ready translation API backend with ML-powered translation service, credit management, and subscription billing.

## Table of Contents

- [Overview](#overview)
- [Architecture](#architecture)
- [Prerequisites](#prerequisites)
- [Quick Start](#quick-start)
- [Project Structure](#project-structure)
- [Environment Configuration](#environment-configuration)
- [Development](#development)
- [Testing](#testing)
- [Deployment](#deployment)
- [API Documentation](#api-documentation)
- [Contributing](#contributing)
- [License](#license)

## Overview

TranslatePressZone provides a scalable translation API service with the following features:

- **AI-Powered Translations**: High-quality neural machine translation
- **Credit System**: Token-based billing with automatic deduction and allocation
- **Subscription Management**: Three-tier pricing with PayPal integration (Starter, Professional, Enterprise)
- **API Key Authentication**: Secure WordPress plugin integration via API keys
- **Job Queue**: Redis-backed Bull queue for async translation jobs
- **Admin Panel**: React-based dashboard for user management, analytics, and system settings
- **Webhook System**: Reliable callback delivery with automatic retries
- **Comprehensive Monitoring**: Structured logging, metrics, and audit trails

## Architecture

The backend consists of two main components:

```
press-zone-backend/
├── api/                    # Node.js + Express API server
└── admin-panel/            # React + TypeScript admin dashboard
```

### Technology Stack

**API Server:**
- Node.js 20+ with TypeScript
- Express.js for HTTP routing
- Prisma ORM with PostgreSQL
- Redis for caching and job queues
- Bull for background job processing
- JWT for authentication
- Winston for logging

**Admin Panel:**
- React 18 with TypeScript
- Vite for build tooling
- React Router for navigation
- Radix UI for components
- Tailwind CSS for styling
- Zustand for state management
- Recharts for analytics

**Translation Service:**
- AI-powered neural translation engine
- Integrated directly into Node.js API
- No separate service deployment needed

**Infrastructure:**
- PostgreSQL 15+ for relational data
- Redis 7+ for caching and queues
- AI translation service (cloud-based)
- PayPal for payment processing

## Prerequisites

Before you begin, ensure you have:

- **Node.js 20.0.0+** and **npm 10.0.0+**
- **PostgreSQL 15+** (with a database created)
- **Redis 7+** (running locally or remote)
- **AI translation service API key** (configured during setup)
- **PayPal Business account** (for subscription billing)
- **SendGrid account** (optional, for email notifications)

### System Requirements

- **Development**: 8GB RAM, 2 CPU cores
- **Production**: 16GB RAM, 4 CPU cores, SSD storage

## Quick Start

### 1. Clone and Install

```bash
# Navigate to press-zone-backend directory
cd press-zone-backend

# Install API dependencies
cd api
npm install

# Install admin panel dependencies
cd ../admin-panel
npm install
```

### 2. Configure Environment

```bash
# Copy environment template
cd ../api
cp .env.example .env

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

Required environment variables (see [Environment Configuration](#environment-configuration) for details):
- `DATABASE_URL`: PostgreSQL connection string
- `REDIS_HOST`, `REDIS_PORT`: Redis connection
- `JWT_ACCESS_SECRET`, `JWT_REFRESH_SECRET`: JWT secrets (generate with `openssl rand -hex 32`)
- `GEMINI_API_KEY`: AI translation service API key
- `PAYPAL_CLIENT_ID`, `PAYPAL_CLIENT_SECRET`: PayPal credentials

### 3. Setup Database

```bash
# Generate Prisma client
npm run prisma:generate

# Run migrations
npm run prisma:migrate

# (Optional) Seed database with test data
npm run prisma:seed
```

### 4. Start Development Servers

```bash
# Terminal 1: Start API server
cd api
npm run dev

# Terminal 2: Start background worker
npm run worker

# Terminal 3: Start admin panel
cd ../admin-panel
npm run dev
```

The services will be available at:
- **API**: http://localhost:3000
- **Admin Panel**: http://localhost:5173
- **API Health Check**: http://localhost:3000/health

## Project Structure

```
press-zone-backend/
├── api/                              # Node.js API server
│   ├── src/
│   │   ├── auth/                     # Authentication services
│   │   │   ├── apiKeyService.ts      # API key management
│   │   │   └── jwtService.ts         # JWT token generation/validation
│   │   ├── config/                   # Configuration management
│   │   │   └── index.ts              # Environment variable validation
│   │   ├── middleware/               # Express middleware
│   │   │   ├── auth.ts               # Authentication middleware
│   │   │   ├── errorHandler.ts       # Global error handler
│   │   │   ├── rateLimiter.ts        # Rate limiting
│   │   │   └── validator.ts          # Request validation
│   │   ├── routes/                   # API routes
│   │   │   ├── admin/                # Admin-only routes
│   │   │   │   ├── analytics.ts      # Analytics endpoints
│   │   │   │   ├── auth.ts           # Admin authentication
│   │   │   │   ├── jobs.ts           # Job management
│   │   │   │   ├── settings.ts       # System settings
│   │   │   │   ├── transactions.ts   # Transaction history
│   │   │   │   └── users.ts          # User management
│   │   │   ├── account.ts            # Account management
│   │   │   ├── auth.ts               # User authentication
│   │   │   ├── health.ts             # Health check
│   │   │   ├── jobs.ts               # Job status queries
│   │   │   ├── translate.ts          # Translation endpoints
│   │   │   └── webhooks.ts           # Webhook handlers
│   │   ├── services/                 # Business logic services
│   │   │   ├── creditService.ts      # Credit allocation/deduction
│   │   │   ├── emailService.ts       # Email notifications
│   │   │   ├── geminiClient.ts       # AI translation client
│   │   │   ├── paypalService.ts      # PayPal integration
│   │   │   ├── translationService.ts # Translation orchestration
│   │   │   └── webhookService.ts     # Webhook delivery
│   │   ├── types/                    # TypeScript type definitions
│   │   │   ├── express.d.ts          # Express type extensions
│   │   │   └── index.ts              # Shared types
│   │   ├── utils/                    # Utility functions
│   │   │   ├── encryption.ts         # Password hashing, token generation
│   │   │   ├── logger.ts             # Winston logger configuration
│   │   │   ├── metrics.ts            # Prometheus metrics
│   │   │   └── tokenCalculation.ts   # Token cost calculations
│   │   ├── index.ts                  # Application entry point
│   │   ├── server.ts                 # Express server setup
│   │   └── worker.ts                 # Background job worker
│   ├── prisma/
│   │   ├── migrations/               # Database migrations
│   │   └── schema.prisma             # Database schema
│   ├── package.json
│   ├── tsconfig.json
│   └── .env.example
│
├── admin-panel/                      # React admin dashboard
│   ├── src/
│   │   ├── components/               # React components
│   │   ├── pages/                    # Page components
│   │   ├── hooks/                    # Custom React hooks
│   │   ├── lib/                      # Utility libraries
│   │   ├── stores/                   # Zustand state stores
│   │   ├── types/                    # TypeScript types
│   │   └── App.tsx                   # Root component
│   ├── package.json
│   ├── tsconfig.json
│   ├── vite.config.ts
│   └── tailwind.config.js
```

## Environment Configuration

### Required Environment Variables

```bash
# Node Environment
NODE_ENV=development              # development | production | test
PORT=3000                         # API server port

# Database (PostgreSQL)
DATABASE_URL=postgresql://user:password@localhost:5432/translation_api
DATABASE_POOL_SIZE=20

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=                   # Optional
REDIS_DB=0

# JWT Secrets (generate with: openssl rand -hex 32)
JWT_ACCESS_SECRET=your-64-char-random-string-here
JWT_REFRESH_SECRET=your-64-char-random-string-here
JWT_ACCESS_EXPIRY=15m
JWT_REFRESH_EXPIRY=7d

# AI Translation Service
GEMINI_API_KEY=your-translation-api-key
GEMINI_MODEL=gemini-3-flash-preview

# PayPal (Subscription Billing)
PAYPAL_CLIENT_ID=your-paypal-client-id
PAYPAL_CLIENT_SECRET=your-paypal-client-secret
PAYPAL_WEBHOOK_ID=your-webhook-id
PAYPAL_MODE=sandbox               # sandbox | live
PAYPAL_PLAN_STARTER_MONTHLY=P-xxx
PAYPAL_PLAN_STARTER_ANNUAL=P-xxx
PAYPAL_PLAN_PROFESSIONAL_MONTHLY=P-xxx
PAYPAL_PLAN_PROFESSIONAL_ANNUAL=P-xxx
PAYPAL_PLAN_ENTERPRISE_MONTHLY=P-xxx
PAYPAL_PLAN_ENTERPRISE_ANNUAL=P-xxx

# Email (SendGrid - Optional)
SENDGRID_API_KEY=SG.xxxxxxxxxxxxxxxxxxxxx
SENDGRID_FROM_EMAIL=noreply@translate.press.zone
SENDGRID_FROM_NAME=translate.press.zone

# Monitoring (Optional)
SENTRY_DSN=https://xxx@sentry.io/xxx
LOG_LEVEL=info                    # error | warn | info | debug

# Alerting (Optional)
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxx

# App URLs
FRONTEND_URL=https://translate.press.zone
ADMIN_PANEL_URL=https://admin.translate.press.zone
API_URL=https://api.translate.press.zone

# CORS
CORS_ALLOWED_ORIGINS=https://admin.translate.press.zone,http://localhost:5173

# Rate Limiting (requests per minute)
RATE_LIMIT_STARTER=60
RATE_LIMIT_PROFESSIONAL=120
RATE_LIMIT_ENTERPRISE=0           # 0 = unlimited

# Content Limits (characters)
MAX_SYNC_CHARS=5000               # Max for synchronous translation
MAX_ASYNC_CHARS=50000             # Max for async jobs

# Webhook Settings
WEBHOOK_MAX_RETRIES=5
WEBHOOK_RETRY_DELAY_MS=2000

# Pricing (cost per 1K tokens in USD)
PRICE_PER_1K_TOKENS=0.002

# Credit Allocations (tokens per billing cycle)
CREDITS_STARTER=100000            # ~100K tokens
CREDITS_PROFESSIONAL=500000       # ~500K tokens
CREDITS_ENTERPRISE=2000000        # ~2M tokens
```

### Generating Secrets

```bash
# Generate JWT secrets
openssl rand -hex 32

# Generate API key prefix
openssl rand -hex 4
```

## Development

### Running API Server

```bash
cd api

# Development with hot reload
npm run dev

# Production build
npm run build
npm start

# Background worker (separate process)
npm run worker
```

### Running Admin Panel

```bash
cd admin-panel

# Development server
npm run dev

# Production build
npm run build
npm run preview
```

### Database Management

```bash
cd api

# Generate Prisma client after schema changes
npm run prisma:generate

# Create new migration
npm run prisma:migrate

# Deploy migrations to production
npm run prisma:migrate:deploy

# Open Prisma Studio (GUI for database)
npm run prisma:studio

# Seed database with test data
npm run prisma:seed
```

### Code Quality

```bash
# Lint code
npm run lint

# Fix linting issues
npm run lint:fix

# Type check (admin panel)
npm run type-check
```

## Testing

### Unit Tests

```bash
cd api

# Run all tests
npm test

# Run unit tests only
npm run test:unit

# Run with coverage report
npm run test:coverage
```

### Integration Tests

```bash
# Run integration tests (requires DB and Redis)
npm run test:integration
```

### End-to-End Tests

```bash
# Run E2E tests (requires all services running)
npm run test:e2e
```

### Manual API Testing

```bash
# Health check
curl http://localhost:3000/health

# Register user
curl -X POST http://localhost:3000/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "SecurePassword123"
  }'

# Login
curl -X POST http://localhost:3000/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "SecurePassword123"
  }'

# Translate (requires API key)
curl -X POST http://localhost:3000/translate \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-api-key-here" \
  -d '{
    "content": "Hello world",
    "source_lang": "en",
    "target_lang": "es",
    "tone": "neutral"
  }'
```

## Deployment

See [DEPLOYMENT.md](./DEPLOYMENT.md) for detailed production deployment instructions including:

- DigitalOcean droplet setup
- Docker containerization
- Nginx reverse proxy configuration
- SSL certificate setup
- Database backup strategies
- Monitoring and alerting
- CI/CD pipelines

### Quick Production Checklist

- [ ] Configure production environment variables
- [ ] Set `NODE_ENV=production`
- [ ] Use production database (PostgreSQL)
- [ ] Use production Redis instance
- [ ] Configure AI translation service API key
- [ ] Switch PayPal to live mode (`PAYPAL_MODE=live`)
- [ ] Generate strong JWT secrets
- [ ] Configure CORS for production domains
- [ ] Enable Sentry for error tracking
- [ ] Set up database backups
- [ ] Configure SSL certificates
- [ ] Set up monitoring and alerts
- [ ] Test all endpoints
- [ ] Load test API server

## API Documentation

### Authentication

The API supports two authentication methods:

**1. JWT Authentication (for user accounts):**
```bash
# Add to request headers
Authorization: Bearer <access_token>
```

**2. API Key Authentication (for WordPress plugin):**
```bash
# Add to request headers
X-API-Key: sk_live_xxxxxxxxxxxxxxxx
```

### Core Endpoints

#### Translation

**POST `/translate`** - Synchronous translation
```json
{
  "content": "Hello world",
  "source_lang": "en",
  "target_lang": "es",
  "tone": "neutral"
}
```

**POST `/translate/async`** - Asynchronous translation (for large content)
```json
{
  "content": "<large content>",
  "source_lang": "en",
  "target_lang": "fr",
  "callback_url": "https://yoursite.com/webhook",
  "callback_secret": "your-secret"
}
```

#### Jobs

**GET `/jobs/:id`** - Get job status
**GET `/jobs`** - List user's jobs
**POST `/jobs/:id/cancel`** - Cancel pending job

#### Account

**GET `/account`** - Get account details
**GET `/account/credits`** - Get credit balance
**GET `/account/usage`** - Get usage statistics
**POST `/account/api-keys`** - Create API key
**DELETE `/account/api-keys/:id`** - Revoke API key

### Rate Limiting

Rate limits are enforced per plan tier:

- **Starter**: 60 requests/minute
- **Professional**: 120 requests/minute
- **Enterprise**: Unlimited

Rate limit headers are included in responses:
```
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1642089600
```

### Error Codes

| Code | Status | Description |
|------|--------|-------------|
| `INVALID_REQUEST` | 400 | Malformed request body |
| `UNAUTHORIZED` | 401 | Missing or invalid credentials |
| `INSUFFICIENT_CREDITS` | 402 | Not enough credits for operation |
| `FORBIDDEN` | 403 | Access denied to resource |
| `NOT_FOUND` | 404 | Resource not found |
| `RATE_LIMIT_EXCEEDED` | 429 | Too many requests |
| `TRANSLATION_FAILED` | 500 | Translation service error |
| `INTERNAL_ERROR` | 500 | Server error |

### AI Translation Service Setup

**1. Get API Key:**
- Obtain your translation service API key
- Copy the key to `GEMINI_API_KEY` in your `.env` file

**2. Configure Model:**
- Model is configured automatically
- Advanced: Override with `GEMINI_MODEL` environment variable if needed

### PayPal Setup

**1. Create PayPal App:**
- Go to https://developer.paypal.com/
- Create a new app
- Copy Client ID and Secret

**2. Create Subscription Plans:**
- Create 6 plans (3 tiers × 2 billing cycles)
- Copy Plan IDs to environment variables

**3. Set up Webhooks:**
- Add webhook URL: `https://api.translate.press.zone/webhooks/paypal`
- Subscribe to events: `BILLING.SUBSCRIPTION.*`, `PAYMENT.SALE.COMPLETED`
- Copy Webhook ID to `PAYPAL_WEBHOOK_ID`

## Contributing

We welcome contributions! Please follow these guidelines:

### Code Style

- Use TypeScript for all new code
- Follow existing code formatting (ESLint config)
- Write JSDoc comments for public functions
- Use meaningful variable and function names

### Commit Messages

Follow conventional commits:
```
feat: add webhook retry logic
fix: resolve credit deduction bug
docs: update API documentation
test: add unit tests for translation service
```

### Pull Request Process

1. Create a feature branch from `master`
2. Make your changes with tests
3. Update documentation if needed
4. Run linting and tests: `npm run lint && npm test`
5. Submit PR with clear description

## License

MIT License

Copyright (c) 2024 Press.Zone

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

---

## Support

For issues and questions:
- GitHub Issues: https://github.com/press-zone/translate-press-zone/issues
- Documentation: https://docs.translate.press.zone
- Email: support@press.zone
