> ## Documentation Index
> Fetch the complete documentation index at: https://developers.manglai.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Guía de integración API

> Guía paso a paso para integrar todos los recursos de la API REST de Manglai en tu sistema

Esta guía recorre todos los recursos disponibles en la API de Manglai, desde la autenticación inicial hasta la sincronización de datos avanzados. Sigue el orden recomendado para garantizar que los datos de referencia estén disponibles antes de crear registros dependientes.

## Paso 1 — Autenticación

Todas las llamadas a la API requieren un token Bearer en la cabecera `Authorization`.

**Genera tu token** en [Manglai → Ajustes → API Tokens](https://www.manglai.io/saas/settings/api-tokens/docs#models).

```bash theme={null}
curl -X GET "https://www.manglai.io/api/v1/companies" \
  -H "Authorization: Bearer TU_TOKEN_AQUI"
```

<Tip>
  Guarda el token como variable de entorno: `export MANGLAI_TOKEN="TU_TOKEN_AQUI"` para reutilizarlo en todos los ejemplos.
</Tip>

***

## Paso 2 — Obtener empresas y edificios

Antes de crear cualquier registro, necesitas los IDs de empresa y edificio.

### Listar empresas

```bash theme={null}
curl "https://www.manglai.io/api/v1/companies" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Listar edificios de una empresa

```bash theme={null}
curl "https://www.manglai.io/api/v1/companies/{companyId}/buildings?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Listar departamentos

```bash theme={null}
curl "https://www.manglai.io/api/v1/companies/{companyId}/departments?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Configuración de años activos

```bash theme={null}
curl "https://www.manglai.io/api/v1/companies/{companyId}/year-configuration?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Paso 3 — Obtener datos de referencia

Estos endpoints devuelven los catálogos necesarios para rellenar campos como `categoryId`, `fuelType`, o `wasteType`.

### Categorías GHG Protocol

Tres niveles: `scope`, `category`, `subcategory`. Para consumos usa siempre `subcategory`.

```bash theme={null}
curl "https://www.manglai.io/api/v1/categories?level=subcategory" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Inputs recomendados (proveedores, combustibles, residuos)

Devuelve proveedores de electricidad, tipos de combustible, métodos de tratamiento de residuos, etc., filtrados por país y tipo.

```bash theme={null}
# Proveedores de electricidad
curl "https://www.manglai.io/api/v1/inputs/recommended?companyId={companyId}&types=provider&countryCode=ES" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"

# Tipos de combustible
curl "https://www.manglai.io/api/v1/inputs/recommended?companyId={companyId}&types=fuel&countryCode=ES" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"

# Tipos de residuo
curl "https://www.manglai.io/api/v1/inputs/recommended?companyId={companyId}&types=waste&countryCode=ES" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Factores de emisión personalizados

```bash theme={null}
curl "https://www.manglai.io/api/v1/emission-factors/custom?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Paso 4 — Facturas de suministros

Las facturas representan documentos de electricidad, gas, agua, combustibles, residuos, etc.

### Listar facturas

```bash theme={null}
curl "https://www.manglai.io/api/v1/invoices?companyId={companyId}&startDate=2024-01-01&endDate=2024-12-31" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Crear o actualizar una factura

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/invoices" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "type": "electricity",
    "companyId": "{companyId}",
    "buildingId": "{buildingId}",
    "totalCost": 1240.50,
    "currency": "EUR",
    "startDate": "2024-01-01",
    "endDate": "2024-01-31",
    "lines": [
      { "quantity": 1500, "unit": "kWh" }
    ]
  }'
```

**Tipos de factura disponibles:** `electricity`, `heat`, `fuel`, `water`, `wastes`, `wastes-expenses`, `generated-energy`, `process-emissions`, `waste-water`, `others`

### Subir factura con escaneo IA

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/invoices/upload-invoice" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -F "companyId={companyId}" \
  -F "invoice=@factura.pdf"
```

***

## Paso 5 — Consumos

Los consumos son los registros granulares de actividad energética o material que generan emisiones.

### Listar consumos

```bash theme={null}
curl "https://www.manglai.io/api/v1/consumptions?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Crear o actualizar un consumo

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/consumptions" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "550e8400-e29b-41d4-a716-446655440001",
    "entityId": "{invoiceId}",
    "categoryId": "{subcategoryId}",
    "companyId": "{companyId}",
    "buildingId": "{buildingId}",
    "startDate": "2024-01-01T00:00:00.000Z",
    "endDate": "2024-01-31T23:59:59.999Z",
    "quantity": 1500.5,
    "unitType": "kWh",
    "provider": "endesa",
    "totalCost": 312.50,
    "currency": "EUR"
  }'
```

