# e-conomic Write Mode Guide

## Overview

Time Tracking modulet kan eksportere godkendte tidsregistreringer til e-conomic som **draft orders**.

**Safety-first approach**: Der er TWO lag af sikkerhedsflag for at beskytte mod utilsigtede ændringer.

## Safety Flags

### Layer 1: Read-Only Mode (BLOCKING)
```bash
TIMETRACKING_ECONOMIC_READ_ONLY=true  # Bloker ALLE skrivninger
```

Når `READ_ONLY=true`:
- Alle write operationer blokeres 100%
- Logger: `🚫 BLOCKED: Export order X to e-conomic - READ_ONLY mode enabled`
- API returnerer fejl med instruktion om at disable flag

### Layer 2: Dry-Run Mode (SIMULATION)
```bash
TIMETRACKING_ECONOMIC_DRY_RUN=true  # Log men send ikke
```

Når `DRY_RUN=true`:
- Write operationer simuleres
- Logger detaljeret payload der VILLE blive sendt
- API returnerer success men med `dry_run: true` flag
- INGEN data sendes til e-conomic

### Production Mode (LIVE WRITES)
```bash
TIMETRACKING_ECONOMIC_READ_ONLY=false
TIMETRACKING_ECONOMIC_DRY_RUN=false
```

Når **BEGGE** flags er `false`:
- ⚠️ REELLE skrivninger til e-conomic
- Logger: `⚠️ EXECUTING WRITE OPERATION: Export order X`
- Kræver også gyldig `economic_customer_number` på kunde

## Activation Steps

### 1. Verify e-conomic Credentials
```bash
# In .env file
ECONOMIC_API_URL=https://restapi.e-conomic.com
ECONOMIC_APP_SECRET_TOKEN=<your_token>
ECONOMIC_AGREEMENT_GRANT_TOKEN=<your_token>
```

Test connection:
```bash
curl http://localhost:8001/api/v1/timetracking/economic/test
```

Expected response:
```json
{
  "status": "connected",
  "read_only": true,
  "dry_run": true
}
```

### 2. Ensure Customers Have e-conomic Numbers

Alle kunder SKAL have `economic_customer_number` for at kunne eksporteres:

```sql
-- Check customers without e-conomic number
SELECT id, name, vtiger_id 
FROM tmodule_customers 
WHERE economic_customer_number IS NULL;
```

e-conomic customer number synces automatisk fra vTiger `cf_854` felt.

**Fix missing numbers:**
1. Opdater vTiger med e-conomic customer number i `cf_854` felt
2. Kør sync: `POST /api/v1/timetracking/sync/customers`
3. Verify: `GET /api/v1/timetracking/customers`

### 3. Test with Dry-Run Mode

**Step 3.1**: Disable READ_ONLY (men behold DRY_RUN)
```bash
# In .env
TIMETRACKING_ECONOMIC_READ_ONLY=false  # ⚠️ Allow operations
TIMETRACKING_ECONOMIC_DRY_RUN=true     # ✅ Still safe - no real writes
```

Restart API:
```bash
docker-compose restart api
```

**Step 3.2**: Generate test order
```bash
# Get approved entries for a customer
curl http://localhost:8001/api/v1/timetracking/wizard/next

# Approve entry
curl -X POST http://localhost:8001/api/v1/timetracking/wizard/approve/123

# Generate order
curl -X POST http://localhost:8001/api/v1/timetracking/orders/generate \
  -H "Content-Type: application/json" \
  -d '{"customer_id": 1}'
```

**Step 3.3**: Test export (dry-run)
```bash
curl -X POST http://localhost:8001/api/v1/timetracking/orders/1/export \
  -H "Content-Type: application/json" \
  -d '{}'
```

Expected response:
```json
{
  "success": true,
  "dry_run": true,
  "order_id": 1,
  "economic_draft_id": null,
  "message": "DRY-RUN: Would export order ORD-2024-001 to e-conomic",
  "details": {
    "order_number": "ORD-2024-001",
    "customer_name": "Test Customer",
    "total_amount": 425.0,
    "line_count": 1,
    "read_only": false,
    "dry_run": true
  }
}
```

**Check logs** for payload details:
```bash
docker-compose logs api | grep "📤 Sending to e-conomic"
```

