# TaxCore Docker Deployment Guide

## Overview

This guide walks you through deploying the TAF ERP system with the TaxCore Node.js service using Docker containers.

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    Docker Host                               │
│                                                               │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │ php-apache   │  │ taxcore      │  │ postgres     │      │
│  │ :8080        │──┤ -service     │  │ :5432        │      │
│  │              │  │ :3001        │  │              │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
│         │                  │                  │              │
│         └──────────────────┼──────────────────┘              │
│                            │                                 │
│                    ┌──────────────┐                         │
│                    │   redis      │                         │
│                    │   :6379      │                         │
│                    └──────────────┘                         │
│                                                               │
│  Network: taf-network (bridge)                              │
└─────────────────────────────────────────────────────────────┘
```

## Services

| Service | Port | Description |
|---------|------|-------------|
| php-apache | 8080 | Main web application |
| taxcore-service | 3001 | TaxCore API integration |
| postgres | 5432 | Database |
| redis | 6379 | Cache & PubSub |

## Prerequisites

### 1. System Requirements

- **Docker**: Version 20.10+ 
- **Docker Compose**: Version 2.0+
- **Disk Space**: Minimum 5GB free
- **RAM**: Minimum 4GB recommended
- **CPU**: 2+ cores recommended

### 2. Install Docker

**Ubuntu/Debian:**
```bash
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

# Add user to docker group
sudo usermod -aG docker $USER

# Install Docker Compose
sudo apt-get update
sudo apt-get install docker-compose-plugin

# Verify installation
docker --version
docker compose version
```

**Other Systems:**
- See: https://docs.docker.com/get-docker/

### 3. Verify Installation

```bash
docker --version
# Expected: Docker version 20.10+

docker compose version
# Expected: Docker Compose version 2.0+
```

## Quick Start

### 1. Prepare Certificate

```bash
# Create certificate directory if it doesn't exist
mkdir -p FRCS_Certs_Install

# Copy your certificate
cp /path/to/your/certificate.pfx FRCS_Certs_Install/

