# Math Operations

> 对数据执行数学计算或聚合。

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

- 标识: `data.math`
- 类别: 数据
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

对数据执行数学计算或聚合。

该算子提供标准的算术和聚合函数。它不使用 JSONata：在 `expr` 模式下，结果就是 Sommatic AI Expression Engine 已经解析出的值。

**操作：**
- **Sum/Avg/Min/Max：** 对 `values`（输入载荷中的数字数组）做聚合。非数值项会被忽略；空列表返回 0。
- **Advanced（Expr）：** 一个 `{{ }}` JavaScript 表达式（例如 `{{ Math.round($json.price * 1.2 * 100) / 100 }}`）。解析后的值作为 `result` 返回，不再做进一步求值。

**适用场景：**
- 计算购物车中商品的总价。
- 在竞价列表中找出最高出价。
- 计算税率百分比。

## 配置

- `op` (string, 可选): 默认值: `sum`. 可选值: `sum`, `avg`, `min`, `max`, `expr`.
- `expression` (string, 可选, 支持表达式): 用 {{ }} 包裹的 Expression Engine 计算式（op 为“expr”时必填），例如 {{ $json.price * 1.2 }}。不支持 JSONata。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): Result
- `error`: Error

## 输入契约

- `values` (array<number>, 可选): 数字列表（用于聚合）。
- `payload` (object, 可选): 自定义表达式的上下文。

## 输出契约

- `result` (number, 可选): 计算结果。

## 在表达式中

后续节点可通过 `$("Math Operations").item.json.<路径>` 读取此节点输出中的内容（请把 `Math Operations` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Math Operations").item.json.result` (number) = `42.5`: 计算结果。


## 工作原理

对输入 payload 中的 `values` 数组做聚合（求和、平均、最小、最大），或返回由 Expression Engine `{{ }}` 计算的值，结果为 `{ result }`。

1. 解析配置；`op` 默认为 `sum`。`expression` 中的 `{{ }}` 由 Expression Engine 求值（JavaScript，限时 100 毫秒）。
2. `expr`：`result` 即解析后的 `expression` 原值，可为任意类型。不使用 JSONata。
3. `sum`、`avg`、`min`、`max`：从输入 payload 读取 `values`（不可配置）。字符串会失败；每个元素用 `Number()` 转换并丢弃 `NaN`；空列表结果为 0。
4. 通过 `out` 返回 `{ result }`；输入 payload 不会保留。

## 在工作流中

### 节点

```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"
}
```

## 输出端口 (代码中的行为)

### `out`

计算完成。

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

### `error`

`op` 未知，或 `values` 无法作为列表读取。

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

## 代码中的行为

- `expression`: 仅在 `op` 为 `expr` 时使用。不含 `{{ }}` 时原样返回文本。若整值 `{{ }}` 抛错，解析器会保留原文本，因此 `result` 就是 `{{ ... }}` 字符串，节点仍从 `out` 输出。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Math Error: Unknown op: <op>` | `error` | `op` 不是 `sum`、`avg`、`min`、`max` 或 `expr`。 |
| `Math Error: Values must be an array for aggregation` | `error` | payload 中的 `values` 是字符串。 |
| `Math Error: (values \|\| []).map is not a function` | `error` | `values` 是数字、对象或 `true`。 |

## 说明与限制

- `values` 中的 `null`、空字符串和布尔值会转为 0 或 1 并参与计算。
- 如需聚合其他字段，请先整理数据（例如用 `data.transform` 返回 `{ "values": items.price }`），或使用 `expr`：`{{ _.sum($json.items.map(item => item.price)) }}`。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（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"
  }
]
```
