# Testing Guide - Cartec API

## Current Status

✅ **API is running** on `http://localhost:3000`  
❌ **Database not fully configured** - OT creation failing

---

## Quick Test Results

```bash
# Run this to test the API
/tmp/full_test_with_setup.sh
```

**Current Result:** HTTP 500 - Database/stored procedure issue

---

## Setup Checklist

### 1. ✅ API Running

```bash
curl http://localhost:3000/api/health
# Expected: {"status":"ok","timestamp":"..."}
```

### 2. ❓ Database Tables

Run this to check:

```sql
USE revisa;  -- or your database name

-- Check if tables exist
SHOW TABLES LIKE 'orden_trabajo';
SHOW TABLES LIKE 'vehiculos_ot';
SHOW TABLES LIKE 'Tecnicos';
```

**If tables DON'T exist:**

The stored procedure expects these new tables that may not be in your current schema. You have two options:

#### Option A: Adapt to Existing Schema
Modify the stored procedure to use existing tables (`OT`, `Vehiculos`, `OT_Vehiculos` instead of `orden_trabajo`, `vehiculos_ot`).

#### Option B: Create New Tables
```sql
CREATE TABLE IF NOT EXISTS orden_trabajo (
    id INT AUTO_INCREMENT PRIMARY KEY,
    rut_cliente VARCHAR(15),
    nombre_cliente VARCHAR(255),
    direccion VARCHAR(255),
    comuna VARCHAR(100),
    telefono VARCHAR(50),
    email VARCHAR(255),
    rut_tecnico VARCHAR(15),
    gps_provider VARCHAR(50),
    tipo_servicio VARCHAR(50),
    taller_install VARCHAR(100),
    fecha_creacion DATETIME,
    INDEX idx_rut_cliente (rut_cliente),
    INDEX idx_rut_tecnico (rut_tecnico)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS vehiculos_ot (
    id INT AUTO_INCREMENT PRIMARY KEY,
    id_ot INT NOT NULL,
    patente VARCHAR(10),
    marca VARCHAR(100),
    modelo VARCHAR(100),
    color VARCHAR(50),
    anio INT,
    INDEX idx_id_ot (id_ot),
    INDEX idx_patente (patente),
    FOREIGN KEY (id_ot) REFERENCES orden_trabajo(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```

### 3. ❓ Stored Procedure Installed

Check:
```sql
SHOW PROCEDURE STATUS WHERE Name = 'prc_api_create_OT';
```

**If NOT installed:**
```bash
mysql -u root -p revisa < /var/www/html/W_CartecInstalador/api_implementation/cartec_api/sql/prc_api_create_OT.sql
```

### 4. ❓ Test Technician Exists

Check:
```sql
SELECT * FROM Tecnicos WHERE rut_tecnico = '11111111-1';
```

**If NOT found:**
```sql
INSERT INTO Tecnicos (rut_tecnico, nombre, telefono, email, creado_en)
VALUES ('11111111-1', 'Test Technician', '+56912345678', 'test@cartec.cl', NOW());
```

---

## Running Tests

### Method 1: Comprehensive Test Script

```bash
/tmp/full_test_with_setup.sh
```

This script:
- ✅ Checks API health
- ❓ Tests OT creation
- 📋 Provides diagnostic steps

### Method 2: Direct curl

```bash
curl -X POST http://localhost:3000/api/ot/create \
  -H "Content-Type: application/json" \
  -d '{
    "cliente": {
      "rut": "12345678-5",
      "nombre": "Test Client",
      "direccion": "Test Address 123",
      "comuna": "Santiago",
      "telefono": "+56912345678",
      "email": "test@test.cl"
    },
    "tecnico": {
      "rut": "11111111-1"
    },
    "servicio": {
      "presGPS": "gpsimple",
      "tiposerv": "instalacion_gps",
      "taller_install": "cartec"
    },
    "vehiculos": [
      {
        "patente": "TEST01",
        "marca": "Toyota",
        "modelo": "Corolla",
        "color": "Blanco",
        "anio": 2020
      }
    ]
  }' | python3 -m json.tool
```

