# measures.define

## What it does

Record a named, versioned measure over the report schema, or a new version of an existing measure by id. The query is checked when recorded (read-only, books-only report schema, allowed parameters :from/:through/:pipeline/:party, declared columns matched) and is never run. Recording identical canonical content returns no_change. When versioning, pass expectedVersion (the version you read and edited) to be refused with a conflict naming the current version if someone else has versioned it since.

## Before you send it

An authorized OAuth connection may call it, including a headless client. Effective membership, application grant and token permissions still apply. Describe `measures.define` through `GET /v1/catalog/commands/{name}` before acting.

This command does not accept `source_document_id` in its envelope. Any input evidence requirements remain as documented below.

## Inputs

Put these fields inside the envelope's `input` object. The outer envelope names the command, a stable `idempotency_key` and `effective_at`; [request and recovery rules](/docs/api/) explain those separately. Use exact minor-unit integer strings for monetary fields. Take existing IDs from prior reads or command results; choose a new identity only where the command asks for one.

Required means required within its containing object; an optional parent can be omitted.

| Field | Type | Required | Meaning and accepted values |
|---|---|---|---|
| `id` | string | No |  Pattern: `"^msr_[0-9A-HJKMNP-TV-Z]{26}$"`. |
| `definition` | object | Yes | A named, versioned read-only SQL measure over the report schema that returns one row of whole numbers for a window. Allowed named parameters: :from, :through, :pipeline and :party (at most one holder parameter).  |
| `definition.spec` | string | Yes |  Must be `"economico.measure/1"`. Example: `"economico.measure/1"`. |
| `definition.report_schema` | schema-defined | Yes |   |
| `definition.name` | string | Yes |  Minimum length: `1`. Maximum length: `120`. Example: `"Pursuits won"`. |
| `definition.description` | string | No |  Minimum length: `1`. |
| `definition.sql` | string | Yes |  Minimum length: `1`. Example: `"SELECT count(*) AS won FROM opportunities o JOIN events e ON e.event_id = o.won_event_id WHERE o.pipeline_key = :pipeline AND o.status = 'won' AND julianday(e.effective_at) >= julianday(:from) AND julianday(e.effective_at) < julianday(:through, '+1 day')"`. |
| `definition.columns` | array | Yes |  Items: object. Minimum items: `1`. Maximum items: `12`. |
| `definition.columns[].name` | string | Yes | Result column name selected by sql. Pattern: `"^[A-Za-z_][A-Za-z0-9_]{0,63}$"`. Example: `"won"`. |
| `definition.columns[].unit` | schema-defined | Yes | "number" for plain whole numbers (counts, ratios), "percent" for percentages (with optional decimals, e.g. decimals 2 and value 1500 mean 15.00%), or an ISO 4217 currency code (e.g. "USD") for minor units. Choose a matching alternative in the exact schema below. Example: `"number"`. |
| `definition.columns[].decimals` | integer | No | Optional, unit "number" or "percent" only: the column's whole number is scaled by ten to this power (decimals 2 and value 120 mean 1.20 or 1.20%). Omit it for a whole-number column; 0 is the default and is refused when written. Minimum: `1`. Maximum: `6`. |
| `definition.columns[].estimate_for` | string | No | Optional: marks this column as the open-pipeline estimate for another declared column of the same unit (its decimals may differ). Pattern: `"^[A-Za-z_][A-Za-z0-9_]{0,63}$"`. |
| `expectedVersion` | integer | No | New versions only: the version you read and edited. When the measure has moved on, the new version is refused with a conflict naming the current version. Leave it out to version whatever is current. Minimum: `1`. |

## After acceptance

When the command emits events, its documented effects and receipt are recorded in the command transaction. The response returns `commandId`, `replayed`, the command-specific `result` below and emitted `events` with their IDs and CIDs. A command is not automatically a cash movement or revenue recognition: use the behavior above to determine what this command records.

Inspect `result` and the affected records or reports before continuing. Save returned identifiers for later calls. Fetch `GET /v1/commands/{id}` with `commandId` to recover the accepted receipt; retry the same intent with the same idempotency key if the response was lost. Some commands can succeed with `events: []` and return a transient result and `commandId` without persisting a receipt. A lookup of that ID can return null; retain the returned result and verify the affected record. Retrying can re-evaluate the current state rather than replay a stored result. A domain `no_change` is a separate success outcome with no persisted receipt.

### Result fields

Required means required within its containing object; an optional parent can be omitted.

| Field | Type | Required | Meaning and accepted values |
|---|---|---|---|
| `id` | string | Yes |  Pattern: `"^msr_[0-9A-HJKMNP-TV-Z]{26}$"`. |
| `version` | integer | Yes |  Minimum: `1`. |
| `reportSchema` | integer | Yes |  Minimum: `1`. |
| `name` | string | Yes |   |
| `description` | string or null | Yes |   |
| `documentId` | string | Yes |   |
| `cid` | string | Yes |   |
| `parameters` | array | Yes |  Each item must be `"from"`, `"through"`, `"pipeline"`, `"party"`. Maximum items: `4`. |


[All commands](/docs/command-reference/) · [Operation and errors](/docs/api-reference/operations/commands-execute/) · [Reusable schemas](/docs/api-reference/components/)

