> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev.prezio.eu/llms.txt
> Use this file to discover all available pages before exploring further.

# Calculate API Endpoint

> Calculate electricity costs based on specific consumption data

The `/calculate/` endpoint processes consumption data to provide detailed cost calculations based on specified tariffs and time periods. This endpoint is ideal for applications that need to determine costs for actual or estimated electricity usage, such as EV charging cost calculations or energy usage analysis.

## Endpoint Overview

```bash
POST /calculate/
```

This endpoint accepts consumption data with timestamps and usage amounts, calculates costs using the specified tariffs, and returns detailed or summarized cost information.

### Data Flow Diagram

```mermaid
flowchart LR
  A(Client Application) -->|Send Consumption Data| B(Prezio API)
  B -->|Return Cost Results| A
  subgraph Prezio Backend
    B
  end
```

## Key Parameters

<ParamField body="country" type="string" required>
  Country code (e.g., `DK`, `SE`) for the location.
</ParamField>

<ParamField body="tariff_id" type="array" required>
  Array of tariff IDs to apply for cost calculations. Each tariff ID must include the `tar_` prefix (e.g., `tar_123`).
</ParamField>

<ParamField body="kwh" type="array" required>
  Array of consumption entries, each with a timestamp and consumed amount:

  ```json
  {
    "interval_start": "2023-10-15T14:00:00Z",
    "amount": "1.25"
  }
  ```
</ParamField>

<ParamField body="address" type="string">
  Location address to determine applicable pricing. Required if coordinates are not provided.
</ParamField>

<ParamField body="latitude" type="number">
  Latitude coordinate of the location. Required if address is not provided.
</ParamField>

<ParamField body="longitude" type="number">
  Longitude coordinate of the location. Required if address is not provided.
</ParamField>

<ParamField body="interval_minutes" type="integer" default="60">
  Time resolution for calculations in minutes. Options: `60`, `30`, or `15`. All consumption timestamps must align with the chosen interval.
</ParamField>

<ParamField body="component_types" type="array" default="['PER_KWH']">
  Types of price components to include in the calculation (e.g., `PER_KWH`, `FIXED`, `TAX`).
</ParamField>

<ParamField body="detail" type="string" default="full">
  Level of detail in the response:

  * `summarized`: Only total cost
  * `semi`: Costs aggregated by organization type
  * `full`: Complete breakdown of all price components
</ParamField>

<ParamField body="vat" type="string" default="excluded">
  How to handle VAT in the response:

  * `excluded`: Prices exclude VAT
  * `included`: VAT included in each price component
  * `separated`: VAT shown as separate components
</ParamField>

## Location Specification

The Calculate endpoint follows the same location specification pattern as other Prezio endpoints:

1. You must provide either an `address` or the `latitude`/`longitude` coordinates, but not both.
2. The provided location is used to determine which tariffs are applicable in that geographic area.
3. For improved accuracy, prefer using an address with postal code when possible.
4. The endpoint will return a confidence score (1-10) for the location resolution.

## Time Window Constraint

<Warning>
  The time window between the earliest and latest intervals in the `kwh` array must not exceed 48 hours. Requests violating this constraint will return an error.
</Warning>

## Price Precision

All price fields in the response use 6 decimal places (e.g., `"0.123456"`), providing high precision for financial calculations and energy cost analysis.

## Example Requests

<CodeGroup>
  ```bash cURL
  curl -X POST "https://api.prezio.dev/v1/calculate/" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -d '{
      "country": "DK",
      "tariff_id": ["tar_123", "tar_456"],
      "address": "Rådhuspladsen 1, Copenhagen",
      "kwh": [
        {"interval_start": "2023-10-15T14:00:00Z", "amount": "1.5"},
        {"interval_start": "2023-10-15T15:00:00Z", "amount": "2.1"}
      ],
      "detail": "full",
      "interval_minutes": 60
    }'
  ```

  ```javascript Node.js
  const axios = require('axios');

  const response = await axios.post('https://api.prezio.dev/v1/calculate/', {
    country: 'DK',
    tariff_id: ['tar_123', 'tar_456'],
    address: 'Rådhuspladsen 1, Copenhagen',
    kwh: [
      {interval_start: '2023-10-15T14:00:00Z', amount: '1.5'},
      {interval_start: '2023-10-15T15:00:00Z', amount: '2.1'}
    ],
    detail: 'full',
    interval_minutes: 60
  }, {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });
  ```