### Method 3: Node.js Test Suite

```bash
cd /var/www/html/W_CartecInstalador/api_implementation/cartec_api
node test/api.test.js
```

### Method 4: Bash Test Suite

```bash
cd /var/www/html/W_CartecInstalador/api_implementation/cartec_api
./test/run_tests.sh
```

---

## Expected Success Response

```json
{
  "success": 1,
  "message": "OT creada correctamente ID: 123 Vehiculos: 1",
  "data": {
    "id_ot": 123,
    "rut_cliente": "12345678-5",
    "rut_tecnico": "11111111-1",
    "vehiculos_procesados": 1
  }
}
```

---

## Troubleshooting

### Error: "Técnico no encontrado" (HTTP 404)

**Solution:** Create test technician (see checklist #4 above)

### Error: "Error al crear la OT" (HTTP 500)

**Possible causes:**
1. Stored procedure not installed
2. Tables don't exist
3. Database connection issue
4. SQL syntax error in procedure

**Check logs:**
```bash
sudo journalctl -u cartec-api -n 50
```

### Error: "Dígito verificador inválido" (HTTP 400)

**Solution:** Use a valid Chilean RUT. Test RUTs:
- `11111111-1`
- `12345678-5`
- `22222222-2`

### Database Connection Refused

**Check `.env` file:**
```bash
cat /opt/cartec_api/.env
```

Verify:
- `DB_HOST=localhost`
- `DB_USER=root` (or your user)
- `DB_PASSWORD=your_password`
- `DB_NAME=revisa` (or your database)

---

## Verification After Success

After a successful OT creation, verify in database:

```sql
-- Check the OT was created
SELECT * FROM orden_trabajo ORDER BY id DESC LIMIT 1;

-- Check vehicles were created
SELECT * FROM vehiculos_ot WHERE id_ot = (SELECT MAX(id) FROM orden_trabajo);

-- Count total OTs
SELECT COUNT(*) as total_ots FROM orden_trabajo;
```

---

## API Test Endpoints

### Health Check
```bash
curl http://localhost:3000/api/health
```

### GPS Providers (all valid)
- `gpsimple`
- `entel`
- `tattersall`
- `cemin`
- `carflex`

### Service Types
- `instalacion_gps`
- `visita_tecnica`
- `desinstalacion_gps`

### Workshops
- `cartec`
- `servitattersall`

---

## Next Steps

1. **Fix Database Issue:**
   - Run diagnostic SQL (Step 2 in checklist)
   - Create missing tables if needed
   - Install stored procedure
   - Create test technician

2. **Re-run Tests:**
   ```bash
   /tmp/full_test_with_setup.sh
   ```

3. **Verify Success:**
   - Check for HTTP 201 response
   - Verify OT ID is returned
   - Check database for inserted records

4. **Production Setup:**
   - Update `.env` with production credentials
   - Create actual technicians
   - Test with real data

---

## Support Files

- **Test Scripts:** `/var/www/html/W_CartecInstalador/api_implementation/cartec_api/test/`
- **Stored Procedure:** `/var/www/html/W_CartecInstalador/api_implementation/cartec_api/sql/prc_api_create_OT.sql`
- **Environment Config:** `/opt/cartec_api/.env`
- **API Source:** `/opt/cartec_api/src/index.js`

---

## Quick Commands Reference

```bash
# Check API status
sudo systemctl status cartec-api

# View API logs
sudo journalctl -u cartec-api -f

# Restart API
sudo systemctl restart cartec-api

# Run tests
node test/api.test.js

# Run bash tests
./test/run_tests.sh

# Check database
mysql -u root -p revisa

# Install stored procedure
mysql -u root -p revisa < sql/prc_api_create_OT.sql
```

