erp-transportistas-v2/docs/30-integraciones/INTEGRACIONES-EXTERNAS.md
Adrian Flores Cortes 457ff6b620 docs: Add Phase 4 architecture and standards
- FLUJO-PRINCIPAL-TRANSPORTE.md: End-to-end transport workflow
  - 8 phases from OT capture to collection
  - State machine diagram
  - Actors and integrations per phase

- INTEGRACIONES-EXTERNAS.md: External integrations spec
  - GPS/Telematics (Geotab, CalAmp, Samsara, etc.)
  - PAC CFDI (Finkok, Facturama) with Carta Porte 3.1
  - Geocoding/Routing (Google, HERE, Mapbox)
  - WhatsApp/SMS notifications
  - TAG/IAVE toll integration
  - Banking (SPEI/CIE)

- MATRIZ-RBAC-TRANSPORTISTAS.yml: 16 roles with permissions
  - Permissions per module (MAI-001 to MAE-018)
  - Data restrictions per role
  - Critical actions requiring authorization

- ESPECIFICACION-KPIS.yml: 17 KPIs defined
  - Formulas, source tables, thresholds
  - Operational, fleet, financial, fuel, quality, compliance
  - Materialized views and calculation jobs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-27 02:31:39 -06:00

493 lines
16 KiB
Markdown

