openapi: 3.0.3 info: title: Agronom Bot Internal API version: "1.10.0" description: | Telegram-бот «Карманный агроном» — API v1.10.0. Fixes: +signature, +UNAUTHORIZED, +monthly limits, +X-API-Ver usage, +multipart required, clarified dosage units, +X-User-ID header, +ask_expert endpoint, +protocol fields category/status/waiting_days, +assistant chat/confirm_plan. contact: name: Ivan Gromov url: https://github.com/agronom-bot email: i.gromov@agrostore.ru servers: - url: https://api.agronom.local description: Production - url: https://staging.agronom.local description: Staging security: - ApiKeyAuth: [] RequestSignAuth: [] components: securitySchemes: ApiKeyAuth: type: apiKey in: header name: X-API-Key RequestSignAuth: type: apiKey in: header name: X-Req-Sign HmacAuth: type: apiKey in: header name: X-Sign parameters: ApiVersionHeader: name: X-API-Ver in: header required: true schema: type: string enum: [v1] UserIdHeader: name: X-User-ID in: header required: true schema: type: integer RequestTimestampHeader: name: X-Req-Ts in: header required: true schema: type: integer description: Unix timestamp (seconds) RequestNonceHeader: name: X-Req-Nonce in: header required: true schema: type: string RequestBodyHashHeader: name: X-Req-Body-Sha256 in: header required: false schema: type: string description: "SHA-256 hex digest of canonical JSON body (required for application/json)." IdempotencyKeyHeader: name: Idempotency-Key in: header required: false schema: type: string description: Idempotency key for payment creation retries. AuthorizationHeader: name: Authorization in: header required: true schema: type: string description: Bearer JWT for authenticated user actions. CsrfTokenHeader: name: X-CSRF-Token in: header required: true schema: type: string description: CSRF token (must match csrf_token cookie). schemas: DiagnoseRequestMultipart: type: object description: | Multipart payload. Передайте либо `image` (один кадр), либо `images` (массив до 8 кадров). Поле `images` используется для комплексного анализа подборки. properties: image: type: string format: binary images: type: array minItems: 1 maxItems: 8 items: type: string format: binary prompt_id: type: string enum: [v1] crop_hint: type: string description: "Необязательная подсказка культуры (например, 'томат')." case_id: type: integer description: "ID кейса при повторной проверке того же растения." DiagnoseRequestBase64: type: object required: [image_base64, prompt_id] properties: image_base64: type: string description: Base64-JPEG/PNG ≤ 2 MB prompt_id: type: string enum: [v1] crop_hint: type: string description: "Необязательная подсказка культуры (например, 'томат')." case_id: type: integer description: "ID кейса при повторной проверке того же растения." DiagnoseResponse: type: object required: [crop, disease, confidence, roi] properties: crop: type: string example: apple crop_ru: type: string example: "яблоня" crop_confidence: type: number format: float description: "Уверенность именно в распознавании культуры (0..1)." example: 0.78 crop_candidates: type: array description: "2-3 наиболее вероятные культуры (используется для выбора, если нужно уточнение)." items: type: string example: ["сансевиерия", "алоэ"] object_id: type: integer description: "ID объекта, если модель или бот смогли его определить/создать." example: 123 case_id: type: integer description: "ID кейса, если запрос относится к повторной проверке." example: 456 variety: type: string description: "Сорт/культивар на языке модели." example: "Гала" variety_ru: type: string description: "Сорт/культивар на русском." example: "Антоновка" disease: type: string example: powdery_mildew disease_name_ru: type: string example: "мучнистая роса" confidence: type: number format: float example: 0.87 roi: type: number format: float example: 1.9 reasoning: type: array items: type: string example: - "Белый налёт по прожилкам" - "Пятна на верхних листьях" treatment_plan: $ref: '#/components/schemas/TreatmentPlan' next_steps: $ref: '#/components/schemas/NextSteps' plan_missing_reason: type: string description: "Причина отсутствия плана лечения (если модель его не прислала)." need_reshoot: type: boolean description: "true, если модель просит переснять фото." reshoot_tips: type: array description: "Набор советов для пересъёмки." items: type: string need_clarify_crop: type: boolean description: "true, если модель хочет уточнить предполагаемую культуру." clarify_crop_variants: type: array items: type: string description: "Список вариантов культуры на выбор пользователя." assistant_ru: type: string description: "Готовый текстовый ответ на русском для пользователя." assistant_followups_ru: type: array items: type: string description: "Короткие ответы на типовые уточняющие вопросы." protocol_status: type: string example: "Бета" protocol: $ref: '#/components/schemas/ProtocolResponse' RecentDiagnosisRecord: type: object required: [id, created_at, expires_at, expired, diagnosis] properties: id: type: integer created_at: type: string format: date-time expires_at: type: string format: date-time expired: type: boolean object_id: type: integer nullable: true plan_id: type: integer nullable: true diagnosis: $ref: '#/components/schemas/DiagnoseResponse' DsrDeleteRequest: type: object required: [user_id] properties: user_id: type: integer DsrDeleteResponse: type: object required: [status] properties: status: type: string example: deleted ConsentStatus: type: object required: [doc_type, doc_version, status, updated_at, source] properties: doc_type: type: string example: privacy doc_version: type: string example: "1.0" status: type: boolean updated_at: type: string format: date-time source: type: string example: api ConsentRequest: type: object required: [doc_type, doc_version] properties: doc_type: type: string example: privacy doc_version: type: string example: "1.0" source: type: string nullable: true example: api meta: type: object additionalProperties: true ProtocolResponse: type: object required: [id, product, dosage_value, dosage_unit, phi] properties: id: type: integer example: 1 product: type: string example: Скор 250 ЭК dosage_value: type: number example: 2 dosage_unit: type: string enum: [ml_10l, g_per_l] example: ml_10l phi: type: integer example: 30 category: type: string example: main status: type: string example: active waiting_days: type: integer example: 30 PhotoItem: allOf: - $ref: '#/components/schemas/DiagnoseResponse' - type: object required: [id, ts] properties: id: type: integer example: 42 ts: type: string format: date-time example: "2025-07-20T12:34:56Z" TreatmentPlan: type: object properties: product: type: string example: "Топаз" substance: type: string example: "Диазенконозол (триазолы)" dosage_value: type: number format: float example: 2.5 dosage_unit: type: string example: "мл/10л" dosage: type: string example: "2 мл на 10 л воды, опрыскивание по листу" method: type: string example: "Опрыскивание по листу" phi: type: string example: "30 дней" phi_days: type: integer example: 30 safety: type: string example: "Перчатки, очки, не распылять при ветре" safety_note: type: string example: "Работай в СИЗ, ветер <5 м/с" NextSteps: type: object required: [reminder, green_window] properties: reminder: type: string example: "Добавь повтор обработки через 7 дней и отметь PHI." green_window: type: string example: "Выбери вечер без дождя и ветра >5 м/с." cta: type: string example: "Добавить обработку" PhotoHistoryItem: type: object required: [photo_id, ts, crop, disease, status, confidence, thumb_url] properties: photo_id: type: integer example: 1 ts: type: string format: date-time example: "2025-07-20T12:34:56Z" crop: type: string example: apple disease: type: string example: scab status: type: string enum: [pending, ok, retrying, failed] example: ok confidence: type: number format: float example: 0.92 thumb_url: type: string format: uri example: https://cdn.example/thumb1.jpg ListPhotosResponse: type: object required: [items] properties: items: type: array items: $ref: '#/components/schemas/PhotoItem' next_cursor: type: string nullable: true description: "Передайте значение в ?cursor=… для следующей страницы (формат `:`)" PaymentWebhook: type: object required: [external_id, status, paid_at, signature] properties: external_id: type: string status: type: string enum: [success, fail, cancel, bank_error] paid_at: type: string format: date-time signature: type: string description: HMAC-SHA256 of payload TinkoffWebhookNotification: type: object required: [TerminalKey, Status, Token] additionalProperties: true properties: TerminalKey: type: string OrderId: type: string nullable: true PaymentId: type: string nullable: true Status: type: string Amount: type: integer nullable: true Success: type: boolean nullable: true Token: type: string RebillId: type: string nullable: true Data: type: object nullable: true additionalProperties: true AutopayWebhook: type: object required: [autopay_charge_id, binding_id, user_id, amount, status, charged_at, signature] properties: autopay_charge_id: type: string example: CHG-1 binding_id: type: string example: BND-1 user_id: type: integer amount: type: integer status: type: string enum: [success, fail, cancel, bank_error] charged_at: type: string format: date-time signature: type: string description: HMAC-SHA256 of payload AutopayCancelRequest: type: object required: [user_id] properties: user_id: type: integer PaymentCreateRequest: type: object required: [user_id, plan] properties: user_id: type: integer plan: type: string enum: [pro] example: pro months: type: integer default: 1 autopay: type: boolean nullable: true description: Enable SBP Autopay binding PaymentStatusResponse: type: object required: [status] properties: status: type: string enum: [pending, success, fail, cancel, bank_error] pro_expires_at: type: string format: date-time nullable: true PhotoStatusResponse: type: object required: [status, updated_at] properties: status: type: string enum: [pending, ok, retrying, failed] updated_at: type: string format: date-time crop: type: string disease: type: string protocol: $ref: '#/components/schemas/ProtocolResponse' DiagnoseQueuedResponse: type: object required: [id, status] properties: id: type: integer example: 1 status: type: string example: pending ErrorResponse: type: object required: [code, message] properties: code: type: string enum: [NO_LEAF, LIMIT_EXCEEDED, GPT_TIMEOUT, BAD_REQUEST, UNAUTHORIZED, UPGRADE_REQUIRED, TOO_MANY_REQUESTS, SERVICE_UNAVAILABLE, FORBIDDEN] message: type: string LimitReached: type: object required: [error, limit] properties: error: type: string example: limit_reached limit: type: integer example: 5 PlanSessionUpsertRequest: type: object required: [token, diagnosis] properties: token: type: string example: mi0jzzh5i6ba7l diagnosis: type: object additionalProperties: true description: "Ответ diagnose API, сохранённый для мастера планов." current_step: type: string example: choose_object state: type: object additionalProperties: true description: "Произвольное состояние мастера (выбор объекта, триггер и т.д.)." recent_diagnosis_id: type: integer nullable: true object_id: type: integer nullable: true plan_id: type: integer nullable: true ttl_hours: type: integer nullable: true description: "Переопределение TTL (по умолчанию берётся из PLAN_SESSION_TTL_H)." PlanSessionRecord: type: object required: [id, user_id, token, created_at, updated_at, expires_at, expired, current_step, state, diagnosis] properties: id: type: integer example: 5 user_id: type: integer example: 42 token: type: string example: mi0jzzh5i6ba7l created_at: type: string format: date-time updated_at: type: string format: date-time expires_at: type: string format: date-time expired: type: boolean current_step: type: string example: time_picker state: type: object additionalProperties: true diagnosis: type: object additionalProperties: true recent_diagnosis_id: type: integer nullable: true object_id: type: integer nullable: true plan_id: type: integer nullable: true PlanSessionPatchRequest: type: object properties: diagnosis: type: object additionalProperties: true current_step: type: string state: type: object additionalProperties: true recent_diagnosis_id: type: integer nullable: true object_id: type: integer nullable: true plan_id: type: integer nullable: true ttl_hours: type: integer nullable: true AssistantChatRequest: type: object required: [message] properties: session_id: type: string example: "chat-6f7c" object_id: type: integer nullable: true message: type: string example: "Что делать с томатами после дождя?" metadata: type: object properties: recent_diagnosis_id: type: integer nullable: true plan_session_id: type: integer nullable: true locale: type: string example: ru history: type: array maxItems: 24 items: type: object required: [role, text] properties: role: type: string enum: [user, assistant] text: type: string minLength: 1 maxLength: 1000 AssistantProposal: type: object required: [proposal_id, kind] properties: proposal_id: type: string kind: type: string enum: [plan, event, clarify] plan_payload: type: object description: "Машинный план (тот же формат, что в PlanSession), draft/proposed." additionalProperties: true suggested_actions: type: array items: type: string enum: [pin, ask_clarification, show_plans, open_logbook] AssistantChatResponse: type: object required: [assistant_message] properties: assistant_message: type: string example: "Предлагаю обработку для 🍅 Грядка №2 и напомню за час." followups: type: array items: type: string proposals: type: array items: $ref: '#/components/schemas/AssistantProposal' AssistantConfirmRequest: type: object required: [proposal_id, object_id] properties: proposal_id: type: string object_id: type: integer preferred_time: type: string format: date-time nullable: true plan_session_id: type: integer nullable: true AssistantConfirmResponse: type: object required: [status] properties: status: type: string enum: [accepted, scheduled] plan_id: type: integer nullable: true event_ids: type: array items: type: integer reminder_ids: type: array items: type: integer PlanCreateStage: type: object properties: stage_id: type: integer nullable: true option_ids: type: array items: type: integer PlanCreateRequest: type: object required: [object_id, plan_payload] properties: object_id: type: integer case_id: type: integer nullable: true source: type: string example: assistant plan_payload: type: object additionalProperties: true PlanCreateResponse: type: object properties: plan_id: type: integer nullable: true stages: type: array items: $ref: '#/components/schemas/PlanCreateStage' errors: type: array items: type: string EventCreateRequest: type: object required: [stage_id] properties: stage_id: type: integer stage_option_id: type: integer nullable: true due_at: type: string format: date-time nullable: true slot_end: type: string format: date-time nullable: true reason: type: string nullable: true EventCreateResponse: type: object properties: event_ids: type: array items: type: integer reminder_ids: type: array items: type: integer AutoplanRequest: type: object required: [stage_id, stage_option_id] properties: stage_id: type: integer stage_option_id: type: integer min_hours_ahead: type: integer default: 2 horizon_hours: type: integer default: 72 AutoplanResponse: type: object properties: autoplan_run_id: type: integer nullable: true status: type: string example: pending paths: /v1/assistant/chat: post: summary: Conversational assistant entrypoint operationId: assistantChat description: "Получить ответ живого ассистента; чат — интерфейс, данные остаются в cases/plans/events." tags: [assistant] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - $ref: '#/components/parameters/IdempotencyKeyHeader' requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/AssistantChatRequest' responses: '200': description: Assistant reply with proposals content: application/json: schema: $ref: '#/components/schemas/AssistantChatResponse' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/assistant/confirm_plan: post: summary: Persist assistant proposal into plan/events/reminders operationId: assistantConfirmPlan description: "По клику «📌 Зафиксировать» создаёт/обновляет plan + события/напоминания через те же сервисы, что мастер." tags: [assistant] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/AssistantConfirmRequest' responses: '200': description: Plan/events persisted content: application/json: schema: $ref: '#/components/schemas/AssistantConfirmResponse' '400': description: Validation failed content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/plans: post: summary: Create plan from plan_payload operationId: createPlan description: "Создаёт план по plan_payload (assistant/master)." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/PlanCreateRequest' responses: '200': description: Plan created content: application/json: schema: $ref: '#/components/schemas/PlanCreateResponse' '400': description: Bad payload content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/plans/{plan_id}/pdf: get: summary: Export plan to PDF operationId: exportPlanPdf description: "Экспортирует план в PDF-заметку." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: plan_id in: path required: true schema: type: integer responses: '200': description: PDF file content: application/pdf: schema: type: string format: binary '404': description: Not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/plans/{plan_id}/events: post: summary: Create event/reminder for plan operationId: createPlanEvent description: "Создаёт событие плана и напоминание (при необходимости)." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: plan_id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/EventCreateRequest' responses: '200': description: Event created content: application/json: schema: $ref: '#/components/schemas/EventCreateResponse' '400': description: Bad payload content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/plans/{plan_id}/autoplan: post: summary: Enqueue autoplan run operationId: enqueueAutoplan description: "Создаёт запись автоплана для поиска окна обработок." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: plan_id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/AutoplanRequest' responses: '202': description: Autoplan enqueued content: application/json: schema: $ref: '#/components/schemas/AutoplanResponse' '400': description: Bad payload content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/diagnoses/recent: get: summary: Get latest recent diagnosis operationId: getRecentDiagnosis description: "Возвращает последний диагноз пользователя за 24 часа." tags: [diagnose] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: include_expired in: query required: false schema: type: boolean default: false responses: '200': description: Recent diagnosis record content: application/json: schema: $ref: '#/components/schemas/RecentDiagnosisRecord' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Not found /v1/diagnoses/recent/{diagnosis_id}: get: summary: Get recent diagnosis by id operationId: getRecentDiagnosisById description: "Возвращает диагноз по recent_diagnosis_id." tags: [diagnose] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: diagnosis_id in: path required: true schema: type: integer responses: '200': description: Recent diagnosis record content: application/json: schema: $ref: '#/components/schemas/RecentDiagnosisRecord' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Not found /v1/ai/diagnose: post: summary: Diagnose plant disease operationId: diagnosePlant description: | Upload a leaf photo and get back the predicted crop, disease and confidence score. Supports multipart uploads via `image` (single) or `images[]` (album up to 8 files), and JSON body with `image_base64`. tags: [diagnose] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: multipart/form-data: schema: $ref: '#/components/schemas/DiagnoseRequestMultipart' application/json: schema: $ref: '#/components/schemas/DiagnoseRequestBase64' responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/DiagnoseResponse' '202': description: Image queued for processing content: application/json: schema: $ref: '#/components/schemas/DiagnoseQueuedResponse' '400': description: Bad image / bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '413': description: Image too large content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '402': description: Free quota exceeded content: application/json: schema: $ref: '#/components/schemas/LimitReached' '429': description: Rate limit exceeded content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '500': description: Unexpected internal error content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' x-rateLimit: ip_limit: 30 user_limit: 120 window: minute /v1/plans/sessions: post: summary: Create or refresh plan wizard session state operationId: upsertPlanSession description: "Сохраняет шаг мастера плана или обновляет существующую сессию." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/PlanSessionUpsertRequest' responses: '200': description: Session stored content: application/json: schema: $ref: '#/components/schemas/PlanSessionRecord' '400': description: Invalid payload content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' get: summary: Fetch the latest or token-specific plan wizard session operationId: getPlanSession description: "Возвращает последнюю сессию или конкретный токен мастера планов." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: token in: query required: false schema: type: string description: "Если не указан, возвращается последняя сессия пользователя." - name: include_expired in: query required: false schema: type: boolean default: false - name: plan_id in: query required: false schema: type: integer description: "Вернуть сессию, связанную с планом (взаимоисключается с token)." responses: '200': description: Session returned content: application/json: schema: $ref: '#/components/schemas/PlanSessionRecord' '404': description: Session not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '410': description: Session expired (unless include_expired=true) content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' delete: summary: Delete plan wizard session(s) operationId: deletePlanSession description: "Удаляет конкретную сессию по токену/плану или все сессии пользователя." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: token in: query required: false schema: type: string description: "Если не указан, удаляются все сессии пользователя." - name: plan_id in: query required: false schema: type: integer description: "Удалить сессии, связанные с планом." responses: '204': description: Deleted '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Session not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/plans/sessions/{session_id}: patch: summary: Update plan wizard session fields operationId: patchPlanSession description: "Частично обновляет состояние конкретной сессии." tags: [plans] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: session_id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/PlanSessionPatchRequest' responses: '200': description: Updated session content: application/json: schema: $ref: '#/components/schemas/PlanSessionRecord' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Session not found content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/photos: get: summary: List user’s photos (history) operationId: listPhotos description: List previously uploaded photos with pagination. tags: [photos] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: limit in: query schema: type: integer default: 10 maximum: 50 - name: cursor in: query schema: type: string description: "Отдаётся в ответе как `next_cursor` (формат: `:`)" responses: '200': description: Paginated list content: application/json: schema: $ref: '#/components/schemas/ListPhotosResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/photos/history: get: summary: Photo history (offset) operationId: listPhotosHistory description: Return past photos ordered by ts DESC. tags: [photos] parameters: - name: limit in: query schema: type: integer default: 10 maximum: 50 - name: offset in: query schema: type: integer default: 0 - name: user_id in: query schema: type: integer description: User ID (stub) responses: '200': description: List of history items content: application/json: schema: type: array items: $ref: '#/components/schemas/PhotoHistoryItem' example: - photo_id: 1 ts: "2025-07-20T12:34:56Z" crop: apple disease: scab status: ok confidence: 0.92 thumb_url: https://cdn.example/1.jpg - photo_id: 2 ts: "2025-07-21T13:45:00Z" crop: tomato disease: blight status: failed confidence: 0.45 thumb_url: https://cdn.example/2.jpg /v1/photos/{photo_id}: get: summary: Get photo status description: Retrieve status and metadata of a previously uploaded photo. operationId: getPhotoStatus tags: [photos] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - in: path name: photo_id required: true schema: type: integer responses: '200': description: Photo details content: application/json: schema: $ref: '#/components/schemas/PhotoStatusResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Not found /v1/limits: get: summary: Возвращает текущие лимиты пользователя operationId: getUserLimits description: Retrieve current monthly usage limits for the authenticated user. tags: [limits] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' responses: '200': description: Текущие лимиты content: application/json: schema: type: object required: [limit_monthly_free, used_this_month] properties: limit_monthly_free: type: integer example: 5 used_this_month: type: integer example: 3 '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/users/{user_id}/export: get: summary: Export user data (ZIP) operationId: exportUserData description: "Экспортирует данные пользователя в ZIP-архив (data.json)." tags: [users] security: - ApiKeyAuth: [] RequestSignAuth: [] HmacAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: user_id in: path required: true schema: type: integer responses: '200': description: ZIP archive content: application/zip: schema: type: string format: binary '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/users/{user_id}/consents: get: summary: List user consents operationId: listUserConsents description: "Возвращает текущий статус согласий пользователя." tags: [users] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: user_id in: path required: true schema: type: integer responses: '200': description: Consent list content: application/json: schema: type: array items: $ref: '#/components/schemas/ConsentStatus' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/users/{user_id}/consents/accept: post: summary: Accept consent operationId: acceptUserConsent description: "Фиксирует согласие пользователя." tags: [users] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: user_id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ConsentRequest' responses: '200': description: Consent accepted content: application/json: schema: type: object required: [status] properties: status: type: string example: ok '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/users/{user_id}/consents/revoke: post: summary: Revoke consent operationId: revokeUserConsent description: "Отзывает согласие пользователя." tags: [users] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - name: user_id in: path required: true schema: type: integer requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/ConsentRequest' responses: '200': description: Consent revoked content: application/json: schema: type: object required: [status] properties: status: type: string example: ok '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/dsr/delete_user: post: summary: Delete user data (DSR) operationId: deleteUserDsr description: "Каскадное удаление данных пользователя по DSR-запросу." tags: [users] security: - ApiKeyAuth: [] RequestSignAuth: [] HmacAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/DsrDeleteRequest' responses: '200': description: Deleted content: application/json: schema: $ref: '#/components/schemas/DsrDeleteResponse' '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/payments/create: post: summary: Create SBP payment description: Initiate a new SBP transaction and return a URL for payment processing. operationId: createPayment tags: [payments] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/PaymentCreateRequest' responses: '200': description: Payment link content: application/json: schema: type: object required: [payment_id, url] properties: payment_id: type: string example: 123e4567e89 url: type: string example: https://pay.tbank.ru/xxxx description: Card payment URL (PaymentURL) autopay_binding_id: type: string nullable: true description: Identifier of SBP Autopay binding sbp_url: type: string nullable: true description: SBP QR payment URL (when available) '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/payments/{payment_id}: get: summary: Payment status description: Check the current status of a previously created SBP payment. operationId: getPaymentStatus tags: [payments] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - in: path name: payment_id required: true schema: type: string responses: '200': description: Payment status content: application/json: schema: $ref: '#/components/schemas/PaymentStatusResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '404': description: Not found /v1/payments/sbp/webhook: post: summary: SBP payment webhook operationId: handleSbpWebhook description: | Process SBP payment callback and update payment status. Accepts either internal HMAC payload (X-Sign + signature) or native T-Bank Token payload (OrderId/PaymentId/Status/Amount/Token). T-Bank callbacks are additionally validated by source IP allowlist (`TINKOFF_IPS`). tags: [payments] security: - HmacAuth: [] requestBody: required: true content: application/json: schema: oneOf: - $ref: '#/components/schemas/PaymentWebhook' - $ref: '#/components/schemas/TinkoffWebhookNotification' responses: '200': description: Accepted '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/payments/sbp/autopay/webhook: post: summary: SBP autopay webhook operationId: handleAutopayWebhook description: | Process SBP Autopay callback and update payment status. Accepts either internal HMAC payload (X-Sign + signature) or native T-Bank Token payload (OrderId/PaymentId/Status/Amount/Token/RebillId). T-Bank callbacks are additionally validated by source IP allowlist (`TINKOFF_IPS`). tags: [payments] security: - HmacAuth: [] requestBody: required: true content: application/json: schema: oneOf: - $ref: '#/components/schemas/AutopayWebhook' - $ref: '#/components/schemas/TinkoffWebhookNotification' responses: '200': description: Accepted '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/payments/sbp/autopay/cancel: post: summary: Cancel SBP autopay operationId: cancelAutopay description: Disable SBP Autopay for the user. tags: [payments] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' - $ref: '#/components/parameters/AuthorizationHeader' - $ref: '#/components/parameters/CsrfTokenHeader' requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/AutopayCancelRequest' responses: '204': description: Autopay canceled '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/partner/orders: post: summary: Order deep-link callback (AgroStore) operationId: partnerOrderCallback description: Receive deep-link order info from partner AgroStore. tags: [partner] security: - HmacAuth: [] - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: application/json: schema: type: object required: [order_id, user_tg_id, protocol_id, price_kopeks, signature] properties: order_id: type: string user_tg_id: type: integer protocol_id: type: integer price_kopeks: type: integer signature: type: string description: HMAC-SHA256 по телу запроса responses: '202': description: Queued '200': description: Already processed '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '403': description: Forbidden content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '429': description: Too many requests content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '503': description: Service unavailable content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/ask_expert: post: summary: Queue question for expert operationId: askExpert description: Send a question to a human agronomist for review. tags: [expert] security: - ApiKeyAuth: [] RequestSignAuth: [] parameters: - $ref: '#/components/parameters/ApiVersionHeader' - $ref: '#/components/parameters/UserIdHeader' - $ref: '#/components/parameters/RequestTimestampHeader' - $ref: '#/components/parameters/RequestNonceHeader' requestBody: required: true content: application/json: schema: type: object required: [question] properties: question: type: string responses: '202': description: Queued '400': description: Bad request content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' /v1/beta_stats: get: summary: Beta houseplants stats snapshot operationId: betaStats tags: [beta] security: - HmacAuth: [] responses: '200': description: Aggregated beta metrics content: application/json: schema: type: object required: [stats, generated_at, scope] properties: scope: type: string example: beta_stats generated_at: type: string format: date-time stats: type: object properties: beta_testers: type: integer beta_users_with_photo: type: integer beta_users_with_case: type: integer beta_users_survey_completed: type: integer beta_users_followup_answered: type: integer '401': description: Unauthorized content: application/json: schema: $ref: '#/components/schemas/ErrorResponse' tags: - name: diagnose description: Disease recognition - name: photos description: Photo history - name: payments description: SBP integration - name: limits description: User usage limits - name: plans description: Plan creation, sessions и автоплан - name: assistant description: Conversational assistant (чат, tool-calls) - name: partner description: External partner callbacks - name: expert description: Human expert questions - name: beta description: Beta houseplants metrics