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

# Создание правила мониторинга транзакций через API

> Создайте правило KYT через API Didit: условия, окна скорости, область применения и действия. Сначала тестовый режим, затем бэктест и активация.



Промпт для API создания правила
        Скопировать промпт в буфер обмена



      
      

\<pre>

\`Create a custom transaction-monitoring rule on my Didit application.

Endpoint:
POST https://verification.didit.me/v3/transactions/rules/

Authentication:
Use the x-api-key header with my Didit API key.

Request body (application/json):
\{
"title": "Structuring - inbound (custom)",   // required, unique per application - duplicate -> 400
"description": "20+ inbound EUR transfers, all under 10,000 EUR, 30 days",
"category": "finance",                        // required: finance, aml_ctf, anomaly_detection, fatf, device_intelligence, crypto_monitoring, travel_rule, responsible_gaming, e_commerce, ...
"mode": "TEST",                               // required: TEST (recommended start - evaluates, never affects transactions), ACTIVE, DISABLED
"evaluation_mode": "ALL",                     // ALL = every condition must match, ANY = at least one
"scope": {"transaction_types": ["finance"], "directions": ["INBOUND"]},  // constrains the transaction being evaluated; optional keys: transaction_types, directions (INBOUND/OUTBOUND), action_types
"conditions": [                               // read the transaction being evaluated, never the history window
\{"field": "currency", "operator": "eq", "value": "EUR"},
\{"field": "amount", "operator": "lt", "value": 10000}
],
"aggregation": [                              // velocity over the history window: ALL entries must match
\{"metric": "count", "operator": "gte", "value": 20, "window": "30d",
 "filters": {"direction": "INBOUND", "transaction_type": "finance", "currency": "EUR", "subject_vendor_data": "__current__"}},
\{"metric": "max", "field": "amount", "operator": "lt", "value": 10000, "window": "30d",
 "filters": {"direction": "INBOUND", "transaction_type": "finance", "currency": "EUR", "subject_vendor_data": "__current__"}}
],
"actions": [{"type": "add_score", "value": 35}]
}

Schema essentials:
\- Condition operators: eq, ne, gt, gte, lt, lte, in, not_in, contains, not_contains, contains_any (list of strings), regex, fuzzy_match (needs "score" 0-100), exists/is_not_empty/is_not_null, not_exists/is_empty/is_null.
\- Condition fields include amount, preferred_currency_amount, direction, action_type, payment_details, subject_vendor_data, counterparty_country, subject_device_fingerprint, subject_payment_method_*, travel_rule_status, tags, and custom_values.<key> for your own custom_properties.
\- value_type turns "value" into a List UUID ("list"), another field path ("field"), or a relative date ("relative_date").
\- Aggregation windows: <N>m (MINUTES), <N>h, <N>d. A filter value of "__current__" means same-as-the-evaluated-transaction. Records without the grouped value are never grouped together: when the evaluated transaction has no value for a "__current__" field (no counterparty, no device fingerprint), that aggregation does not match, whatever its operator.
\- Conditions and aggregation filters are NOT interchangeable. A condition constrains only the transaction being evaluated; an aggregation filter constrains only the historical window, and it compares by equality or list membership - there is no lt/gte filter. Express a range over the window as a max/min aggregation (e.g. max amount lt 10000 with currency pinned to EUR keeps every transaction in that window under 10,000 EUR), and repeat direction/currency/transaction_type on BOTH halves when the rule promises them - otherwise the rule fires on transactions it never meant to cover.
\- Actions: add_score {value}, change_status {value, workflow_id (REQUIRED for AWAITING_USER)}, add_tags {tag_uuid|tag_name, tag_color}, add_note {note}, add_to_list {list_id}, open_case {blueprint, grouping, attach_matched_transaction}.

Recommended workflow:
1\. Create in mode TEST.
2\. POST /v3/transactions/rules/backtest/ with the SAME conditions, aggregation, evaluation_mode and scope to see matches over your history. Omitted conditions, aggregation and scope add no constraints of their own; dropping scope can include directions or transaction types the saved rule skips. Omitted evaluation_mode defaults to ALL (which can reduce matches for an ANY rule), and omitted period_days defaults to 90 days, not unlimited history.
3\. PATCH the rule to mode ACTIVE once the numbers look right.

Sandbox fixtures for this example: at least 20 inbound EUR finance transactions for the same subject within 30 days, each with raw amount below 10000. No normalized amount is required. Sandbox ingestion does not evaluate rules; call backtest explicitly.

Failure modes:
\- 400 - duplicate title, unknown operator/metric, malformed window, invalid scope direction, contains_any without a list, fuzzy_match without a score, or AWAITING_USER without workflow_id. The body names the exact index and problem.
\- 401 - missing or malformed x-api-key.

Full guide: /transaction-monitoring/rules-api.`

\</pre>



      
      

Вставьте в



## OpenAPI

