# Docker Setup for TaxCore Implementation

## Quick Start

### 1. Prerequisites
- Docker Desktop or Docker Engine installed
- Docker Compose installed
- Certificate file in `FRCS_Certs_Install/` directory

### 2. Start All Services with Docker Compose

```bash
# Build and start all services
docker-compose up --build

# Or run in detached mode (background)
docker-compose up --build -d

# View logs
docker-compose logs -f

# View TaxCore service logs only
docker-compose logs -f taxcore-service
```

### 3. Verify Services are Running

```bash
# Check all containers
docker-compose ps

# Should show:
# NAME                 STATUS              PORTS
# php-apache           Up                  0.0.0.0:8080->80/tcp
# postgres             Up                  0.0.0.0:5432->5432/tcp
# redis                Up                  0.0.0.0:6379->6379/tcp
# taxcore-service      Up (healthy)        0.0.0.0:3001->3001/tcp

# Test TaxCore service health
curl http://localhost:3001/health
# Returns: {"status":"ok","service":"TaxCore Service"}

# Test TaxCore tax rates endpoint
curl http://localhost:3001/tax-rates
# Returns: {"success":true,"data":[...]}
```

## Services Overview

### 1. php-apache (Port 8080)
- Main PHP application server
- Serves frontend and API endpoints
- Connects to TaxCore service via: `http://taxcore-service:3001`

### 2. postgres (Port 5432)
- PostgreSQL database
- Stores all application data
- Tables: `sales_receipts`, `lineitems_payments`, etc.

### 3. redis (Port 6379)
- Cache and message broker
- Used for WebSocket synchronization
- Pub/Sub for real-time updates

### 4. taxcore-service (Port 3001) ⭐ NEW
- Node.js TaxCore integration service
- Handles mTLS certificate authentication
- Communicates with FRCS TaxCore API
- Transforms browser payloads to TaxCore format

## Docker Compose Configuration

### Environment Variables

Create a `.env` file in the project root (or use `.env.docker`):

```bash
# TaxCore Service Configuration
TAXCORE_SERVICE_PORT=3001
TAXCORE_TAX_URL=https://api.sandbox.vms.frcs.org.fj/api
TAXCORE_VSDC_URL=http://devesdc.sandbox.vms.frcs.org.fj:8888/20f351f3-9b39-4c63-b9e0-d8a00b6e93fb/api

# Certificate Configuration
TAXCORE_PFX_FILE=LK2VRSH4-DeveloperAuthenticationCertificate.pfx
TAXCORE_PFX_PASSWORD=2CBP6HMW
TAXCORE_PIN_JSON=3840

# Debug Mode
TAXCORE_DEBUG=true

# PostgreSQL
POSTGRES_USER=taf
POSTGRES_PASSWORD=TAF123*
POSTGRES_DB=tafdb
```

### Volume Mounts

The TaxCore service uses these volumes:

```yaml
volumes:
  - ./websocket-server:/usr/src/app          # Source code
  - ./FRCS_Certs_Install:/usr/src/app/certs:ro  # Certificates (read-only)
  - ./logs:/usr/src/logs                     # Log files
```

**Important:** Place your certificate file in `FRCS_Certs_Install/` directory before starting.

## Common Docker Commands

### Start/Stop Services

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

# Stop all services
docker-compose down

# Restart a specific service
docker-compose restart taxcore-service

# Rebuild and restart
docker-compose up --build -d
```

### View Logs

```bash
# All services
docker-compose logs -f

# Specific service
docker-compose logs -f taxcore-service
docker-compose logs -f php-apache
docker-compose logs -f postgres

# Last 100 lines
docker-compose logs --tail=100 taxcore-service
```

### Execute Commands in Containers

```bash
# Enter TaxCore service container
docker-compose exec taxcore-service sh

# Enter PHP container
docker-compose exec php-apache bash

# Run npm install in TaxCore service
docker-compose exec taxcore-service npm install

