openapi: 3.1.0
info:
  title: BloomCore API - Flower Subscriptions
  version: 1.0.0
  description: |
    API v1 для управления клиентскими подписками на цветы в tenant/store контексте.
    В публичном API все поля `id` и `*_id` являются UUID-строками; внутренние
    bigint ID из БД не принимаются и не возвращаются. Использование API может
    необратимо изменить заказы, подписки, оплаты, уведомления и связанные данные,
    поэтому интеграции должны использовать минимальные scopes, allowed IPs и
    `Idempotency-Key` для изменяющих запросов.
    `subscriptionId` всегда резолвится только в магазине текущего поддомена.
    `manager_id` принимается только для активного сотрудника tenant с активным
    доступом к текущему магазину, а `customer_id` остается tenant-wide.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина или tenant-контекста.
security:
  - bearerAuth: []
tags:
  - name: FlowerSubscriptions
    description: Клиентские подписки на цветы.
paths:
  /flower-subscriptions:
    get:
      tags: [FlowerSubscriptions]
      summary: Список подписок
      parameters:
        - $ref: '#/components/parameters/status'
        - $ref: '#/components/parameters/type'
        - $ref: '#/components/parameters/frequency'
        - $ref: '#/components/parameters/search'
        - $ref: '#/components/parameters/customerId'
        - $ref: '#/components/parameters/perPage'
        - $ref: '#/components/parameters/page'
      responses:
        '200':
          description: Список подписок текущего tenant/store.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubscriptionListResponse'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/TooManyRequests'
    post:
      tags: [FlowerSubscriptions]
      summary: Создать подписку
      parameters:
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SubscriptionWriteRequest'
      responses:
        '201':
          description: Подписка создана.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubscriptionResponse'
        '400':
          $ref: '#/components/responses/InvalidIdempotencyKey'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '422':
          $ref: '#/components/responses/ValidationError'
  /flower-subscriptions/{subscriptionId}:
    get:
      tags: [FlowerSubscriptions]
      summary: Получить подписку
      parameters:
        - $ref: '#/components/parameters/subscriptionId'
      responses:
        '200':
          description: Детальная карточка подписки.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubscriptionResponse'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
    patch:
      tags: [FlowerSubscriptions]
      summary: Изменить подписку
      parameters:
        - $ref: '#/components/parameters/subscriptionId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SubscriptionPatchRequest'
      responses:
        '200':
          description: Подписка обновлена.
          headers:
            Idempotency-Replayed:
              $ref: '#/components/headers/IdempotencyReplayed'
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubscriptionResponse'
        '400':
          $ref: '#/components/responses/InvalidIdempotencyKey'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '422':
          $ref: '#/components/responses/ValidationError'
  /flower-subscriptions/{subscriptionId}/pause:
    post:
      tags: [FlowerSubscriptions]
      summary: Поставить подписку на паузу
      parameters:
        - $ref: '#/components/parameters/subscriptionId'
        - $ref: '#/components/parameters/idempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                paused_until:
                  type: string
                  format: date-time
                  nullable: true
                reason:
                  type: string
                  nullable: true
                  maxLength: 1000
      responses:
        '200':
          description: Подписка поставлена на паузу.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubscriptionResponse'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '422':
          $ref: '#/components/responses/ValidationError'
  /flower-subscriptions/{subscriptionId}/resume:
    post:
      tags: [FlowerSubscriptions]
      summary: Снять подписку с паузы
      parameters:
        - $ref: '#/components/parameters/subscriptionId'
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Подписка активирована.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubscriptionResponse'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '422':
          $ref: '#/components/responses/ValidationError'
  /flower-subscriptions/{subscriptionId}/skip-next:
    post:
      tags: [FlowerSubscriptions]
      summary: Пропустить ближайшую поставку
      parameters:
        - $ref: '#/components/parameters/subscriptionId'
        - $ref: '#/components/parameters/idempotencyKey'
      responses:
        '200':
          description: Ближайшая поставка пропущена, расписание пересчитано.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SubscriptionResponse'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '422':
          $ref: '#/components/responses/ValidationError'
