# TaxCore Integration Refactoring Summary

## Overview

The POS system has been refactored to use a Node.js service as an intermediary between the browser/PHP and the FRCS TaxCore API, improving certificate handling, performance, and maintainability.

## Changes Made

### 1. New Node.js TaxCore Service (`websocket-server/taxcore-service.js`)

**Purpose**: Handles all TaxCore API communication with proper mutual TLS (mTLS) certificate handling.

**Key Features**:
- Standalone HTTP service (port 3001)
- Handles PFX certificate authentication via curl
- Auto-discovers certificate from multiple locations
- Supports all sale types: Normal, Advance, Proforma, Training, Copy
- Provides tax rates endpoint
- Comprehensive error handling and logging

**Endpoints**:
- `GET /health` - Service health check
- `GET /tax-rates` - Fetch tax rates from TaxCore
- `POST /sale` - Create sales (supports all types via `type` field)

**Configuration** (Environment Variables):
```bash
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/.../api
TAXCORE_PFX_PATH=../FRCS_Certs_Install/certificate.pfx
TAXCORE_PFX_PASSWORD=password
TAXCORE_PIN_JSON=3840
TAXCORE_DEBUG=true
```

### 2. Updated PHP Controller (`api/controllers/PosController.php`)

**Changes**:
- Added `$taxcoreServiceUrl` property (default: `http://localhost:3001`)
- Added `callTaxCoreService()` method to proxy requests to Node.js
- Updated `taxcore()` method to use Node.js service instead of direct TaxCoreClient
- Updated `getTaxRates()` to use Node.js service
- Maintains backward compatibility with TaxCoreClient class

**Configuration**:
```php
// Environment variable
TAXCORE_SERVICE_URL=http://localhost:3001
```

### 3. Updated Frontend (`FrontEnd/js/modules/POS/POS.js`)

**Changes**:
- Modified `sendTaxCoreData()` to support both direct and proxy modes
- Added connection mode detection via localStorage
- Added `showTaxCoreSettingsModal()` function for runtime configuration
- Improved error handling and logging

**Configuration** (localStorage):
```javascript
localStorage.setItem('taxcore_direct', 'true');  // or 'false' for PHP proxy
localStorage.setItem('taxcore_service_url', 'http://localhost:3001');
```

### 4. New Configuration File (`FrontEnd/js/config/taxcore-config.js`)

**Purpose**: Centralized TaxCore connection configuration (optional reference file).

### 5. Documentation and Scripts

- `websocket-server/TAXCORE_SERVICE.md` - Comprehensive service documentation
- `websocket-server/start-taxcore.sh` - Startup script with health checks
- `websocket-server/package.json` - Added npm scripts for running services

**NPM Scripts**:
```bash
npm run taxcore    # Start TaxCore service only
npm start          # Start WebSocket server only
npm run dev        # Start both services
```

## Architecture

### Option 1: Direct Connection (Recommended)
```
Browser (POS) ──→ Node.js Service (port 3001) ──→ TaxCore API
```

**Advantages**:
- Lower latency
- No PHP overhead
- Simpler architecture
- Better for high-volume transactions

### Option 2: PHP Proxy
```
Browser (POS) ──→ PHP (PosController) ──→ Node.js Service (port 3001) ──→ TaxCore API
```

**Advantages**:
- Maintains existing auth/session logic
- PHP can log/audit requests
- Easier integration with existing PHP infrastructure

## Installation & Setup

### 1. Install Node.js Dependencies
```bash
cd websocket-server
npm install
```

### 2. Verify Certificate
```bash
ls -la ../FRCS_Certs_Install/*.pfx
```

### 3. Set Environment Variables (Optional)
```bash
export TAXCORE_SERVICE_PORT=3001
export TAXCORE_PFX_PATH=/path/to/certificate.pfx
export TAXCORE_PFX_PASSWORD=your_password
```

### 4. Start TaxCore Service
```bash
# Option 1: Direct
cd websocket-server
npm run taxcore

# Option 2: Using startup script
./start-taxcore.sh

# Option 3: Using PM2 (production)
pm2 start taxcore-service.js --name taxcore
pm2 save
```

### 5. Configure Frontend (Optional)

**For Direct Connection**:
```javascript
// In browser console
localStorage.setItem('taxcore_direct', 'true');
localStorage.setItem('taxcore_service_url', 'http://localhost:3001');
```

