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

# Generate Report

> Generate a complete ISO 14083 report for a client in a specific period

# Generate ISO 14083 Report

Generate a complete logistics emissions report for a client following ISO 14083 methodology. Includes aggregated KPIs and breakdowns by transport type.

## Request

### Headers

<ParamField header="x-api-key" type="string" required>
  Your API key for authentication

  **Example:** `sk_live_1234567890abcdef`
</ParamField>

<ParamField header="x-organization-id" type="string" required>
  Your organization UUID

  **Example:** `ff4adcc7-8172-45fe-9cf1-e90a6de53aa9`
</ParamField>

<ParamField header="x-user-id" type="string" required>
  Your user UUID

  **Example:** `a1b2c3d4-e5f6-7890-abcd-ef1234567890`
</ParamField>

### Query Parameters

<ParamField query="client" type="string" required>
  Exact client name (case-sensitive)

  **Example:** `"Correos Express"`
</ParamField>

<ParamField query="start_date" type="string" required>
  Period start date (format: YYYY-MM-DD)

  **Example:** `"2024-01-01"`
</ParamField>

<ParamField query="end_date" type="string" required>
  Period end date (format: YYYY-MM-DD)

  **Example:** `"2024-12-31"`
</ParamField>

## Response

<ResponseField name="client" type="string">
  Client name
</ResponseField>

<ResponseField name="period" type="object">
  <Expandable title="properties">
    <ResponseField name="start_date" type="string">
      Start date
    </ResponseField>

    <ResponseField name="end_date" type="string">
      End date
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="summary" type="object">
  <Expandable title="properties">
    <ResponseField name="total_co2e" type="number">
      Total emissions in kg CO2e
    </ResponseField>

    <ResponseField name="total_distance" type="number">
      Total distance in km
    </ResponseField>

    <ResponseField name="total_load" type="number">
      Total transported load
    </ResponseField>

    <ResponseField name="total_shipments" type="integer">
      Total number of shipments
    </ResponseField>

    <ResponseField name="avg_co2e_per_shipment" type="number">
      Average CO2e per shipment
    </ResponseField>

    <ResponseField name="avg_distance_per_shipment" type="number">
      Average distance per shipment
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="by_transport_type" type="array">
  Breakdown by transport type

  <Expandable title="properties">
    <ResponseField name="toc" type="string">
      Transport type
    </ResponseField>

    <ResponseField name="shipments" type="integer">
      Number of shipments
    </ResponseField>

    <ResponseField name="co2e" type="number">
      Emissions in kg
    </ResponseField>

    <ResponseField name="distance" type="number">
      Distance in km
    </ResponseField>

    <ResponseField name="percentage_co2e" type="number">
      Percentage of total emissions
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="methodology" type="string">
  Methodology used (always "ISO 14083")
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/api/v1/logistics/clients/report?client=Correos+Express&start_date=2024-01-01&end_date=2024-12-31" \
    -H "Authorization: Bearer ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "x-user-id: ${DCYCLE_USER_ID}"
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests
  import os

  api_key = os.getenv("DCYCLE_API_KEY")
  org_id = os.getenv("DCYCLE_ORG_ID")

  headers = {
      "Authorization": f"Bearer {api_key}",
      "x-organization-id": org_id,
      "x-user-id": user_id
  }

  params = {
      "client": "Correos Express",
      "start_date": "2024-01-01",
      "end_date": "2024-12-31"
  }

  response = requests.get(
      "https://api.dcycle.io/api/v1/logistics/clients/report",
      headers=headers,
      params=params
  )

  report = response.json()
  print(f"Total CO2e: {report['summary']['total_co2e']} kg")
  print(f"Total shipments: {report['summary']['total_shipments']}")
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const axios = require('axios');

  const apiKey = process.env.DCYCLE_API_KEY;
  const orgId = process.env.DCYCLE_ORG_ID;

  const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'x-organization-id': orgId,
    'x-user-id': userId
  };

  const params = {
    client: 'Correos Express',
    start_date: '2024-01-01',
    end_date: '2024-12-31'
  };

  axios.get(
    'https://api.dcycle.io/api/v1/logistics/clients/report',
    { headers, params }
  )
  .then(response => {
    const { summary } = response.data;
    console.log(`Total CO2e: ${summary.total_co2e} kg`);
    console.log(`Total shipments: ${summary.total_shipments}`);
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "client": "Correos Express",
  "period": {
    "start_date": "2024-01-01",
    "end_date": "2024-12-31"
  },
  "summary": {
    "total_co2e": 125430.75,
    "total_distance": 456789.5,
    "total_load": 3500000,
    "total_shipments": 15234,
    "avg_co2e_per_shipment": 8.23,
    "avg_distance_per_shipment": 29.97
  },
  "by_transport_type": [
    {
      "toc": "van_diesel",
      "shipments": 8500,
      "co2e": 72000.50,
      "distance": 255000.0,
      "percentage_co2e": 57.4
    },
    {
      "toc": "truck_diesel",
      "shipments": 4200,
      "co2e": 38430.25,
      "distance": 156789.5,
      "percentage_co2e": 30.6
    },
    {
      "toc": "van_electric",
      "shipments": 2534,
      "co2e": 15000.00,
      "distance": 45000.0,
      "percentage_co2e": 12.0
    }
  ],
  "methodology": "ISO 14083"
}
```

## Use Cases

### Annual Report

Generate the complete annual report for audits:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def generate_annual_report(client, year):
    """Generate annual ISO 14083 report"""
    start_date = f"{year}-01-01"
    end_date = f"{year}-12-31"

    report = get_report(client, start_date, end_date)

    # Save report
    filename = f"report_{client}_{year}_ISO14083.json"
    with open(filename, 'w') as f:
        json.dump(report, f, indent=2)

    return report

# Example
annual_report = generate_annual_report("Correos Express", 2024)
print(f"Annual emissions: {annual_report['summary']['total_co2e']/1000:.2f} tons CO2e")
```

### Monthly Comparison

Compare emissions month by month:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import calendar

def monthly_comparison(client, year):
    """Compare emissions by month"""
    monthly_data = []

    for month in range(1, 13):
        # Calculate last day of month
        last_day = calendar.monthrange(year, month)[1]

        start_date = f"{year}-{month:02d}-01"
        end_date = f"{year}-{month:02d}-{last_day}"

        report = get_report(client, start_date, end_date)

        monthly_data.append({
            "month": calendar.month_name[month],
            "co2e": report['summary']['total_co2e'],
            "shipments": report['summary']['total_shipments']
        })

    return monthly_data

# Usage
comparison = monthly_comparison("Correos Express", 2024)
for month_data in comparison:
    print(f"{month_data['month']}: {month_data['co2e']:.2f} kg CO2e ({month_data['shipments']} shipments)")
```

### Sustainability Dashboard

Extract KPIs for a dashboard:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_sustainability_kpis(client, start_date, end_date):
    """Extract key KPIs for dashboard"""
    report = get_report(client, start_date, end_date)

    kpis = {
        "total_emissions_tons": report['summary']['total_co2e'] / 1000,
        "avg_emissions_per_shipment": report['summary']['avg_co2e_per_shipment'],
        "total_shipments": report['summary']['total_shipments'],
        "total_distance_km": report['summary']['total_distance'],
        "most_used_transport": max(
            report['by_transport_type'],
            key=lambda x: x['shipments']
        )['toc'],
        "greenest_transport": min(
            report['by_transport_type'],
            key=lambda x: x['co2e'] / x['shipments']
        )['toc']
    }

    return kpis
```

## Common Errors

### 404 Not Found - Client Not Found

**Cause:** No data found for client 'Correos Express'

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "No data found for client 'Correos Express'",
  "code": "CLIENT_NOT_FOUND"
}
```

**Cause:** The client name doesn't exist or has a typo

**Solution:**

1. Use the [Get Clients](/api-docs/logistics/get-clients) endpoint to see exact names
2. Verify you wrote the name exactly the same (case-sensitive)

### 400 Bad Request - Invalid Date Format

**Cause:** Invalid date format. Use YYYY-MM-DD

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid date format. Use YYYY-MM-DD",
  "code": "INVALID_DATE_FORMAT"
}
```

