# Cartec OT Creation API - Implementation Guide

## 📋 Overview

This is a production-ready Node.js API for creating Órdenes de Trabajo (OT) in the Cartec system. The API provides a single endpoint to create OTs with automatic client management and vehicle registration.

**Version:** 1.0.0  
**Date:** December 2025

---

## 🎯 Features

- ✅ Create OT with single API call
- ✅ Automatic client creation/update (UPSERT)
- ✅ Vehicle registration and linking
- ✅ Chilean RUT validation
- ✅ GPS provider mapping (gpsimple, entel, tattersall, cemin, carflex)
- ✅ Service type mapping (instalacion_gps, visita_tecnica, desinstalacion_gps)
- ✅ Taller mapping (cartec, servitattersall)
- ✅ Database transaction safety
- ✅ Comprehensive error handling

---

## 📦 Prerequisites

### System Requirements
- Ubuntu 22.04 LTS (or similar)
- Node.js 12+ (recommended: 16 LTS)
- MySQL 8.0+
- Root or sudo access

### Database Requirements
- Existing `revisa` database
- Tables: `OT`, `Clientes`, `Tecnicos`, `Vehiculos`, `OT_Vehiculos`
- At least one technician registered in `Tecnicos` table

---

## 🚀 Installation Steps

### Step 1: Install Node.js

```bash
# Check if Node.js is installed
node --version

# If not installed, install Node.js 16 LTS
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs

# Verify installation
node --version
npm --version
```

---

### Step 2: Deploy API Files

```bash
# Create API directory
sudo mkdir -p /opt/cartec_api
sudo chown $USER:$USER /opt/cartec_api

# Copy files from api_deployment folder
cd /var/www/html/W_CartecInstalador/api_deployment
cp -r src package.json .env.example .gitignore /opt/cartec_api/
cp -r sql /opt/cartec_api/
cp -r docs /opt/cartec_api/

# Navigate to API directory
cd /opt/cartec_api
```

---

### Step 3: Configure Environment

```bash
# Copy example environment file
cp .env.example .env

# Edit environment variables
nano .env
```

**Required variables:**
```env
# Server Configuration
PORT=3000
NODE_ENV=production

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=your_mysql_password
DB_NAME=revisa
DB_CONNECTION_LIMIT=10
```

**Save and exit:** `Ctrl+X`, `Y`, `Enter`

---

### Step 4: Install Dependencies

```bash
cd /opt/cartec_api
npm install
```

Expected output:
```
added 50 packages, and audited 51 packages in 3s
```

---

### Step 5: Install Stored Procedure

```bash
# Install the stored procedure
mysql -u root -p revisa < /opt/cartec_api/sql/api_procedure.sql

# Verify installation
mysql -u root -p revisa -e "SHOW PROCEDURE STATUS WHERE Name = 'prc_api_create_OT';"
```

Expected output should show the procedure exists.

---

### Step 6: Create Test Technician (if needed)

```bash
mysql -u root -p revisa -e "
INSERT IGNORE INTO Tecnicos (rut_tecnico, nombre, creado_en) 
VALUES ('11111111-1', 'Test Technician API', NOW());
"
```

---

### Step 7: Test API Manually

```bash
# Start API manually (for testing)
cd /opt/cartec_api
node src/index.js
```

Expected output:
```
Server running on port 3000
```

**In another terminal, test the API:**
```bash
curl -X POST http://localhost:3000/api/health | python3 -m json.tool
```

Expected response:
```json
{
  "status": "ok",
  "timestamp": "2025-12-29T20:00:00.000Z"
}
```

**Stop the manual test:** `Ctrl+C`

---

### Step 8: Install as System Service

```bash
# Copy service file
sudo cp /var/www/html/W_CartecInstalador/api_deployment/config/cartec-api.service /etc/systemd/system/

# Reload systemd
sudo systemctl daemon-reload

# Enable service (start on boot)
sudo systemctl enable cartec-api

# Start service
sudo systemctl start cartec-api

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

Expected output:
```
● cartec-api.service - Cartec OT Creation API
   Loaded: loaded (/etc/systemd/system/cartec-api.service; enabled)
   Active: active (running) since ...
```

---

### Step 9: Verify API is Working

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

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

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

---

## 🔍 Verification

### Check Database Records

```bash
# Run verification script
mysql -u root -p revisa < /opt/cartec_api/sql/verify_ot_data.sql
```

### Check Service Logs

```bash
# View recent logs
sudo journalctl -u cartec-api -n 50