````yaml ru/openapi-25.json POST /v3/transactions/rules/
openapi: 3.0.0
info:
  version: 3.0.0
  title: Didit Verification API
  description: >-
    API верификации личности. Аутентификация выполняется с помощью заголовка
    x-api-key.
servers:
  - url: https://verification.didit.me
security: []
tags: []
paths:
  /v3/transactions/rules/:
    post:
      tags:
        - Transactions
      summary: Создать правило
      description: >-
        Создать правило мониторинга транзакций типа CUSTOM. Названия уникальны
        для каждого приложения (дубликат -> 400). Действие `change_status`,
        направленное на `AWAITING_USER`, должно содержать `workflow_id`.
        Правила, созданные в режиме ACTIVE, сразу применяются к новым
        транзакциям; рекомендуемый порядок действий: создать в режиме TEST,
        провести бэктестинг, затем переключить режим на ACTIVE. Чтобы изменить
        библиотечное правило, создайте его копию: передайте определение
        библиотечного правила с параметрами `metadata.based_on` (его
        библиотечный ключ) и `metadata.based_on_rule_uuid`.
      operationId: createTransactionRule
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TransactionRuleCreateRequest'
            example:
              title: Structuring - inbound (custom)
              description: 20+ inbound EUR transfers, all under 10,000 EUR, 30 days
              category: finance
              mode: TEST
              evaluation_mode: ALL
              scope:
                transaction_types:
                  - finance
                directions:
                  - INBOUND
              conditions:
                - field: currency
                  operator: eq
                  value: EUR
                - field: amount
                  operator: lt
                  value: 10000
              aggregation:
                - metric: count
                  operator: gte
                  value: 20
                  window: 30d
                  filters:
                    direction: INBOUND
                    transaction_type: finance
                    subject_vendor_data: __current__
                    currency: EUR
                - metric: max
                  field: amount
                  operator: lt
                  value: 10000
                  window: 30d
                  filters:
                    direction: INBOUND
                    transaction_type: finance
                    subject_vendor_data: __current__
                    currency: EUR
              actions:
                - type: add_score
                  value: 35
      responses:
        '201':
          description: Созданное правило.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TransactionRuleDetail'
        '400':
          description: >-
            Ошибка валидации: дублирующийся заголовок, неизвестный
            оператор/метрика, некорректный формат окна, недопустимое направление
            области действия или AWAITING_USER без workflow_id.
          content:
            application/json:
              schema:
                type: object
              example:
                title:
                  - A rule with this name already exists.
      security:
        - ApiKeyAuth: []
      x-codeSamples:
        - lang: curl
          label: curl
          source: >-
            curl -X POST 'https://verification.didit.me/v3/transactions/rules/'
            \
              -H 'x-api-key: YOUR_API_KEY' \
              -H 'Content-Type: application/json' \
              -d '{"title": "Structuring - inbound (custom)", "description": "20+ inbound EUR transfers, all under 10,000 EUR, 30 days", "category": "finance", "mode": "TEST", "evaluation_mode": "ALL", "scope": {"transaction_types": ["finance"], "directions": ["INBOUND"]}, "conditions": [{"field": "currency", "operator": "eq", "value": "EUR"}, {"field": "amount", "operator": "lt", "value": 10000}], "aggregation": [{"metric": "count", "operator": "gte", "value": 20, "window": "30d", "filters": {"direction": "INBOUND", "transaction_type": "finance", "subject_vendor_data": "__current__", "currency": "EUR"}}, {"metric": "max", "field": "amount", "operator": "lt", "value": 10000, "window": "30d", "filters": {"direction": "INBOUND", "transaction_type": "finance", "subject_vendor_data": "__current__", "currency": "EUR"}}], "actions": [{"type": "add_score", "value": 35}]}'
        - lang: python
          label: Python
          source: |-
            from didit import Didit

            # Reads DIDIT_API_KEY.
            client = Didit()

            result = client.transactions.rules.create(
                title="Structuring - inbound (custom)",
                description="20+ inbound EUR transfers, all under 10,000 EUR, 30 days",
                category="finance",
                mode="TEST",
                evaluation_mode="ALL",
                scope={
                    "transaction_types": ["finance"],
                    "directions": ["INBOUND"],
                },
                conditions=[{
                    "field": "currency",
                    "operator": "eq",
                    "value": "EUR",
                }, {
                    "field": "amount",
                    "operator": "lt",
                    "value": 10000,
                }],
                aggregation=[{
                    "metric": "count",
                    "operator": "gte",
                    "value": 20.0,
                    "window": "30d",
                    "filters": {"direction": "INBOUND", "transaction_type": "finance", "subject_vendor_data": "__current__", "currency": "EUR"},
                }, {
                    "metric": "max",
                    "field": "amount",
                    "operator": "lt",
                    "value": 10000.0,
                    "window": "30d",
                    "filters": {"direction": "INBOUND", "transaction_type": "finance", "subject_vendor_data": "__current__", "currency": "EUR"},
                }],
                actions=[{
                    "type": "add_score",
                    "value": 35,
                }],
            )
            print(result)
        - lang: javascript
          label: Node.js
          source: |-
            import Didit from "@didit-protocol/sdk-node";

            // Reads DIDIT_API_KEY.
            const didit = new Didit();

            const result = await didit.transactions.rules.create({
              title: "Structuring - inbound (custom)",
              description: "20+ inbound EUR transfers, all under 10,000 EUR, 30 days",
              category: "finance",
              mode: "TEST",
              evaluation_mode: "ALL",
              scope: {
                transaction_types: ["finance"],
                directions: ["INBOUND"],
              },
              conditions: [{
                field: "currency",
                operator: "eq",
                value: "EUR",
              }, {
                field: "amount",
                operator: "lt",
                value: 10000,
              }],
              aggregation: [{
                metric: "count",
                operator: "gte",
                value: 20.0,
                window: "30d",
                filters: { direction: "INBOUND", transaction_type: "finance", subject_vendor_data: "__current__", currency: "EUR" },
              }, {
                metric: "max",
                field: "amount",
                operator: "lt",
                value: 10000.0,
                window: "30d",
                filters: { direction: "INBOUND", transaction_type: "finance", subject_vendor_data: "__current__", currency: "EUR" },
              }],
              actions: [{
                type: "add_score",
                value: 35,
              }],
            });
            console.log(result);
        - lang: go
          label: Go
          source: "ctx := context.Background()\n// Reads DIDIT_API_KEY.\nclient := didit.NewClient()\n\nresult, err := client.Transactions.Rules.Create(ctx, didit.TransactionRuleCreateRequest{\n\tTitle:          \"Structuring - inbound (custom)\",\n\tDescription:    didit.String(\"20+ inbound EUR transfers, all under 10,000 EUR, 30 days\"),\n\tCategory:       \"finance\",\n\tMode:           \"TEST\",\n\tEvaluationMode: didit.Some(didit.TransactionRuleCreateRequestEvaluationMode(\"ALL\")),\n\tScope: didit.Some(didit.TransactionRuleScopeParam{\n\t\tTransactionTypes: didit.Some([]string{\"finance\"}),\n\t\tDirections:       didit.Some([]didit.TransactionRuleScopeDirections{\"INBOUND\"}),\n\t}),\n\tConditions: didit.Some([]didit.TransactionRuleConditionParam{{\n\t\tField:    \"currency\",\n\t\tOperator: \"eq\",\n\t\tValue:    didit.Some[any](\"EUR\"),\n\t}, {\n\t\tField:    \"amount\",\n\t\tOperator: \"lt\",\n\t\tValue:    didit.Some[any](10000),\n\t}}),\n\tAggregation: didit.Some([]didit.TransactionRuleAggregationParam{{\n\t\tMetric:   didit.Some(didit.TransactionRuleAggregationMetric(\"count\")),\n\t\tOperator: didit.Some(didit.TransactionRuleAggregationOperator(\"gte\")),\n\t\tValue:    20.0,\n\t\tWindow:   didit.String(\"30d\"),\n\t\tFilters:  didit.Some(map[string]any{\"direction\": \"INBOUND\", \"transaction_type\": \"finance\", \"subject_vendor_data\": \"__current__\", \"currency\": \"EUR\"}),\n\t}, {\n\t\tMetric:   didit.Some(didit.TransactionRuleAggregationMetric(\"max\")),\n\t\tField:    didit.String(\"amount\"),\n\t\tOperator: didit.Some(didit.TransactionRuleAggregationOperator(\"lt\")),\n\t\tValue:    10000.0,\n\t\tWindow:   didit.String(\"30d\"),\n\t\tFilters:  didit.Some(map[string]any{\"direction\": \"INBOUND\", \"transaction_type\": \"finance\", \"subject_vendor_data\": \"__current__\", \"currency\": \"EUR\"}),\n\t}}),\n\tActions: didit.Some([]didit.TransactionRuleActionParam{{\n\t\tType:  \"add_score\",\n\t\tValue: didit.Some[any](35),\n\t}}),\n})\nif err != nil {\n\tlog.Fatal(err)\n}\nfmt.Printf(\"%+v\\n\", result)"
        - lang: java
          label: Java
          source: >-
            import java.util.List;

            import java.util.Map;

            import me.didit.Didit;

            import me.didit.types.TransactionRuleAction;

            import me.didit.types.TransactionRuleActionAddScore;

            import me.didit.types.TransactionRuleAggregation;

            import me.didit.types.TransactionRuleCondition;

            import me.didit.types.TransactionRuleCreateRequest;

            import me.didit.types.TransactionRuleScope;


            // Reads DIDIT_API_KEY.

            Didit client = new Didit();


            var result =
            client.transactions().rules().create(TransactionRuleCreateRequest.builder()
                    .title("Structuring - inbound (custom)")
                    .description("20+ inbound EUR transfers, all under 10,000 EUR, 30 days")
                    .category("finance")
                    .mode(TransactionRuleCreateRequest.Mode.of("TEST"))
                    .evaluationMode(TransactionRuleCreateRequest.EvaluationMode.of("ALL"))
                    .scope(TransactionRuleScope.builder()
                            .transactionTypes(List.of("finance"))
                            .directions(List.of(TransactionRuleScope.Directions.of("INBOUND")))
                            .build())
                    .conditions(List.of(
                            TransactionRuleCondition.builder()
                                    .field("currency")
                                    .operator(TransactionRuleCondition.Operator.of("eq"))
                                    .value("EUR")
                                    .build(),
                            TransactionRuleCondition.builder()
                                    .field("amount")
                                    .operator(TransactionRuleCondition.Operator.of("lt"))
                                    .value(10000)
                                    .build()))
                    .aggregation(List.of(
                            TransactionRuleAggregation.builder()
                                    .metric(TransactionRuleAggregation.Metric.of("count"))
                                    .operator(TransactionRuleAggregation.Operator.of("gte"))
                                    .value(20.0)
                                    .window("30d")
                                    .filters(Map.of("direction", "INBOUND", "transaction_type", "finance", "subject_vendor_data", "__current__", "currency", "EUR"))
                                    .build(),
                            TransactionRuleAggregation.builder()
                                    .metric(TransactionRuleAggregation.Metric.of("max"))
                                    .field("amount")
                                    .operator(TransactionRuleAggregation.Operator.of("lt"))
                                    .value(10000.0)
                                    .window("30d")
                                    .filters(Map.of("direction", "INBOUND", "transaction_type", "finance", "subject_vendor_data", "__current__", "currency", "EUR"))
                                    .build()))
                    .actions(List.of(TransactionRuleAction.ofAddScore(TransactionRuleActionAddScore.builder()
                            .type(TransactionRuleActionAddScore.Type.of("add_score"))
                            .value(35L)
                            .build())))
                    .build());
            System.out.println(result);
        - lang: php
          label: PHP
          source: |-
            <?php

            require 'vendor/autoload.php';

            use Didit\DiditClient;

            // Reads DIDIT_API_KEY.
            $didit = new DiditClient();

            $result = $didit->transactions->rules->create([
                'title' => 'Structuring - inbound (custom)',
                'description' => '20+ inbound EUR transfers, all under 10,000 EUR, 30 days',
                'category' => 'finance',
                'mode' => 'TEST',
                'evaluation_mode' => 'ALL',
                'scope' => [
                    'transaction_types' => ['finance'],
                    'directions' => ['INBOUND'],
                ],
                'conditions' => [[
                    'field' => 'currency',
                    'operator' => 'eq',
                    'value' => 'EUR',
                ], [
                    'field' => 'amount',
                    'operator' => 'lt',
                    'value' => 10000,
                ]],
                'aggregation' => [[
                    'metric' => 'count',
                    'operator' => 'gte',
                    'value' => 20.0,
                    'window' => '30d',
                    'filters' => ['direction' => 'INBOUND', 'transaction_type' => 'finance', 'subject_vendor_data' => '__current__', 'currency' => 'EUR'],
                ], [
                    'metric' => 'max',
                    'field' => 'amount',
                    'operator' => 'lt',
                    'value' => 10000.0,
                    'window' => '30d',
                    'filters' => ['direction' => 'INBOUND', 'transaction_type' => 'finance', 'subject_vendor_data' => '__current__', 'currency' => 'EUR'],
                ]],
                'actions' => [[
                    'type' => 'add_score',
                    'value' => 35,
                ]],
            ]);
            print_r($result->toArray());
        - lang: ruby
          label: Ruby
          source: |-
            require "didit"

            # Reads DIDIT_API_KEY.
            didit = Didit::Client.new

            result = didit.transactions.rules.create(
              title: "Structuring - inbound (custom)",
              description: "20+ inbound EUR transfers, all under 10,000 EUR, 30 days",
              category: "finance",
              mode: "TEST",
              evaluation_mode: "ALL",
              scope: {
                transaction_types: ["finance"],
                directions: ["INBOUND"],
              },
              conditions: [{
                field: "currency",
                operator: "eq",
                value: "EUR",
              }, {
                field: "amount",
                operator: "lt",
                value: 10000,
              }],
              aggregation: [{
                metric: "count",
                operator: "gte",
                value: 20.0,
                window: "30d",
                filters: { direction: "INBOUND", transaction_type: "finance", subject_vendor_data: "__current__", currency: "EUR" },
              }, {
                metric: "max",
                field: "amount",
                operator: "lt",
                value: 10000.0,
                window: "30d",
                filters: { direction: "INBOUND", transaction_type: "finance", subject_vendor_data: "__current__", currency: "EUR" },
              }],
              actions: [{
                type: "add_score",
                value: 35,
              }]
            )
            puts result.to_h
        - lang: csharp
          label: .NET
          source: >-
            using System;

            using System.Collections.Generic;

            using System.Text.Json;

            using Didit;


            // Reads DIDIT_API_KEY.

            using var client = new DiditClient();


            var result = await client.Transactions.Rules.CreateAsync(new
            TransactionRuleCreateRequest

            {
                Title = "Structuring - inbound (custom)",
                Description = "20+ inbound EUR transfers, all under 10,000 EUR, 30 days",
                Category = "finance",
                Mode = "TEST",
                EvaluationMode = new TransactionRuleCreateRequestEvaluationMode("ALL"),
                Scope = new TransactionRuleScope
                {
                    TransactionTypes = new string[] { "finance" },
                    Directions = new TransactionRuleScopeDirections[] { "INBOUND" },
                },
                Conditions = new TransactionRuleCondition[]
                {
                    new()
                    {
                        Field = "currency",
                        Operator = "eq",
                        Value = "EUR",
                    },
                    new()
                    {
                        Field = "amount",
                        Operator = "lt",
                        Value = 10000,
                    },
                },
                Aggregation = new TransactionRuleAggregation[]
                {
                    new()
                    {
                        Metric = new TransactionRuleAggregationMetric("count"),
                        Operator = new TransactionRuleAggregationOperator("gte"),
                        Value = 20.0,
                        Window = "30d",
                        Filters = new Dictionary<string, object> { ["direction"] = "INBOUND", ["transaction_type"] = "finance", ["subject_vendor_data"] = "__current__", ["currency"] = "EUR" },
                    },
                    new()
                    {
                        Metric = new TransactionRuleAggregationMetric("max"),
                        Field = "amount",
                        Operator = new TransactionRuleAggregationOperator("lt"),
                        Value = 10000.0,
                        Window = "30d",
                        Filters = new Dictionary<string, object> { ["direction"] = "INBOUND", ["transaction_type"] = "finance", ["subject_vendor_data"] = "__current__", ["currency"] = "EUR" },
                    },
                },
                Actions = new TransactionRuleAction[]
                {
                    new()
                    {
                        Type = new TransactionRuleActionType("add_score"),
                        Value = 35,
                    },
                },
            });

            Console.WriteLine(JsonSerializer.Serialize(result));