**Solution:** Use the `YYYY-MM-DD` format (for example: `"2024-11-20"`)

### 400 Bad Request - Date Range Too Large

**Cause:** Date range cannot exceed 1 year

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Date range cannot exceed 1 year",
  "code": "DATE_RANGE_TOO_LARGE"
}
```

**Solution:** Divide the period into smaller ranges (maximum 1 year per request)

## ISO 14083 Compliance

This report complies with ISO 14083:2023 standard requirements:

✅ **WTW (Well-to-Wheel) Emissions** - Includes complete fuel cycle emissions

✅ **Transport Mode Breakdown** - Clear separation by vehicle type

✅ **Traceability** - Each emission is linked to a specific shipment

✅ **Documented Methodology** - Transparent emission factors and calculations

✅ **Temporal Aggregation** - Reports by defined periods

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Get Clients" icon="list" href="/api-docs/logistics/get-clients">
    List available clients
  </Card>

  <Card title="Upload CSV" icon="upload" href="/api-docs/logistics/upload-csv">
    Upload bulk shipments
  </Card>

  <Card title="Calculate Shipment" icon="calculator" href="/api-docs/logistics/calculate-shipment">
    Individual calculation
  </Card>

  <Card title="Get TOCs" icon="truck" href="/api-docs/logistics/get-tocs">
    List transport types
  </Card>
</CardGroup>