# Follow logs in real-time
sudo journalctl -u cartec-api -f
```

### Check API Process

```bash
# Check if API is running
ps aux | grep node

# Check port is listening
sudo netstat -tlnp | grep 3000
```

---

## 🔧 Maintenance

### Restart Service

```bash
sudo systemctl restart cartec-api
```

### Stop Service

```bash
sudo systemctl stop cartec-api
```

### View Logs

```bash
sudo journalctl -u cartec-api -n 100 --no-pager
```

### Update Code

```bash
cd /opt/cartec_api
# Pull new code or copy updated files
npm install  # If dependencies changed
sudo systemctl restart cartec-api
```

### Update Stored Procedure

```bash
mysql -u root -p revisa < /opt/cartec_api/sql/api_procedure.sql
# No need to restart API
```

---

## 🛡️ Security Considerations

### Firewall Configuration

```bash
# If exposing API externally
sudo ufw allow 3000/tcp
```

### Database User Permissions

**Recommended:** Create dedicated database user for API:
```sql
CREATE USER 'cartec_api'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT, INSERT, UPDATE ON revisa.* TO 'cartec_api'@'localhost';
FLUSH PRIVILEGES;
```

Update `.env`:
```env
DB_USER=cartec_api
DB_PASSWORD=secure_password
```

### SSL/TLS (Production)

For production, use **Nginx as reverse proxy** with SSL:

```nginx
server {
    listen 443 ssl;
    server_name api.cartec.cl;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location /api/ {
        proxy_pass http://localhost:3000/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
```

---

## 🐛 Troubleshooting

### API Won't Start

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

**Common issues:**
1. **Port already in use:**
   ```bash
   sudo netstat -tlnp | grep 3000
   sudo kill <PID>
   ```

2. **Database connection failed:**
   - Check `.env` credentials
   - Verify MySQL is running: `sudo systemctl status mysql`

3. **Node.js not found:**
   - Check Node.js path: `which node`
   - Update service file if needed

### OT Creation Fails

**Check stored procedure exists:**
```bash
mysql -u root -p revisa -e "SHOW PROCEDURE STATUS WHERE Name = 'prc_api_create_OT';"
```

**Check technician exists:**
```bash
mysql -u root -p revisa -e "SELECT * FROM Tecnicos WHERE rut_tecnico = '11111111-1';"
```

**Check database constraints:**
```bash
mysql -u root -p revisa -e "SHOW CREATE TABLE OT\G"
```

### Performance Issues

**Check connection pool:**
```env
DB_CONNECTION_LIMIT=20  # Increase if needed
```

**Monitor database:**
```sql
SHOW PROCESSLIST;
```

---

## 📊 Monitoring

### Health Check Endpoint

```bash
# Add to cron for monitoring
*/5 * * * * curl -f http://localhost:3000/api/health || echo "API DOWN" | mail -s "Cartec API Alert" admin@cartec.cl
```

### Log Rotation

Service logs are automatically managed by systemd journal.

**Manual cleanup:**
```bash
sudo journalctl --vacuum-time=7d  # Keep only 7 days
```

---

## 📚 Additional Resources

- **API Documentation:** `/opt/cartec_api/docs/API_DOCUMENTATION.md`
- **Testing Guide:** `/opt/cartec_api/docs/TESTING.md`
- **SQL Scripts:** `/opt/cartec_api/sql/`
- **Source Code:** `/opt/cartec_api/src/index.js`

---

## 📞 Support

For issues or questions:
1. Check logs: `sudo journalctl -u cartec-api -n 100`
2. Review documentation in `/opt/cartec_api/docs/`
3. Verify database connectivity and stored procedure
4. Check service status: `sudo systemctl status cartec-api`

---

## ✅ Implementation Checklist

- [ ] Node.js installed
- [ ] API files deployed to `/opt/cartec_api`
- [ ] `.env` configured with database credentials
- [ ] Dependencies installed (`npm install`)
- [ ] Stored procedure installed in database
- [ ] Test technician created
- [ ] API tested manually
- [ ] Systemd service installed and enabled
- [ ] API accessible on port 3000
- [ ] Health check endpoint working
- [ ] Test OT created successfully
- [ ] Database records verified
- [ ] Logs reviewed for errors
- [ ] Firewall configured (if needed)
- [ ] Monitoring/alerts configured (optional)

---

**Implementation Complete! 🎉**

Your Cartec OT Creation API is now running in production.

