# TaxCore Test Site Configuration

## Overview

The POS system now automatically detects test/development sites and configures the TaxCore connection mode accordingly:

- **Test Sites:** Use PHP proxy by default (for easier backend debugging)
- **Production Sites:** Use direct Node.js connection (for best performance)

## Automatic Detection

The system automatically detects connection mode based on hostname:

### PHP Proxy Sites (Test/Staging)
Sites that use **PHP proxy** for backend debugging:
- `frcs.cybexpte.com` (main staging server) ← **Specific configuration**
- Hostnames containing: `test`, `staging`, `dev`, `demo`

### Direct Node.js Sites (Production/Local Dev)
Sites that use **direct Node.js** connection for performance:
- `localhost` or `127.0.0.1` (local development) ← **Special case for fast iteration**
- All production domains (e.g., `pos.taf.com`, `erp.company.com`)

### Examples:

| URL | Auto-Detected As | Default Mode | Reason |
|-----|------------------|--------------|--------|
| `http://localhost:8080` | **Production** | **Direct Node.js** | Local dev - fast iteration |
| `http://frcs.cybexpte.com` | **Test Site** | **PHP Proxy** | Main staging server |
| `http://test.example.com` | Test Site | PHP Proxy | Contains 'test' |
| `http://staging.taf.com` | Test Site | PHP Proxy | Contains 'staging' |
| `http://demo.taf.com` | Test Site | PHP Proxy | Contains 'demo' |
| `http://pos.taf.com` | Production | Direct Node.js | Production domain |
| `https://erp.company.com` | Production | Direct Node.js | Production domain |

## Connection Modes

### Direct Connection (Production)
```
Browser → Node.js (port 3001) → TaxCore API
```
**Advantages:**
- Faster (one less hop)
- Better for production load
- Real-time receipt generation

**Use When:**
- Production environment
- High transaction volume
- Performance is critical

### PHP Proxy (Testing/Debugging)
```
Browser → PHP (port 8080) → Node.js (port 3001) → TaxCore API
```
**Advantages:**
- Easier to debug (can inspect PHP logs)
- Can add business logic in PHP layer
- Consistent with legacy architecture

**Use When:**
- Development environment
- Testing backend changes
- Debugging TaxCore integration
- Need to inspect/log requests server-side

## Configuration UI

### Access Settings
1. Open POS interface
2. Click "TaxCore Settings" button (or gear icon)
3. Configure options

### Settings Options

#### 1. Site Type Override
- **Auto-detect (Default):** System automatically detects test vs production
- **Force Test Site Mode:** Always use PHP proxy regardless of hostname
- **Force Production Mode:** Always use direct connection regardless of hostname

#### 2. Connection Mode
- **Direct Connection (Production):** Browser connects directly to Node.js
- **PHP Proxy (Testing/Debugging):** Browser connects through PHP backend

#### 3. Node.js Service URL
- Default: `http://localhost:3001`
- Docker: Auto-detects `http://{hostname}:3001`
- Custom: Can override for any environment

### Test Connection
Click "Test Connection" button to verify Node.js service is reachable and responding.

## Manual Configuration (localStorage)

Settings are stored in browser localStorage:

```javascript
// Force test site mode
localStorage.setItem('taxcore_test_site', 'true');

// Force production mode
localStorage.setItem('taxcore_test_site', 'false');

// Auto-detect (remove override)
localStorage.removeItem('taxcore_test_site');

// Set connection mode
localStorage.setItem('taxcore_direct', 'true');  // Direct
localStorage.setItem('taxcore_direct', 'false'); // Proxy

// Set service URL
localStorage.setItem('taxcore_service_url', 'http://localhost:3001');
```

## Console Logging

The system logs connection mode for each sale:

```javascript
// Test site using proxy
🧪 TEST SITE | 🔌 TaxCore Connection Mode: PROXY via PHP
📡 Endpoint: ../api/POS/taxcore

// Production site using direct
🚀 PRODUCTION | 🔌 TaxCore Connection Mode: DIRECT to Node.js
📡 Endpoint: http://localhost:3001/sale

// Docker environment
🐳 Docker environment detected, using: http://docker-host:3001
```

## Use Cases

### Scenario 1: Development Testing
**Setup:**
- Hostname: `localhost:8080`
- Auto-detected: Test Site
- Default Mode: PHP Proxy

**Benefit:** Can add `error_log()` statements in `PosController.php` to debug requests.

### Scenario 2: Staging Server
**Setup:**
- Hostname: `staging.taf.com`
- Auto-detected: Test Site
- Default Mode: PHP Proxy

**Benefit:** QA team can test with backend logging enabled.

### Scenario 3: Production Server
**Setup:**
- Hostname: `pos.taf.com`
- Auto-detected: Production
- Default Mode: Direct Node.js

**Benefit:** Maximum performance for live transactions.

### Scenario 4: Demo on Production URL
**Setup:**
- Hostname: `demo.taf.com` (contains 'demo')
- Auto-detected: Test Site
- Default Mode: PHP Proxy

