# TaxCore Node.js Service

This directory contains the Node.js service that handles communication with the Fiji Revenue and Customs Service (FRCS) TaxCore API.

## Architecture

The POS system now uses a Node.js service as an intermediary between the browser/PHP and TaxCore:

```
Browser (POS.js)
    ↓
    ├─→ Direct to Node.js (port 3001)    [Recommended]
    │       ↓
    │   taxcore-service.js
    │       ↓
    │   TaxCore API (with mTLS)
    │
    └─→ Via PHP Proxy
            ↓
        PosController.php
            ↓
        taxcore-service.js
            ↓
        TaxCore API (with mTLS)
```

## Why Node.js Service?

1. **Better Certificate Handling**: Node.js handles mutual TLS (mTLS) with PFX certificates more reliably than PHP
2. **Performance**: Reduces PHP overhead for TaxCore operations
3. **Scalability**: Can be deployed separately and scaled independently
4. **Modern Architecture**: Separates concerns between web server and external API communication

## Services

### 1. TaxCore Service (`taxcore-service.js`)

Handles all communication with the FRCS TaxCore API.

**Port**: 3001 (configurable via `TAXCORE_SERVICE_PORT`)

**Endpoints**:
- `GET /health` - Health check
- `GET /tax-rates` - Fetch tax rates from TaxCore
- `POST /sale` - Create a sale (Normal, Advance, Proforma, Training, or Copy)

**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/20f351f3-9b39-4c63-b9e0-d8a00b6e93fb/api
TAXCORE_PFX_PATH=../FRCS_Certs_Install/LK2VRSH4-DeveloperAuthenticationCertificate.pfx
TAXCORE_PFX_PASSWORD=2CBP6HMW
TAXCORE_PIN_JSON=3840
TAXCORE_DEBUG=true
```

### 2. WebSocket Server (`server.js`)

Handles real-time synchronization via Redis and PostgreSQL NOTIFY/LISTEN.

**Port**: 8080 (configurable via `WS_PORT`)

## Installation

1. Install dependencies:
```bash
cd websocket-server
npm install
```

2. Ensure certificate file exists:
```bash
ls -la ../FRCS_Certs_Install/*.pfx
```

3. Set environment variables (optional, defaults are provided):
```bash
export TAXCORE_SERVICE_PORT=3001
export TAXCORE_PFX_PATH=/path/to/certificate.pfx
export TAXCORE_PFX_PASSWORD=your_password
```

## Running the Services

### Start TaxCore Service Only
```bash
npm run taxcore
```

### Start WebSocket Server Only
```bash
npm start
```

### Start Both Services (Development)
```bash
npm run dev
```

### Production Deployment

Use a process manager like PM2:

```bash
# Install PM2 globally
npm install -g pm2

# Start services
pm2 start taxcore-service.js --name taxcore
pm2 start server.js --name websocket

# Save configuration
pm2 save

# Setup auto-start on reboot
pm2 startup
```

## Frontend Configuration

The POS frontend can connect in two modes:

### 1. Direct Connection (Recommended)

Browser connects directly to Node.js service:

```javascript
// In browser console or app initialization
localStorage.setItem('taxcore_direct', 'true');
localStorage.setItem('taxcore_service_url', 'http://localhost:3001');
```

### 2. PHP Proxy Mode

Browser connects to PHP which proxies to Node.js:

```javascript
// In browser console or app initialization
localStorage.setItem('taxcore_direct', 'false');
```

Or use the configuration file at `/FrontEnd/js/config/taxcore-config.js`

## Testing

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

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

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

### 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",
    "Cashier": "Test Cashier"
  }'
```

## Troubleshooting

### Certificate Not Found

If you see "Certificate not found" errors:

1. Check certificate path:
```bash
ls -la /var/www/html/TAF/FRCS_Certs_Install/*.pfx
```

2. Ensure read permissions:
```bash
chmod 644 /var/www/html/TAF/FRCS_Certs_Install/*.pfx
```

3. Set explicit path:
```bash
export TAXCORE_PFX_PATH=/full/path/to/certificate.pfx
```

### Connection Refused

If browser can't connect to Node.js service:

1. Verify service is running:
```bash
ps aux | grep taxcore-service
```

2. Check if port is listening:
```bash
netstat -tlnp | grep 3001
```

3. Check firewall rules:
```bash
sudo ufw status
sudo ufw allow 3001
```

### CORS Issues

If browser shows CORS errors, verify the service is setting proper headers (already configured in `taxcore-service.js`):
```javascript
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
```

## Logs

Logs are written to:
- `/logs/taxcore-service.log` - TaxCore service operations
- `/logs/ws-server.log` - WebSocket server operations

View logs:
```bash
tail -f ../logs/taxcore-service.log
tail -f ../logs/ws-server.log
```

## Security Considerations

1. **Certificate Security**: The PFX certificate contains private keys. Ensure:
   - File permissions are restricted (600 or 644)
   - File is not exposed via web server
   - Backups are encrypted

2. **Network Security**: In production:
   - Run services behind a reverse proxy (nginx)
   - Use HTTPS for all external connections
   - Restrict Node.js service to localhost if using PHP proxy
   - Implement rate limiting

3. **Environment Variables**: Use `.env` file or system environment variables. Never commit secrets to version control.

## Migration from PHP TaxCoreClient

The PHP `TaxCoreClient` class is still available but deprecated. To migrate:

1. Start the Node.js service
2. Update `PosController.php` configuration (already done)
3. Enable direct connection in frontend (optional)
4. Test thoroughly in sandbox environment
5. Monitor logs during transition

## Development

### Adding New Sale Types

To add a new sale type:

1. Add case in `taxcore-service.js`:
```javascript
case 'newsaletype':
  result = await createNewSaleType(payload);
  break;
```

2. Implement the function:
```javascript
async function createNewSaleType(payload) {
  const enrichedPayload = injectDefaults(payload, 'NewSaleType');
  const url = `${TAXCORE_CONFIG.vsdcUrl}/v3/invoices`;
  return await executeCurlCommand(url, enrichedPayload, true);
}
```

3. Export the function at the bottom of the file

### Debugging

Enable debug logging:
```bash
export TAXCORE_DEBUG=true
npm run taxcore
```

## Support

For issues:
1. Check logs first
2. Verify certificate and network connectivity
3. Test with curl commands above
4. Review TaxCore API documentation

## License

Part of the TAF ERP system.
