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

# Create a new business-logic rule for the authenticated organization

> Creates a business-logic rule in the caller's organization. Validates all scope entity IDs against the organization before persisting. When no `ruleGroupIds` are provided, the rule is automatically attached to the organization's default ruleset. Requires `intelligenceLayer.configure` permission.



## OpenAPI

````yaml /openapi.json post /api/business-logic-rules
openapi: 3.0.3
info:
  contact:
    email: dev@solya.io
    name: Solya Team
  description: >-

    # Solya API


    Solya is a fashion retail inventory management platform for buyers and
    merchandisers.

    This API exposes all capabilities needed to manage the inventory lifecycle:
    catalog

    browsing, risk detection, plan creation (Restock / Markdown / Rebalance),
    analytics

    queries, and data-platform operations.


    ## Authentication


    Three authentication schemes are supported:


    | Scheme | Header | Use case |

    |---|---|---|

    | **BearerAuth** | `Authorization: Bearer <nextauth-token>` | Human users
    via the Solya web app (NextAuth session) |

    | **InternalBearerAuth** | `Authorization: Bearer <static-token>` | Internal
    jobs and cron tasks (static token per service) |

    | **ServiceAccountToken** | `Authorization: Bearer solya_sa_*` | LLM agents
    and programmatic clients (opaque token created via Settings) |


    All endpoints except `GET /api/health` require one of the above.

    See [Agent authentication guide](/docs/api/AGENT_AUTH.md) for the Service
    Account token flow.


    ## Response format


    Every endpoint returns an `ActionResponse<T>` envelope:


    **Success:**

    ```json

    { "success": true, "data": { ... } }

    ```


    **Error:**

    ```json

    { "success": false, "errorCode": "PLAN_NOT_FOUND", "error": "Human-readable
    message" }

    ```


    The `errorCode` is a stable machine-readable string (see common error codes
    below).

    The `error` field is for human display only and may change between versions.


    ## Pagination


    List endpoints accept `page` (1-indexed, default 1) and `pageSize` (default
    20, max 100).

    Responses include a `total` field with the total number of matching records.


    ```

    GET /api/shops?page=2&pageSize=50

    → { "success": true, "data": { "data": [...], "total": 120, "page": 2,
    "pageSize": 50 } }

    ```


    ## Common error codes


    | HTTP status | errorCode | Meaning |

    |---|---|---|

    | 401 | `UNAUTHORIZED` | Token missing, expired, or invalid |

    | 403 | `FORBIDDEN` | Token valid but lacks the required permission or scope
    |

    | 404 | `NOT_FOUND` | Requested resource does not exist |

    | 409 | `BUSINESS_RULE_VIOLATION` | Business rule blocked the operation (see
    response details) |

    | 422 | `VALIDATION_ERROR` | Input failed Zod schema validation |

    | 429 | `RATE_LIMIT_EXCEEDED` | Rate limit hit (100 req/min per token) |

    | 500 | `INTERNAL_ERROR` | Unexpected server error |


    ## Rate limiting


    Default limit: **100 requests per minute** per authentication token.

    When the limit is exceeded the API returns HTTP 429 with `errorCode:
    "RATE_LIMIT_EXCEEDED"`.

    Agents should implement exponential back-off and respect the `Retry-After`
    header when present.


    ## Further reading


    See the [Agent guide](/docs/api/AGENT_GUIDE.md) for end-to-end workflows,
    call-chaining

    patterns, and anti-patterns to avoid.
        
  license:
    name: Proprietary
    url: https://solya.app/terms
  title: Solya API
  version: 1.0.0
  x-ai-context: >-
    Solya is a fashion retail inventory management platform for retailers.

    Core concepts:

    - **Organization** (tenant): every endpoint is scoped by organizationId
    extracted from the token.

    - **Shop**: a physical point of sale belonging to the organization.

    - **ProductVariant**: a SKU — a product variant with size and color.

    - **Plan**: a Restock / Markdown / Rebalance grouping PlanItems to
    orchestrate inventory decisions.


    Typical agent workflow:

    1. List the organization's shops — GET /api/shops

    2. List variants at risk (stockout, overstock, slow-mover) — GET
    /api/inventory/risks

    3. Create a plan — POST /api/restock-plans, /api/markdown-plans, or
    /api/rebalance-plans

    4. Add items to the plan — POST /api/restock-plans/{planId}/items (or
    equivalent for other plan types)

    5. Validate / submit the plan via the corresponding action endpoint


    Auth: use a Service Account token (see /docs/api/AGENT_AUTH.md).

    The token is created by an org admin via Settings and has the format
    solya_sa_<43 base64url chars>.


    All responses follow the ActionResponse envelope:

    - Success: { success: true, data: T }

    - Error:   { success: false, errorCode: string, error: string }


    Use the errorCode field to drive retry logic or surface user-facing
    messages.