webhooks:
  flowerSubscriptionCreated:
    post:
      summary: Создана цветочная подписка
      description: |
        Exact snapshot подписки, получателей и адресов. Проверяйте HMAC до JSON
        parsing, UUID tenant/store и event_id. Полное тело содержит PII и финансовые
        условия и не должно попадать в открытые логи.
      parameters:
        - name: X-CRM-Webhook-Event
          in: header
          required: true
          schema: {type: string, const: flower_subscription.created}
        - name: X-CRM-Webhook-Id
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Delivery
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Timestamp
          in: header
          required: true
          schema: {type: string, pattern: '^[0-9]{10}$'}
        - name: X-CRM-Webhook-Signature
          in: header
          required: true
          schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/FlowerSubscriptionCreatedWebhookEnvelope'}
      responses:
        '200': {description: Событие принято интеграцией.}
  flowerSubscriptionNextOrderCreated:
    post:
      summary: Создан очередной заказ цветочной подписки
      description: |
        Получатель проверяет HMAC до JSON parsing, дедуплицирует по event_id и
        проверяет tenant/store UUID. Payload содержит персональные и финансовые
        данные заказа и не должен полностью попадать в открытые логи.
      parameters:
        - name: X-CRM-Webhook-Event
          in: header
          required: true
          schema: {type: string, const: flower_subscription.next_order_created}
        - name: X-CRM-Webhook-Id
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Delivery
          in: header
          required: true
          schema: {type: string, format: uuid}
        - name: X-CRM-Webhook-Timestamp
          in: header
          required: true
          schema: {type: string, pattern: '^[0-9]{10}$'}
        - name: X-CRM-Webhook-Signature
          in: header
          required: true
          schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/FlowerSubscriptionNextOrderCreatedWebhookEnvelope'}
      responses:
        '200': {description: Событие принято интеграцией.}
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: Sanctum
      description: "Реальный Laravel Sanctum Bearer token. Session/cookie авторизация для публичного API не используется. Токен проверяется по tenant/store, revoke, expires_at, allowed IP/CIDR и scopes."
  parameters:
    subscriptionId:
      name: subscriptionId
      in: path
      required: true
      description: UUID подписки текущего магазина поддомена. UUID подписки другого магазина возвращает 404.
      schema:
        type: string
        format: uuid
    idempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      schema:
        type: string
        minLength: 8
        maxLength: 128
        pattern: '^[A-Za-z0-9._:-]{8,128}$'
      description: Ключ идемпотентности для POST/PATCH. Повтор с тем же payload возвращает сохраненный ответ, другой payload с тем же ключом возвращает 409.
    status:
      name: status
      in: query
      schema:
        $ref: '#/components/schemas/SubscriptionStatus'
    type:
      name: type
      in: query
      schema:
        $ref: '#/components/schemas/SubscriptionType'
    frequency:
      name: frequency
      in: query
      schema:
        $ref: '#/components/schemas/SubscriptionFrequency'
    search:
      name: search
      in: query
      schema:
        type: string
        maxLength: 255
    customerId:
      name: customer_id
      in: query
      description: UUID клиента текущего tenant. Клиентская база доступна между магазинами tenant, поэтому фильтр не ограничивается primary_store_id.
      schema:
        type: string
        format: uuid
    perPage:
      name: per_page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 25
    page:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100000
  headers:
    IdempotencyReplayed:
      description: "`true`, если ответ возвращен из idempotency cache."
      schema:
        type: string
        enum: ['true']
    RateLimitLimit:
      description: Настроенный лимит запросов API-токена в минуту для текущего endpoint.
      schema:
        type: integer
        minimum: 1
    RateLimitRemaining:
      description: Остаток запросов в текущем минутном окне.
      schema:
        type: integer
        minimum: 0
    RetryAfter:
      description: Через сколько секунд можно повторить запрос после `429`.
      schema:
        type: integer
        minimum: 1
  responses:
    ValidationError:
      description: Ошибка валидации.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthenticated:
      description: "Неавторизованный запрос. Возможные коды: `api_token_required`, `api_token_revoked`, `unauthenticated`."
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: "Недостаточно прав. Возможные коды: `api_token_scope_denied`, `api_token_ip_denied`, `api_token_tenant_mismatch`, `api_token_store_mismatch`, `api_token_user_inactive`, `forbidden`."
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFound:
      description: Ресурс не найден.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    InvalidIdempotencyKey:
      description: Некорректный Idempotency-Key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    IdempotencyConflict:
      description: Idempotency-Key уже используется другим payload или запрос еще выполняется.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    TooManyRequests:
      description: Превышен лимит запросов API-токена.
      headers:
        Retry-After:
          $ref: '#/components/headers/RetryAfter'
        X-RateLimit-Limit:
          $ref: '#/components/headers/RateLimitLimit'
        X-RateLimit-Remaining:
          $ref: '#/components/headers/RateLimitRemaining'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  schemas:
    FlowerSubscriptionCreatedWebhookEnvelope:
      type: object
      additionalProperties: false
      required: [event, event_id, created_at, payload_schema_version, tenant_id, store_id, retry_count, data]
      properties:
        event: {type: string, const: flower_subscription.created}
        event_id:
          type: string
          format: uuid
        created_at: {type: string, format: date-time}
        payload_schema_version: {type: string, const: crm.webhook.v1}
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/FlowerSubscriptionCreatedWebhookData'}
    FlowerSubscriptionCreatedWebhookData:
      type: object
      additionalProperties: false
      required: [subscription]
      properties:
        subscription: {$ref: '#/components/schemas/FlowerSubscriptionCreatedWebhookSubscription'}
    FlowerSubscriptionCreatedWebhookSubscription:
      type: object
      additionalProperties: false
      required: [id, number, title, type, status, frequency, customer_id, manager_id, store_id, tenant_id, starts_at, ends_at, next_order_at, paused_until, auto_create_orders, notify_manager_before_hours, notify_customer_before_hours, budget_per_delivery, delivery_price, currency_code, payment_mode, prepaid_balance, comment, created_at, updated_at, recipients, addresses]
      properties:
        id:
          type: string
          format: uuid
        number: {type: string, minLength: 1}
        title: {type: string, minLength: 1, maxLength: 255}
        type: {type: string, enum: [personal, corporate]}
        status: {type: string, enum: [draft, active, paused, expired, cancelled]}
        frequency: {type: string, enum: [weekly, twice_monthly, monthly]}
        customer_id:
          type: [string, 'null']
          format: uuid
        manager_id:
          type: [string, 'null']
          format: uuid
        store_id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        starts_at: {type: [string, 'null'], format: date}
        ends_at: {type: [string, 'null'], format: date}
        next_order_at: {type: [string, 'null'], format: date-time}
        paused_until: {type: [string, 'null'], format: date-time}
        auto_create_orders: {type: boolean}
        notify_manager_before_hours: {type: integer, minimum: 0, maximum: 720}
        notify_customer_before_hours: {type: integer, minimum: 0, maximum: 720}
        budget_per_delivery: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
        delivery_price: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
        currency_code: {type: string, pattern: '^[A-Z]{3}$'}
        payment_mode: {type: string, enum: [per_order, prepaid_period, postpaid_b2b]}
        prepaid_balance: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
        comment: {type: [string, 'null'], maxLength: 2000}
        created_at: {type: string, format: date-time}
        updated_at: {type: string, format: date-time}
        recipients:
          type: array
          items: {$ref: '#/components/schemas/FlowerSubscriptionCreatedWebhookRecipient'}
        addresses:
          type: array
          items: {$ref: '#/components/schemas/FlowerSubscriptionCreatedWebhookAddress'}
    FlowerSubscriptionCreatedWebhookRecipient:
      type: object
      additionalProperties: false
      required: [id, customer_id, name, phone, is_primary, sort_order]
      properties:
        id:
          type: string
          format: uuid
        customer_id:
          type: [string, 'null']
          format: uuid
        name: {type: string, minLength: 1, maxLength: 255}
        phone: {type: [string, 'null'], maxLength: 64}
        is_primary: {type: boolean}
        sort_order: {type: integer, minimum: 0}
    FlowerSubscriptionCreatedWebhookAddress:
      type: object
      additionalProperties: false
      required: [id, title, recipient_name, phone, city, street, house, apartment, is_primary, sort_order]
      properties:
        id:
          type: string
          format: uuid
        title: {type: [string, 'null'], maxLength: 128}
        recipient_name: {type: [string, 'null'], maxLength: 255}
        phone: {type: [string, 'null'], maxLength: 64}
        city: {type: [string, 'null'], maxLength: 128}
        street: {type: [string, 'null'], maxLength: 255}
        house: {type: [string, 'null'], maxLength: 64}
        apartment: {type: [string, 'null'], maxLength: 64}
        is_primary: {type: boolean}
        sort_order: {type: integer, minimum: 0}
    FlowerSubscriptionNextOrderCreatedWebhookEnvelope:
      type: object
      additionalProperties: false
      required: [event, event_id, created_at, payload_schema_version, tenant_id, store_id, retry_count, data]
      properties:
        event: {type: string, const: flower_subscription.next_order_created}
        event_id:
          type: string
          format: uuid
        created_at: {type: string, format: date-time}
        payload_schema_version: {type: string, const: crm.webhook.v1}
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/FlowerSubscriptionNextOrderCreatedWebhookData'}
    FlowerSubscriptionNextOrderCreatedWebhookData:
      type: object
      additionalProperties: false
      required: [subscription, subscription_order, order]
      properties:
        subscription: {$ref: '#/components/schemas/FlowerSubscriptionWebhookSubscription'}
        subscription_order: {$ref: '#/components/schemas/FlowerSubscriptionWebhookSubscriptionOrder'}
        order: {$ref: './order-webhooks.v1.yaml#/components/schemas/OrderWebhookOrder'}
    FlowerSubscriptionWebhookSubscription:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, customer_id, manager_id, number, title, type, status, frequency, next_order_at, last_order_at, budget_per_delivery, delivery_price, currency_code, payment_mode, prepaid_balance]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        customer_id:
          type: string
          format: uuid
        manager_id:
          type: [string, 'null']
          format: uuid
        number: {type: string, minLength: 1}
        title: {type: string, minLength: 1}
        type: {type: string, enum: [personal, corporate]}
        status: {type: string, enum: [draft, active, paused, expired, cancelled]}
        frequency: {type: string, enum: [weekly, twice_monthly, monthly]}
        next_order_at: {type: [string, 'null'], format: date-time}
        last_order_at: {type: [string, 'null'], format: date-time}
        budget_per_delivery: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
        delivery_price: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
        currency_code: {type: string, pattern: '^[A-Z]{3}$'}
        payment_mode: {type: string, enum: [per_order, prepaid_period, postpaid_b2b]}
        prepaid_balance: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
    FlowerSubscriptionWebhookSubscriptionOrder:
      type: object
      additionalProperties: false
      required: [id, tenant_id, customer_subscription_id, order_id, scheduled_for, status, generated_at, created_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        customer_subscription_id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        scheduled_for: {type: string, format: date-time}
        status: {type: string, const: generated}
        generated_at: {type: string, format: date-time}
        created_at: {type: string, format: date-time}
    SubscriptionType:
      type: string
      enum: [personal, corporate]
    SubscriptionStatus:
      type: string
      enum: [draft, active, paused, expired, cancelled]
    SubscriptionFrequency:
      type: string
      enum: [weekly, twice_monthly, monthly]
    PaymentMode:
      type: string
      enum: [per_order, prepaid_period, postpaid_b2b]
    SubscriptionWriteRequest:
      type: object
      required: [title, type, status, frequency, next_order_at, budget_per_delivery, delivery_price, payment_mode]
      properties:
        customer_id:
          type: string
          format: uuid
          nullable: true
          description: UUID клиента текущего tenant. Клиентская база tenant-wide, поэтому клиент может быть зарегистрирован в другом магазине этой же компании.
        manager_id:
          type: string
          format: uuid
          nullable: true
          description: UUID активного сотрудника tenant с активным доступом к магазину текущего поддомена. Менеджер другого магазина возвращает 422 validation_failed.
        title:
          type: string
          maxLength: 255
        type:
          $ref: '#/components/schemas/SubscriptionType'
        status:
          $ref: '#/components/schemas/SubscriptionStatus'
        frequency:
          $ref: '#/components/schemas/SubscriptionFrequency'
        starts_at:
          type: string
          format: date
          nullable: true
        ends_at:
          type: string
          format: date
          nullable: true
          description: Дата окончания не может быть раньше даты начала, включая сохранённую дату при частичном обновлении.
        next_order_at:
          type: string
          format: date-time
        auto_create_orders:
          type: boolean
          default: true
        notify_manager_before_hours:
          type: integer
          minimum: 0
          maximum: 720
          default: 24
        notify_customer_before_hours:
          type: integer
          minimum: 0
          maximum: 720
          default: 0
        budget_per_delivery:
          type: number
          format: decimal
          minimum: 0
          maximum: 999999999999.99
        delivery_price:
          type: number
          format: decimal
          minimum: 0
          maximum: 999999999999.99
        payment_mode:
          $ref: '#/components/schemas/PaymentMode'
        comment:
          type: string
          nullable: true
          maxLength: 2000
        recipients:
          type: array
          items:
            $ref: '#/components/schemas/SubscriptionRecipientWrite'
        addresses:
          type: array
          items:
            $ref: '#/components/schemas/SubscriptionAddressWrite'
    SubscriptionPatchRequest:
      type: object
      properties:
        customer_id:
          type: string
          format: uuid
          nullable: true
          description: UUID клиента текущего tenant. Можно передать null, чтобы отвязать клиента.
        manager_id:
          type: string
          format: uuid
          nullable: true
          description: UUID активного сотрудника tenant с активным доступом к магазину подписки. Менеджер другого магазина возвращает 422 validation_failed.
        title:
          type: string
          maxLength: 255
        status:
          $ref: '#/components/schemas/SubscriptionStatus'
        type:
          $ref: '#/components/schemas/SubscriptionType'
        frequency:
          $ref: '#/components/schemas/SubscriptionFrequency'
        starts_at:
          type: string
          format: date
          nullable: true
        ends_at:
          type: string
          format: date
          nullable: true
          description: Дата окончания не может быть раньше даты начала, включая сохранённую дату при частичном обновлении.
        next_order_at:
          type: string
          format: date-time
          nullable: true
        auto_create_orders:
          type: boolean
        notify_manager_before_hours:
          type: integer
          minimum: 0
          maximum: 720
        notify_customer_before_hours:
          type: integer
          minimum: 0
          maximum: 720
        budget_per_delivery:
          type: number
          format: decimal
          minimum: 0
          maximum: 999999999999.99
        delivery_price:
          type: number
          format: decimal
          minimum: 0
          maximum: 999999999999.99
        payment_mode:
          $ref: '#/components/schemas/PaymentMode'
        comment:
          type: string
          nullable: true
          maxLength: 2000
        recipients:
          type: array
          items:
            $ref: '#/components/schemas/SubscriptionRecipientWrite'
        addresses:
          type: array
          items:
            $ref: '#/components/schemas/SubscriptionAddressWrite'
    SubscriptionRecipientWrite:
      type: object
      properties:
        customer_id:
          type: string
          format: uuid
          nullable: true
          description: UUID клиента текущего tenant. Получатель может быть клиентом из общей клиентской базы tenant.
        name:
          type: string
          maxLength: 255
        phone:
          type: string
          nullable: true
          maxLength: 64
        is_primary:
          type: boolean
          default: false
        sort_order:
          type: integer
          minimum: 0
    SubscriptionAddressWrite:
      type: object
      properties:
        title:
          type: string
          nullable: true
          maxLength: 128
        recipient_name:
          type: string
          nullable: true
          maxLength: 255
        phone:
          type: string
          nullable: true
          maxLength: 64
        country_code:
          type: string
          nullable: true
          minLength: 2
          maxLength: 2
        city:
          type: string
          nullable: true
          maxLength: 128
        street:
          type: string
          nullable: true
          maxLength: 255
        house:
          type: string
          nullable: true
          maxLength: 64
        apartment:
          type: string
          nullable: true
          maxLength: 64
        is_primary:
          type: boolean
          default: false
        sort_order:
          type: integer
          minimum: 0
    Subscription:
      type: object
      properties:
        id:
          type: string
          format: uuid
        number:
          type: string
        title:
          type: string
        type:
          $ref: '#/components/schemas/SubscriptionType'
        status:
          $ref: '#/components/schemas/SubscriptionStatus'
        frequency:
          $ref: '#/components/schemas/SubscriptionFrequency'
        customer_id:
          type: string
          format: uuid
          nullable: true
        manager_id:
          type: string
          format: uuid
          nullable: true
        store_id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        starts_at:
          type: string
          format: date
          nullable: true
        ends_at:
          type: string
          format: date
          nullable: true
        next_order_at:
          type: string
          format: date-time
          nullable: true
        paused_until:
          type: string
          format: date-time
          nullable: true
        auto_create_orders:
          type: boolean
        budget_per_delivery:
          type: string
        delivery_price:
          type: string
        currency_code:
          type: string
        payment_mode:
          $ref: '#/components/schemas/PaymentMode'
        prepaid_balance:
          type: string
        recipients:
          type: array
          items:
            $ref: '#/components/schemas/SubscriptionRecipient'
        addresses:
          type: array
          items:
            $ref: '#/components/schemas/SubscriptionAddress'
    SubscriptionRecipient:
      allOf:
        - $ref: '#/components/schemas/SubscriptionRecipientWrite'
        - type: object
          properties:
            id:
              type: string
              format: uuid
    SubscriptionAddress:
      allOf:
        - $ref: '#/components/schemas/SubscriptionAddressWrite'
        - type: object
          properties:
            id:
              type: string
              format: uuid
    SuccessResponseBase:
      type: object
      required: [success, data, request_id]
      properties:
        success:
          type: boolean
          const: true
        request_id:
          type: string
          format: uuid
    SubscriptionResponse:
      allOf:
        - $ref: '#/components/schemas/SuccessResponseBase'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/Subscription'
    SubscriptionListResponse:
      allOf:
        - $ref: '#/components/schemas/SuccessResponseBase'
        - type: object
          properties:
            data:
              type: object
              required: [items, meta]
              properties:
                items:
                  type: array
                  items:
                    $ref: '#/components/schemas/Subscription'
                meta:
                  type: object
                  properties:
                    total:
                      type: integer
                    per_page:
                      type: integer
                    current_page:
                      type: integer
                    last_page:
                      type: integer
    ErrorResponse:
      type: object
      required: [success, error, request_id]
      properties:
        success:
          type: boolean
          const: false
        error:
          type: object
          required: [code, message]
          properties:
            code:
              type: string
              examples: [validation_failed, not_found, forbidden, too_many_requests, api_token_required, api_token_revoked, api_token_scope_denied, api_token_ip_denied, idempotency_key_conflict]
            message:
              type: string
            details:
              type: object
              additionalProperties: true
        request_id:
          type: string
          format: uuid