# Check certificate in container
docker-compose exec taxcore-service ls -la /usr/src/app/certs/
```

### Health Checks

```bash
# Check health status
docker-compose ps

# Manual health check
docker-compose exec taxcore-service curl http://localhost:3001/health

# View health check logs
docker inspect taxcore-service --format='{{json .State.Health}}' | jq
```

### Clean Up

```bash
# Stop and remove containers
docker-compose down

# Remove containers and volumes (⚠️ deletes database data)
docker-compose down -v

# Remove containers, volumes, and images
docker-compose down -v --rmi all

# Prune unused Docker resources
docker system prune -a
```

## Networking

All services are connected via the `taf-network` bridge network:

```
php-apache (8080) ──┐
postgres (5432) ────┼──→ taf-network (bridge)
redis (6379) ───────┤
taxcore-service (3001) ─┘
```

### Internal DNS Resolution

Services can communicate using container names:
- `http://taxcore-service:3001` - From PHP to TaxCore service
- `postgres:5432` - PostgreSQL database
- `redis:6379` - Redis cache

### External Access

From host machine:
- `http://localhost:8080` - PHP application
- `http://localhost:3001` - TaxCore service
- `localhost:5432` - PostgreSQL
- `localhost:6379` - Redis

## TaxCore Service Configuration in PHP

The PHP application automatically connects to the TaxCore service via Docker network:

```php
// In PosController.php
private $taxcoreServiceUrl = 'http://taxcore-service:3001';

// Environment variable (set in docker-compose.yaml)
TAXCORE_SERVICE_URL=http://taxcore-service:3001
```

## Browser Configuration for Docker

When running in Docker, the browser needs to access TaxCore service:

### Option 1: Proxy Mode (Recommended for Docker)
```javascript
// Browser connects to PHP, PHP connects to TaxCore service
localStorage.setItem('taxcore_direct', 'false');
```

This is recommended because:
- Browser → PHP (port 8080) ✅ Works
- PHP → TaxCore service (internal network) ✅ Works

### Option 2: Direct Mode (Host Network Only)
```javascript
// Browser connects directly to TaxCore service
localStorage.setItem('taxcore_direct', 'true');
localStorage.setItem('taxcore_service_url', 'http://localhost:3001');
```

This only works if:
- TaxCore service port 3001 is exposed to host
- Browser can reach `localhost:3001`

## Troubleshooting

### TaxCore Service Won't Start

**Check certificate file:**
```bash
# From host
ls -la FRCS_Certs_Install/*.pfx

# From container
docker-compose exec taxcore-service ls -la /usr/src/app/certs/
```

**Check logs:**
```bash
docker-compose logs taxcore-service
```

**Common errors:**
- "Certificate not found" → Place certificate in `FRCS_Certs_Install/`
- "ENOENT" → Check volume mounts in docker-compose.yaml
- "Permission denied" → Check file permissions: `chmod 644 FRCS_Certs_Install/*.pfx`

### Health Check Failing

```bash
# Check health status
docker-compose ps

# Manual test
curl http://localhost:3001/health

# Inside container
docker-compose exec taxcore-service curl http://localhost:3001/health
```

### Can't Connect from PHP

**Check network:**
```bash
docker network inspect taf_taf-network

# Should show all 4 containers
```

**Test connection from PHP container:**
```bash
docker-compose exec php-apache curl http://taxcore-service:3001/health
```

**Check PHP environment variable:**
```bash
docker-compose exec php-apache env | grep TAXCORE
# Should show: TAXCORE_SERVICE_URL=http://taxcore-service:3001
```

### Certificate Issues

**Verify certificate in container:**
```bash
docker-compose exec taxcore-service ls -la /usr/src/app/certs/
docker-compose exec taxcore-service cat /usr/src/app/certs/*.pfx | head -c 100
```