**For PHP Proxy** (default):
```javascript
localStorage.setItem('taxcore_direct', 'false');
```

Or use the TaxCore Settings button in POS (if implemented in UI).

## Testing

### 1. Test Service Health
```bash
curl http://localhost:3001/health
```

**Expected Response**:
```json
{"status":"ok","service":"TaxCore Service"}
```

### 2. Test Tax Rates
```bash
curl http://localhost:3001/tax-rates
```

### 3. Test Sale Creation
```bash
curl -X POST http://localhost:3001/sale \
  -H "Content-Type: application/json" \
  -d '{
    "items": [{"name": "Test Item", "qty": 1, "price": 100, "labels": ["G"]}],
    "payments": [{"method": "Cash", "amount": 100}],
    "type": "Normal"
  }'
```

### 4. Test from POS
1. Open POS interface
2. Add items to cart
3. Complete a sale
4. Check browser console for connection mode
5. Verify receipt generation

## Migration Path

### Phase 1: Parallel Running (Current)
- Node.js service runs alongside existing PHP TaxCoreClient
- PHP PosController can use either method
- Zero downtime migration

### Phase 2: Gradual Transition
- Enable PHP proxy mode for all users
- Monitor logs and performance
- Verify all sale types work correctly

### Phase 3: Direct Connection (Optional)
- Enable direct browser-to-Node connection for performance
- Maintain PHP proxy as fallback

### Phase 4: Deprecation (Future)
- Once stable, deprecate direct PHP TaxCoreClient usage
- Keep class for compatibility but log warnings

## Benefits

1. **Better Certificate Handling**: Node.js + curl handles PFX certificates more reliably than PHP
2. **Performance**: Reduced PHP overhead, faster response times
3. **Scalability**: Node.js service can be scaled independently
4. **Flexibility**: Support both direct and proxy modes
5. **Maintainability**: Separation of concerns, easier to debug
6. **Modern Architecture**: Aligns with microservices approach

## Troubleshooting

### Service Won't Start
- Check Node.js is installed: `node --version`
- Verify port is available: `netstat -tlnp | grep 3001`
- Check certificate path and permissions

### Certificate Not Found
```bash
# Find certificates
find / -name "*.pfx" 2>/dev/null

# Check permissions
ls -l /path/to/certificate.pfx

# Set correct permissions
chmod 644 /path/to/certificate.pfx
```

### Connection Refused
```bash
# Check if service is running
ps aux | grep taxcore-service

# Check firewall
sudo ufw allow 3001

# Check logs
tail -f ../logs/taxcore-service.log
```

### CORS Errors
- Verify service is setting CORS headers (already configured)
- Check browser console for detailed error messages
- Ensure service URL is correct

## Rollback Plan

If issues occur, the system can immediately fall back to:

1. **PHP Proxy Mode**: Change frontend to use PHP proxy
2. **Direct PHP Client**: Modify PosController to use TaxCoreClient directly
3. **Service Restart**: `pm2 restart taxcore` or `npm run taxcore`

## Future Enhancements

1. **Rate Limiting**: Add request rate limiting to Node.js service
2. **Caching**: Cache tax rates for performance
3. **Queue System**: Add Redis queue for high-volume scenarios
4. **Monitoring**: Integrate with monitoring tools (Prometheus, Grafana)
5. **Authentication**: Add API key authentication for service
6. **Load Balancing**: Run multiple instances behind load balancer
7. **Docker**: Containerize service for easier deployment

## Security Considerations

1. **Certificate Security**: 
   - Store PFX file with restricted permissions (600 or 644)
   - Never expose via web server
   - Rotate certificates as per FRCS guidelines

2. **Network Security**:
   - Run behind reverse proxy (nginx) in production
   - Use HTTPS for all external connections
   - Consider restricting Node.js service to localhost if using PHP proxy

3. **Environment Variables**:
   - Use `.env` file for sensitive data
   - Never commit secrets to version control

## Support & Documentation

- **Service Documentation**: `websocket-server/TAXCORE_SERVICE.md`
- **Logs Location**: `logs/taxcore-service.log`
- **Configuration**: Environment variables or `.env` file

## Conclusion

The TaxCore integration has been successfully refactored to use a Node.js microservice architecture. The system maintains full backward compatibility while providing improved performance, reliability, and maintainability. Both direct and proxy connection modes are supported for flexibility during migration.