components:
  schemas:
    TransactionRuleCreateRequest:
      type: object
      required:
        - title
        - category
        - mode
      properties:
        title:
          type: string
          description: >-
            Название правила. Уникально для приложения среди неудалённых правил;
            дубликаты возвращают 400.
        description:
          type: string
          nullable: true
        category:
          type: string
          description: >-
            Тематика риска, используемая для группировки и отчётов, например
            finance, aml_ctf, anomaly_detection, fatf, device_intelligence,
            crypto_monitoring, travel_rule, responsible_gaming, e_commerce.
        mode:
          type: string
          enum:
            - ACTIVE
            - DISABLED
            - TEST
          description: >-
            ACTIVE оценивает в реальном времени. TEST оценивает и записывает
            запуски правил, но никогда не влияет на оценку или статус -
            рекомендуемый режим для начала работы. DISABLED пропускается.
        evaluation_mode:
          type: string
          enum:
            - ALL
            - ANY
          default: ALL
          description: >-
            Должны ли совпадать все условия (ALL) или хотя бы одно (ANY).
            Игнорируется, если в условиях используется group_index.
        scope:
          $ref: '#/components/schemas/TransactionRuleScope'
        conditions:
          type: array
          items:
            $ref: '#/components/schemas/TransactionRuleCondition'
        aggregation:
          type: array
          items:
            $ref: '#/components/schemas/TransactionRuleAggregation'
        actions:
          type: array
          items:
            $ref: '#/components/schemas/TransactionRuleAction'
        metadata:
          type: object
          description: Метаданные в свободной форме, сохранённые в правиле.
      description: >-
        Создаёт правило типа CUSTOM. Правила в режиме ACTIVE вступают в силу
        немедленно для новых транзакций: создавайте их в режиме TEST и сначала
        проводите бэктестинг.
    TransactionRuleDetail:
      type: object
      properties:
        uuid:
          type: string
          format: uuid
        title:
          type: string
          description: >-
            Название правила. Уникально для приложения среди неудалённых правил;
            дубликаты возвращают 400.
        description:
          type: string
          nullable: true
        category:
          type: string
          description: >-
            Тематика риска, используемая для группировки и отчётов, например
            finance, aml_ctf, anomaly_detection, fatf, device_intelligence,
            crypto_monitoring, travel_rule, responsible_gaming, e_commerce.
        mode:
          type: string
          enum:
            - ACTIVE
            - DISABLED
            - TEST
          description: >-
            ACTIVE оценивает в реальном времени. TEST оценивает и записывает
            запуски правил, но никогда не влияет на оценку или статус -
            рекомендуемый режим для начала работы. DISABLED пропускается.
        evaluation_mode:
          type: string
          enum:
            - ALL
            - ANY
          default: ALL
          description: >-
            Должны ли совпадать все условия (ALL) или хотя бы одно (ANY).
            Игнорируется, если в условиях используется group_index.
        scope:
          $ref: '#/components/schemas/TransactionRuleScope'
        conditions:
          type: array
          items:
            $ref: '#/components/schemas/TransactionRuleCondition'
        aggregation:
          type: array
          items:
            $ref: '#/components/schemas/TransactionRuleAggregation'
        actions:
          type: array
          items:
            $ref: '#/components/schemas/TransactionRuleAction'
        metadata:
          type: object
          description: Метаданные в свободной форме, сохранённые в правиле.
        severity:
          type: string
          enum:
            - UNKNOWN
            - LOW
            - MEDIUM
            - HIGH
            - CRITICAL
          nullable: true
          description: >-
            Информационный уровень серьёзности, присваиваемый библиотечными
            правилами; недоступен для настройки в пользовательских правилах.
        source:
          type: string
          enum:
            - PRESET
            - CUSTOM
          description: >-
            Правила PRESET берутся из библиотеки (установка/удаление,
            редактирование только режима); правила CUSTOM полностью
            настраиваются вами.
        library_key:
          type: string
          nullable: true
          description: >-
            Постоянный идентификатор библиотеки; null для пользовательских
            правил.
        latest_triggered_at:
          type: string
          format: date-time
          nullable: true
        run_count:
          type: integer
          description: Количество транзакций, подошедших под это правило.
        approved_count:
          type: integer
        reviewed_count:
          type: integer
        declined_count:
          type: integer
        awaiting_user_count:
          type: integer
        approved_pct:
          type: number
        reviewed_pct:
          type: number
        declined_pct:
          type: number
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    TransactionRuleScope:
      type: object
      properties:
        transaction_types:
          type: array
          items:
            type: string
          description: >-
            Ограничить типами транзакций, например finance, kyc, travel_rule,
            user_event. Пустое или отсутствующее значение = без ограничений.
        directions:
          type: array
          items:
            type: string
            enum:
              - INBOUND
              - OUTBOUND
          description: >-
            Ограничить направлениями транзакций (нечувствительно к регистру при
            записи).
        action_types:
          type: array
          items:
            type: string
          description: >-
            Ограничить вашими значениями action_type, например withdrawal,
            deposit.
      description: >-
        К каким транзакциям применяется правило. Принимаются только эти три
        ключа.
    TransactionRuleCondition:
      type: object
      required:
        - field
        - operator
      properties:
        field:
          type: string
          description: >-
            Путь к полю транзакции для вычисления. Основные поля: amount,
            currency, direction, action_type, score, severity, transaction_type,
            payment_details, preferred_currency_amount (по умолчанию
            amount_in_default_currency), default_currency_code, subject_country,
            counterparty_country, subject_vendor_data, counterparty_vendor_data,
            subject_device_fingerprint, counterparty_device_fingerprint,
            subject_browser_family, subject_browser_version, subject_platform,
            subject_accept_language, subject_session_age_ms, subject_ip_country,
            counterparty_ip_country, subject_ip_address,
            counterparty_ip_address, subject_payment_method_type,
            subject_payment_method_country, subject_payment_method_fingerprint,
            subject_payment_method_account_id (и эквиваленты
            counterparty_payment_method_*), travel_rule_status,
            travel_rule_required, travel_rule_obligations_count,
            counterparty_dd_status (ваше решение по контрагенту Travel Rule:
            APPROVED, RESTRICTED или BLOCKED; сущность наследует статус своего
            бренда), counterparty_risk_level (LOW, MEDIUM или HIGH; HIGH, пока
            по вашему собственному скринингу контрагента выставлен флаг),
            counterparty_jurisdiction (страна VASP контрагента),
            counterparty_responsiveness (RESPONSIVE, UNRESPONSIVE или UNKNOWN),
            subject_days_since_previous_transaction, tags, а также
            custom_values.<key> для любого ключа, переданного в
            custom_properties при создании транзакции. Поля с кодами стран
            принимают ISO-2 или ISO-3; обе стороны нормализуются до ISO-3 перед
            сравнением.
        operator:
          type: string
          enum:
            - eq
            - ne
            - gt
            - gte
            - lt
            - lte
            - in
            - not_in
            - contains
            - not_contains
            - contains_any
            - regex
            - fuzzy_match
            - exists
            - is_not_empty
            - is_not_null
            - not_exists
            - is_empty
            - is_null
          description: >-
            Оператор сравнения. in/not_in проверяют принадлежность (значение
            может быть списком или отдельным скалярным значением).
            contains/not_contains представляют собой нечувствительные к регистру
            проверки подстроки для строкового значения. contains_any принимает
            список строк и срабатывает, если любая из них является
            нечувствительной к регистру подстрокой значения поля. regex
            сопоставляет шаблон значения с полем. fuzzy_match сравнивает со
            строковым значением с требуемым порогом `score` (0-100).
            gt/gte/lt/lte никогда не срабатывают, если одна из сторон
            отсутствует. exists/is_not_empty/is_not_null (псевдонимы) и
            not_exists/is_empty/is_null (псевдонимы) являются проверками
            наличия, которые игнорируют `value`.
        value:
          description: >-
            Значение для сравнения. Его формат зависит от оператора и
            value_type; опустите его для операторов проверки наличия. Для всех
            остальных операторов требуется значение, отличное от `null` или
            пустого списка, иначе правило будет отклонено с ошибкой `400`. Для
            `contains_any` требуется список строк, а для `contains`,
            `not_contains` и `regex` требуется одна строка.
        value_type:
          type: string
          enum:
            - list
            - field
            - relative_date
          description: >-
            Необязательная интерпретация значения. `list`: значение является
            UUID списка, и элементы списка становятся значением для сравнения.
            `field`: значение является путём к другому полю, сравниваемое с
            другим полем. `relative_date`: значение является объектом
            относительной даты, например {"direction": "past", "unit": "days",
            "amount": 30}.
        score:
          type: number
          minimum: 0
          maximum: 100
          description: >-
            Обязательно, когда operator имеет значение fuzzy_match: порог
            сходства от 0 до 100.
        group_index:
          type: integer
          description: >-
            Необязательная групповая логика. Если какое-либо условие содержит
            group_index, условия с одинаковым индексом образуют группу, а
            групповая оценка заменяет evaluation_mode.
        group_logic:
          type: string
          enum:
            - AND
            - OR
          default: AND
          description: Как объединяются условия ВНУТРИ группы.
        groups_logic:
          type: string
          enum:
            - AND
            - OR
          default: OR
          description: >-
            Как объединяются результаты групп МЕЖДУ группами. Считывается из
            первого условия.
      description: >-
        Условие считывает только оцениваемую транзакцию: оно никогда не
        фильтрует окно агрегации.
    TransactionRuleAggregation:
      type: object
      required:
        - value
      properties:
        metric:
          type: string
          enum:
            - count
            - sum
            - max
            - min
            - avg
            - distinct_count
          default: count
          description: >-
            Как агрегируются подходящие исторические транзакции. unique_count
            принимается как псевдоним distinct_count.
        field:
          type: string
          default: amount
          description: >-
            Поле, агрегированное с помощью sum/max/min/avg/distinct_count.
            Игнорируется для count.
        operator:
          type: string
          enum:
            - eq
            - ne
            - gt
            - gte
            - lt
            - lte
          default: eq
          description: Сравнение, применяемое к вычисленной метрике.
        value:
          type: number
          description: Порог, с которым сравнивается вычисленная метрика.
        window:
          type: string
          pattern: ^\d+(m|h|d)$
          default: 1d
          description: >-
            Окно ретроспективного анализа, заканчивающееся на txn_date
            транзакции: <N>m (МИНУТЫ, не месяцы), <N>h (часы) или <N>d (дни),
            например 30m, 24h, 7d, 30d.
        filters:
          type: object
          additionalProperties: true
          description: >-
            Ограничивает круг исторических транзакций для агрегации. Ключи
            представляют собой пути к полям из каталога полей условий; значение
            "__current__" разрешается в значение того же поля оцениваемой
            транзакции (например, {"subject_vendor_data": "__current__"}
            ограничивает окно тем же субъектом), а значение в виде списка
            означает принадлежность к множеству. Записи без группируемого
            значения никогда не объединяются в одну группу: если в оцениваемой
            транзакции нет значения для поля "__current__" (нет контрагента, нет
            цифрового отпечатка устройства), агрегация не срабатывает независимо
            от её оператора. Фильтры сравнивают ТОЛЬКО по равенству или
            принадлежности к множеству: фильтров lt/gte нет, поэтому диапазон
            вроде «исторические транзакции менее 10 000» здесь выразить нельзя.
            Задайте диапазон в метрике (метрика max с оператором lt оставляет в
            окне только транзакции ниже порога).
      description: >-
        Проверка скорости операций (velocity check) по историческим транзакциям
        приложения в пределах окна. Каждая запись агрегации должна совпадать для
        срабатывания правила, независимо от evaluation_mode. Агрегация
        ограничивает только окно; оцениваемая транзакция ограничивается областью
        (scope) и условиями, поэтому дублируйте direction, currency или
        transaction_type в обеих частях, когда правило их предусматривает.
    TransactionRuleAction:
      oneOf:
        - $ref: '#/components/schemas/TransactionRuleActionAddScore'
        - $ref: '#/components/schemas/TransactionRuleActionChangeStatus'
        - $ref: '#/components/schemas/TransactionRuleActionAddTags'
        - $ref: '#/components/schemas/TransactionRuleActionAddNote'
        - $ref: '#/components/schemas/TransactionRuleActionAddToList'
        - $ref: '#/components/schemas/TransactionRuleActionOpenCase'
      discriminator:
        propertyName: type
        mapping:
          add_score: '#/components/schemas/TransactionRuleActionAddScore'
          change_status: '#/components/schemas/TransactionRuleActionChangeStatus'
          add_tags: '#/components/schemas/TransactionRuleActionAddTags'
          add_note: '#/components/schemas/TransactionRuleActionAddNote'
          add_to_list: '#/components/schemas/TransactionRuleActionAddToList'
          open_case: '#/components/schemas/TransactionRuleActionOpenCase'
      description: >-
        Одно действие правила. Правило может содержать несколько действий; все
        они применяются одновременно при срабатывании правила. Правила в режиме
        TEST фиксируют, что они бы сделали, не применяя ни одного действия.
    TransactionRuleActionAddScore:
      type: object
      required:
        - type
        - value
      properties:
        type:
          type: string
          enum:
            - add_score
        value:
          type: integer
          description: >-
            Баллы, добавленные к оценке риска транзакции. Могут быть
            отрицательными.
      description: >-
        Добавьте баллы к совокупной оценке риска транзакции; итоговое значение
        определяет статус с учётом заданных приложением порогов проверки и
        отклонения.
    TransactionRuleActionChangeStatus:
      type: object
      required:
        - type
        - value
      properties:
        type:
          type: string
          enum:
            - change_status
        value:
          type: string
          enum:
            - APPROVED
            - IN_REVIEW
            - DECLINED
            - AWAITING_USER
          description: >-
            Статус, который необходимо установить немедленно, независимо от
            оценки. Псевдоним ключа: status.
        workflow_id:
          type: string
          format: uuid
          description: >-
            ОБЯЗАТЕЛЬНО, если значение равно AWAITING_USER: сценарий
            верификации, который субъект должен пройти. Ключ псевдонима:
            remediation_workflow_id. Didit создаёт размещённую сессию для
            устранения проблемы для субъекта при срабатывании правила.
      description: >-
        Напрямую устанавливает статус транзакции. DECLINED всегда имеет
        приоритет среди сработавших правил.
    TransactionRuleActionAddTags:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          enum:
            - add_tags
        tag_uuid:
          type: string
          format: uuid
          description: Существующий тег приложения, который нужно прикрепить.
        tag_name:
          type: string
          description: >-
            Имя тега для прикрепления; создается при первом использовании
            (сохраняется в верхнем регистре). Укажите tag_uuid или tag_name.
        tag_color:
          type: string
          description: >-
            Шестнадцатеричный цвет (hex), используемый, когда tag_name создаёт
            новый тег, например #007AFE.
      description: Прикрепить тег приложения к совпавшей транзакции.
    TransactionRuleActionAddNote:
      type: object
      required:
        - type
        - note
      properties:
        type:
          type: string
          enum:
            - add_note
        note:
          type: string
          description: >-
            Текст заметки, прикреплённой к транзакции (автор: Rule Engine).
            Ключ-алиас: значение.
      description: Прикрепить автоматическую заметку аналитика к совпавшей транзакции.
    TransactionRuleActionAddToList:
      type: object
      required:
        - type
        - list_id
      properties:
        type:
          type: string
          enum:
            - add_to_list
        list_id:
          type: string
          format: uuid
          description: Список, в который нужно добавить vendor_data субъекта.
      description: >-
        Добавьте vendor_data субъекта в список блокировки, список разрешений или
        пользовательский список.
    TransactionRuleActionOpenCase:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          enum:
            - open_case
        blueprint:
          type: string
          format: uuid
          description: >-
            UUID шаблона кейса; по умолчанию используется шаблон по умолчанию
            для приложения.
        grouping:
          type: string
          enum:
            - by_applicant
            - by_rule_and_applicant
          description: >-
            Объединяются ли повторные совпадения в один кейс на заявителя или в
            один кейс на комбинацию правила и заявителя.
        attach_matched_transaction:
          type: boolean
          description: Прикрепить совпавшую транзакцию к кейсу.
      description: >-
        Открыть кейс расследования (или добавить в существующий). Применяется
        только первое действие open_case в правиле.
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        API-ключ вашего приложения из раздела «Разработчикам» -> «API-ключи» в
        Business Console. Основной ключ имеет полный доступ. Именованный ключ
        может иметь ограниченную область действия: без доступа, чтение или
        запись для каждого ресурса, ограничение определенными сценариями или
        одобренными сессиями, списком IP-адресов и сроком действия. 401
        означает, что ключ неверен, отозван или его срок действия истек; 403
        означает, что ключ не был передан, у ключа нет доступа к этому ресурсу
        или действию, либо запрос поступил с адреса вне его списка IP-адресов;
        404 на маршруте сессии означает, что сессия не входит в сценарии или
        статусы ключа. Ключ без доступа к медиа получает URL изображений, видео
        и PDF как null, а ключ без прав на запись сессий получает ссылки на
        сессии и токены как null. См. https://docs.didit.me/console/api-keys.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.