# Integraciones Externas - ERP Transportistas
**Version:** 1.0.0
**Fecha:** 2026-01-27
---
## Resumen de Integraciones
| Categoria | Proveedor | Proposito | Prioridad |
|-----------|-----------|-----------|-----------|
| GPS/Telematica | Varios | Tracking tiempo real | P0 |
| PAC (CFDI) | Varios | Timbrado fiscal | P0 |
| Geocoding/Mapas | Google/Here/Mapbox | Rutas y direcciones | P0 |
| Mensajeria | WhatsApp/SMS | Notificaciones | P1 |
| Combustible | TAG/IAVE | Peajes automaticos | P2 |
| Bancos | SPEI/CIE | Cobranza/Pagos | P2 |
---
## 1. GPS y Telematica
### 1.1 Proposito
Recibir posiciones de unidades en tiempo real para tracking, geocercas y alertas.
### 1.2 Proveedores Soportados
| Proveedor | Protocolo | Frecuencia | Datos |
|-----------|-----------|------------|-------|
| Geotab | API REST | 30 seg | Posicion, velocidad, eventos motor |
| CalAmp | Push HTTP | 60 seg | Posicion, velocidad, odometro |
| Queclink | TCP/IP | 30 seg | Posicion, velocidad, bateria |
| Teltonika | TCP/IP | Variable | Posicion, sensores |
| Omnitracs | API REST | 60 seg | Posicion, HOS, mensajes |
| Samsara | Webhooks | 30 seg | Posicion, combustible, DVIR |
### 1.3 Arquitectura de Integracion
```
┌──────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Unidad │────▶│ Proveedor │────▶│ ERP Backend │
│ (GPS/AVL) │ │ Telematica │ │ (Webhook/API) │
└──────────────┘ └─────────────────┘ └─────────────────┘
┌─────────────────┐
│ Redis │
│ (Cache tiempo │
│ real) │
└─────────────────┘
┌─────────────────┐
│ PostgreSQL │
│ + TimescaleDB │
└─────────────────┘
```
### 1.4 Modelo de Datos Recibidos
```typescript
interface PosicionGPS {
unidad_id: string; // ID interno o IMEI
timestamp: Date; // UTC
latitud: number; // -90 a 90
longitud: number; // -180 a 180
velocidad_kmh: number; // km/h
rumbo: number; // 0-360 grados
odometro_km?: number; // km totales
nivel_combustible?: number; // 0-100%
motor_encendido?: boolean;
eventos?: string[]; // Alertas del dispositivo
}
```
### 1.5 Tabla de Mapeo Unidad-Dispositivo
```sql
-- tracking.dispositivos_gps
CREATE TABLE tracking.dispositivos_gps (
id UUID PRIMARY KEY,
unidad_id UUID REFERENCES fleet.unidades(id),
proveedor_id UUID REFERENCES tracking.proveedores_telematica(id),
imei VARCHAR(20) NOT NULL,
numero_serie VARCHAR(50),
modelo VARCHAR(100),
activo BOOLEAN DEFAULT true,
ultima_posicion JSONB,
ultima_comunicacion TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
);
```
### 1.6 Procesamiento de Eventos
| Evento | Condicion | Accion |
|--------|-----------|--------|
| GEOCERCA_ENTRADA | Posicion dentro de poligono | Registrar evento, notificar |
| GEOCERCA_SALIDA | Posicion fuera de poligono | Registrar evento, notificar |
| EXCESO_VELOCIDAD | velocidad > limite_ruta | Alerta operaciones |
| MOTOR_APAGADO | motor_encendido = false en zona no autorizada | Alerta seguridad |
| SIN_COMUNICACION | > 30 min sin posicion | Alerta torre control |
---
## 2. PAC - Proveedores Autorizados de Certificacion
### 2.1 Proposito
Timbrado de CFDI (factura electronica) con Complemento Carta Porte 3.1.
### 2.2 Proveedores Soportados
| PAC | Metodo | Ambiente | Notas |
|-----|--------|----------|-------|
| Finkok | SOAP/REST | Sandbox + Produccion | Recomendado |
| Facturama | REST | Sandbox + Produccion | API moderna |
| SW Sapien | SOAP | Produccion | Economico alto volumen |
| Diverza | REST | Sandbox + Produccion | Buen soporte |
| TimbradoFiscal | SOAP | Produccion | Legacy |
### 2.3 Flujo de Timbrado
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ ERP Backend │────▶│ Generador │────▶│ PAC │
│ (Datos factura) │ │ XML CFDI │ │ (Timbrado) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
┌─────────────────┐
│ SAT │
│ (Validacion) │
└─────────────────┘
┌─────────────────┐
│ CFDI Timbrado │
│ (UUID, sello) │
└─────────────────┘
```
### 2.4 Datos Carta Porte 3.1
```typescript
interface CartaPorte31 {
// Ubicaciones
ubicaciones: {
tipo: 'Origen' | 'Destino';
id_ubicacion: string;
rfc_remitente_destinatario: string;
nombre: string;
domicilio: DomicilioFiscal;
fecha_hora_salida_llegada: Date;
}[];
// Mercancias
mercancias: {
bienes_transp: string; // Clave SAT
descripcion: string;
cantidad: number;
clave_unidad: string;
peso_kg: number;
material_peligroso?: string; // Si aplica
embalaje?: string;
}[];
// Autotransporte
autotransporte: {
perm_sct: string; // Permiso SCT
num_permiso_sct: string;
config_vehicular: string; // Clave SAT
placa_vm: string;
anio_modelo_vm: number;
identificador_vehicular?: string;
remolques?: {
subtipo_rem: string;
placa: string;
}[];
};
// Figura transporte (operador)
figura_transporte: {
tipo_figura: string;
rfc_figura: string;
nombre_figura: string;
num_licencia: string;
domicilio?: DomicilioFiscal;
}[];
}
```
### 2.5 Validaciones Pre-Timbrado
| Validacion | Campo | Regla |
|------------|-------|-------|
| RFC valido | rfc_emisor, rfc_receptor | Formato y lista negra SAT |
| CP vigente | codigo_postal | Catalogo SAT actualizado |
| Clave SAT | bienes_transp | Catalogo c_ClaveProdServCP |
| Permiso SCT | perm_sct + num_permiso | Formato valido |
| Peso total | suma mercancias | <= capacidad unidad |
| Config vehicular | config_vehicular | Match con unidad registrada |
---
## 3. Geocoding y Mapas
### 3.1 Proposito
- Validar y geocodificar direcciones
- Calcular rutas optimas
- Estimar distancias y tiempos
- Visualizar tracking en mapa
### 3.2 Proveedores Soportados
| Proveedor | Servicios | Costo | Uso recomendado |
|-----------|-----------|-------|-----------------|
| Google Maps | Geocoding, Directions, Places | $$$$ | Alta precision |
| HERE | Geocoding, Routing, Traffic | $$$ | Transporte pesado |
| Mapbox | Geocoding, Directions | $$ | Alto volumen |
| OpenRouteService | Routing | $ | Optimizacion |
| OSRM | Routing local | Gratis | Self-hosted |
### 3.3 API de Geocoding
```typescript
interface GeocodingRequest {
direccion: string; // Texto libre
// o componentes:
calle?: string;
numero_exterior?: string;
colonia?: string;
municipio?: string;
estado?: string;
codigo_postal?: string;
pais?: string;
}
interface GeocodingResponse {
latitud: number;
longitud: number;
direccion_formateada: string;
precision: 'ROOFTOP' | 'RANGE_INTERPOLATED' | 'GEOMETRIC_CENTER' | 'APPROXIMATE';
componentes: {
calle: string;
numero: string;
colonia: string;
municipio: string;
estado: string;
codigo_postal: string;
pais: string;
};
}
```
### 3.4 API de Routing
```typescript
interface RoutingRequest {
origen: { lat: number; lng: number };
destino: { lat: number; lng: number };
waypoints?: { lat: number; lng: number }[];
tipo_vehiculo: 'truck' | 'trailer' | 'car';
restricciones?: {
evitar_casetas?: boolean;
evitar_autopistas?: boolean;
peso_bruto_kg?: number;
altura_m?: number;
longitud_m?: number;
materiales_peligrosos?: boolean;
};
optimizar_por?: 'distancia' | 'tiempo' | 'costo';
}
interface RoutingResponse {
distancia_km: number;
duracion_minutos: number;
duracion_trafico_minutos?: number;
costo_casetas?: number;
geometria: string; // Polyline encoded
pasos: {
instruccion: string;
distancia_km: number;
duracion_min: number;
coordenadas: { lat: number; lng: number };
}[];
}
```
### 3.5 Cache de Rutas
```sql
-- transport.cache_rutas
CREATE TABLE transport.cache_rutas (
id UUID PRIMARY KEY,
origen_hash VARCHAR(32), -- MD5 de coordenadas
destino_hash VARCHAR(32),
tipo_vehiculo VARCHAR(20),
distancia_km DECIMAL(10,2),
duracion_minutos INTEGER,
costo_casetas DECIMAL(10,2),
geometria TEXT,
proveedor VARCHAR(50),
created_at TIMESTAMPTZ DEFAULT NOW(),
expires_at TIMESTAMPTZ,
UNIQUE(origen_hash, destino_hash, tipo_vehiculo)
);
```
---
## 4. Mensajeria (WhatsApp/SMS)
### 4.1 Proposito
Notificaciones automaticas a clientes y operadores.
### 4.2 Proveedores
| Proveedor | Canal | Uso |
|-----------|-------|-----|
| Twilio | WhatsApp + SMS | Notificaciones bidireccionales |
| MessageBird | WhatsApp + SMS | Alto volumen |
| Infobip | WhatsApp + SMS | Enterprise |
| Meta Business | WhatsApp directo | Templates aprobados |
### 4.3 Plantillas de Mensajes
| Evento | Destinatario | Template |
|--------|--------------|----------|
| OT Confirmada | Cliente | "Su orden de transporte #{{ot_folio}} ha sido confirmada. Recoleccion: {{fecha_pickup}}" |
| Viaje en Camino | Cliente | "Su embarque esta en camino. ETA: {{eta}}. Track: {{url_tracking}}" |
| Llegada Destino | Cliente | "Unidad {{placa}} ha llegado a destino. POD pendiente." |
| Entrega Completada | Cliente | "Entrega completada. POD: {{url_pod}}. Gracias por su preferencia." |
| Asignacion Viaje | Operador | "Nuevo viaje asignado: {{origen}} -> {{destino}}. Ver detalles en app." |
| Documento por Vencer | Operador | "Su {{documento}} vence en {{dias}} dias. Favor de renovar." |
### 4.4 Webhook Respuestas
```typescript
interface WhatsAppWebhook {
from: string; // Numero remitente
message_id: string;
timestamp: number;
type: 'text' | 'image' | 'document' | 'location';
text?: { body: string };
image?: { id: string; caption?: string };
location?: { latitude: number; longitude: number };
context?: {
message_id: string; // Mensaje al que responde
};
}
```
---
## 5. TAG/IAVE (Peajes)
### 5.1 Proposito
Registro automatico de cruces de peaje para control de gastos.
### 5.2 Integracion
| Sistema | Metodo | Datos |
|---------|--------|-------|
| IAVE | Portal web scraping | Movimientos por TAG |
| TAG Pase | API no oficial | Movimientos y saldo |
| Televia | Portal | Movimientos |
### 5.3 Datos de Cruce
```typescript
interface CrucePeaje {
tag_numero: string;
plaza: string;
carril: number;
fecha_hora: Date;
monto: number;
saldo_posterior: number;
tipo_vehiculo: string;
}
```
### 5.4 Conciliacion
- Vincular TAG a unidad
- Importar movimientos diarios
- Comparar vs viajes activos
- Detectar anomalias (cruces sin viaje, rutas incorrectas)
---
## 6. Bancos (SPEI/CIE)
### 6.1 Proposito
- Recepcion de pagos de clientes
- Pagos a proveedores y operadores
### 6.2 Integraciones
| Banco | Servicio | Uso |
|-------|----------|-----|
| BBVA | CIE | Referencias de pago |
| Santander | CIE | Referencias de pago |
| Banorte | SPEI entrada | Notificacion pagos |
| STP | SPEI salida | Pagos dispersos |
### 6.3 Flujo CIE (Cobro)
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ ERP Backend │────▶│ Banco (API) │────▶│ Genera CIE │
│ (Monto + Cliente)│ │ │ │ (Referencia) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Pago del cliente ◀───────┘
┌─────────────────┐
│ Webhook pago │
│ recibido │
└─────────────────┘
┌─────────────────┐
│ Aplicar pago │
│ automatico │
└─────────────────┘
```
---
## 7. Seguridad y Autenticacion
### 7.1 Manejo de Credenciales
```yaml
# Variables de entorno (NO en codigo)
GPS_PROVIDER_API_KEY: "encrypted_value"
PAC_USUARIO: "encrypted_value"
PAC_PASSWORD: "encrypted_value"
PAC_CERTIFICADO: "path_to_cert.cer"
PAC_LLAVE_PRIVADA: "path_to_key.key"
GOOGLE_MAPS_API_KEY: "encrypted_value"
TWILIO_ACCOUNT_SID: "encrypted_value"
TWILIO_AUTH_TOKEN: "encrypted_value"
```
### 7.2 Rate Limiting
| Servicio | Limite | Accion |
|----------|--------|--------|
| Geocoding | 1000/min | Cola y retry |
| Routing | 500/min | Cache agresivo |
| Timbrado | Sin limite | Batch nocturno |
| WhatsApp | 1000/día por numero | Templates |
### 7.3 Fallbacks
| Servicio primario | Fallback | Condicion |
|-------------------|----------|-----------|
| Google Maps | HERE | Error o rate limit |
| PAC Finkok | PAC Facturama | Timeout |
| Twilio WhatsApp | Twilio SMS | Template rechazado |
---
## 8. Monitoreo de Integraciones
### 8.1 Health Checks
```typescript
interface IntegrationHealth {
servicio: string;
status: 'UP' | 'DOWN' | 'DEGRADED';
latencia_ms: number;
ultima_verificacion: Date;
errores_ultimas_24h: number;
tasa_exito: number;
}
```
### 8.2 Alertas
| Condicion | Severidad | Accion |
|-----------|-----------|--------|
| Servicio DOWN > 5 min | CRITICA | Alerta inmediata |
| Latencia > 5s | WARNING | Notificar |
| Tasa error > 10% | WARNING | Investigar |
| Credencial expira < 7 dias | INFO | Recordatorio |
---
*INTEGRACIONES EXTERNAS v1.0.0 - ERP Transportistas*