# ✅ TaxCore Node.js Integration - Implementation Complete

## 🎯 What Was Done

The POS TaxCore integration has been successfully refactored to use a **Node.js microservice architecture**. The system now routes TaxCore API calls through a dedicated Node.js service instead of directly from PHP.

## 📁 Files Created/Modified

### ✨ New Files Created:

1. **`websocket-server/taxcore-service.js`**
   - Main Node.js service handling TaxCore API communication
   - Supports all sale types (Normal, Advance, Proforma, Training, Copy)
   - Handles mutual TLS with PFX certificates via curl
   - Provides health check and tax rates endpoints

2. **`websocket-server/TAXCORE_SERVICE.md`**
   - Comprehensive documentation for the TaxCore service
   - Installation, configuration, and troubleshooting guide

3. **`websocket-server/start-taxcore.sh`**
   - Startup script with certificate verification
   - Automatic port checking and process management

4. **`start-taxcore-service.sh`** (project root)
   - Quick start wizard for initial setup
   - Dependency checking and guided configuration

5. **`FrontEnd/js/config/taxcore-config.js`**
   - Frontend configuration for TaxCore connection modes

6. **`docs/TaxCore_NodeJS_Migration.md`**
   - Complete migration guide and architecture documentation

7. **`.env.example`**
   - Environment variables template for configuration

### 🔧 Files Modified:

1. **`api/controllers/PosController.php`**
   - Added `$taxcoreServiceUrl` property
   - Added `callTaxCoreService()` method
   - Updated `taxcore()` to use Node.js service
   - Updated `getTaxRates()` to use Node.js service

2. **`FrontEnd/js/modules/POS/POS.js`**
   - Updated `sendTaxCoreData()` to support direct and proxy modes
   - Added `showTaxCoreSettingsModal()` for runtime configuration
   - Added localStorage-based connection mode switching

3. **`websocket-server/package.json`**
   - Added npm scripts for running services
   - Added service description

4. **`websocket-server/README.md`**
   - Updated to document both WebSocket and TaxCore services

## 🏗️ Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                         Browser (POS)                        │
└────────────────┬───────────────────────┬────────────────────┘
                 │                       │
                 │ Option 1:             │ Option 2:
                 │ Direct                │ PHP Proxy
                 │                       │
                 ▼                       ▼
┌────────────────────────┐   ┌──────────────────────────┐
│  Node.js TaxCore       │   │  PHP PosController       │
│  Service (port 3001)   │◄──┤  (taxcore method)        │
└────────┬───────────────┘   └──────────────────────────┘
         │
         │ curl + mTLS (PFX cert)
         │
         ▼
┌────────────────────────────────────────────────────────────┐
│              FRCS TaxCore API (V-SDC)                       │
└────────────────────────────────────────────────────────────┘
```

## 🚀 How to Start the Service

### Option 1: Quick Start (Recommended)
```bash
./start-taxcore-service.sh
```
This wizard will:
- Check Node.js installation
- Install dependencies
- Verify certificate location
- Check port availability
- Start the service

### Option 2: Manual Start
```bash
cd websocket-server
npm install
npm run taxcore
```

### Option 3: Production (PM2)
```bash
cd websocket-server
pm2 start taxcore-service.js --name taxcore
pm2 save
pm2 startup  # Enable auto-start on reboot
```

## ⚙️ Configuration

### Environment Variables (Optional)

Create a `.env` file in the project root or set these 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=/path/to/certificate.pfx
TAXCORE_PFX_PASSWORD=your_password
TAXCORE_PIN_JSON=3840
TAXCORE_DEBUG=true
```

### Frontend Configuration

The POS can work in two modes:

#### Mode 1: Direct Connection (Best Performance)
```javascript
// Set in browser console or app initialization
localStorage.setItem('taxcore_direct', 'true');
localStorage.setItem('taxcore_service_url', 'http://localhost:3001');
```

#### Mode 2: PHP Proxy (Default, More Secure)
```javascript
localStorage.setItem('taxcore_direct', 'false');
```

You can also use the **TaxCore Settings** button in the POS interface (if `taxcoreSettingsBtn` element exists).

## 🧪 Testing

### 1. Test Service Health
```bash
curl http://localhost:3001/health
```
**Expected**: `{"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",
    "Cashier": "Test User"
  }'
```

### 4. Test from POS
1. Start the TaxCore service
2. Open the POS interface
3. Add items and complete a sale
4. Check browser console for connection logs
5. Verify receipt is generated

## 📊 Monitoring

### View Logs
```bash
# TaxCore service logs
tail -f logs/taxcore-service.log

# WebSocket server logs
tail -f logs/ws-server.log

# Both services (if using PM2)
pm2 logs
```

### Check Service Status
```bash
# If using PM2
pm2 status

# Or check process
ps aux | grep taxcore-service

# Check port
netstat -tlnp | grep 3001
```

## 🔍 Troubleshooting

### Service Won't Start
- **Check Node.js**: `node --version` (need 14+)
- **Check port**: `netstat -tlnp | grep 3001`
- **Check logs**: `tail -f logs/taxcore-service.log`

### Certificate Issues
```bash
# Find certificate
find / -name "*.pfx" 2>/dev/null

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

# Fix permissions
chmod 644 /path/to/certificate.pfx
```

### Connection Issues
- Ensure service is running: `curl http://localhost:3001/health`
- Check firewall: `sudo ufw allow 3001`
- Verify CORS headers in service (already configured)

## ✅ Benefits of This Approach

1. **Better Certificate Handling** - Node.js + curl handles PFX certificates more reliably than PHP
2. **Improved Performance** - Reduced PHP overhead, faster response times
3. **Scalability** - Service can be scaled independently on multiple servers
4. **Flexibility** - Supports both direct and proxy connection modes
5. **Maintainability** - Clear separation of concerns, easier debugging
6. **Modern Architecture** - Microservices approach, ready for containerization

## 🔄 Migration Path

### Current State (Zero Downtime)
- ✅ Node.js service runs alongside existing PHP code
- ✅ PHP can proxy to Node.js OR use old TaxCoreClient
- ✅ Browser can connect directly OR through PHP
- ✅ Full backward compatibility

### Recommended Rollout
1. **Phase 1**: Start Node.js service, use PHP proxy mode (CURRENT)
2. **Phase 2**: Monitor and verify all sale types work correctly
3. **Phase 3**: Optionally enable direct connection for performance
4. **Phase 4**: Eventually deprecate direct PHP TaxCoreClient usage

## 📚 Documentation

- **Service Details**: `websocket-server/TAXCORE_SERVICE.md`
- **Migration Guide**: `docs/TaxCore_NodeJS_Migration.md`
- **Quick Reference**: `websocket-server/README.md`

## 🆘 Getting Help

If you encounter issues:
1. Check logs in `logs/taxcore-service.log`
2. Verify certificate exists and is readable
3. Test service health endpoint
4. Review documentation in `TAXCORE_SERVICE.md`

## 🎉 Next Steps

1. **Start the service**: `./start-taxcore-service.sh`
2. **Test a sale** in the POS interface
3. **Monitor logs** to ensure everything works
4. **Configure settings** via frontend if needed
5. **Set up PM2** for production deployment

---

**Status**: ✅ Implementation Complete and Ready for Testing

The system maintains full backward compatibility while providing a modern, scalable architecture for TaxCore integration.
