# Math Operations

> Realiza cálculos matemáticos o agregaciones sobre los datos.

Source: https://docs.sommatic.ai/es/nodes/data.math/

- Slug: `data.math`
- Familia: Datos
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Realiza cálculos matemáticos o agregaciones sobre los datos.

Este operador ofrece funciones aritméticas y de agregación estándar. No usa JSONata: en el modo `expr`, el resultado es el valor que ya resolvió el Sommatic AI Expression Engine.

**Operaciones:**
- **Sum/Avg/Min/Max:** Agregaciones sobre `values` (un arreglo de números del payload de entrada). Las entradas no numéricas se ignoran; una lista vacía devuelve 0.
- **Avanzado (Expr):** Una expresión JavaScript `{{ }}` (p. ej. `{{ Math.round($json.price * 1.2 * 100) / 100 }}`). El valor resuelto se devuelve como `result` sin evaluarse de nuevo.

**Casos de uso:**
- Calcular el valor total de los artículos de un carrito de compras.
- Encontrar la oferta más alta en una lista de subasta.
- Calcular porcentajes de impuestos.

## Configuración

- `op` (string, opcional): Por defecto: `sum`. Valores permitidos: `sum`, `avg`, `min`, `max`, `expr`.
- `expression` (string, opcional, acepta expresiones): Cálculo del Expression Engine encerrado en {{ }} (obligatorio si op es "expr"), p. ej. {{ $json.price * 1.2 }}. JSONata no es compatible.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): Result
- `error`: Error

## Contrato de entrada

- `values` (array<number>, opcional): Lista de números (para agregaciones).
- `payload` (object, opcional): Contexto para las expresiones personalizadas.

## Contrato de salida

- `result` (number, opcional): Resultado del cálculo.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Math Operations").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Math Operations`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Math Operations").item.json.result` (number) = `42.5`: Resultado del cálculo.


## Cómo funciona

Agrega el arreglo `values` del payload de entrada (suma, promedio, mínimo, máximo) o devuelve un valor calculado por un `{{ }}` del Expression Engine, como `{ result }`.

1. Resuelve la configuración; `op` vale `sum` por defecto. El Expression Engine evalúa los `{{ }}` de `expression` (JavaScript, límite de 100 ms).
2. `expr`: `result` es el `expression` resuelto tal cual, de cualquier tipo. No usa JSONata.
3. `sum`, `avg`, `min`, `max`: leen `values` del payload de entrada (no es configurable). Una cadena falla; cada elemento se convierte con `Number()` y se descartan los `NaN`; una lista vacía da 0.
4. Devuelve `{ result }` por `out`; el payload de entrada no se conserva.

## En un workflow

### Nodo

```json
{
  "node_id": "node-cart-total",
  "label": "Cart total",
  "operator_slug": "data.math",
  "operator_version": "1.0.0",
  "config": {
    "op": "expr",
    "expression": "{{ Math.round(_.sum($json.items.map(item => item.price * item.qty)) * 100) / 100 }}"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": 42.5
  },
  "port": "out"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

El cálculo terminó.

```json
{
  "result": 42.5
}
```

### `error`

`op` desconocido o `values` no se puede leer como lista.

```json
{
  "ok": false,
  "errors": [
    "Math Error: Values must be an array for aggregation"
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `expression`: Solo se usa con `op` `expr`. Sin `{{ }}` se devuelve el texto literal. Si un `{{ }}` de valor completo lanza un error, el resolvedor conserva el texto original, así que `result` es la cadena `{{ ... }}` y el nodo sale igual por `out`.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Math Error: Unknown op: <op>` | `error` | `op` no es `sum`, `avg`, `min`, `max` ni `expr`. |
| `Math Error: Values must be an array for aggregation` | `error` | `values` en el payload es una cadena. |
| `Math Error: (values \|\| []).map is not a function` | `error` | `values` es un número, un objeto o `true`. |

## Notas y límites

- `null`, las cadenas vacías y los booleanos de `values` se convierten en 0 o 1 y se cuentan.
- Para agregar otro campo, dale forma antes (por ejemplo un `data.transform` que devuelva `{ "values": items.price }`) o usa `expr` con `{{ _.sum($json.items.map(item => item.price)) }}`.
- Cuando el sobre no trae `data` (o `data` es falsy), el motor guarda el sobre completo como salida del nodo: por `error` el siguiente nodo recibe `{ ok: false, errors: [...], port: "error" }` como payload.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "data.math",
  "name": "Math Operations",
  "category": "data",
  "version": "1.0.0",
  "description": "Performs mathematical calculations or aggregations on data.\n\n  This operator provides standard arithmetic and aggregation functions. It does not use JSONata: in `expr` mode the result is the value already resolved by the Sommatic AI Expression Engine.\n\n  **Operations:**\n  - **Sum/Avg/Min/Max:** Aggregations over `values` (an array of numbers in the input payload). Non-numeric entries are ignored; an empty list returns 0.\n  - **Advanced (Expr):** A `{{ }}` JavaScript expression (e.g. `{{ Math.round($json.price * 1.2 * 100) / 100 }}`). The resolved value is returned as `result` without further evaluation.\n\n  **Use Cases:**\n  - Calculating the total value of items in a shopping cart.\n  - Finding the highest bid in an auction list.\n  - Computing tax percentages.",
  "capabilities": [
    "math",
    "calculation",
    "aggregation"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "op": {
        "type": "string",
        "enum": [
          "sum",
          "avg",
          "min",
          "max",
          "expr"
        ],
        "default": "sum",
        "title": "Operation"
      },
      "expression": {
        "type": "string",
        "format": "expression",
        "title": "Custom Expression",
        "description": "Expression Engine calculation wrapped in {{ }} (required if op is \"expr\"), e.g. {{ $json.price * 1.2 }}. JSONata is not supported."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "values": {
        "type": "array",
        "items": {
          "type": "number"
        },
        "description": "List of numbers (for aggregations)."
      },
      "payload": {
        "type": "object",
        "description": "Context for custom expressions."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "number",
        "description": "Calculation result."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Result",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "math",
    "calc",
    "sum",
    "stats"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "op": {
      "type": "string",
      "enum": [
        "sum",
        "avg",
        "min",
        "max",
        "expr"
      ],
      "default": "sum",
      "title": "Operation"
    },
    "expression": {
      "type": "string",
      "format": "expression",
      "title": "Custom Expression",
      "description": "Expression Engine calculation wrapped in {{ }} (required if op is \"expr\"), e.g. {{ $json.price * 1.2 }}. JSONata is not supported."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "values": {
      "type": "array",
      "items": {
        "type": "number"
      },
      "description": "List of numbers (for aggregations)."
    },
    "payload": {
      "type": "object",
      "description": "Context for custom expressions."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "number",
      "description": "Calculation result."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Result",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