### Dashboard de consumos

```bash theme={null}
curl "https://www.manglai.io/api/v1/consumptions/dashboard?companyId={companyId}&startDate=2024-01-01&endDate=2024-12-31" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Paso 6 — Emisiones

Las emisiones son calculadas automáticamente a partir de los consumos. Solo necesitas leerlas.

### Listar emisiones

```bash theme={null}
curl "https://www.manglai.io/api/v1/emissions?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Dashboard de emisiones (por scope, categoría, edificio)

```bash theme={null}
curl "https://www.manglai.io/api/v1/emissions/dashboard?companyId={companyId}&startDate=2024-01-01&endDate=2024-12-31" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

La respuesta incluye el desglose por `scope`, `category`, `subcategory` y mes.

***

## Paso 7 — Vehículos

### Registrar un vehículo

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/vehicles" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "{uuid}",
    "type": "vehicle",
    "motorType": "combustion",
    "companyId": "{companyId}",
    "buildingId": "{buildingId}",
    "licencePlate": "1234ABC",
    "vehicleCategoryId": "{categoryId}"
  }'
```

### Consumo de vehículo

Para registrar consumo de combustible o electricidad de un vehículo, usa el endpoint de consumos con `entityId` apuntando al `vehicleId` y las categorías de transporte correspondientes.

```bash theme={null}
curl "https://www.manglai.io/api/v1/vehicles?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Paso 8 — Logística GLEC / ISO 14083

Registra servicios de transporte de mercancías siguiendo el estándar GLEC e ISO 14083.

### Listar servicios

```bash theme={null}
curl "https://www.manglai.io/api/v1/service-footprint/glec?companyId={companyId}&startDate=2024-01-01&endDate=2024-12-31" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Crear un servicio de transporte

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/service-footprint/glec" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "{uuid}",
    "companyId": "{companyId}",
    "clientId": "{supplierId}",
    "startDate": "2024-07-03",
    "endDate": "2024-07-18",
    "from": "Madrid, Spain",
    "to": "Barcelona, Spain",
    "actions": [
      {
        "id": "{uuid}",
        "mode": "external",
        "vehicleType": "hgv_diesel",
        "transportType": "articulated",
        "vehicleTransportSize": "40_t_gvw",
        "from": "Madrid, Spain",
        "to": "Barcelona, Spain",
        "distance": "621",
        "load": 20000,
        "loadUnit": "kg"
      }
    ]
  }'
```

***

## Paso 9 — Viajes de negocio

### Listar viajes

```bash theme={null}
curl "https://www.manglai.io/api/v1/business-travels?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Registrar un viaje

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/business-travels" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "{uuid}",
    "companyId": "{companyId}",
    "employeeId": "{employeeId}",
    "origin": "Madrid, Spain",
    "destination": "London, UK",
    "transportType": "flight",
    "travelClass": "economy",
    "date": "2024-04-10",
    "returnTrip": true
  }'
```

### Dashboard de viajes

```bash theme={null}
curl "https://www.manglai.io/api/v1/business-travels/dashboard?companyId={companyId}&startDate=2024-01-01&endDate=2024-12-31" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Paso 10 — Compras (Scope 3)

Sincroniza gastos de compra para calcular emisiones de Scope 3 Categoría 1.

### Listar gastos

```bash theme={null}
curl "https://www.manglai.io/api/v1/purchased-goods/expenses?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Registrar un gasto

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/purchased-goods/expenses" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "{uuid}",
    "companyId": "{companyId}",
    "supplierId": "{supplierId}",
    "description": "Material de oficina",
    "amount": 4500.00,
    "currency": "EUR",
    "date": "2024-03-15"
  }'
```

***

## Paso 11 — Proveedores y clientes

Los proveedores (`type: suppliers`) y clientes (`type: clients`) se usan en logística, compras y certificados.

### Listar proveedores

```bash theme={null}
curl "https://www.manglai.io/api/v1/suppliers?companyId={companyId}&type=suppliers" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Crear proveedor

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/suppliers" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "{uuid}",
    "companyId": "{companyId}",
    "name": "Proveedor Logístico S.L.",
    "email": "contacto@proveedor.com",
    "address": "Calle Mayor 1, Madrid",
    "type": "suppliers",
    "externalId": "EXT-PROV-001"
  }'
```