**Benefit:** Safe for demonstrations with logging enabled.

### Scenario 5: Force Production Mode on Test Server
**Setup:**
- Hostname: `localhost:8080`
- Override: Force Production Mode
- Actual Mode: Direct Node.js

**Benefit:** Test production behavior in development environment.

## Implementation Details

### Code Location
`FrontEnd/js/modules/POS/POS.js`

### Key Functions

#### checkIfTestSite()
```javascript
// Returns true if current site is test/development
function checkIfTestSite() {
  // Check manual override
  const manualTestSite = localStorage.getItem('taxcore_test_site');
  if (manualTestSite === 'true') return true;
  if (manualTestSite === 'false') return false;
  
  // Auto-detect based on hostname
  const hostname = window.location.hostname.toLowerCase();
  const testHostnames = ['localhost', '127.0.0.1', 'test', 'staging', 'dev', 'demo'];
  if (testHostnames.some(test => hostname.includes(test))) return true;
  
  // Check for test ports
  const port = window.location.port;
  const testPorts = ['3000', '8000', '8080', '8888'];
  if (testPorts.includes(port)) return true;
  
  return false;
}
```

#### sendTaxCoreData()
```javascript
async function sendTaxCoreData(saleData) {
  const isTestSite = checkIfTestSite();
  const taxcoreDirectSetting = localStorage.getItem('taxcore_direct');
  
  // Test sites use PHP proxy by default, production uses direct
  let useDirectConnection;
  if (taxcoreDirectSetting !== null) {
    useDirectConnection = taxcoreDirectSetting !== 'false';
  } else {
    useDirectConnection = !isTestSite; // Auto-detect
  }
  
  const endpoint = useDirectConnection 
    ? `${serviceUrl}/sale`      // Direct: http://localhost:3001/sale
    : '../api/POS/taxcore';     // Proxy:  /api/POS/taxcore
  
  // Send request...
}
```

## Backend Support

### PHP Proxy Endpoint
**File:** `api/controllers/PosController.php`

```php
public function taxcore() {
    // Receive sale data from browser
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Forward to Node.js TaxCore service
    $sale = $this->callTaxCoreService($input);
    
    // Save receipt to database
    $qb->table('sales_receipts')->insert([...]);
    
    // Return receipt to browser
    respond(200, ['success' => true, 'receipt' => $journal, 'taxcore' => $sale]);
}

private function callTaxCoreService(array $payload): array {
    $url = $this->taxcoreServiceUrl . '/sale';  // http://localhost:3001/sale
    
    // Send via cURL to Node.js
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    $response = curl_exec($ch);
    
    return json_decode($response, true);
}
```

## Troubleshooting

### Issue: Test site using direct mode
**Check:**
1. View console logs - look for "🧪 TEST SITE" or "🚀 PRODUCTION"
2. Open TaxCore Settings
3. Verify "Site Type Override" is set correctly
4. Check if manual `taxcore_direct=true` is set in localStorage

**Fix:**
- Set "Connection Mode" to "PHP Proxy"
- Or remove `taxcore_direct` from localStorage

### Issue: Production site using proxy mode
**Check:**
1. View console logs
2. Verify hostname doesn't contain test keywords
3. Check for manual overrides in localStorage

**Fix:**
- Set "Connection Mode" to "Direct Connection"
- Or set `taxcore_direct=true` in localStorage

### Issue: "Connection failed" in settings
**Check:**
1. Verify Node.js service is running: `curl http://localhost:3001/health`
2. Check service URL is correct
3. Verify firewall isn't blocking port 3001

**Fix:**
```bash
# Start TaxCore service
cd /var/www/html/TAF/websocket-server
node taxcore-service.js &

# Or restart Docker
docker-compose restart taxcore-service
```

## Best Practices

### Development
1. Use auto-detection (don't override unless needed)
2. Keep PHP proxy mode enabled for debugging
3. Add `error_log()` statements in `PosController.php` for testing

### Testing
1. Test both modes on staging server
2. Verify direct mode works before production
3. Use "Test Connection" button to validate setup

### Production
1. Use direct connection for performance
2. Only use proxy if specific business logic required
3. Monitor Node.js service health regularly

## Migration Path

### Legacy PHP-only System → Current Hybrid System

**Before:**
```
Browser → PHP → TaxCore API (PHP mTLS)
```

**Current (Test Sites):**
```
Browser → PHP → Node.js → TaxCore API (Node.js mTLS)
```

**Current (Production):**
```
Browser → Node.js → TaxCore API (Node.js mTLS)
```

**Benefit:** Maintains backward compatibility while enabling better performance.

---

## Related Documentation

- `docs/TaxCore_Current_Architecture.md` - Overall architecture
- `docs/TaxCore_Configuration_Guide.md` - Configuration reference
- `docs/TaxCore_Environment_Separation.md` - Environment setup
- `websocket-server/ENVIRONMENT.md` - Node.js environment config

---

**Last Updated:** October 2, 2025  
**Feature Added:** Auto-detection of test sites for optimal connection mode