# Set correct permissions
chmod 644 FRCS_Certs_Install/*.pfx

# Verify
ls -la FRCS_Certs_Install/
```

### 2. Configure Environment (Optional)

The system has sensible defaults in `docker-compose.yaml`. You only need to configure if you want to override defaults.

```bash
# Copy environment template (optional)
cp .env.docker .env

# Edit with your values (optional)
nano .env
```

**Optional variables to override:**
```bash
# Certificate Configuration (if different from default)
TAXCORE_PFX_FILE=your-certificate-file.pfx
TAXCORE_PFX_PASSWORD=your_certificate_password
TAXCORE_PIN_JSON=your_pin

# API URLs (if different from sandbox)
TAXCORE_TAX_URL=https://api.production.vms.frcs.org.fj/api
TAXCORE_VSDC_URL=http://production.vms.frcs.org.fj:8888/your-uuid/api
```

### 3. Build and Start Services

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

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

This single command will:
- Build all Docker images
- Start all containers
- Set up networking
- Mount volumes

### 4. Verify Deployment

```bash
# Check all services are running
docker-compose ps

# Test TaxCore service health
curl http://localhost:3001/health

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

### 7. Access Application

- **Web Application**: http://localhost:8080
- **TaxCore Service**: http://localhost:3001
- **Health Check**: http://localhost:3001/health

## Detailed Deployment Steps

### Step 1: Clone Repository

```bash
cd /path/to/projects
git clone <repository-url> TAF
cd TAF
```

### Step 2: Setup Certificate

```bash
# Create directory
mkdir -p FRCS_Certs_Install

# Copy certificate (replace with your actual path)
cp ~/Downloads/certificate.pfx FRCS_Certs_Install/

# Verify
ls -lh FRCS_Certs_Install/
# Should show your .pfx file
```

### Step 3: Configure Environment

```bash
# Copy template
cp .env.docker .env

# Edit configuration
nano .env
```

**Minimum Configuration:**
```bash
# Database
POSTGRES_USER=taf
POSTGRES_PASSWORD=your_secure_password
POSTGRES_DB=tafdb

# TaxCore
TAXCORE_PFX_FILE=certificate.pfx
TAXCORE_PFX_PASSWORD=your_cert_password
TAXCORE_PIN_JSON=your_pin
TAXCORE_DEBUG=true
```

### Step 4: Build and Start Services

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

**Expected output:**
```
[+] Building 45.2s (12/12) FINISHED
 => [taxcore-service internal] load build definition
 => => transferring dockerfile: 1.23kB
 ...
 => => writing image sha256:...
 => => naming to docker.io/library/taf-taxcore-service
[+] Running 4/4
 ✔ Container taf-postgres-1       Started
 ✔ Container taf-redis-1          Started  
 ✔ Container taf-php-apache-1     Started
 ✔ Container taf-taxcore-service-1 Started
```

### Step 5: Verify Services

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

# Expected output shows all services "Up" with healthy status
```

**Verify all services are running:**
```bash
docker-compose ps

# Expected output:
NAME              IMAGE               STATUS
php-apache        taf-php-apache      Up
postgres          taf-postgres        Up
redis             redis:7             Up
taxcore-service   taf-taxcore         Up (healthy)
```

### Step 7: Test TaxCore Service

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

# Expected: {"status":"ok","service":"TaxCore Service"}

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

# From PHP container
docker-compose exec php-apache curl http://taxcore-service:3001/health
```

### Step 8: Configure PHP Application

The PHP application automatically connects to TaxCore service via environment variable:

```bash
# Verify PHP environment
docker-compose exec php-apache env | grep TAXCORE

# Expected: TAXCORE_SERVICE_URL=http://taxcore-service:3001
```

### Step 9: Test from Web Interface

1. Open browser: http://localhost:8080
2. Navigate to POS module
3. Add items to cart
4. Complete a sale
5. Verify receipt is generated

**Check logs if issues occur:**
```bash
# TaxCore service logs
docker-compose logs -f taxcore-service

# PHP application logs
docker-compose logs -f php-apache
```

## Management Commands

### Basic Operations

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

# Start specific service
docker-compose up -d taxcore-service

# Stop services
docker-compose down

# Restart services
docker-compose restart
docker-compose restart taxcore-service  # single service

# Rebuild after code changes
docker-compose up --build

# View logs
docker-compose logs -f                    # all services
docker-compose logs -f taxcore-service    # single service

# Check status
docker-compose ps

# Execute commands in container
docker-compose exec taxcore-service sh

# Test TaxCore health
curl http://localhost:3001/health
docker-compose restart taxcore-service

# View service status
docker-compose ps
```

## Monitoring & Logs

### View Logs

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

# Specific service
docker-compose logs -f taxcore-service

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

# Since specific time
docker-compose logs --since="2025-10-01T00:00:00" taxcore-service
```

### Monitor Resources

```bash
# Real-time stats
docker stats

# Service status
docker-compose ps

# Detailed inspection
docker inspect taxcore-service
```

### Health Checks

```bash
# Check container health
docker ps --filter name=taxcore-service

# View health check logs
docker inspect taxcore-service | grep -A 10 Health

# Manual health check
curl http://localhost:3001/health
```

## Troubleshooting

### Service Won't Start

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

**2. Common issues:**
- Port 3001 already in use
- Certificate not found
- Invalid environment variables

**3. Solutions:**
```bash
# Check port
sudo lsof -i :3001

# Verify certificate
docker-compose exec taxcore-service ls -la /usr/src/app/certs/

# Check environment
docker-compose exec taxcore-service env | grep TAXCORE
```

### Certificate Not Found

**1. Verify certificate exists:**
```bash
ls -la FRCS_Certs_Install/
```

**2. Check volume mount:**
```bash
docker-compose exec taxcore-service ls -la /usr/src/app/certs/
```

**3. Fix permissions:**
```bash
chmod 644 FRCS_Certs_Install/*.pfx
```

**4. Update .env file:**
```bash
TAXCORE_PFX_FILE=correct-filename.pfx
```

**5. Restart service:**
```bash
docker-compose restart taxcore-service
```

### Health Check Failing

**1. Check if service is running:**
```bash
curl http://localhost:3001/health
```

**2. Check container logs:**
```bash
docker-compose logs -f taxcore-service
```

**3. Verify certificate and password:**
```bash
# Check environment
docker-compose exec taxcore-service env | grep TAXCORE_PFX
```

**4. Test from inside container:**
```bash
docker-compose exec taxcore-service curl http://localhost:3001/health
```

### PHP Can't Connect to TaxCore

**1. Verify network:**
```bash
docker network inspect taf_taf-network
```

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

**3. Check environment variable:**
```bash
docker-compose exec php-apache env | grep TAXCORE_SERVICE_URL
```

**4. Ensure services are on same network:**
```bash
docker-compose ps
# All should show "taf_taf-network"
```

### Database Connection Issues

**1. Check PostgreSQL is running:**
```bash
docker-compose ps postgres
```

**2. Test connection:**
```bash
docker-compose exec postgres psql -U taf -d tafdb -c "SELECT version();"
```

**3. Check from PHP:**
```bash
docker-compose exec php-apache php -r "var_dump(pg_connect('host=postgres dbname=tafdb user=taf password=TAF123*'));"
```

## Production Deployment

### Security Hardening

1. **Use Docker Secrets for sensitive data:**
```yaml
# docker-compose.prod.yml
secrets:
  taxcore_cert_password:
    file: ./secrets/cert_password.txt

services:
  taxcore-service:
    secrets:
      - taxcore_cert_password
```

2. **Run as non-root user:**
```dockerfile
RUN addgroup -g 1001 taxcore && \
    adduser -D -u 1001 -G taxcore taxcore
USER taxcore
```

3. **Limit resources:**
```yaml
services:
  taxcore-service:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M
        reservations:
          memory: 256M
```

### High Availability

1. **Use Docker Swarm or Kubernetes**
2. **Add load balancer (nginx)**
3. **Scale TaxCore service:**
```bash
docker-compose up -d --scale taxcore-service=3
```

### Backup Strategy

```bash
# Backup certificates
tar -czf cert-backup-$(date +%Y%m%d).tar.gz FRCS_Certs_Install/

# Backup database
docker-compose exec postgres pg_dump -U taf tafdb > backup-$(date +%Y%m%d).sql

# Backup logs
tar -czf logs-backup-$(date +%Y%m%d).tar.gz logs/
```

### Monitoring Setup

1. **Enable Prometheus metrics**
2. **Configure alerting**
3. **Set up log aggregation (ELK stack)**
4. **Use health check endpoints**

## Updating Services

### Update TaxCore Service

```bash
# Pull latest code
git pull

# Rebuild and restart
docker-compose up --build -d taxcore-service

# Verify
curl http://localhost:3001/health
```

### Update All Services

```bash
# Pull latest code
git pull

# Rebuild and restart all services
docker-compose up --build -d

# Check status
docker-compose ps
```

## Cleanup

### Remove Stopped Containers

```bash
docker-compose rm -f
```

### Remove Images

```bash
docker image prune -a
```

### Complete Cleanup

```bash
# Stop and remove everything
docker-compose down -v

# Remove images
docker rmi $(docker images -q 'taf-*')

# Clean system
docker system prune -a
```

## Support & Resources

- **Docker Documentation**: `docker/taxcore-service/README.md`
- **Service Details**: `websocket-server/TAXCORE_SERVICE.md`
- **Implementation Guide**: `TAXCORE_IMPLEMENTATION_SUMMARY.md`
- **Architecture Diagrams**: `docs/TaxCore_Architecture_Diagrams.md`

## Checklist

### Pre-Deployment
- [ ] Docker installed and running
- [ ] Certificate file present in FRCS_Certs_Install/
- [ ] .env file configured
- [ ] Ports 8080, 3001, 5432, 6379 available

### Deployment
- [ ] Images built successfully
- [ ] All containers running
- [ ] Health checks passing
- [ ] Logs show no errors

### Post-Deployment
- [ ] Web application accessible
- [ ] TaxCore service responding
- [ ] Test sale completed successfully
- [ ] Receipt generated correctly

### Production
- [ ] Secrets management configured
- [ ] Monitoring enabled
- [ ] Backup strategy in place
- [ ] SSL/TLS certificates configured
- [ ] Firewall rules set
- [ ] Auto-restart enabled

---

**Ready to Deploy!** Start with: `docker-compose up --build`