**Test with curl manually:**
```bash
docker-compose exec taxcore-service sh
cd /usr/src/app
curl -v --cert-type P12 \
  --cert certs/LK2VRSH4-DeveloperAuthenticationCertificate.pfx:2CBP6HMW \
  http://devesdc.sandbox.vms.frcs.org.fj:8888/.../api/v1/tax-rates
```

### Port Already in Use

```bash
# Find process using port 3001
lsof -i :3001
# or
netstat -tuln | grep 3001

# Kill the process or change port in docker-compose.yaml
```

### Database Connection Issues

```bash
# Check PostgreSQL is running
docker-compose exec postgres pg_isready -U taf

# Connect to database
docker-compose exec postgres psql -U taf -d tafdb

# Test from PHP
docker-compose exec php-apache php -r "new PDO('pgsql:host=postgres;dbname=tafdb', 'taf', 'TAF123*');"
```

## Production Deployment

### 1. Use Environment-Specific Configs

```bash
# Create .env.production
cp .env.docker .env.production

# Update with production values
TAXCORE_TAX_URL=https://api.vms.frcs.org.fj/api
TAXCORE_VSDC_URL=https://production-vsdc-url/api
TAXCORE_DEBUG=false
APP_ENV=production
```

### 2. Use Docker Secrets for Sensitive Data

```yaml
# docker-compose.prod.yaml
services:
  taxcore-service:
    secrets:
      - taxcore_pfx_password
      - taxcore_pin

secrets:
  taxcore_pfx_password:
    external: true
  taxcore_pin:
    external: true
```

### 3. Set Resource Limits

```yaml
services:
  taxcore-service:
    deploy:
      resources:
        limits:
          cpus: '1'
          memory: 512M
        reservations:
          cpus: '0.5'
          memory: 256M
```

### 4. Use Proper Logging

```yaml
services:
  taxcore-service:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
```

### 5. Enable Auto-Restart

```yaml
services:
  taxcore-service:
    restart: always
```

## Monitoring

### Health Checks

Docker Compose automatically monitors service health:

```bash
# View health status
docker-compose ps

# Watch health status
watch docker-compose ps
```

### Log Monitoring

```bash
# Follow all logs
docker-compose logs -f

# Follow with timestamps
docker-compose logs -f --timestamps

# Filter by service
docker-compose logs -f taxcore-service | grep -i error
```

### Resource Usage

```bash
# View resource usage
docker stats

# Specific container
docker stats taxcore-service
```

## Development Workflow

### 1. Make Changes to Code

```bash
# Edit code in websocket-server/taxcore-service.js
vim websocket-server/taxcore-service.js
```

### 2. Restart Service to Apply Changes

```bash
# Restart just TaxCore service
docker-compose restart taxcore-service

# Or rebuild if dependencies changed
docker-compose up --build -d taxcore-service
```

### 3. View Logs

```bash
docker-compose logs -f taxcore-service
```

### 4. Test Changes

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

# Tax rates
curl http://localhost:3001/tax-rates

# Complete sale from browser
# Check logs for debugging
```

## CI/CD Integration

### GitHub Actions Example

```yaml
name: Docker Build and Test

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Build and start services
        run: docker-compose up --build -d
      
      - name: Wait for services
        run: sleep 30
      
      - name: Test TaxCore health
        run: curl -f http://localhost:3001/health
      
      - name: Run tests
        run: docker-compose exec -T php-apache vendor/bin/phpunit
      
      - name: Stop services
        run: docker-compose down
```

## References

- **Docker Compose Docs**: https://docs.docker.com/compose/
- **Node.js Docker Best Practices**: https://github.com/nodejs/docker-node/blob/main/docs/BestPractices.md
- **TaxCore Service Docs**: `websocket-server/TAXCORE_SERVICE.md`
- **Architecture**: `docs/TaxCore_Current_Architecture.md`
- **Quick Start**: `docs/TaxCore_Quick_Start.md`

---

**Ready to Deploy with Docker!** 🐳