</CodeGroup>

## Response Structure

The response returns both total cost and interval-by-interval breakdown of electricity costs:

<Tabs>
  <Tab title="Full Detail">
    ```json
    {
      "context": {
        "currency": "DKK",
        "unit": "per_kwh",
        "interval_minutes": 60,
        "location": {
          "input_address": "Rådhuspladsen 1, Copenhagen",
          "coordinates": {
            "latitude": 55.6761,
            "longitude": 12.5683,
            "confidence": 9
          }
        }
      },
      "tariff_elements": [
        {
          "element_id": "com_123",
          "element_name": "Grid Usage Fee",
          "tariff_id": "tar_123",
          "tariff_name": "Copenhagen DSO Standard",
          "organization_id": "org_456",
          "organization_name": "Copenhagen Energy Grid",
          "organization_type": "DSO"
        },
        {
          "element_id": "com_789",
          "element_name": "Energy Cost",
          "tariff_id": "tar_456",
          "tariff_name": "Variable Spot Price",
          "organization_id": "org_101",
          "organization_name": "Nordic Power Retail",
          "organization_type": "RET"
        }
      ],
      "total_price": "0.567150",
      "results": [
        {
          "interval_start": "2023-10-15T14:00:00Z",
          "elements": [
            {
              "id": "com_123",
              "unit_price": "0.052100",
              "calculated_price": "0.078150"
            },
            {
              "id": "com_789",
              "unit_price": "0.104500",
              "calculated_price": "0.156750"
            }
          ],
          "interval_price": "0.234900"
        },
        {
          "interval_start": "2023-10-15T15:00:00Z",
          "elements": [
            {
              "id": "com_123",
              "unit_price": "0.052100",
              "calculated_price": "0.109410"
            },
            {
              "id": "com_789",
              "unit_price": "0.106100",
              "calculated_price": "0.222840"
            }
          ],
          "interval_price": "0.332250"
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Semi Detail">
    ```json
    {
      "context": {
        "currency": "DKK",
        "unit": "per_kwh",
        "interval_minutes": 60,
        "location": {
          "input_address": "Rådhuspladsen 1, Copenhagen",
          "coordinates": {
            "latitude": 55.6761,
            "longitude": 12.5683,
            "confidence": 9
          }
        }
      },
      "tariff_elements": [
        {
          "element_id": "key_DSO",
          "organization_type": "DSO"
        },
        {
          "element_id": "key_RET",
          "organization_type": "RET"
        }
      ],
      "total_price": "0.567150",
      "results": [
        {
          "interval_start": "2023-10-15T14:00:00Z",
          "elements": [
            {
              "id": "key_DSO",
              "calculated_price": "0.078150"
            },
            {
              "id": "key_RET",
              "calculated_price": "0.156750"
            }
          ],
          "interval_price": "0.234900"
        },
        {
          "interval_start": "2023-10-15T15:00:00Z",
          "elements": [
            {
              "id": "key_DSO",
              "calculated_price": "0.109410"
            },
            {
              "id": "key_RET",
              "calculated_price": "0.222840"
            }
          ],
          "interval_price": "0.332250"
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Summarized">
    ```json
    {
      "context": {
        "currency": "DKK",
        "unit": "per_kwh",
        "interval_minutes": 60,
        "location": {
          "input_address": "Rådhuspladsen 1, Copenhagen",
          "coordinates": {
            "latitude": 55.6761,
            "longitude": 12.5683,
            "confidence": 9
          }
        }
      },
      "total_price": "0.567150"
    }
    ```
  </Tab>
</Tabs>

## Detail Levels

<CardGroup cols={3}>
  <Card title="Full Detail" icon="list-check" color="#83b5ab">
    Returns all price components individually with metadata about each component, ideal for detailed cost analysis.
  </Card>

  <Card title="Semi Detail" icon="layer-group" color="#3f8376">
    Aggregates costs by organization type (DSO, Retailer, etc.), providing a simplified but still informative breakdown.
  </Card>

  <Card title="Summarized" icon="calculator" color="#c7beff">
    Returns only the total cost for the entire consumption period, useful when only the bottom line matters.
  </Card>
</CardGroup>

## VAT Handling

Control how Value Added Tax is represented in the response:

<AccordionGroup>
  <Accordion title="VAT Excluded" icon="circle-minus" defaultOpen>
    All prices exclude VAT (default behavior).

    ```json
    {
      "elements": [
        {"id": "com_123", "unit_price": "0.052100", "calculated_price": "0.078150"},
        {"id": "com_789", "unit_price": "0.104500", "calculated_price": "0.156750"}
      ],
      "interval_price": "0.234900"
    }
    ```
  </Accordion>

  <Accordion title="VAT Included" icon="circle-plus">
    Each price component includes its applicable VAT.

    ```json
    {
      "elements": [
        {"id": "com_123", "unit_price": "0.065125", "calculated_price": "0.097688"},
        {"id": "com_789", "unit_price": "0.130625", "calculated_price": "0.195938"}
      ],
      "interval_price": "0.293625"
    }
    ```
  </Accordion>

  <Accordion title="VAT Separated" icon="layer-group">
    VAT is shown as separate component(s).

    ```json
    {
      "elements": [
        {"id": "com_123", "unit_price": "0.052100", "calculated_price": "0.078150"},
        {"id": "com_789", "unit_price": "0.104500", "calculated_price": "0.156750"},
        {"id": "vat_25_com_123", "calculated_price": "0.019538"},
        {"id": "vat_25_com_789", "calculated_price": "0.039188"}
      ],
      "interval_price": "0.293625"
    }
    ```
  </Accordion>
</AccordionGroup>

## Best Practices

<Tip>
  Provide consumption data aligned with the specified `interval_minutes`. For example, if `interval_minutes` is `60`, ensure timestamps are on the hour (e.g., `14:00:00`). Misaligned timestamps will result in errors.
</Tip>

<Warning>
  Ensure the total time window for consumption data does not exceed 48 hours between the earliest and latest timestamps. Exceeding this limit will trigger a validation error.
</Warning>

<Check>
  Use the `detail` parameter to control response size. If you only need total costs, use `detail=summarized` to minimize response payload size.
</Check>

## Common Use Cases

<CardGroup cols={2}>
  <Card title="EV Charging Cost Calculation" icon="bolt" color="#83b5ab">
    Calculate the exact cost of charging sessions for electric vehicles based on actual consumption data.
  </Card>

  <Card title="Home Energy Billing" icon="house" color="#3f8376">
    Determine costs for home energy usage over specific periods for billing or reimbursement purposes.
  </Card>

  <Card title="Energy Usage Analysis" icon="chart-line" color="#c7beff">
    Analyze cost breakdowns by component to understand the impact of different tariff elements on total expenses.
  </Card>

  <Card title="Fleet Management" icon="car-side" color="#ffb07c">
    Compute aggregated costs for EV fleets, supporting expense tracking and optimization.
  </Card>
</CardGroup>

## Error Handling

The Calculate endpoint may return specific errors for invalid inputs:

* **400 Bad Request**: Invalid or misaligned timestamps, missing required fields, or time window exceeding 48 hours.
* **401 Unauthorized**: Missing or invalid API key.
* **404 Not Found**: Specified tariffs are not applicable for the given location.
* **422 Validation Error**: Consumption data format issues or unsupported `interval_minutes` values.

Ensure your application handles these errors gracefully and provides meaningful feedback to users.