servers:
  - description: Current environment
    url: https://app.solya.app
security:
  - BearerAuth: []
tags:
  - description: >-
      Health and liveness endpoints. Use GET /api/health to verify the service
      is reachable before starting a workflow. No authentication required.
    name: System
  - description: >-
      Physical points of sale belonging to the organization. Supports listing,
      creation, update, and deactivation. Shops are referenced by all Plan types
      (Restock, Markdown, Rebalance) and by every inventory analytics endpoint.
    name: Shops
  - description: >-
      Product brands configured for the organization. Brands are used to filter
      catalog queries and analytics. Supports CRUD operations.
    name: Brands
  - description: >-
      The product catalog: style-level entities grouping one or more
      ProductVariants. Supports listing with rich filter options (brand, family,
      gender, season) and individual retrieval.
    name: Products
  - description: >-
      SKU-level product entities (a Product with a specific size and color).
      Variants are the atomic unit referenced by PlanItems, inventory risk
      alerts, and analytics queries.
    name: Variants
  - description: >-
      Curated product groupings used for seasonal assortment management. A
      Collection groups Variants and can be referenced when creating or
      filtering Plans.
    name: Collections
  - description: >-
      Current on-hand stock records per Variant per Shop. Used to understand the
      live inventory position before creating a restock or rebalance plan.
    name: Inventory Items
  - description: >-
      AI-detected inventory risk signals: stockout risk, overstock, slow-movers,
      and displaced stock. The primary input for agents building
      recommendation-driven plans. Supports filtering by shop, brand, risk type,
      and severity.
    name: Inventory Risks
  - description: >-
      AI-generated restock quantity recommendations per Variant per Shop.
      Consumed by agents to pre-populate Restock plan items. Based on sales
      velocity, stock coverage, and lead time.
    name: Recommendations - Restock
  - description: >-
      AI-generated markdown discount recommendations for slow-moving or
      overstock Variants. Consumed by agents to pre-populate Markdown plan
      items. Includes recommended discount rate and expected clearance timeline.
    name: Recommendations - Markdown
  - description: >-
      AI-generated stock transfer recommendations between shops to balance
      supply with demand. Consumed by agents to pre-populate Rebalance plan
      items.
    name: Recommendations - Rebalance
  - description: >-
      Historical sales transaction lines at the Variant + Shop + date level.
      Used by analytics and by the AI recommendation engine. Supports date-range
      and multi-dimensional filtering.
    name: Sales Lines
  - description: >-
      Purchase order lines tracking inbound stock from suppliers. Combined with
      stock and sales data to compute forward coverage and restock needs.
    name: Order Lines
  - description: >-
      Inventory movement records (transfers, returns, adjustments). Used to
      reconcile the stock ledger and audit stock changes between shops.
    name: Movement Lines
  - description: >-
      Running stock balance log per Variant per Shop. Provides a point-in-time
      view of stock levels and is the source of truth for coverage computations.
    name: Stock Ledger
  - description: >-
      Rebalance plans orchestrate stock transfers between shops. Supports
      creating plans, adding Variant items with proposed transfer quantities,
      reviewing, and submitting. Business rules are evaluated on item addition.
    name: Plans - Rebalance
  - description: >-
      Restock plans (order plans) orchestrate purchase orders to suppliers.
      Supports creating sessions, adding Variant items with proposed order
      quantities, reviewing totals, and submitting. Integrates with the order
      plan workflow.
    name: Plans - Restock
  - description: >-
      Autocomplete and typeahead search endpoints for catalog dimensions:
      products, brands, shops, sizes, families, genders, and more. Designed for
      fast UI search (low latency, small result sets). Use catalog list
      endpoints for full paginated access.
    name: Search
  - description: >-
      Manage file-based data ingestion: upload CSV/XLSX files, poll ingestion
      status, list historical ingestion runs, and trigger batch reprocessing.
      Used by the data team to import POS data and catalog updates.
    name: Data Platform - File Ingestions
  - description: >-
      Organization-level configuration for the data platform: data source
      connections, POS integration settings, and ingestion schedules. Requires
      elevated permissions.
    name: Data Platform - Settings
  - description: >-
      Configuration of automated inventory alerts: threshold-based rules that
      monitor stock levels, sales velocity, and coverage gaps. Supports CRUD for
      alert definitions; alert evaluation runs are triggered by the data
      platform scheduler.
    name: Data Platform - Alerts
  - description: >-
      Endpoints designed for LLM agents and programmatic clients. These
      endpoints expose agent-optimized response shapes. Authenticate with a
      Service Account token (format: solya_sa_*) created via Settings → API
      Tokens.
    name: Agent