***

## Paso 12 — Empleados

```bash theme={null}
# Listar empleados
curl "https://www.manglai.io/api/v1/employees?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"

# Obtener empleado por ID
curl "https://www.manglai.io/api/v1/employees/{id}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Paso 13 — Usuarios

### Listar usuarios

```bash theme={null}
curl "https://www.manglai.io/api/v1/users?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Invitar usuario

```bash theme={null}
curl -X POST "https://www.manglai.io/api/v1/users/invite" \
  -H "Authorization: Bearer $MANGLAI_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "nuevo@empresa.com",
    "companyId": "{companyId}",
    "roles": ["ROLE_MANAGER"]
  }'
```

**Roles disponibles:** `ROLE_OWNER` (gestor), `ROLE_MANAGER` (inventario), `ROLE_VALIDATOR`, `ROLE_VIEWER`

***

## Paso 14 — Objetivos y tareas de reducción

```bash theme={null}
# Listar objetivos
curl "https://www.manglai.io/api/v1/goals?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"

# Tareas asociadas a objetivos
curl "https://www.manglai.io/api/v1/goals/tasks?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"

# Escenarios de proyección
curl "https://www.manglai.io/api/v1/goals/scenarios?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Paso 15 — Otros recursos

### Operadores de residuos

```bash theme={null}
curl "https://www.manglai.io/api/v1/waste-operators?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Certificados (REGOs, GOs)

```bash theme={null}
curl "https://www.manglai.io/api/v1/certificates?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Efluentes

```bash theme={null}
curl "https://www.manglai.io/api/v1/effluents?companyId={companyId}&year=2024" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Inversiones

```bash theme={null}
curl "https://www.manglai.io/api/v1/investments?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Métricas personalizadas

```bash theme={null}
curl "https://www.manglai.io/api/v1/custom-metrics?companyId={companyId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

### Comentarios

```bash theme={null}
curl "https://www.manglai.io/api/v1/comments?companyId={companyId}&entityId={entityId}" \
  -H "Authorization: Bearer $MANGLAI_TOKEN"
```

***

## Resumen de recursos

| Recurso             | Método     | Endpoint                             |
| ------------------- | ---------- | ------------------------------------ |
| Empresas            | GET        | `/api/v1/companies`                  |
| Edificios           | GET        | `/api/v1/companies/{id}/buildings`   |
| Departamentos       | GET        | `/api/v1/companies/{id}/departments` |
| Categorías GHG      | GET        | `/api/v1/categories`                 |
| Inputs recomendados | GET        | `/api/v1/inputs/recommended`         |
| Facturas            | GET / POST | `/api/v1/invoices`                   |
| Subida de facturas  | POST       | `/api/v1/invoices/upload-invoice`    |
| Consumos            | GET / POST | `/api/v1/consumptions`               |
| Emisiones           | GET        | `/api/v1/emissions`                  |
| Dashboard emisiones | GET        | `/api/v1/emissions/dashboard`        |
| Vehículos           | GET / POST | `/api/v1/vehicles`                   |
| Logística GLEC      | GET / POST | `/api/v1/service-footprint/glec`     |
| Viajes de negocio   | GET / POST | `/api/v1/business-travels`           |
| Compras (gastos)    | GET / POST | `/api/v1/purchased-goods/expenses`   |
| Proveedores         | GET / POST | `/api/v1/suppliers`                  |
| Empleados           | GET        | `/api/v1/employees`                  |
| Usuarios            | GET / POST | `/api/v1/users`                      |
| Objetivos           | GET        | `/api/v1/goals`                      |
| Operadores residuos | GET / POST | `/api/v1/waste-operators`            |
| Certificados        | GET        | `/api/v1/certificates`               |
| Efluentes           | GET / POST | `/api/v1/effluents`                  |
| Métricas custom     | GET        | `/api/v1/custom-metrics`             |
| Factores de emisión | GET        | `/api/v1/emission-factors/custom`    |

## Siguiente paso

<CardGroup cols={2}>
  <Card title="API Reference interactiva" icon="book" href="/api-reference">
    Prueba todos los endpoints directamente desde la documentación
  </Card>

  <Card title="Integrar el MCP" icon="robot" href="/guides/integrate-mcp">
    Conecta Claude, Cursor o ChatGPT a tus datos de Manglai
  </Card>
</CardGroup>