Keep credentials out of prompts; rehearse writes only in a disposable sandbox.

## Exact request schema


```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "const": "measures.define"
    },
    "input": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "id": {
          "type": "string",
          "pattern": "^msr_[0-9A-HJKMNP-TV-Z]{26}$"
        },
        "definition": {
          "type": "object",
          "additionalProperties": false,
          "description": "A named, versioned read-only SQL measure over the report schema that returns one row of whole numbers for a window. Allowed named parameters: :from, :through, :pipeline and :party (at most one holder parameter).",
          "properties": {
            "spec": {
              "const": "economico.measure/1"
            },
            "report_schema": {},
            "name": {
              "type": "string",
              "minLength": 1,
              "maxLength": 120
            },
            "description": {
              "type": "string",
              "minLength": 1
            },
            "sql": {
              "type": "string",
              "minLength": 1
            },
            "columns": {
              "type": "array",
              "minItems": 1,
              "maxItems": 12,
              "items": {
                "type": "object",
                "additionalProperties": false,
                "properties": {
                  "name": {
                    "type": "string",
                    "pattern": "^[A-Za-z_][A-Za-z0-9_]{0,63}$",
                    "description": "Result column name selected by sql."
                  },
                  "unit": {
                    "anyOf": [
                      {
                        "const": "number"
                      },
                      {
                        "const": "percent"
                      },
                      {
                        "type": "string",
                        "pattern": "^[A-Z]{3}$"
                      }
                    ],
                    "description": "\"number\" for plain whole numbers (counts, ratios), \"percent\" for percentages (with optional decimals, e.g. decimals 2 and value 1500 mean 15.00%), or an ISO 4217 currency code (e.g. \"USD\") for minor units."
                  },
                  "decimals": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 6,
                    "description": "Optional, unit \"number\" or \"percent\" only: the column's whole number is scaled by ten to this power (decimals 2 and value 120 mean 1.20 or 1.20%). Omit it for a whole-number column; 0 is the default and is refused when written."
                  },
                  "estimate_for": {
                    "type": "string",
                    "pattern": "^[A-Za-z_][A-Za-z0-9_]{0,63}$",
                    "description": "Optional: marks this column as the open-pipeline estimate for another declared column of the same unit (its decimals may differ)."
                  }
                },
                "required": [
                  "name",
                  "unit"
                ]
              }
            }
          },
          "required": [
            "spec",
            "report_schema",
            "name",
            "sql",
            "columns"
          ]
        },
        "expectedVersion": {
          "type": "integer",
          "minimum": 1,
          "description": "New versions only: the version you read and edited. When the measure has moved on, the new version is refused with a conflict naming the current version. Leave it out to version whatever is current."
        }
      },
      "required": [
        "definition"
      ]
    },
    "idempotency_key": {
      "type": "string",
      "minLength": 1,
      "maxLength": 256,
      "description": "A key you choose, stable for this one command: retrying with it returns the original receipt instead of running again; reusing it for a different command is refused."
    },
    "effective_at": {
      "type": "string",
      "format": "date-time",
      "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$",
      "description": "When the change takes effect in the books, in UTC with Z: the business date it happened, not when you record it."
    }
  },
  "required": [
    "name",
    "input",
    "idempotency_key",
    "effective_at"
  ],
  "additionalProperties": false
}
```

## Accepted command receipt


```json
{
  "type": "object",
  "required": [
    "commandId",
    "replayed",
    "result",
    "events"
  ],
  "properties": {
    "commandId": {
      "type": "string"
    },
    "replayed": {
      "type": "boolean"
    },
    "imported": {
      "const": true,
      "description": "The command's events are history from before the business joined Economico, recorded as an import: free of monthly events."
    },
    "result": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "id": {
          "type": "string",
          "pattern": "^msr_[0-9A-HJKMNP-TV-Z]{26}$"
        },
        "version": {
          "type": "integer",
          "minimum": 1
        },
        "reportSchema": {
          "type": "integer",
          "minimum": 1
        },
        "name": {
          "type": "string"
        },
        "description": {
          "type": [
            "string",
            "null"
          ]
        },
        "documentId": {
          "type": "string"
        },
        "cid": {
          "type": "string"
        },
        "parameters": {
          "type": "array",
          "maxItems": 4,
          "items": {
            "enum": [
              "from",
              "through",
              "pipeline",
              "party"
            ]
          }
        }
      },
      "required": [
        "id",
        "version",
        "reportSchema",
        "name",
        "description",
        "documentId",
        "cid",
        "parameters"
      ]
    },
    "events": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "cid": {
            "type": "string"
          }
        }
      }
    }
  }
}
```

## Example request


```json
{
  "name": "measures.define",
  "input": {
    "definition": {
      "spec": "economico.measure/1",
      "name": "Pursuits won",
      "sql": "SELECT count(*) AS won FROM opportunities o JOIN events e ON e.event_id = o.won_event_id WHERE o.pipeline_key = :pipeline AND o.status = 'won' AND julianday(e.effective_at) >= julianday(:from) AND julianday(e.effective_at) < julianday(:through, '+1 day')",
      "columns": [
        {
          "name": "won",
          "unit": "number"
        }
      ]
    }
  },
  "effective_at": "2026-09-01T00:00:00Z",
  "idempotency_key": "measures.define-example-0"
}
```