externalDocs:
  description: >-
    Complete guide for LLM agents and programmatic clients: authentication,
    pagination patterns, ActionResponse interpretation, call chaining, business
    rule error handling.
  url: /docs/api/AGENT_GUIDE.md
paths:
  /api/business-logic-rules:
    post:
      tags:
        - Business Logic Rules
      summary: Create a new business-logic rule for the authenticated organization
      description: >-
        Creates a business-logic rule in the caller's organization. Validates
        all scope entity IDs against the organization before persisting. When no
        `ruleGroupIds` are provided, the rule is automatically attached to the
        organization's default ruleset. Requires `intelligenceLayer.configure`
        permission.
      operationId: createBusinessLogicRule
      requestBody:
        content:
          application/json:
            examples:
              sample:
                summary: Create a WARN rule for ordering capacity
                value:
                  actionFamily: RESTOCK_PLAN
                  category: ORDERING
                  conditions:
                    operator: AND
                    rules:
                      - conditionOperator: LOWER_THAN
                        metricId: order_total_value
                        periodFilter: null
                        thresholdValue: 500
                        type: METRIC
                  description: Warn when a restock item total is below the supplier minimum
                  enforcementMode: WARN
                  evaluationPoints:
                    - PRE_PLAN_ITEM_ADD
                  logAllEvaluations: false
                  name: Minimum order value
                  paradigm: VALIDATION
                  priority: 1
                  scope:
                    checkLevel: PLAN_ITEM
                  validationHooks:
                    - RESTOCK_PRE_ADD_ITEM
            schema:
              properties:
                actionFamily:
                  enum:
                    - RESTOCK_PLAN
                    - REBALANCE_PLAN
                    - MARKDOWN_PLAN
                    - PRE_SEASON_PLAN
                    - RECOMMENDATION
                    - WORKFLOW
                    - SUPPLIER_RETURN_PLAN
                    - SUPPLIER_EXCHANGE_PLAN
                  nullable: true
                  type: string
                category:
                  enum:
                    - CAPACITY
                    - ASSORTMENT
                    - ORDERING
                    - TRANSFER
                    - PRICING
                    - DISTRIBUTION
                    - COMPLIANCE
                  type: string
                conditions:
                  anyOf:
                    - properties:
                        operator:
                          enum:
                            - AND
                            - OR
                          type: string
                        rules:
                          items:
                            oneOf:
                              - properties:
                                  conditionOperator:
                                    enum:
                                      - LOWER_THAN
                                      - LOWER_OR_EQUAL
                                      - GREATER_THAN
                                      - GREATER_OR_EQUAL
                                      - EQUAL
                                      - NOT_EQUAL
                                    type: string
                                  metricId:
                                    minLength: 1
                                    type: string
                                  periodFilter:
                                    nullable: true
                                    properties:
                                      custom:
                                        properties:
                                          endDate:
                                            type: string
                                          startDate:
                                            type: string
                                        required:
                                          - startDate
                                          - endDate
                                        type: object
                                      type:
                                        enum:
                                          - last7Days
                                          - last30Days
                                          - last90Days
                                          - last6Months
                                          - last12Months
                                          - last2Years
                                          - last3Years
                                          - last5Years
                                          - last10Years
                                          - thisMonth
                                          - thisQuarter
                                          - thisYear
                                          - yearToDate
                                          - lastMonth
                                          - lastQuarter
                                          - lastYear
                                          - 2MonthsAgo
                                          - 3MonthsAgo
                                          - 6MonthsAgo
                                          - 1YearAgo
                                          - 2YearsAgo
                                          - allTime
                                          - CUSTOM
                                        type: string
                                    required:
                                      - type
                                    type: object
                                  thresholdValue:
                                    type: number
                                  type:
                                    enum:
                                      - METRIC
                                    type: string
                                required:
                                  - type
                                  - metricId
                                  - conditionOperator
                                  - thresholdValue
                                type: object
                              - properties:
                                  columnId:
                                    minLength: 1
                                    type: string
                                  columnOperator:
                                    enum:
                                      - EQUALS
                                      - NOT_EQUALS
                                      - CONTAINS
                                      - NOT_CONTAINS
                                      - STARTS_WITH
                                      - ENDS_WITH
                                      - MATCHES_REGEX
                                      - IS_EMPTY
                                      - IS_NOT_EMPTY
                                      - BEFORE
                                      - AFTER
                                      - BETWEEN
                                      - ON_DATE
                                      - IS_TRUE
                                      - IS_FALSE
                                      - LOWER_THAN
                                      - LOWER_OR_EQUAL
                                      - GREATER_THAN
                                      - GREATER_OR_EQUAL
                                      - EQUAL
                                      - NOT_EQUAL
                                    type: string
                                  secondaryValue:
                                    anyOf:
                                      - type: string
                                      - type: number
                                  type:
                                    enum:
                                      - COLUMN
                                    type: string
                                  value:
                                    anyOf:
                                      - type: string
                                      - type: number
                                      - type: boolean
                                required:
                                  - type
                                  - columnId
                                  - columnOperator
                                  - value
                                type: object
                              - properties:
                                  conditionOperator:
                                    enum:
                                      - LOWER_THAN
                                      - LOWER_OR_EQUAL
                                      - GREATER_THAN
                                      - GREATER_OR_EQUAL
                                      - EQUAL
                                      - NOT_EQUAL
                                    type: string
                                  contextParams:
                                    additionalProperties:
                                      type: string
                                    type: object
                                  contextType:
                                    enum:
                                      - PLAN_TOTAL_VALUE
                                      - PLAN_TOTAL_QUANTITY
                                      - PLAN_ITEM_COUNT
                                      - PLAN_BRAND_TOTAL_VALUE
                                      - PLAN_SHOP_ITEM_COUNT
                                      - VARIANT_PLAN_QUANTITY
                                      - CURRENT_STOCK
                                      - STOCK_AFTER_ADD
                                      - SELL_THROUGH_RATE
                                      - DAYS_OF_STOCK
                                      - GROSS_MARGIN_PCT
                                      - SUPPLIER_BRAND_MISMATCH_COUNT
                                      - EXCHANGE_RETURN_VALUE
                                      - EXCHANGE_RECEIVE_VALUE
                                      - EXCHANGE_TOLERANCE_DEVIATION
                                      - MARGIN_AFTER_DISCOUNT_PCT
                                      - RECENT_MARKDOWN_COUNT_FOR_VARIANT
                                      - SOURCE_SHOP_STOCK_AFTER_REMOVE
                                      - REBALANCE_TRANSFER_COST
                                      - OVERLAPPING_PLAN_QTY_FOR_VARIANT
                                      - PLAN_BRAND_VALUE_RATIO
                                      - SUPPLIER_FIRST_ORDER_FOR_BRAND
                                      - ORG_OPEN_PLANS_TOTAL_VALUE
                                      - RECENT_RETURN_PLAN_QTY_FOR_SUPPLIER
                                      - SUPPLIER_BRAND_MISMATCH_COUNT_RETURN
                                      - SUPPLIER_BRAND_MISMATCH_COUNT_RECEIVE
                                      - SUPPLIER_IS_BLACKLISTED
                                      - BRAND_IS_RESTRICTED
                                      - RETURN_WINDOW_EXCEEDED
                                      - RESTOCKING_FEE_PCT
                                      - RETURN_REASON_CODE_MISSING
                                      - CONDITION_ASSESSMENT_MISSING
                                      - OTB_REMAINING_FOR_SCOPE
                                      - OTB_CONSUMED_PCT
                                      - OTB_PROJECTED_OVERSPEND
                                      - SIZE_CURVE_PROJECTED_DEVIATION
                                      - MARKDOWN_IN_ACTIVE_WINDOW
                                      - SUPPLIER_VARIANT_BELOW_MOQ
                                      - SUPPLIER_VARIANT_PACK_MULTIPLE_GAP
                                      - SUPPLIER_VARIANT_ABOVE_MAX
                                      - SUPPLIER_ORDER_TOTAL_VALUE
                                      - SUPPLIER_ORDER_TOTAL_QUANTITY
                                      - SUPPLIER_ORDER_BELOW_MIN_VALUE
                                      - SUPPLIER_ORDER_BELOW_MIN_QUANTITY
                                      - PRICE_BELOW_MAP
                                    type: string
                                  thresholdValue:
                                    type: number
                                  type:
                                    enum:
                                      - CONTEXT
                                    type: string
                                required:
                                  - type
                                  - contextType
                                  - contextParams
                                  - conditionOperator
                                  - thresholdValue
                                type: object
                          minItems: 1
                          type: array
                        templateId:
                          type: string
                        version:
                          enum:
                            - 2
                          type: number
                      required:
                        - version
                        - operator
                        - rules
                      type: object
                    - properties:
                        operator:
                          enum:
                            - AND
                            - OR
                          type: string
                        rules:
                          items:
                            oneOf:
                              - properties:
                                  conditionOperator:
                                    enum:
                                      - LOWER_THAN
                                      - LOWER_OR_EQUAL
                                      - GREATER_THAN
                                      - GREATER_OR_EQUAL
                                      - EQUAL
                                      - NOT_EQUAL
                                    type: string
                                  metricId:
                                    minLength: 1
                                    type: string
                                  periodFilter:
                                    nullable: true
                                    properties:
                                      custom:
                                        properties:
                                          endDate:
                                            type: string
                                          startDate:
                                            type: string
                                        required:
                                          - startDate
                                          - endDate
                                        type: object
                                      type:
                                        enum:
                                          - last7Days
                                          - last30Days
                                          - last90Days
                                          - last6Months
                                          - last12Months
                                          - last2Years
                                          - last3Years
                                          - last5Years
                                          - last10Years
                                          - thisMonth
                                          - thisQuarter
                                          - thisYear
                                          - yearToDate
                                          - lastMonth
                                          - lastQuarter
                                          - lastYear
                                          - 2MonthsAgo
                                          - 3MonthsAgo
                                          - 6MonthsAgo
                                          - 1YearAgo
                                          - 2YearsAgo
                                          - allTime
                                          - CUSTOM
                                        type: string
                                    required:
                                      - type
                                    type: object
                                  thresholdValue:
                                    type: number
                                  type:
                                    enum:
                                      - METRIC
                                    type: string
                                required:
                                  - type
                                  - metricId
                                  - conditionOperator
                                  - thresholdValue
                                type: object
                              - properties:
                                  columnId:
                                    minLength: 1
                                    type: string
                                  columnOperator:
                                    enum:
                                      - EQUALS
                                      - NOT_EQUALS
                                      - CONTAINS
                                      - NOT_CONTAINS
                                      - STARTS_WITH
                                      - ENDS_WITH
                                      - MATCHES_REGEX
                                      - IS_EMPTY
                                      - IS_NOT_EMPTY
                                      - BEFORE
                                      - AFTER
                                      - BETWEEN
                                      - ON_DATE
                                      - IS_TRUE
                                      - IS_FALSE
                                      - LOWER_THAN
                                      - LOWER_OR_EQUAL
                                      - GREATER_THAN
                                      - GREATER_OR_EQUAL
                                      - EQUAL
                                      - NOT_EQUAL
                                    type: string
                                  secondaryValue:
                                    anyOf:
                                      - type: string
                                      - type: number
                                  type:
                                    enum:
                                      - COLUMN
                                    type: string
                                  value:
                                    anyOf:
                                      - type: string
                                      - type: number
                                      - type: boolean
                                required:
                                  - type
                                  - columnId
                                  - columnOperator
                                  - value
                                type: object
                              - properties:
                                  conditionOperator:
                                    enum:
                                      - LOWER_THAN
                                      - LOWER_OR_EQUAL
                                      - GREATER_THAN
                                      - GREATER_OR_EQUAL
                                      - EQUAL
                                      - NOT_EQUAL
                                    type: string
                                  contextParams:
                                    additionalProperties:
                                      type: string
                                    type: object
                                  contextType:
                                    enum:
                                      - PLAN_TOTAL_VALUE
                                      - PLAN_TOTAL_QUANTITY
                                      - PLAN_ITEM_COUNT
                                      - PLAN_BRAND_TOTAL_VALUE
                                      - PLAN_SHOP_ITEM_COUNT
                                      - VARIANT_PLAN_QUANTITY
                                      - CURRENT_STOCK
                                      - STOCK_AFTER_ADD
                                      - SELL_THROUGH_RATE
                                      - DAYS_OF_STOCK
                                      - GROSS_MARGIN_PCT
                                      - SUPPLIER_BRAND_MISMATCH_COUNT
                                      - EXCHANGE_RETURN_VALUE
                                      - EXCHANGE_RECEIVE_VALUE
                                      - EXCHANGE_TOLERANCE_DEVIATION
                                      - MARGIN_AFTER_DISCOUNT_PCT
                                      - RECENT_MARKDOWN_COUNT_FOR_VARIANT
                                      - SOURCE_SHOP_STOCK_AFTER_REMOVE
                                      - REBALANCE_TRANSFER_COST
                                      - OVERLAPPING_PLAN_QTY_FOR_VARIANT
                                      - PLAN_BRAND_VALUE_RATIO
                                      - SUPPLIER_FIRST_ORDER_FOR_BRAND
                                      - ORG_OPEN_PLANS_TOTAL_VALUE
                                      - RECENT_RETURN_PLAN_QTY_FOR_SUPPLIER
                                      - SUPPLIER_BRAND_MISMATCH_COUNT_RETURN
                                      - SUPPLIER_BRAND_MISMATCH_COUNT_RECEIVE
                                      - SUPPLIER_IS_BLACKLISTED
                                      - BRAND_IS_RESTRICTED
                                      - RETURN_WINDOW_EXCEEDED
                                      - RESTOCKING_FEE_PCT
                                      - RETURN_REASON_CODE_MISSING
                                      - CONDITION_ASSESSMENT_MISSING
                                      - OTB_REMAINING_FOR_SCOPE
                                      - OTB_CONSUMED_PCT
                                      - OTB_PROJECTED_OVERSPEND
                                      - SIZE_CURVE_PROJECTED_DEVIATION
                                      - MARKDOWN_IN_ACTIVE_WINDOW
                                      - SUPPLIER_VARIANT_BELOW_MOQ
                                      - SUPPLIER_VARIANT_PACK_MULTIPLE_GAP
                                      - SUPPLIER_VARIANT_ABOVE_MAX
                                      - SUPPLIER_ORDER_TOTAL_VALUE
                                      - SUPPLIER_ORDER_TOTAL_QUANTITY
                                      - SUPPLIER_ORDER_BELOW_MIN_VALUE
                                      - SUPPLIER_ORDER_BELOW_MIN_QUANTITY
                                      - PRICE_BELOW_MAP
                                    type: string
                                  thresholdValue:
                                    type: number
                                  type:
                                    enum:
                                      - CONTEXT
                                    type: string
                                required:
                                  - type
                                  - contextType
                                  - contextParams
                                  - conditionOperator
                                  - thresholdValue
                                type: object
                          minItems: 1
                          type: array
                      required:
                        - operator
                        - rules
                      type: object
                description:
                  nullable: true
                  type: string
                enforcementMode:
                  default: WARN
                  enum:
                    - BLOCK
                    - WARN
                    - LOG
                  type: string
                evaluationPoints:
                  default: []
                  items:
                    enum:
                      - PRE_PLAN_ITEM_ADD
                      - PRE_PLAN_VALIDATE
                      - RECOMMENDATION_GENERATION
                      - WORKFLOW_EXECUTION
                      - MANUAL_CHECK
                    type: string
                  type: array
                logAllEvaluations:
                  default: true
                  type: boolean
                name:
                  maxLength: 255
                  minLength: 1
                  type: string
                phase:
                  enum:
                    - SCORING
                    - SIZING
                    - SOURCING
                    - APPROVAL
                  nullable: true
                  type: string
                priority:
                  default: 0
                  maximum: 9007199254740991
                  minimum: 0
                  type: integer
                ruleGroupIds:
                  items:
                    minLength: 1
                    type: string
                  type: array
                scope:
                  properties:
                    brandIds:
                      items:
                        type: string
                      type: array
                    checkLevel:
                      enum:
                        - SHOP
                        - BRAND
                        - PRODUCT
                        - VARIANT
                        - INVENTORY_ITEM
                        - PLAN
                        - PLAN_ITEM
                      type: string
                    collections:
                      items:
                        type: string
                      type: array
                    familyIds:
                      items:
                        type: string
                      type: array
                    productIds:
                      items:
                        type: string
                      type: array
                    shopIds:
                      items:
                        type: string
                      type: array
                    supplierIds:
                      items:
                        type: string
                      type: array
                    tagConditions:
                      properties:
                        operator:
                          enum:
                            - AND
                            - OR
                          type: string
                        tagIds:
                          items:
                            minLength: 1
                            type: string
                          minItems: 1
                          type: array
                      required:
                        - operator
                        - tagIds
                      type: object
                    taxonomies:
                      items:
                        properties:
                          type:
                            minLength: 1
                            type: string
                          values:
                            items:
                              minLength: 1
                              type: string
                            minItems: 1
                            type: array
                        required:
                          - type
                          - values
                        type: object
                      type: array
                    variantIds:
                      items:
                        type: string
                      type: array
                  required:
                    - checkLevel
                  type: object
                sourceTemplateId:
                  maxLength: 100
                  nullable: true
                  type: string
                validationHooks:
                  default: []
                  items:
                    enum:
                      - RESTOCK_PRE_ADD_ITEM
                      - RESTOCK_PRE_VALIDATE_ITEM
                      - RESTOCK_PRE_CHANGE_STATUS
                      - REBALANCE_PRE_ADD_ITEM
                      - REBALANCE_PRE_VALIDATE_ITEM
                      - REBALANCE_PRE_CHANGE_STATUS
                      - MARKDOWN_PRE_ADD_ITEM
                      - MARKDOWN_PRE_VALIDATE_ITEM
                      - PRE_SEASON_PRE_ADD_ITEM
                      - PRE_SEASON_PRE_VALIDATE_ITEM
                      - PRE_SEASON_PRE_CHANGE_STATUS
                      - RECOMMENDATION_PRE_GENERATE
                      - MANUAL_CHECK
                      - SUPPLIER_RETURN_PRE_ADD_ITEM
                      - SUPPLIER_RETURN_PRE_CHANGE_STATUS
                      - SUPPLIER_EXCHANGE_PRE_ADD_ITEM
                      - SUPPLIER_EXCHANGE_PRE_CHANGE_STATUS
                    type: string
                  type: array
                violationMessage:
                  nullable: true
                  properties:
                    template:
                      minLength: 1
                      type: string
                  required:
                    - template
                  type: object
              required:
                - name
                - category
                - conditions
                - scope
              type: object
        required: true
      responses:
        '200':
          content:
            application/json:
              examples:
                sample:
                  summary: Created rule
                  value:
                    actionFamily: RESTOCK_PLAN
                    category: ORDERING
                    conditions:
                      operator: AND
                      rules:
                        - conditionOperator: LOWER_THAN
                          metricId: order_total_value
                          periodFilter: null
                          thresholdValue: 500
                          type: METRIC
                    createdAt: '2026-06-04T10:00:00.000Z'
                    description: >-
                      Warn when a restock item total is below the supplier
                      minimum
                    enforcementMode: WARN
                    evaluationPoints:
                      - PRE_PLAN_ITEM_ADD
                    id: rule-uuid-new-1
                    isActive: true
                    logAllEvaluations: false
                    name: Minimum order value
                    paradigm: VALIDATION
                    phase: null
                    priority: 1
                    ruleGroupIds:
                      - ruleset-uuid-default
                    scope:
                      checkLevel: PLAN_ITEM
                    sourceTemplateId: null
                    updatedAt: null
                    validationHooks:
                      - RESTOCK_PRE_ADD_ITEM
                    violationMessage: null
              schema:
                properties:
                  data:
                    properties:
                      actionFamily:
                        description: >-
                          Action family this rule applies to (e.g. RESTOCK_PLAN,
                          MARKDOWN_PLAN), or null if transversal
                        nullable: true
                        type: string
                      category:
                        description: >-
                          Business domain category of the rule. One of: CAPACITY
                          (quantity caps, coverage limits), ASSORTMENT
                          (range/selection rules), ORDERING (MOQ, order-value,
                          pack-multiple), TRANSFER (rebalance conditions),
                          PRICING (margin/discount guards), DISTRIBUTION
                          (allocation rules), COMPLIANCE (regulatory or policy
                          constraints).
                        enum:
                          - CAPACITY
                          - ASSORTMENT
                          - ORDERING
                          - TRANSFER
                          - PRICING
                          - DISTRIBUTION
                          - COMPLIANCE
                        type: string
                      conditions:
                        description: >-
                          Structured condition tree evaluated against the
                          EvaluationContext
                      createdAt:
                        description: ISO 8601 timestamp when the rule was created
                        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))$
                        type: string
                      description:
                        description: Optional long description of the rule
                        nullable: true
                        type: string
                      enforcementMode:
                        description: >-
                          What happens when this rule fires. BLOCK — aborts the
                          mutation and returns an error to the caller; the plan
                          item is NOT persisted. WARN — the mutation proceeds
                          and the warning is surfaced to the caller (e.g. shown
                          in the UI but not blocking). LOG — the violation is
                          silently recorded in the evaluation history with no
                          user-visible signal; the mutation proceeds normally.
                        enum:
                          - BLOCK
                          - WARN
                          - LOG
                        type: string
                      evaluationPoints:
                        description: List of evaluation points where this rule is triggered
                        items:
                          type: string
                        type: array
                      id:
                        description: Unique identifier of the rule (UUID)
                        type: string
                      isActive:
                        description: Whether the rule is currently active
                        type: boolean
                      logAllEvaluations:
                        description: >-
                          When true, every evaluation (pass or fail) is written
                          to the evaluation history
                        type: boolean
                      name:
                        description: Human-readable name of the rule
                        type: string
                      paradigm:
                        description: >-
                          Discriminator for how the rule is evaluated.
                          VALIDATION rules are run by the app-side hook pipeline
                          and can BLOCK or WARN on plan mutations.
                          DECISION_SHAPING rules are skipped by the hook
                          pipeline and delegated exclusively to the Databricks
                          decision layer for recommendation vector shaping. All
                          rules default to VALIDATION.
                        enum:
                          - VALIDATION
                          - DECISION_SHAPING
                        type: string
                      phase:
                        description: >-
                          Business phase this rule applies to (e.g.
                          PRE_DECISION), or null if any phase
                        nullable: true
                        type: string
                      priority:
                        description: Evaluation priority — lower numbers run first
                        type: number
                      ruleGroupIds:
                        description: IDs of the rule groups this rule belongs to
                        items:
                          type: string
                        type: array
                      scope:
                        description: >-
                          Scope restrictions (shopIds, brandIds, supplierIds,
                          etc.) — empty means transversal
                      sourceTemplateId:
                        description: >-
                          ID of the rule template this rule was created from, or
                          null if custom
                        nullable: true
                        type: string
                      updatedAt:
                        description: >-
                          ISO 8601 timestamp of the last update, or null if
                          never updated
                        format: date-time
                        nullable: true
                        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))$
                        type: string
                      validationHooks:
                        description: List of validation hooks associated with this rule
                        items:
                          type: string
                        type: array
                      violationMessage:
                        description: >-
                          Custom violation message shown when the rule fires, or
                          null for the default
                        nullable: true
                    required:
                      - id
                      - name
                      - description
                      - category
                      - actionFamily
                      - paradigm
                      - ruleGroupIds
                      - conditions
                      - scope
                      - enforcementMode
                      - evaluationPoints
                      - validationHooks
                      - violationMessage
                      - priority
                      - logAllEvaluations
                      - isActive
                      - sourceTemplateId
                      - phase
                      - createdAt
                      - updatedAt
                    type: object
                  success:
                    enum:
                      - true
                    type: boolean
                required:
                  - success
                  - data
                type: object
          description: Successful response
        '400':
          description: Validation error
        '401':
          description: Unauthorized
        '500':
          description: Internal server error
      security:
        - BearerAuth: []
components:
  securitySchemes:
    BearerAuth:
      bearerFormat: JWT
      description: >-
        User session token issued by NextAuth. For human users accessing Solya
        via the web application.
      scheme: bearer
      type: http

````