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

# Получение результатов формул для item_set

> Получение всех результатов вычислений формул для конкретного item_set в рамках проекта

<Callout emoji="📊">
  Возвращает массив результатов всех формул для указанного item\_set в рамках проекта.
</Callout>

## Параметры URL

* `project_id` (int, path, **обязательный**) - ID проекта (для валидации принадлежности item\_set)
* `item_set_id` (int, path, **обязательный**) - ID item set, для которого нужны результаты

## Headers

```http theme={null}
API-Access-Key: {token}
```

## Описание полей ответа

Возвращается массив объектов с результатами формул:

* `id` (integer) - Уникальный идентификатор записи
* `id_formula` (integer) - ID формулы из таблицы `object.project_formula`
* `id_project_item_set_output` (integer) - ID project item set processing output
* `id_item_set` (integer) - ID item set
* `result` (float, nullable) - Результат вычисления (null если была ошибка)
* `error` (string, nullable) - Текст ошибки (null если вычисление успешно)
* `created_at` (datetime, ISO 8601) - Дата и время создания записи
* `updated_at` (datetime, ISO 8601) - Дата и время последнего обновления
* `formula` (object) - Объект с информацией о формуле:
  * `name` (string) - Название формулы
  * `text` (string) - Текст формулы
  * `is_default` (boolean) - Флаг, указывающий является ли формула формулой по умолчанию

## Пример ответа

```json theme={null}
[
  {
    "id": 1,
    "id_formula": 123,
    "id_project_item_set_output": 456,
    "id_item_set": 448,
    "result": 85.5,
    "error": null,
    "created_at": "2024-01-01T00:00:00",
    "updated_at": "2024-01-01T00:00:00",
    "formula": {
      "name": "total_score",
      "text": "AVG(score_i WHERE score_i != '')",
      "is_default": true
    }
  }
]
```

### Примечания

* Если вычисление успешно: `result` содержит число, `error = null`
* Если произошла ошибка: `result = null`, `error` содержит описание ошибки
* Каждая формула = отдельная запись в массиве

## Логика работы

### Когда создаются записи

Записи в таблице `output.formula_output` создаются автоматически при записи в отчет:

1. Заполнение отчета Google Sheets
2. **Вычисление формул**
3. **Сохранение результатов** - для каждой формулы создается отдельная запись:
   * Если вычисление успешно: `result` = число, `error` = null
   * Если произошла ошибка: `result` = null, `error` = текст ошибки

### Структура данных

**Принцип:** Одна запись = один результат одной формулы для одного item\_set

**Item Set 456 + 3 формулы = 3 записи в таблице**

| id | id\_formula | id\_item\_set | result | error              |
| -- | ----------- | ------------- | ------ | ------------------ |
| 1  | 5           | 456           | 4.5    | null               |
| 2  | 6           | 456           | null   | "Division by zero" |
| 3  | 7           | 456           | 8.2    | null               |

## Коды ошибок

| HTTP Код | Описание           | Рекомендуемое действие                             |
| -------- | ------------------ | -------------------------------------------------- |
| 200      | Успешно            | Обработать результаты                              |
| 401      | Не авторизован     | Обновить/получить новый JWT токен                  |
| 404      | Item set не найден | Проверить корректность project\_id и item\_set\_id |
| 422      | Ошибка валидации   | Проверить формат параметров (должны быть integer)  |
| 500      | Ошибка сервера     | Повторить запрос или обратиться в поддержку        |


## OpenAPI

````yaml GET /output/formulas/project/{project_id}/item-set/{item_set_id}
openapi: 3.1.0
info:
  title: SpellIt API
  description: >-
    API для обработки Items через создание проекта, загрузку Item Set и загрузку
    Items
  version: 1.0.0
servers:
  - url: https://api.spellit.ai/api/