### 4. Enable Production Mode (LIVE WRITES)

⚠️ **CRITICAL**: Only proceed if dry-run tests succeeded!

**Step 4.1**: Disable DRY_RUN
```bash
# In .env
TIMETRACKING_ECONOMIC_READ_ONLY=false  # ⚠️ Writes enabled
TIMETRACKING_ECONOMIC_DRY_RUN=false    # ⚠️⚠️ REAL WRITES TO PRODUCTION!
```

**Step 4.2**: Restart API
```bash
docker-compose restart api
```

**Step 4.3**: Export ONE test order
```bash
curl -X POST http://localhost:8001/api/v1/timetracking/orders/1/export \
  -H "Content-Type: application/json" \
  -d '{}'
```

Expected response (success):
```json
{
  "success": true,
  "dry_run": false,
  "order_id": 1,
  "economic_draft_id": 12345,
  "economic_order_number": "12345",
  "message": "Successfully exported to e-conomic draft 12345",
  "details": {
    "draftOrderNumber": 12345,
    ...
  }
}
```

**Step 4.4**: Verify in e-conomic
- Login to e-conomic
- Go to **Sales → Draft Orders**
- Find order number `12345`
- Verify customer, lines, amounts

## Error Handling

### Missing Customer Number
```json
{
  "status_code": 400,
  "detail": "Customer ABC has no e-conomic customer number"
}
```

**Fix**: Sync customer data from vTiger (ensure `cf_854` is populated).

### e-conomic API Error
```json
{
  "status_code": 400,
  "detail": "e-conomic API error: customer.customerNumber: Customer not found"
}
```

**Fix**: Verify customer exists in e-conomic with correct number.

### Network/Timeout Error
```json
{
  "status_code": 500,
  "detail": "Internal error: Timeout connecting to e-conomic"
}
```

**Fix**: Check network, verify `ECONOMIC_API_URL` is correct.

## Audit Trail

All export operations are logged to `tmodule_sync_log`:

```sql
SELECT * FROM tmodule_sync_log 
WHERE event_type = 'export_completed' 
ORDER BY created_at DESC 
LIMIT 10;
```

Fields tracked:
- `order_id` - Which order was exported
- `economic_draft_id` - Draft order number in e-conomic
- `economic_order_number` - Order number in e-conomic
- `dry_run` - Whether it was a simulation
- `created_by` - User ID who triggered export
- `created_at` - Timestamp

## Rollback Plan

If issues occur in production:

**Step 1**: Immediately re-enable safety flags
```bash
TIMETRACKING_ECONOMIC_READ_ONLY=true
TIMETRACKING_ECONOMIC_DRY_RUN=true
docker-compose restart api
```

**Step 2**: Review audit log
```sql
SELECT * FROM tmodule_sync_log 
WHERE event_type LIKE 'export_%' 
  AND created_at > NOW() - INTERVAL '1 hour';
```

**Step 3**: Manual cleanup in e-conomic
- Go to **Sales → Draft Orders**
- Filter by date (today)
- Review and delete erroneous drafts
- Draft orders can be deleted without impact

## Best Practices

1. **Always test with dry-run first**
2. **Export ONE order to production** before bulk operations
3. **Verify in e-conomic** after first export
4. **Monitor audit logs** regularly
5. **Re-enable safety flags** when not actively exporting
6. **Keep `EXPORT_TYPE=draft`** - never book automatically

## Configuration Reference

```bash
# Safety Flags (default: SAFE)
TIMETRACKING_ECONOMIC_READ_ONLY=true   # Block all writes
TIMETRACKING_ECONOMIC_DRY_RUN=true     # Simulate writes

# Export Settings
TIMETRACKING_EXPORT_TYPE=draft         # draft|booked (ALWAYS use draft)

# e-conomic Credentials
ECONOMIC_API_URL=https://restapi.e-conomic.com
ECONOMIC_APP_SECRET_TOKEN=<token>
ECONOMIC_AGREEMENT_GRANT_TOKEN=<token>
```

## Support

If export fails consistently:
1. Check `docker-compose logs api | grep ERROR`
2. Verify customer has `economic_customer_number`
3. Test e-conomic connection: `GET /timetracking/economic/test`
4. Review payload in dry-run logs
5. Contact e-conomic support if API errors persist