security: []
paths:
  /output/formulas/project/{project_id}/item-set/{item_set_id}:
    get:
      description: >-
        Получение всех результатов вычислений формул для конкретного item_set в
        рамках проекта
      parameters:
        - name: project_id
          in: path
          required: true
          description: ID проекта (для валидации принадлежности item_set)
          schema:
            type: integer
        - name: item_set_id
          in: path
          required: true
          description: ID item set, для которого нужны результаты
          schema:
            type: integer
      responses:
        '200':
          description: >-
            Успешный ответ - возвращает массив результатов всех формул для
            указанного item_set
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id:
                      type: integer
                      description: Уникальный идентификатор записи
                    id_formula:
                      type: integer
                      description: ID формулы из таблицы object.project_formula
                    id_project_item_set_output:
                      type: integer
                      description: ID project item set processing output
                    id_item_set:
                      type: integer
                      description: ID item set
                    result:
                      type: number
                      nullable: true
                      description: Результат вычисления (null если была ошибка)
                    error:
                      type: string
                      nullable: true
                      description: Текст ошибки (null если вычисление успешно)
                    created_at:
                      type: string
                      format: date-time
                      description: Дата и время создания записи
                    updated_at:
                      type: string
                      format: date-time
                      description: Дата и время последнего обновления
                    formula:
                      type: object
                      description: Объект с информацией о формуле
                      properties:
                        name:
                          type: string
                          description: Название формулы
                        text:
                          type: string
                          description: Текст формулы
                        is_default:
                          type: boolean
                          description: >-
                            Флаг, указывающий является ли формула формулой по
                            умолчанию
                      required:
                        - name
                        - text
                        - is_default
                  required:
                    - id
                    - id_formula
                    - id_project_item_set_output
                    - id_item_set
                    - created_at
                    - updated_at
                    - formula
              examples:
                default:
                  summary: Успешные результаты с ошибками
                  value:
                    - id: 1
                      id_formula: 5
                      id_project_item_set_output: 123
                      id_item_set: 456
                      result: 4.5
                      error: null
                      created_at: '2025-11-17T10:00:00Z'
                      updated_at: '2025-11-17T10:00:00Z'
                      formula:
                        name: total_score
                        text: AVG(score_i WHERE score_i != '')
                        is_default: true
                    - id: 2
                      id_formula: 6
                      id_project_item_set_output: 123
                      id_item_set: 456
                      result: null
                      error: Division by zero
                      created_at: '2025-11-17T10:00:01Z'
                      updated_at: '2025-11-17T10:00:01Z'
                      formula:
                        name: average_rating
                        text: SUM(rating) / COUNT(rating)
                        is_default: false
                    - id: 3
                      id_formula: 7
                      id_project_item_set_output: 123
                      id_item_set: 456
                      result: 8.234567
                      error: null
                      created_at: '2025-11-17T10:00:02Z'
                      updated_at: '2025-11-17T10:00:02Z'
                      formula:
                        name: max_value
                        text: MAX(value_i)
                        is_default: false
                successful_only:
                  summary: Только успешные результаты
                  value:
                    - id: 1
                      id_formula: 5
                      id_project_item_set_output: 123
                      id_item_set: 456
                      result: 4.5
                      error: null
                      created_at: '2025-11-17T10:00:00Z'
                      updated_at: '2025-11-17T10:00:00Z'
                      formula:
                        name: total_score
                        text: AVG(score_i WHERE score_i != '')
                        is_default: true
                    - id: 3
                      id_formula: 7
                      id_project_item_set_output: 123
                      id_item_set: 456
                      result: 8.234567
                      error: null
                      created_at: '2025-11-17T10:00:02Z'
                      updated_at: '2025-11-17T10:00:02Z'
                      formula:
                        name: max_value
                        text: MAX(value_i)
                        is_default: false
        '401':
          description: Unauthorized - Пользователь не авторизован или токен невалиден
          content:
            application/json:
              example:
                detail: Not authenticated
        '404':
          description: Not Found - Item set не найден или не принадлежит указанному проекту
          content:
            application/json:
              example:
                detail: Item set 456 not found in project 304
        '422':
          description: >-
            Unprocessable Entity - Ошибка валидации параметров (например,
            некорректный тип данных)
          content:
            application/json:
              example:
                detail:
                  - loc:
                      - path
                      - project_id
                    msg: value is not a valid integer
                    type: type_error.integer
        '500':
          description: Internal Server Error - Внутренняя ошибка сервера
          content:
            application/json:
              example:
                detail: Internal server error
      security:
        - ApiKeyAuth: []
        - BearerAuth: []
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: API-Access-Key
      description: API-ключ для доступа к эндпоинтам
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT-токен для авторизации (Bearer Token)

````