mirror of
https://github.com/dartdavros/chatballs.git
synced 2026-10-05 09:14:58 +03:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bd76042d2 | ||
|
|
c286ba7903 | ||
|
|
234a3e43da | ||
|
|
17b0c9387f | ||
|
|
27091c0234 | ||
|
|
3c01486aa3 | ||
|
|
15ff9bf2c3 | ||
|
|
5d8362e8f6 | ||
|
|
eeed0ed51a | ||
|
|
42a468ec97 | ||
|
|
44718142b3 | ||
|
|
4cba376c0e | ||
|
|
a4c6b960a8 | ||
|
|
0098e147ac | ||
|
|
4ab26a1bcd | ||
|
|
09fb0177b1 | ||
|
|
b76871caf0 | ||
|
|
8580b480e7 | ||
|
|
eff6d7ac0c | ||
|
|
1cff9e2183 | ||
|
|
d8420e4379 | ||
|
|
21b8100598 | ||
|
|
1da84c9734 | ||
|
|
82805f7b1a | ||
|
|
eca0e52667 | ||
|
|
54c35e281a | ||
|
|
5396dda8ad | ||
|
|
29164db094 | ||
|
|
c5a53ccec5 | ||
|
|
049217505a | ||
|
|
132c684630 | ||
|
|
bfe90e9abd | ||
|
|
5b49904d6a | ||
|
|
cd50cce5a8 |
No files matched your search
@@ -23,9 +23,9 @@ jobs:
|
||||
name: ruff
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
@@ -46,9 +46,9 @@ jobs:
|
||||
name: deployment CLI
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
|
||||
@@ -39,12 +39,13 @@ env:
|
||||
GATEWAY_BASE_IMAGE: caddy:2.8.4
|
||||
REDIS_IMAGE: redis:7-alpine
|
||||
COTURN_IMAGE: coturn/coturn:4.6
|
||||
UPDATER_BASE_IMAGE: docker:27-cli
|
||||
|
||||
jobs:
|
||||
images:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Версия релиза
|
||||
id: version
|
||||
@@ -57,9 +58,9 @@ jobs:
|
||||
echo "value=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "repo=$(echo '${{ github.repository }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
- uses: docker/login-action@v3
|
||||
- uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -78,13 +79,16 @@ jobs:
|
||||
echo "gateway=${GATEWAY_BASE_IMAGE}@$(digest_of "$GATEWAY_BASE_IMAGE")" >> "$GITHUB_OUTPUT"
|
||||
echo "redis=${REDIS_IMAGE}@$(digest_of "$REDIS_IMAGE")" >> "$GITHUB_OUTPUT"
|
||||
echo "coturn=${COTURN_IMAGE}@$(digest_of "$COTURN_IMAGE")" >> "$GITHUB_OUTPUT"
|
||||
echo "updater=${UPDATER_BASE_IMAGE}@$(digest_of "$UPDATER_BASE_IMAGE")" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Backend
|
||||
id: backend
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ${{ env.APP_DIR }}
|
||||
file: ${{ env.APP_DIR }}/apps/backend/Dockerfile.production
|
||||
build-args: |
|
||||
CHATBALLS_VERSION=${{ steps.version.outputs.value }}
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ steps.version.outputs.repo }}/backend:${{ steps.version.outputs.value }}
|
||||
@@ -94,7 +98,7 @@ jobs:
|
||||
|
||||
- name: Frontend
|
||||
id: frontend
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ${{ env.APP_DIR }}
|
||||
file: ${{ env.APP_DIR }}/deploy/docker/frontend.Dockerfile
|
||||
@@ -109,7 +113,7 @@ jobs:
|
||||
# а не монтируются с хоста. Ради этого установка и стала одним файлом.
|
||||
- name: Gateway
|
||||
id: gateway
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ${{ env.APP_DIR }}
|
||||
file: ${{ env.APP_DIR }}/deploy/docker/gateway.Dockerfile
|
||||
@@ -124,7 +128,7 @@ jobs:
|
||||
|
||||
- name: Postgres
|
||||
id: postgres
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ${{ env.APP_DIR }}
|
||||
file: ${{ env.APP_DIR }}/deploy/docker/postgres.Dockerfile
|
||||
@@ -137,6 +141,23 @@ jobs:
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
# Сервис обновления по кнопке (ADR-CHATBALLS-0049): docker CLI с compose
|
||||
# и два сценария внутри; единственный, кому монтируется docker.sock.
|
||||
- name: Updater
|
||||
id: updater
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: ${{ env.APP_DIR }}
|
||||
file: ${{ env.APP_DIR }}/deploy/docker/updater.Dockerfile
|
||||
build-args: |
|
||||
CHATBALLS_UPDATER_BASE_IMAGE=${{ steps.bases.outputs.updater }}
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ steps.version.outputs.repo }}/updater:${{ steps.version.outputs.value }}
|
||||
${{ env.REGISTRY }}/${{ steps.version.outputs.repo }}/updater:latest
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Релизный compose.yaml и release.env
|
||||
id: artifacts
|
||||
run: |
|
||||
@@ -148,6 +169,7 @@ jobs:
|
||||
frontend="$prefix/frontend:$version@${{ steps.frontend.outputs.digest }}"
|
||||
gateway="$prefix/gateway:$version@${{ steps.gateway.outputs.digest }}"
|
||||
postgres="$prefix/postgres:$version@${{ steps.postgres.outputs.digest }}"
|
||||
updater="$prefix/updater:$version@${{ steps.updater.outputs.digest }}"
|
||||
redis="${{ steps.bases.outputs.redis }}"
|
||||
coturn="${{ steps.bases.outputs.coturn }}"
|
||||
|
||||
@@ -160,7 +182,8 @@ jobs:
|
||||
--pin "CHATBALLS_GATEWAY_IMAGE=$gateway" \
|
||||
--pin "CHATBALLS_POSTGRES_IMAGE=$postgres" \
|
||||
--pin "CHATBALLS_REDIS_IMAGE=$redis" \
|
||||
--pin "CHATBALLS_COTURN_IMAGE=$coturn"
|
||||
--pin "CHATBALLS_COTURN_IMAGE=$coturn" \
|
||||
--pin "CHATBALLS_UPDATER_IMAGE=$updater"
|
||||
|
||||
{
|
||||
echo "# release.env — digest-пины релиза $version для \`chatballs deploy\`."
|
||||
@@ -172,6 +195,7 @@ jobs:
|
||||
echo "CHATBALLS_POSTGRES_IMAGE=$postgres"
|
||||
echo "CHATBALLS_REDIS_IMAGE=$redis"
|
||||
echo "CHATBALLS_COTURN_IMAGE=$coturn"
|
||||
echo "CHATBALLS_UPDATER_IMAGE=$updater"
|
||||
} > dist/release.env
|
||||
|
||||
# Файл, который скачает человек, обязан быть валидным сам по себе —
|
||||
@@ -180,7 +204,7 @@ jobs:
|
||||
|
||||
cat dist/compose.yaml
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-compose
|
||||
path: |
|
||||
@@ -189,7 +213,7 @@ jobs:
|
||||
|
||||
- name: Приложить к релизу
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
files: |
|
||||
dist/compose.yaml
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
Если в окружении не доступен инструмент, например - Python, PHP, попробуй docker, если в проекте есть его файлы.
|
||||
|
||||
Тесты: гонять только те, что относятся к изменённому в текущем шаге. Полный
|
||||
прогон — только по моему явному указанию, никогда по своей инициативе. Полный
|
||||
набор идёт ~20 минут, и гонять его после каждой правки запрещено.
|
||||
|
||||
Без моего явного указания не меняй ничего!
|
||||
Если я задал вопросы, это не значит что ты можешь менять файлы!
|
||||
Любые правки только после моего явного указания, например - "делай".
|
||||
@@ -16,7 +20,7 @@ Production deployment / миграция:
|
||||
- Перед любым изменяющим действием в production сначала представить владельцу точный план миграции и получить его явное согласование. Разрешение на диагностику или общая просьба «исправить» не являются разрешением самостоятельно выбирать архитектуру миграции.
|
||||
|
||||
UI / дизайн:
|
||||
- Никакой отсебятины в UI: не добавлять экраны, блоки, карточки, иконки, тексты, анимации, цвета, layout-решения и состояния, которых нет в утвержденной документации или design-system.
|
||||
- Никакой отсебятины в UI: не добавлять экраны, блоки, карточки, иконки, тексты, анимации, цвета, layout-решения и состояния, которых нет в утверждённом дизайн-макете (`design/baseline/<фича>/*.dc.html`). Макет — источник истины, README рядом с ним лишь пересказ.
|
||||
- Если UI-этап еще не наступил, UI не считается реализованным и не должен маскироваться под готовый продуктовый интерфейс.
|
||||
- Для построения UI использовать существующие компоненты и их стили, если они уже реализованы; если подходящего компонента нет, создавать переиспользуемый компонент в рамках существующей системы.
|
||||
- Не упрощать UI, анимации, иконки, состояния или поведение по своему усмотрению. Любое отклонение от baseline требует явного согласования до правок.
|
||||
@@ -56,7 +60,11 @@ Engineering rules / обязательные практики:
|
||||
- Демо-набор ставится на языке организации: манифесты лежат в `demo_seed/data/<язык>/`, наборы ключей в них совпадают. Бинарные вложения (аватары, голосовые) общие, текстовые документы — свои на каждый язык.
|
||||
|
||||
Definition of Done:
|
||||
- Запускать только тесты, относящиеся к изменениям текущей итерации. Полный прогон всех тестов выполнять только по явному указанию владельца.
|
||||
- Запускать только тесты, относящиеся к изменениям текущей итерации: изменил
|
||||
presence — гоняешь тесты присутствия, изменил тексты — гоняешь каталог i18n.
|
||||
Полный прогон всех тестов выполнять ТОЛЬКО по явному указанию владельца.
|
||||
Использовать `--reuse-db`; `--create-db` — лишняя минута на переигрывание
|
||||
миграций, она нужна только когда схема действительно поменялась.
|
||||
- Измененные файлы должны быть проверены на NO GOD violations.
|
||||
- Новый компонент не должен владеть несвязанными ответственностями.
|
||||
- Не должно быть придуманных текстов, иконок, layout-решений или состояний вне design/docs.
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
|
||||
Chatballs takes over the first line of customer conversations. An AI agent answers from your knowledge base in Telegram, MAX, email and the chat on your website. When the agent is not confident or the customer asks for a person, the conversation goes to your team together with a notification.
|
||||
|
||||
The platform installs on your own server with a single command. Customer data stays with you. You connect the AI model with your own key and set your own budget.
|
||||
The platform installs on your own server with a single command. Customer data stays with you. You connect the AI model with your own key.
|
||||
|
||||
---
|
||||
|
||||
@@ -101,7 +101,7 @@ Everything else is done in **Settings**.
|
||||
|---|---|
|
||||
| **Platform** | Set the installation domain. The gateway issues a Let's Encrypt certificate on its own and switches to HTTPS. Outgoing SMTP mail is configured here as well: it is needed for employee invitations and password recovery. |
|
||||
| **Integrations** | Connect an AI model provider: OpenRouter, any OpenAI-compatible service or a local model. A demo provider that needs no key is available for a first look. Then connect entry points: a Telegram bot, a MAX bot, a mailbox over IMAP/SMTP or a web widget for your site. |
|
||||
| **Agents** | Create an AI agent: who it is, how it speaks, what rules it follows. Choose the model and a daily budget. Attach articles from the knowledge base. |
|
||||
| **Agents** | Create an AI agent: who it is, how it speaks, what rules it follows. Choose the model. Attach articles from the knowledge base. |
|
||||
| **Employees** | Invite your team by email, assign roles and groups. |
|
||||
|
||||
The home screen shows a launch checklist: create an agent, connect an entry point, invite employees.
|
||||
@@ -132,7 +132,9 @@ By default files are stored in a Docker volume. In **Settings → Storage** the
|
||||
|
||||
### Updating
|
||||
|
||||
Download the new release's `compose.yaml` over the old one and restart:
|
||||
When a new release is out, the installation administrator sees a banner in the interface and updates with one button; the same lives in **Settings → Platform → Updates**. The installation updates itself on the server: it downloads the release `compose.yaml`, pulls the images and restarts the services, with about a minute of downtime.
|
||||
|
||||
Manually, from the server console: download the new release's `compose.yaml` over the old one and restart:
|
||||
|
||||
```bash
|
||||
docker compose pull && docker compose up -d --wait
|
||||
@@ -190,7 +192,7 @@ Waiting conversations and new messages reach the employee in Telegram or MAX. Li
|
||||
|
||||
### Your own server and your own AI model
|
||||
|
||||
Installs with one command, data stays with you. Connect any AI model provider with your own key: OpenRouter, an OpenAI-compatible service, a local model. A daily budget per agent in dollars, token and cost accounting for every call.
|
||||
Installs with one command, data stays with you. Connect any AI model provider with your own key: OpenRouter, an OpenAI-compatible service, a local model.
|
||||
|
||||
### Customer data protection
|
||||
|
||||
@@ -242,8 +244,7 @@ Check in order:
|
||||
1. The agent status is **Active**, not **Draft**.
|
||||
2. The agent has an AI model provider selected. Without it no answer is possible.
|
||||
3. The provider in **Integrations** has the **Connected** status. Run the check to refresh it.
|
||||
4. The agent's daily budget is not exhausted. Blocked calls are visible in the AI usage log.
|
||||
5. The conversation is not switched to **Operator** or **Paused** mode.
|
||||
4. The conversation is not switched to **Operator** or **Paused** mode.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
+7
-6
@@ -45,7 +45,7 @@
|
||||
|
||||
Chatballs берёт на себя первую линию общения с клиентами. ИИ-агент отвечает по вашей базе знаний в Telegram, MAX, электронной почте и в чате на сайте. Когда агент не уверен в ответе или клиент просит человека, диалог уходит вашим сотрудникам вместе с уведомлением.
|
||||
|
||||
Платформа ставится на ваш сервер одной командой. Данные клиентов остаются у вас. ИИ-модель вы подключаете сами по своему ключу и сами задаёте бюджет.
|
||||
Платформа ставится на ваш сервер одной командой. Данные клиентов остаются у вас. ИИ-модель вы подключаете сами по своему ключу.
|
||||
|
||||
---
|
||||
|
||||
@@ -101,7 +101,7 @@ docker compose up -d --wait
|
||||
|---|---|
|
||||
| **Платформа** | Укажите домен установки. Шлюз сам выпустит сертификат Let's Encrypt и переведёт работу на HTTPS. Здесь же задаётся исходящая почта по SMTP: она нужна для приглашений сотрудников и восстановления паролей. |
|
||||
| **Интеграции** | Подключите провайдера ИИ-моделей: OpenRouter, любой OpenAI-совместимый сервис или локальную модель. Для первого знакомства есть демо-провайдер, которому не нужен ключ. Затем подключите точки входа: бота Telegram, бота MAX, почтовый ящик по IMAP/SMTP или веб-виджет для сайта. |
|
||||
| **Агенты** | Создайте ИИ-агента: кто он, как говорит, по каким правилам работает. Выберите модель и дневной бюджет. Прикрепите статьи из базы знаний. |
|
||||
| **Агенты** | Создайте ИИ-агента: кто он, как говорит, по каким правилам работает. Выберите модель. Прикрепите статьи из базы знаний. |
|
||||
| **Сотрудники** | Пригласите команду по почте, распределите роли и группы. |
|
||||
|
||||
На главном экране есть чек-лист запуска: создать агента, подключить точку входа, пригласить сотрудников.
|
||||
@@ -132,7 +132,9 @@ Relay слушает выделенный IP, чтобы порт 443 не ко
|
||||
|
||||
### Обновление
|
||||
|
||||
Скачайте `compose.yaml` нового релиза поверх старого и повторите запуск:
|
||||
Когда выходит новый релиз, администратор установки видит баннер в интерфейсе и обновляется одной кнопкой; то же есть в **Настройки → Платформа → Обновления**. Установка идёт на сервере сама: скачивается `compose.yaml` релиза, загружаются образы, сервисы перезапускаются, приложение недоступно около минуты.
|
||||
|
||||
Вручную, из консоли сервера: скачайте `compose.yaml` нового релиза поверх старого и повторите запуск:
|
||||
|
||||
```bash
|
||||
docker compose pull && docker compose up -d --wait
|
||||
@@ -190,7 +192,7 @@ Telegram, MAX, электронная почта и чат на сайте по
|
||||
|
||||
### Свой сервер и своя ИИ-модель
|
||||
|
||||
Ставится одной командой, данные остаются у вас. Подключаете любого провайдера ИИ-моделей по своему ключу: OpenRouter, OpenAI-совместимый сервис, локальная модель. Дневной бюджет на агента в долларах, учёт токенов и стоимости по каждому вызову.
|
||||
Ставится одной командой, данные остаются у вас. Подключаете любого провайдера ИИ-моделей по своему ключу: OpenRouter, OpenAI-совместимый сервис, локальная модель.
|
||||
|
||||
### Защита данных клиентов
|
||||
|
||||
@@ -242,8 +244,7 @@ docker compose logs gateway
|
||||
1. Агент в статусе **Активен**, а не **Черновик**.
|
||||
2. У агента выбран провайдер ИИ-моделей. Без него ответ невозможен.
|
||||
3. Провайдер в **Интеграциях** имеет статус **Подключено**. Нажмите проверку, чтобы обновить статус.
|
||||
4. Не исчерпан дневной бюджет агента. Заблокированные вызовы видны в учёте ИИ.
|
||||
5. Диалог не переведён в режим **Оператор** или **Пауза**.
|
||||
4. Диалог не переведён в режим **Оператор** или **Пауза**.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
@@ -6,6 +6,11 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Версия релиза попадает в образ при сборке: по ней приложение решает,
|
||||
# есть ли обновление. Сборка из исходников остаётся «dev».
|
||||
ARG CHATBALLS_VERSION=dev
|
||||
ENV CHATBALLS_VERSION=${CHATBALLS_VERSION}
|
||||
|
||||
RUN addgroup --system hub && adduser --system --ingroup hub hub
|
||||
|
||||
COPY apps/backend/requirements.txt /app/apps/backend/requirements.txt
|
||||
|
||||
@@ -128,7 +128,6 @@ def agent_card_payload(channel: Channel, *, knowledge_total: int | None = None)
|
||||
"model": agent.model,
|
||||
"providerIntegrationId": agent.provider_integration_id,
|
||||
"modelParams": agent.model_params,
|
||||
"limits": agent.limits,
|
||||
"answerLanguage": agent.answer_language,
|
||||
"persona": agent.persona,
|
||||
"tone": agent.tone,
|
||||
@@ -232,7 +231,6 @@ def update_agent_card(
|
||||
ai_fields = {
|
||||
"providerIntegrationId",
|
||||
"modelParams",
|
||||
"limits",
|
||||
"persona",
|
||||
"tone",
|
||||
"instructions",
|
||||
@@ -249,11 +247,8 @@ def update_agent_card(
|
||||
):
|
||||
raise ValidationError({"knowledgeIds": t("api.list_of_ids_required")})
|
||||
model_params = body.get("modelParams", agent.model_params)
|
||||
limits = body.get("limits", agent.limits)
|
||||
if not isinstance(model_params, dict):
|
||||
raise ValidationError({"modelParams": t("api.object_required")})
|
||||
if not isinstance(limits, dict):
|
||||
raise ValidationError({"limits": t("api.object_required")})
|
||||
provider_integration_id = body.get(
|
||||
"providerIntegrationId", agent.provider_integration_id
|
||||
)
|
||||
@@ -270,7 +265,6 @@ def update_agent_card(
|
||||
provider_integration_id=provider_integration_id,
|
||||
model_params=model_params,
|
||||
allowed_tools=agent.allowed_tools,
|
||||
limits=limits,
|
||||
persona=str(body.get("persona", agent.persona)),
|
||||
tone=str(body.get("tone", agent.tone)),
|
||||
instructions=str(body.get("instructions", agent.instructions)),
|
||||
|
||||
@@ -2,7 +2,6 @@ import time
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from chatballs.ai import limits, pricing
|
||||
from chatballs.ai.models import LlmInvocation, LlmInvocationStatus
|
||||
from chatballs.ai.pii import redact
|
||||
from chatballs.ai.provider import routing
|
||||
@@ -19,18 +18,6 @@ from chatballs.ai.provider.resilience import CircuitBreaker, call_with_resilienc
|
||||
_breaker = CircuitBreaker()
|
||||
|
||||
|
||||
def _record_blocked(*, channel, purpose: str, model: str, error: Exception) -> None:
|
||||
LlmInvocation.objects.create(
|
||||
organization=channel.organization,
|
||||
channel=channel,
|
||||
purpose=purpose,
|
||||
operation="chat",
|
||||
model=model,
|
||||
status=LlmInvocationStatus.BLOCKED,
|
||||
error=str(error),
|
||||
)
|
||||
|
||||
|
||||
def _prepare_invocation(*, channel, requested_model: str | None) -> tuple[LLMProvider, str]:
|
||||
# BYOK — единственный режим (ADR-CHATBALLS-0042 §3): модель берётся из интеграции
|
||||
# организации с fallback на модель агента. Без интеграции модель остаётся
|
||||
@@ -52,18 +39,7 @@ def invoke_chat(
|
||||
params: dict | None = None,
|
||||
used_fragment_ids: list | None = None,
|
||||
) -> ChatResult:
|
||||
fallback_model = model or channel.ai_agent.model
|
||||
try:
|
||||
provider, model = _prepare_invocation(channel=channel, requested_model=model)
|
||||
limits.assert_within_limits(channel, channel.ai_agent)
|
||||
except limits.LimitExceeded as error:
|
||||
_record_blocked(
|
||||
channel=channel,
|
||||
purpose=purpose,
|
||||
model=fallback_model,
|
||||
error=error,
|
||||
)
|
||||
raise
|
||||
provider, model = _prepare_invocation(channel=channel, requested_model=model)
|
||||
|
||||
safe_messages = [ChatMessage(role=item.role, content=redact(item.content)) for item in messages]
|
||||
started = time.monotonic()
|
||||
@@ -96,8 +72,6 @@ def invoke_chat(
|
||||
prompt_tokens=result.prompt_tokens,
|
||||
completion_tokens=result.completion_tokens,
|
||||
total_tokens=result.total_tokens,
|
||||
cost_micros=result.cost_micros
|
||||
or pricing.cost_micros(result.model, result.prompt_tokens, result.completion_tokens),
|
||||
latency_ms=int((time.monotonic() - started) * 1000),
|
||||
status=LlmInvocationStatus.SUCCESS,
|
||||
used_fragment_ids=used_fragment_ids or [],
|
||||
@@ -128,7 +102,6 @@ def embed_texts(
|
||||
model=model,
|
||||
prompt_tokens=tokens,
|
||||
total_tokens=tokens,
|
||||
cost_micros=pricing.cost_micros(model, tokens, 0),
|
||||
status=LlmInvocationStatus.SUCCESS,
|
||||
)
|
||||
return results
|
||||
@@ -1,32 +0,0 @@
|
||||
from django.conf import settings
|
||||
from django.db.models import Sum
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.ai.models import LlmInvocation, LlmInvocationStatus
|
||||
|
||||
|
||||
class LimitExceeded(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _day_start():
|
||||
now = timezone.localtime()
|
||||
return now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
|
||||
def daily_cost_micros(channel=None) -> int:
|
||||
queryset = LlmInvocation.objects.filter(created_at__gte=_day_start(), status=LlmInvocationStatus.SUCCESS)
|
||||
if channel is not None:
|
||||
queryset = queryset.filter(channel=channel)
|
||||
return queryset.aggregate(total=Sum("cost_micros"))["total"] or 0
|
||||
|
||||
|
||||
def assert_within_limits(channel, agent) -> None:
|
||||
global_limit = settings.CHATBALLS_AI_GLOBAL_DAILY_COST_LIMIT_MICROS
|
||||
if global_limit and daily_cost_micros() >= global_limit:
|
||||
raise LimitExceeded("Global daily AI cost limit reached")
|
||||
# Канальный лимит хранится в целых центах USD (dailyCostUsd); расход учитывается
|
||||
# в micro-USD. 1 цент = 10 000 micro-USD.
|
||||
channel_limit = (agent.limits or {}).get("dailyCostUsd")
|
||||
if channel_limit and daily_cost_micros(channel) >= int(channel_limit) * 10_000:
|
||||
raise LimitExceeded("Channel daily AI cost limit reached")
|
||||
@@ -0,0 +1,18 @@
|
||||
# Дневной бюджет агента снят вместе с полем `limits`: расход считался по
|
||||
# прайс-таблице из двух моделей, а для всех остальных оставался нулевым — лимит
|
||||
# не срабатывал никогда. Единственный оставшийся предохранитель — общий лимит
|
||||
# установки из переменной окружения (CHATBALLS_AI_GLOBAL_DAILY_COST_LIMIT_MICROS).
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("ai", "0017_agent_answer_language"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name="aiagent",
|
||||
name="limits",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,34 @@
|
||||
# Учёт стоимости вызовов удалён вместе с лимитами. Считать было нечем: цена
|
||||
# бралась из ответа провайдера, а его присылает только OpenRouter; на остальных
|
||||
# оставалась прайс-таблица из двух моделей и ноль для всех прочих. Ни одна
|
||||
# цифра расхода в продукте не показывалась.
|
||||
#
|
||||
# Статус BLOCKED уходит вместе с лимитами — блокировать вызовы больше нечему.
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def drop_blocked_rows(apps, schema_editor):
|
||||
"""Строк со снятым статусом в журнале остаться не должно."""
|
||||
|
||||
apps.get_model("ai", "LlmInvocation").objects.filter(status="BLOCKED").delete()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("ai", "0018_remove_agent_limits"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(drop_blocked_rows, migrations.RunPython.noop),
|
||||
migrations.RemoveField(model_name="llminvocation", name="cost_micros"),
|
||||
migrations.RemoveField(model_name="llminvocation", name="currency"),
|
||||
migrations.AlterField(
|
||||
model_name="llminvocation",
|
||||
name="status",
|
||||
field=models.CharField(
|
||||
choices=[("SUCCESS", "Успех"), ("ERROR", "Ошибка")],
|
||||
default="SUCCESS",
|
||||
max_length=16,
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -417,10 +417,6 @@ class AIAgent(TenantRelationModel):
|
||||
|
||||
allowed_tools = models.JSONField(default=list, blank=True)
|
||||
|
||||
# Единственный поддерживаемый лимит — дневной бюджет dailyCostUsd (центы USD).
|
||||
|
||||
limits = models.JSONField(default=dict, blank=True)
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
@@ -463,8 +459,6 @@ class LlmInvocationStatus(models.TextChoices):
|
||||
|
||||
ERROR = "ERROR", "Ошибка"
|
||||
|
||||
BLOCKED = "BLOCKED", "Заблокировано лимитом"
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -489,10 +483,6 @@ class LlmInvocation(TenantRelationModel):
|
||||
|
||||
total_tokens = models.PositiveIntegerField(default=0)
|
||||
|
||||
cost_micros = models.PositiveBigIntegerField(default=0)
|
||||
|
||||
currency = models.CharField(max_length=3, default="USD")
|
||||
|
||||
latency_ms = models.PositiveIntegerField(default=0)
|
||||
|
||||
status = models.CharField(max_length=16, choices=LlmInvocationStatus.choices, default=LlmInvocationStatus.SUCCESS)
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
from django.conf import settings
|
||||
|
||||
# micro-USD за токен (1 USD = 1_000_000 micro); значение = цена в USD за 1M токенов.
|
||||
# Fallback на случай, если провайдер не вернул фактическую стоимость (usage.cost).
|
||||
# Реальные/уточнённые цены задаются через CHATBALLS_AI_PRICING.
|
||||
DEFAULT_PRICING = {
|
||||
"openai/gpt-4o-mini": {"prompt": 0.15, "completion": 0.60},
|
||||
"anthropic/claude-sonnet-4.6": {"prompt": 3.0, "completion": 15.0},
|
||||
}
|
||||
|
||||
|
||||
def cost_micros(model: str, prompt_tokens: int, completion_tokens: int) -> int:
|
||||
table = {**DEFAULT_PRICING, **getattr(settings, "CHATBALLS_AI_PRICING", {})}
|
||||
price = table.get(model)
|
||||
if not price:
|
||||
return 0
|
||||
return round(prompt_tokens * price["prompt"] + completion_tokens * price["completion"])
|
||||
@@ -18,9 +18,6 @@ class ChatResult:
|
||||
model: str
|
||||
prompt_tokens: int
|
||||
completion_tokens: int
|
||||
# Фактическая стоимость, сообщённая провайдером (micro-USD). 0 — провайдер не
|
||||
# вернул цену, тогда считаем по прайс-таблице (ai/pricing.py).
|
||||
cost_micros: int = 0
|
||||
|
||||
@property
|
||||
def total_tokens(self) -> int:
|
||||
|
||||
@@ -12,7 +12,7 @@ speak the same Chat Completions shape:
|
||||
|
||||
- POST /chat/completions with {model, messages, ...}; response has
|
||||
|
||||
choices[0].message.content and usage (optionally usage.cost in USD).
|
||||
choices[0].message.content and usage (prompt/completion tokens).
|
||||
|
||||
- POST /embeddings with {model, input}; response has data[].embedding and usage.
|
||||
|
||||
@@ -24,7 +24,7 @@ This module owns the HTTP transport and response parsing so the three adapters
|
||||
|
||||
do not duplicate it. Adapters stay responsible for their own product semantics
|
||||
|
||||
(name, cost handling, catalog). Stdlib only — no third-party HTTP client.
|
||||
(name, catalog). Stdlib only — no third-party HTTP client.
|
||||
|
||||
"""
|
||||
|
||||
@@ -116,21 +116,9 @@ def get_json(*, base_url: str, path: str, api_key: str, timeout: float, proxy_ur
|
||||
|
||||
def chat_completions(*, base_url: str, api_key: str, messages: list[ChatMessage], model: str,
|
||||
|
||||
timeout: float, proxy_url: str = "", params: dict | None = None,
|
||||
timeout: float, proxy_url: str = "", params: dict | None = None) -> ChatResult:
|
||||
|
||||
include_cost: bool = False) -> ChatResult:
|
||||
|
||||
"""POST /chat/completions and parse the OpenAI-shaped response.
|
||||
|
||||
|
||||
|
||||
`include_cost=True` requests the OpenRouter-style usage.include flag and reads
|
||||
|
||||
usage.cost (USD, converted to micros). Providers that do not report cost
|
||||
|
||||
(Custom, CustoAI) leave cost_micros=0; ai/pricing.py computes a fallback.
|
||||
|
||||
"""
|
||||
"""POST /chat/completions and parse the OpenAI-shaped response."""
|
||||
|
||||
payload: dict = {
|
||||
|
||||
@@ -142,10 +130,6 @@ def chat_completions(*, base_url: str, api_key: str, messages: list[ChatMessage]
|
||||
|
||||
}
|
||||
|
||||
if include_cost:
|
||||
|
||||
payload["usage"] = {"include": True}
|
||||
|
||||
data = post_json(base_url=base_url, path="/chat/completions", api_key=api_key,
|
||||
|
||||
payload=payload, timeout=timeout, proxy_url=proxy_url)
|
||||
@@ -160,8 +144,6 @@ def chat_completions(*, base_url: str, api_key: str, messages: list[ChatMessage]
|
||||
|
||||
usage = data.get("usage") or {}
|
||||
|
||||
cost = usage.get("cost")
|
||||
|
||||
return ChatResult(
|
||||
|
||||
text=text,
|
||||
@@ -172,8 +154,6 @@ def chat_completions(*, base_url: str, api_key: str, messages: list[ChatMessage]
|
||||
|
||||
completion_tokens=int(usage.get("completion_tokens", 0)),
|
||||
|
||||
cost_micros=round(float(cost) * 1_000_000) if cost is not None else 0,
|
||||
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -22,10 +22,9 @@ class OpenRouterProvider(LLMProvider):
|
||||
self.proxy_url = proxy_url or ""
|
||||
|
||||
def chat(self, *, messages: list[ChatMessage], model: str, params: dict | None = None) -> ChatResult:
|
||||
# usage.include=true — OpenRouter возвращает фактическую стоимость в usage.cost (USD).
|
||||
return openai_http.chat_completions(
|
||||
base_url=self.base_url, api_key=self.api_key, messages=messages, model=model,
|
||||
timeout=self.timeout, proxy_url=self.proxy_url, params=params, include_cost=True,
|
||||
timeout=self.timeout, proxy_url=self.proxy_url, params=params,
|
||||
)
|
||||
|
||||
def embed(self, *, texts: list[str], model: str) -> list[EmbeddingResult]:
|
||||
|
||||
@@ -21,7 +21,6 @@ class AgentInput:
|
||||
provider_integration_id: int | None
|
||||
model_params: dict
|
||||
allowed_tools: list
|
||||
limits: dict
|
||||
persona: str
|
||||
tone: str
|
||||
instructions: str
|
||||
@@ -39,20 +38,6 @@ class AgentCreateInput:
|
||||
knowledge_ids: list[int]
|
||||
|
||||
|
||||
# Единственный поддерживаемый лимит агента — дневной бюджет в целых центах USD
|
||||
# (dailyCostUsd). Прочие исторические ключи (dailyCostMicros, dailyBudgetRub,
|
||||
# dailyDialogs, maxMessagesPerDialog) бэкендом не используются и отбрасываются.
|
||||
def _normalize_limits(raw: dict | None) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
value = raw.get("dailyCostUsd")
|
||||
try:
|
||||
cents = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
return {"dailyCostUsd": cents} if cents > 0 else {}
|
||||
|
||||
|
||||
def knowledge_for_agent_ids(
|
||||
*, context: TenantContext, channel: Channel, knowledge_ids: list[int]
|
||||
) -> list[Knowledge]:
|
||||
@@ -146,7 +131,6 @@ def update_agent(*, context: TenantContext, agent: AIAgent, data: AgentInput) ->
|
||||
locked.provider_integration = selection.integration
|
||||
locked.model_params = data.model_params
|
||||
locked.allowed_tools = data.allowed_tools
|
||||
locked.limits = _normalize_limits(data.limits)
|
||||
locked.persona = data.persona
|
||||
locked.tone = data.tone
|
||||
locked.instructions = data.instructions
|
||||
@@ -158,7 +142,6 @@ def update_agent(*, context: TenantContext, agent: AIAgent, data: AgentInput) ->
|
||||
"provider_integration",
|
||||
"model_params",
|
||||
"allowed_tools",
|
||||
"limits",
|
||||
"persona",
|
||||
"tone",
|
||||
"instructions",
|
||||
|
||||
@@ -343,15 +343,6 @@ class ChatInvocationTests(TestCase):
|
||||
invocation = LlmInvocation.objects.get(channel=self.channel, operation="chat")
|
||||
self.assertEqual(invocation.status, LlmInvocationStatus.SUCCESS)
|
||||
self.assertGreater(invocation.total_tokens, 0)
|
||||
# Технический учёт стоимости (ADR-CHATBALLS-0042 §2): считается по прайсу модели.
|
||||
from chatballs.ai import pricing
|
||||
|
||||
self.assertEqual(
|
||||
invocation.cost_micros,
|
||||
pricing.cost_micros(
|
||||
invocation.model, invocation.prompt_tokens, invocation.completion_tokens
|
||||
),
|
||||
)
|
||||
|
||||
def test_pii_is_redacted_before_reaching_provider(self) -> None:
|
||||
from unittest import mock
|
||||
@@ -378,24 +369,6 @@ class ChatInvocationTests(TestCase):
|
||||
|
||||
self.assertNotIn("a@b.com", captured["messages"][0].content)
|
||||
|
||||
def test_limit_blocks_and_records(self) -> None:
|
||||
from chatballs.ai import limits as ai_limits
|
||||
from chatballs.ai.invocation import invoke_chat
|
||||
from chatballs.ai.models import LlmInvocation, LlmInvocationStatus
|
||||
from chatballs.ai.provider.base import ChatMessage
|
||||
|
||||
self.agent.limits = {"dailyCostUsd": 1}
|
||||
self.agent.save(update_fields=["limits"])
|
||||
# 1 цент = 10 000 micro-USD; лимит превышен расходом в 10_001 micros.
|
||||
LlmInvocation.objects.create(
|
||||
channel=self.channel, purpose="seed", operation="chat", model="x", cost_micros=10_001,
|
||||
status=LlmInvocationStatus.SUCCESS,
|
||||
)
|
||||
|
||||
with self.assertRaises(ai_limits.LimitExceeded):
|
||||
invoke_chat(channel=self.channel, messages=[ChatMessage(role="user", content="hi")], purpose="agent_chat")
|
||||
self.assertTrue(LlmInvocation.objects.filter(channel=self.channel, status=LlmInvocationStatus.BLOCKED).exists())
|
||||
|
||||
def test_invocation_records_used_fragment_ids(self) -> None:
|
||||
from chatballs.ai.invocation import invoke_chat
|
||||
from chatballs.ai.models import LlmInvocation
|
||||
|
||||
@@ -22,6 +22,7 @@ from chatballs.conversations.models import (
|
||||
LifecycleState,
|
||||
ReplyTemplate,
|
||||
)
|
||||
from chatballs.conversations.queue_models import policy_for
|
||||
from chatballs.conversations.selectors import apply_conversation_visibility
|
||||
from chatballs.conversations.serializers import conversation_payload
|
||||
from chatballs.conversations.view_base import ConversationViewBase
|
||||
@@ -30,6 +31,7 @@ from chatballs.identity.avatars import user_avatar_url
|
||||
from chatballs.identity.group_models import EmployeeGroup
|
||||
from chatballs.identity.models import HumanUser, OrganizationMembership
|
||||
from chatballs.identity.policy import can_administer_access
|
||||
from chatballs.presence import ONLINE_WITHIN_SECONDS, last_seen
|
||||
|
||||
|
||||
def _label_payload(label: ConversationLabel) -> dict[str, object]:
|
||||
@@ -258,10 +260,21 @@ class ConversationCountersView(ConversationViewBase):
|
||||
}
|
||||
for assignee in assignees:
|
||||
assignee["avatarUrl"] = user_avatar_url(avatars.get(assignee["id"]), request.tenant_context.organization.public_id)
|
||||
# Два разных ожидания (макет Q3): диалог ничей — взять может любой;
|
||||
# диалог назначен лично на меня и ждёт, пока я его возьму. Смешивать их
|
||||
# в одном счётчике значит прятать своё среди чужого.
|
||||
waiting_qs = open_qs.filter(control_mode=ControlMode.PAUSED)
|
||||
return Response(
|
||||
{
|
||||
"all": open_qs.count(),
|
||||
"waiting": open_qs.filter(control_mode=ControlMode.PAUSED).count(),
|
||||
"waiting": waiting_qs.count(),
|
||||
"queue": waiting_qs.filter(assigned_operator__isnull=True).count(),
|
||||
"waitingOnMe": waiting_qs.filter(assigned_operator_id=request.user.id).count(),
|
||||
# Срок личной очереди: по нему клиент считает, через сколько
|
||||
# диалог вернётся всем.
|
||||
"assignmentTimeoutMinutes": policy_for(
|
||||
request.tenant_context.organization
|
||||
).assignment_timeout_minutes,
|
||||
"mine": base.filter(assigned_operator_id=request.user.id).count(),
|
||||
"ungrouped": ungrouped,
|
||||
"groups": groups,
|
||||
@@ -301,6 +314,22 @@ class ConversationDirectoryView(APIView):
|
||||
# Ответственного можно назначить и вне выдачи — по поиску, поэтому
|
||||
# оставшихся не прячем молча, а сообщаем признаком hasMore.
|
||||
rows = list(members[: DIRECTORY_LIMIT + 1])
|
||||
shown = rows[:DIRECTORY_LIMIT]
|
||||
# Присутствие и загрузка — второй и третий признак при выборе
|
||||
# ответственного (макет «Очередь и уведомления», кадр Q5). Назначить
|
||||
# отсутствующего можно: признак приблизительный и ничего не запрещает.
|
||||
user_ids = [member.user_id for member in shown]
|
||||
seen = last_seen(organization_id, user_ids)
|
||||
now = timezone.now()
|
||||
load = dict(
|
||||
Conversation.objects.filter(
|
||||
organization_id=organization_id,
|
||||
lifecycle=LifecycleState.OPEN,
|
||||
assigned_operator_id__in=user_ids,
|
||||
)
|
||||
.values_list("assigned_operator_id")
|
||||
.annotate(total=Count("id"))
|
||||
)
|
||||
return Response(
|
||||
{
|
||||
"groups": [{"id": group.id, "name": group.name, "color": group.color} for group in groups],
|
||||
@@ -309,8 +338,15 @@ class ConversationDirectoryView(APIView):
|
||||
"id": member.user_id,
|
||||
"name": member.user.full_name or member.user.email,
|
||||
"avatarUrl": user_avatar_url(member.user, request.tenant_context.organization.public_id),
|
||||
"role": member.role,
|
||||
"online": member.user_id in seen
|
||||
and (now - seen[member.user_id]).total_seconds() <= ONLINE_WITHIN_SECONDS,
|
||||
"lastSeenAt": (
|
||||
seen[member.user_id].isoformat() if member.user_id in seen else None
|
||||
),
|
||||
"openDialogs": load.get(member.user_id, 0),
|
||||
}
|
||||
for member in rows[:DIRECTORY_LIMIT]
|
||||
for member in shown
|
||||
],
|
||||
"hasMoreEmployees": len(rows) > DIRECTORY_LIMIT,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
"""WebSocket оповещений о диалогах (см. chatballs.conversations.realtime).
|
||||
"""WebSocket оповещений рабочего места (см. chatballs.conversations.realtime и
|
||||
chatballs.notifications.realtime).
|
||||
|
||||
Сокет один на сессию: по нему идут и события диалогов, и события уведомлений.
|
||||
Второй сокет ради второго источника означал бы второе переподключение, вторую
|
||||
аутентификацию и вторую точку отказа на ровном месте.
|
||||
|
||||
Правила:
|
||||
- аутентификация — сессией того же SPA (AuthMiddlewareStack), отдельного токена
|
||||
@@ -23,6 +28,8 @@ from chatballs.conversations.models import Conversation
|
||||
from chatballs.conversations.realtime import conversation_group, inbox_group
|
||||
from chatballs.conversations.selectors import conversation_is_visible
|
||||
from chatballs.identity.models import OrganizationMembership
|
||||
from chatballs.notifications.realtime import user_group
|
||||
from chatballs.presence import touch
|
||||
from chatballs.tenancy.database import tenant_atomic
|
||||
from chatballs.tenancy.lookup import organization_by_public_id
|
||||
|
||||
@@ -36,6 +43,8 @@ class ConversationEventsConsumer(AsyncJsonWebsocketConsumer):
|
||||
self.organization_id: int | None = None
|
||||
self.membership_id: int | None = None
|
||||
self.watched: str | None = None
|
||||
self.personal: str | None = None
|
||||
self.user_id: int | None = None
|
||||
user = self.scope.get("user")
|
||||
if user is None or not user.is_authenticated:
|
||||
await self.close(code=NOT_A_MEMBER_CLOSE)
|
||||
@@ -46,20 +55,42 @@ class ConversationEventsConsumer(AsyncJsonWebsocketConsumer):
|
||||
await self.close(code=NOT_A_MEMBER_CLOSE)
|
||||
return
|
||||
self.organization_id, self.membership_id = resolved
|
||||
self.user_id = user.id
|
||||
# Открытый сокет и есть присутствие: ничего специально «включать» для
|
||||
# этого сотрудник не должен (chatballs.presence).
|
||||
await self._touch_presence()
|
||||
await self.channel_layer.group_add(inbox_group(self.organization_id), self.channel_name)
|
||||
# Уведомления адресованы человеку, а не организации: у каждого своя группа.
|
||||
self.personal = user_group(user.id)
|
||||
await self.channel_layer.group_add(self.personal, self.channel_name)
|
||||
await self.accept()
|
||||
|
||||
async def disconnect(self, code: int) -> None:
|
||||
if self.organization_id is not None and self.user_id is not None:
|
||||
# Не «его нет», а «здесь он был в последний раз».
|
||||
await database_sync_to_async(touch)(self.organization_id, self.user_id)
|
||||
if self.organization_id is not None:
|
||||
await self.channel_layer.group_discard(
|
||||
inbox_group(self.organization_id), self.channel_name
|
||||
)
|
||||
if self.personal is not None:
|
||||
await self.channel_layer.group_discard(self.personal, self.channel_name)
|
||||
if self.watched is not None:
|
||||
await self.channel_layer.group_discard(self.watched, self.channel_name)
|
||||
|
||||
async def receive_json(self, content: dict, **kwargs) -> None:
|
||||
"""Клиент сообщает, какой диалог открыт: событий по нему он и ждёт."""
|
||||
if content.get("type") != "watch" or self.organization_id is None:
|
||||
"""Клиент сообщает, какой диалог открыт: событий по нему он и ждёт.
|
||||
|
||||
Он же раз в минуту присылает heartbeat — по нему продлевается отметка
|
||||
присутствия. Без неё ключ истекает сам, и оборванное соединение
|
||||
перестаёт считаться живым без отдельного уборщика.
|
||||
"""
|
||||
if self.organization_id is None:
|
||||
return
|
||||
if content.get("type") == "ping":
|
||||
await self._touch_presence()
|
||||
return
|
||||
if content.get("type") != "watch":
|
||||
return
|
||||
conversation_id = content.get("conversationId")
|
||||
if self.watched is not None:
|
||||
@@ -80,6 +111,11 @@ class ConversationEventsConsumer(AsyncJsonWebsocketConsumer):
|
||||
async def fanout(self, event: dict) -> None:
|
||||
await self.send_json(event["payload"])
|
||||
|
||||
async def _touch_presence(self) -> None:
|
||||
if self.organization_id is None or self.user_id is None:
|
||||
return
|
||||
await database_sync_to_async(touch)(self.organization_id, self.user_id)
|
||||
|
||||
@database_sync_to_async
|
||||
def _membership(self, user_id: int, raw_public_id: str) -> tuple[int, int] | None:
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Что происходит, когда диалог ждёт слишком долго.
|
||||
|
||||
Раньше не происходило ничего. Про ждущий диалог операторов окликали ровно один
|
||||
раз, и дальше `dedup_key` на сутки гарантировал тишину: если в тот момент никто
|
||||
не смотрел на экран, диалог мог провисеть до автозакрытия, и узнать об этом было
|
||||
неоткуда.
|
||||
|
||||
Уровень выбирается по времени ожидания, а не по счётчику попыток: состояние
|
||||
хранить не нужно, потому что повтор гасит тот же `dedup_key` — свой у каждого
|
||||
уровня. Свип идеемпотентен и может выполняться сколь угодно часто.
|
||||
|
||||
Назначенный диалог не эскалируется: он не в общей очереди, а в личной, и у неё
|
||||
свой срок — не взял, значит возвращаем всем.
|
||||
|
||||
Присутствие сокращает ожидание, но не заменяет его. Если в группе диалога сейчас
|
||||
никого нет за рабочим местом, ждать второго порога бессмысленно: напоминать
|
||||
некому, и круг расширяется сразу. Обратного правила нет — присутствие никого не
|
||||
задерживает и ничего не запрещает, потому что ошибается в обе стороны.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.conversations.models import (
|
||||
ControlMode,
|
||||
Conversation,
|
||||
LifecycleState,
|
||||
Message,
|
||||
MessageAuthor,
|
||||
SystemEvent,
|
||||
)
|
||||
from chatballs.conversations.queue_models import QueueEscalationPolicy, policy_for
|
||||
from chatballs.conversations.services import operator_label
|
||||
from chatballs.i18n import t
|
||||
from chatballs.notifications.models import (
|
||||
NotificationAudience,
|
||||
NotificationLevel,
|
||||
NotificationType,
|
||||
)
|
||||
from chatballs.notifications.recipients import audience_user_ids
|
||||
from chatballs.notifications.services import notify, notify_management
|
||||
from chatballs.presence import online_user_ids
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _contact_name(conversation: Conversation) -> str:
|
||||
return getattr(conversation.contact, "name", "") or t("conversations.guest")
|
||||
|
||||
|
||||
def _waiting_conversations(context: TenantContext):
|
||||
return Conversation.objects.filter(
|
||||
organization=context.organization,
|
||||
lifecycle=LifecycleState.OPEN,
|
||||
control_mode=ControlMode.PAUSED,
|
||||
waiting_since__isnull=False,
|
||||
).select_related("contact", "assigned_operator", "group")
|
||||
|
||||
|
||||
def sweep_waiting_conversations(context: TenantContext) -> int:
|
||||
"""Оклики по ждущим диалогам организации. Возвращает число новых уведомлений."""
|
||||
policy = policy_for(context.organization)
|
||||
now = timezone.now()
|
||||
fired = 0
|
||||
for conversation in _waiting_conversations(context):
|
||||
if conversation.assigned_operator_id:
|
||||
fired += _expire_stale_assignment(context, conversation, policy, now)
|
||||
else:
|
||||
fired += _escalate(context, conversation, policy, now)
|
||||
return fired
|
||||
|
||||
|
||||
def _nobody_is_watching(context: TenantContext, conversation: Conversation) -> bool:
|
||||
"""В группе диалога никого нет за рабочим местом."""
|
||||
watchers = audience_user_ids(
|
||||
organization_id=context.organization_id,
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
group_id=conversation.group_id,
|
||||
)
|
||||
return not online_user_ids(context.organization_id, watchers)
|
||||
|
||||
|
||||
def _escalate(
|
||||
context: TenantContext,
|
||||
conversation: Conversation,
|
||||
policy: QueueEscalationPolicy,
|
||||
now: datetime,
|
||||
) -> int:
|
||||
waited = now - conversation.waiting_since
|
||||
contact = _contact_name(conversation)
|
||||
common = {
|
||||
"context": context,
|
||||
"type": NotificationType.DIALOG_WAITING_LONG,
|
||||
"text_params": {"contact": contact},
|
||||
"target_id": conversation.id,
|
||||
"source_type": "Conversation",
|
||||
"source_id": conversation.id,
|
||||
}
|
||||
fired = 0
|
||||
if waited >= timedelta(minutes=policy.remind_after_minutes):
|
||||
# Тот же круг, что и в первый раз: смена на месте, просто не заметила.
|
||||
fired += notify(
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=conversation.group,
|
||||
level=NotificationLevel.WARNING,
|
||||
title=f"Диалог всё ещё ждёт · {contact}",
|
||||
title_key="notifications.still_waiting",
|
||||
body_key="notifications.still_waiting_body",
|
||||
dedup_key=f"waiting:{conversation.id}:remind",
|
||||
**common,
|
||||
) is not None
|
||||
widen_after = policy.widen_after_minutes
|
||||
if waited >= timedelta(minutes=policy.remind_after_minutes) and _nobody_is_watching(
|
||||
context, conversation
|
||||
):
|
||||
# Некому заметить напоминание — второй порог ждать незачем.
|
||||
widen_after = min(widen_after, policy.remind_after_minutes)
|
||||
if waited >= timedelta(minutes=widen_after):
|
||||
# Круг шире группы: в своей группе ответить некому.
|
||||
fired += notify(
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=None,
|
||||
level=NotificationLevel.WARNING,
|
||||
title=f"Диалог всё ещё ждёт · {contact}",
|
||||
title_key="notifications.still_waiting",
|
||||
body_key="notifications.still_waiting_body",
|
||||
dedup_key=f"waiting:{conversation.id}:widen",
|
||||
**common,
|
||||
) is not None
|
||||
if waited >= timedelta(minutes=policy.escalate_after_minutes):
|
||||
# Это уже не про сменщика, а про то, что смены нет.
|
||||
fired += notify_management(
|
||||
level=NotificationLevel.CRITICAL,
|
||||
title=f"Диалог никто не берёт · {contact}",
|
||||
title_key="notifications.waiting_unattended",
|
||||
body_key="notifications.waiting_unattended_body",
|
||||
dedup_key=f"waiting:{conversation.id}:management",
|
||||
**common,
|
||||
)
|
||||
return fired
|
||||
|
||||
|
||||
def _expire_stale_assignment(
|
||||
context: TenantContext,
|
||||
conversation: Conversation,
|
||||
policy: QueueEscalationPolicy,
|
||||
now: datetime,
|
||||
) -> int:
|
||||
if conversation.assigned_at is None:
|
||||
return 0
|
||||
if now - conversation.assigned_at < timedelta(minutes=policy.assignment_timeout_minutes):
|
||||
return 0
|
||||
label = operator_label(conversation.assigned_operator)
|
||||
conversation.assigned_operator = None
|
||||
conversation.assigned_at = None
|
||||
conversation.save(update_fields=["assigned_operator", "assigned_at"])
|
||||
Message.objects.create(
|
||||
conversation=conversation,
|
||||
author_type=MessageAuthor.SYSTEM,
|
||||
system_event=SystemEvent.ASSIGNMENT_EXPIRED,
|
||||
system_params={"operator": label},
|
||||
text=f"{label} не взял диалог — он вернулся в очередь",
|
||||
)
|
||||
logger.info("Assignment on conversation %s expired", conversation.id)
|
||||
contact = _contact_name(conversation)
|
||||
return notify(
|
||||
context=context,
|
||||
type=NotificationType.OPERATOR_REQUESTED,
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=conversation.group,
|
||||
level=NotificationLevel.WARNING,
|
||||
title=f"Диалог снова ничей · {contact}",
|
||||
title_key="notifications.assignment_expired",
|
||||
text_params={"contact": contact, "operator": label},
|
||||
target_id=conversation.id,
|
||||
source_type="Conversation",
|
||||
source_id=conversation.id,
|
||||
dedup_key=f"unassigned:{conversation.id}:{conversation.waiting_since.isoformat()}",
|
||||
) is not None
|
||||
@@ -13,7 +13,6 @@ from dataclasses import dataclass
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.ai.limits import LimitExceeded
|
||||
from chatballs.ai.provider.base import ProviderError
|
||||
from chatballs.ai.runtime import HANDOFF_TOKEN
|
||||
from chatballs.channels.runtime import run_channel_turn
|
||||
@@ -31,6 +30,7 @@ from chatballs.conversations.models import (
|
||||
SystemEvent,
|
||||
TranscriptStatus,
|
||||
)
|
||||
from chatballs.conversations.queue import QUEUE_FIELDS, enter_queue, is_waiting
|
||||
from chatballs.conversations.transports.base import InboundMessage
|
||||
from chatballs.events.models import EventOwnership, InboxEvent
|
||||
from chatballs.i18n import t
|
||||
@@ -250,6 +250,7 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
external_chat_id=inbound.chat_id,
|
||||
control_mode=ControlMode.AI if ai_available else ControlMode.PAUSED,
|
||||
expected_responder=ExpectedResponder.AI if ai_available else ExpectedResponder.OPERATOR,
|
||||
waiting_since=None if ai_available else timezone.now(),
|
||||
previous_conversation=previous,
|
||||
)
|
||||
elif inbound.chat_id and not conversation.external_chat_id:
|
||||
@@ -283,9 +284,8 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
conversation.last_activity_at = timezone.now()
|
||||
update_fields = ["external_chat_id", "last_activity_at"]
|
||||
if conversation.control_mode == ControlMode.AI and not ai_available:
|
||||
conversation.control_mode = ControlMode.PAUSED
|
||||
conversation.expected_responder = ExpectedResponder.OPERATOR
|
||||
update_fields.extend(["control_mode", "expected_responder"])
|
||||
enter_queue(conversation)
|
||||
update_fields.extend(QUEUE_FIELDS)
|
||||
if inbound.thread_meta:
|
||||
# Email: Message-ID последнего входящего — для ответа в тред;
|
||||
# тема диалога фиксируется по первому письму (ADR-CHATBALLS-0035).
|
||||
@@ -299,10 +299,18 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
conversation.save(update_fields=update_fields)
|
||||
|
||||
if is_new:
|
||||
# Диалог, которым занялся агент, — это «новый диалог» и больше ничего.
|
||||
# Диалог, отвечать в котором некому, — уже просьба о человеке: событие
|
||||
# одно, а смысл для смены разный, и подписки на них тоже разные.
|
||||
notify(
|
||||
context=context,
|
||||
type=NotificationType.DIALOG_WAITING,
|
||||
type=(
|
||||
NotificationType.OPERATOR_REQUESTED
|
||||
if is_waiting(conversation)
|
||||
else NotificationType.NEW_DIALOG
|
||||
),
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=conversation.group,
|
||||
title=f"Новый диалог · {channel.name}",
|
||||
body=f"{contact.name or 'Гость'} · {integration.provider}: {message_text[:80]}",
|
||||
title_key="notifications.new_dialog",
|
||||
@@ -325,6 +333,7 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
context=context,
|
||||
type=NotificationType.DIALOG_NEW_MESSAGE,
|
||||
audience=NotificationAudience.USER if operator else NotificationAudience.OPERATORS,
|
||||
audience_group=conversation.group,
|
||||
recipient_user=operator,
|
||||
title=f"Новое сообщение · {contact.name or 'Гость'}",
|
||||
body=message_text[:120],
|
||||
@@ -354,15 +363,15 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
ai_input = transcribe_voice_message(channel, message)
|
||||
if (is_voice and not ai_input) or files_only:
|
||||
if conversation.control_mode == ControlMode.AI:
|
||||
conversation.control_mode = ControlMode.PAUSED
|
||||
conversation.expected_responder = ExpectedResponder.OPERATOR
|
||||
conversation.save(update_fields=["control_mode", "expected_responder"])
|
||||
enter_queue(conversation)
|
||||
conversation.save(update_fields=QUEUE_FIELDS)
|
||||
if is_new:
|
||||
return
|
||||
notify(
|
||||
context=context,
|
||||
type=NotificationType.DIALOG_WAITING,
|
||||
type=NotificationType.OPERATOR_REQUESTED,
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=conversation.group,
|
||||
title=f"Нужен оператор · {contact.name or 'Гость'}",
|
||||
title_key="notifications.operator_needed",
|
||||
text_params={"contact": contact.name or t("conversations.guest")},
|
||||
@@ -382,15 +391,13 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
|
||||
try:
|
||||
result = run_channel_turn(channel=channel, message=ai_input, history=_history(conversation))
|
||||
except (ProviderError, LimitExceeded) as error:
|
||||
# Сбой AI (провайдер недоступен) или срабатывание лимита стоимости не должны
|
||||
# «терять» сообщение: переводим диалог в очередь к оператору, уведомляем и
|
||||
# отвечаем клиенту понятным fallback.
|
||||
except ProviderError as error:
|
||||
# Сбой AI не должен «терять» сообщение: переводим диалог в очередь к
|
||||
# оператору, уведомляем и отвечаем клиенту понятным fallback.
|
||||
logger.warning("AI turn failed for conversation %s: %s", conversation.id, error)
|
||||
conversation.control_mode = ControlMode.PAUSED
|
||||
conversation.expected_responder = ExpectedResponder.OPERATOR
|
||||
enter_queue(conversation)
|
||||
conversation.last_activity_at = timezone.now()
|
||||
conversation.save(update_fields=["control_mode", "expected_responder", "last_activity_at"])
|
||||
conversation.save(update_fields=[*QUEUE_FIELDS, "last_activity_at"])
|
||||
Message.objects.create(
|
||||
conversation=conversation,
|
||||
author_type=MessageAuthor.SYSTEM,
|
||||
@@ -401,8 +408,9 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
Message.objects.create(conversation=conversation, author_type=MessageAuthor.AI, text=fallback)
|
||||
notify(
|
||||
context=context,
|
||||
type=NotificationType.DIALOG_WAITING,
|
||||
type=NotificationType.OPERATOR_REQUESTED,
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=conversation.group,
|
||||
title=f"Нужен оператор · {contact.name or 'Гость'}",
|
||||
title_key="notifications.operator_needed",
|
||||
text_params={"contact": contact.name or t("conversations.guest")},
|
||||
@@ -415,7 +423,7 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
)
|
||||
notify_management(
|
||||
context=context,
|
||||
type=NotificationType.INTEGRATION_ERROR,
|
||||
type=NotificationType.AI_STOPPED,
|
||||
title=f"Ошибка AI · {channel.name}",
|
||||
body="AI временно недоступен, диалог передан оператору",
|
||||
title_key="notifications.ai_error",
|
||||
@@ -437,11 +445,10 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
Message.objects.create(conversation=conversation, author_type=MessageAuthor.AI, text=reply)
|
||||
conversation.last_activity_at = timezone.now()
|
||||
if handoff:
|
||||
conversation.control_mode = ControlMode.PAUSED
|
||||
conversation.expected_responder = ExpectedResponder.OPERATOR
|
||||
enter_queue(conversation)
|
||||
else:
|
||||
conversation.expected_responder = ExpectedResponder.CUSTOMER
|
||||
conversation.save(update_fields=["control_mode", "last_activity_at", "expected_responder"])
|
||||
conversation.save(update_fields=[*QUEUE_FIELDS, "last_activity_at"])
|
||||
|
||||
if handoff:
|
||||
Message.objects.create(
|
||||
@@ -452,8 +459,9 @@ def ingest_inbound(integration, inbound: InboundMessage) -> None:
|
||||
)
|
||||
notify(
|
||||
context=context,
|
||||
type=NotificationType.DIALOG_WAITING,
|
||||
type=NotificationType.OPERATOR_REQUESTED,
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=conversation.group,
|
||||
title=f"AI передал диалог · {contact.name or 'Гость'}",
|
||||
title_key="notifications.ai_handed_over",
|
||||
text_params={"contact": contact.name or t("conversations.guest")},
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Время ожидания в очереди — отдельным полем.
|
||||
|
||||
Раньше «дольше всех ждущий» вычислялся по времени последнего сообщения, и
|
||||
очередь работала обратно смыслу: клиент, напомнивший о себе, двигал
|
||||
last_message_at вперёд и падал в конец очереди. Поле ставится один раз при входе
|
||||
в очередь (chatballs.conversations.queue) и снимается при выходе из неё.
|
||||
|
||||
Backfill берёт last_message_at — единственное, что известно про уже ждущие
|
||||
диалоги. Для них порядок не ухудшится: в старой сортировке ключ был тот же.
|
||||
"""
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
BACKFILL = """
|
||||
UPDATE conversations_conversation
|
||||
SET waiting_since = last_message_at
|
||||
WHERE lifecycle = 'OPEN' AND control_mode = 'PAUSED' AND waiting_since IS NULL
|
||||
"""
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('conversations', '0021_i18n_events'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='conversation',
|
||||
name='waiting_since',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.RunSQL(sql=BACKFILL, reverse_sql=migrations.RunSQL.noop),
|
||||
migrations.AddIndex(
|
||||
model_name='conversation',
|
||||
index=models.Index(
|
||||
fields=['organization', 'waiting_since'], name='conv_waiting_order'
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Личная очередь и пороги эскалации.
|
||||
|
||||
assigned_at нужен, чтобы у назначения был срок: waiting_since для этого не
|
||||
годится — назначить могут и через час после того, как диалог встал в очередь.
|
||||
Пороги — строка на организацию с дефолтами: «долго» у круглосуточной
|
||||
поддержки и у приёма по будням означает разное.
|
||||
"""
|
||||
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('conversations', '0022_conversation_waiting_since'),
|
||||
('identity', '0039_remove_organization_currency'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='conversation',
|
||||
name='assigned_at',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='message',
|
||||
name='system_event',
|
||||
field=models.CharField(blank=True, choices=[('operator_took', 'Оператор перехватил диалог'), ('returned_to_ai', 'Диалог возвращён AI'), ('returned_to_queue', 'Диалог возвращён в очередь'), ('ai_unavailable', 'AI недоступен'), ('ai_handed_over', 'AI передал диалог оператору'), ('assigned_to', 'Диалог назначен сотруднику'), ('assignment_expired', 'Назначение истекло'), ('call_requested', 'Запрошен звонок'), ('call_accepted', 'Клиент принял приглашение'), ('call_declined', 'Клиент отклонил приглашение'), ('call_cancelled', 'Приглашение отменено'), ('call_missed', 'Звонок пропущен'), ('call_expired', 'Приглашение истекло'), ('call_started', 'Звонок начался'), ('call_ended', 'Звонок завершён'), ('call_failed', 'Звонок не состоялся')], default='', max_length=32),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='QueueEscalationPolicy',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('remind_after_minutes', models.PositiveIntegerField(default=5)),
|
||||
('widen_after_minutes', models.PositiveIntegerField(default=15)),
|
||||
('escalate_after_minutes', models.PositiveIntegerField(default=30)),
|
||||
('assignment_timeout_minutes', models.PositiveIntegerField(default=10)),
|
||||
('organization', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='queue_policy', to='identity.organization')),
|
||||
],
|
||||
options={
|
||||
'db_table': 'conversations_queueescalationpolicy',
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,26 @@
|
||||
# Generated by Django 5.2.16 on 2026-09-13 19:15
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('conversations', '0023_queue_escalation'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='queueescalationpolicy',
|
||||
name='updated_at',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='queueescalationpolicy',
|
||||
name='updated_by',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL),
|
||||
),
|
||||
]
|
||||
@@ -166,6 +166,10 @@ class Conversation(models.Model):
|
||||
lifecycle = models.CharField(max_length=16, choices=LifecycleState.choices, default=LifecycleState.OPEN)
|
||||
control_mode = models.CharField(max_length=16, choices=ControlMode.choices, default=ControlMode.AI)
|
||||
expected_responder = models.CharField(max_length=16, choices=ExpectedResponder.choices, default=ExpectedResponder.AI)
|
||||
# С какого момента диалог ждёт человека (chatballs.conversations.queue).
|
||||
# Не «последнее сообщение»: клиент, написавший повторно, ждёт не меньше, а
|
||||
# больше прежнего, и в очереди обязан оставаться выше, а не ниже.
|
||||
waiting_since = models.DateTimeField(null=True, blank=True)
|
||||
# Группа видимости (ADR-CHATBALLS-0043): наследуется от group агента/канала при
|
||||
# создании, переносится вручную. NULL — диалог виден всем сотрудникам.
|
||||
group = models.ForeignKey(
|
||||
@@ -177,6 +181,9 @@ class Conversation(models.Model):
|
||||
)
|
||||
# «Ответственный» (ADR-CHATBALLS-0043): видит диалог независимо от групп.
|
||||
assigned_operator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="assigned_conversations")
|
||||
# Когда назначили. С этого момента идёт срок личной очереди: не взял —
|
||||
# диалог возвращается в общую (chatballs.conversations.escalation).
|
||||
assigned_at = models.DateTimeField(null=True, blank=True)
|
||||
# Дизайн-базлайн v2: приоритет, метки и заметка оператора.
|
||||
priority = models.CharField(
|
||||
max_length=8, choices=ConversationPriority.choices, default=ConversationPriority.NONE
|
||||
@@ -219,6 +226,10 @@ class Conversation(models.Model):
|
||||
models.Index(
|
||||
fields=["contact", "-last_activity_at"], name="conv_contact_recent"
|
||||
),
|
||||
# Очередь к оператору: кто ждёт дольше всех и не дождался порога.
|
||||
models.Index(
|
||||
fields=["organization", "waiting_since"], name="conv_waiting_order"
|
||||
),
|
||||
]
|
||||
constraints = [
|
||||
# Диалог всегда принадлежит контакту.
|
||||
@@ -274,6 +285,8 @@ class SystemEvent(models.TextChoices):
|
||||
RETURNED_TO_QUEUE = "returned_to_queue", "Диалог возвращён в очередь"
|
||||
AI_UNAVAILABLE = "ai_unavailable", "AI недоступен"
|
||||
AI_HANDED_OVER = "ai_handed_over", "AI передал диалог оператору"
|
||||
ASSIGNED_TO = "assigned_to", "Диалог назначен сотруднику"
|
||||
ASSIGNMENT_EXPIRED = "assignment_expired", "Назначение истекло"
|
||||
CALL_REQUESTED = "call_requested", "Запрошен звонок"
|
||||
CALL_ACCEPTED = "call_accepted", "Клиент принял приглашение"
|
||||
CALL_DECLINED = "call_declined", "Клиент отклонил приглашение"
|
||||
@@ -400,3 +413,11 @@ class ReplyTemplate(models.Model):
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"template:{self.organization_id}/{self.title}"
|
||||
|
||||
|
||||
# Django импортирует только models.py: пороги очереди лежат рядом, чтобы не
|
||||
# растить этот файл, и переэкспортируются здесь ради регистрации модели.
|
||||
from chatballs.conversations.queue_models import ( # noqa: E402, F401
|
||||
QueueEscalationPolicy,
|
||||
policy_for,
|
||||
)
|
||||
@@ -22,6 +22,8 @@ def poll_all_messengers(context) -> int:
|
||||
channel__is_active=True,
|
||||
).exclude(secret="")
|
||||
if integration.config.get("purpose") != "notifications"
|
||||
# Демо-подключения из демо-набора: токены ненастоящие, опрашивать нечего.
|
||||
and not integration.config.get("demoSeed")
|
||||
]
|
||||
total = 0
|
||||
for integration in integrations:
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Очередь к оператору: единственное место, где диалог в неё входит и выходит.
|
||||
|
||||
Правило «диалог ждёт человека» — это три поля сразу: control_mode = PAUSED,
|
||||
expected_responder = OPERATOR и момент, с которого пошло ожидание. Раньше первые
|
||||
два выставлялись в шести местах подряд (создание диалога без доступного AI,
|
||||
клиент написал в диалог без AI, голосовое без расшифровки, сбой провайдера,
|
||||
хендофф агента, ручной возврат оператором), а третьего не было вовсе: «дольше
|
||||
всех ждущий» считался по времени последнего сообщения.
|
||||
|
||||
Из-за этого очередь вела себя обратно смыслу. Клиент, который писал повторно,
|
||||
двигал last_message_at вперёд и падал в конец очереди: чем настойчивее человек,
|
||||
тем позже до него доходили руки. Поэтому waiting_since ставится один раз — при
|
||||
входе в очередь — и не обновляется, пока диалог из неё не вышел.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.conversations.models import (
|
||||
ControlMode,
|
||||
Conversation,
|
||||
ExpectedResponder,
|
||||
LifecycleState,
|
||||
)
|
||||
|
||||
# Что пишет enter_queue. Вызывающий кладёт это в update_fields своего save():
|
||||
# состояние диалога меняется вместе с остальными полями, одной записью.
|
||||
QUEUE_FIELDS = ("control_mode", "expected_responder", "waiting_since")
|
||||
|
||||
|
||||
def is_waiting(conversation: Conversation) -> bool:
|
||||
"""Диалог стоит в очереди к человеку.
|
||||
|
||||
Закрытый и спам тоже лежат в PAUSED, но никого не ждут — отсюда проверка
|
||||
жизненного цикла.
|
||||
"""
|
||||
return (
|
||||
conversation.lifecycle == LifecycleState.OPEN
|
||||
and conversation.control_mode == ControlMode.PAUSED
|
||||
)
|
||||
|
||||
|
||||
def enter_queue(conversation: Conversation, *, now: datetime | None = None) -> bool:
|
||||
"""Ставит диалог в очередь. True — если он в неё только что попал.
|
||||
|
||||
Возврат нужен вызывающему, чтобы решить, звать ли операторов: повторное
|
||||
сообщение клиента в уже ждущий диалог очередь не меняет и второго оклика не
|
||||
заслуживает.
|
||||
"""
|
||||
entered = not is_waiting(conversation)
|
||||
conversation.control_mode = ControlMode.PAUSED
|
||||
conversation.expected_responder = ExpectedResponder.OPERATOR
|
||||
if entered:
|
||||
conversation.waiting_since = now or timezone.now()
|
||||
return entered
|
||||
|
||||
|
||||
def leave_queue(conversation: Conversation) -> None:
|
||||
"""Диалог больше никого не ждёт.
|
||||
|
||||
Несимметрично enter_queue намеренно: вход в очередь — одно состояние, а
|
||||
выходов несколько (оператор взял, диалог вернули AI, закрыли, пометили
|
||||
спамом), и control_mode у каждого свой. Общее у них только одно — ожидание
|
||||
закончилось, и его начало больше не имеет смысла.
|
||||
"""
|
||||
conversation.waiting_since = None
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Пороги очереди: через сколько напоминать, расширять круг и звать руководство.
|
||||
|
||||
Числа разные у разных организаций — у круглосуточной поддержки хостинга и у
|
||||
клиники с приёмом по будням «долго» означает не одно и то же, — поэтому они
|
||||
настройка, а не константа в коде. Строка одна на организацию и заводится с
|
||||
дефолтами при первом обращении.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
|
||||
class QueueEscalationPolicy(models.Model):
|
||||
organization = models.OneToOneField(
|
||||
"identity.Organization", on_delete=models.CASCADE, related_name="queue_policy"
|
||||
)
|
||||
# Диалог ждёт дольше этого — повторный оклик той же группе.
|
||||
remind_after_minutes = models.PositiveIntegerField(default=5)
|
||||
# Ждёт ещё дольше — круг расширяется за пределы группы диалога.
|
||||
widen_after_minutes = models.PositiveIntegerField(default=15)
|
||||
# Совсем долго — это уже не про сменщика, а про руководство.
|
||||
escalate_after_minutes = models.PositiveIntegerField(default=30)
|
||||
# Назначили ответственного, а он не взял — диалог возвращается в общую
|
||||
# очередь. Без этого назначение работает как способ спрятать диалог: из
|
||||
# общей очереди он ушёл, а отвечать некому.
|
||||
assignment_timeout_minutes = models.PositiveIntegerField(default=10)
|
||||
# Кто и когда менял: в разделе настроек это подпись под формой. Сроки —
|
||||
# правило работы смены, и знать, чьё это решение, важнее, чем кажется.
|
||||
updated_at = models.DateTimeField(null=True, blank=True)
|
||||
updated_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
|
||||
)
|
||||
|
||||
# Значения по умолчанию — они же «обычные сроки» в кнопке сброса.
|
||||
DEFAULTS = {
|
||||
"remind_after_minutes": 5,
|
||||
"widen_after_minutes": 15,
|
||||
"escalate_after_minutes": 30,
|
||||
"assignment_timeout_minutes": 10,
|
||||
}
|
||||
|
||||
class Meta:
|
||||
db_table = "conversations_queueescalationpolicy"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"queue-policy:{self.organization_id}"
|
||||
|
||||
|
||||
def policy_for(organization) -> QueueEscalationPolicy:
|
||||
policy, _ = QueueEscalationPolicy.objects.get_or_create(organization=organization)
|
||||
return policy
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Сроки очереди: раздел «Когда звать на помощь» (макет Q2).
|
||||
|
||||
До этого пороги правились только в служебной админке — то есть де-факто никем.
|
||||
Читает их тот, кто видит настройки; меняет — тот, кто ими управляет.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from django.utils import timezone
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.request import Request
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from chatballs.conversations.queue_models import QueueEscalationPolicy, policy_for
|
||||
from chatballs.i18n import t
|
||||
from chatballs.identity.policy import ResourceScope, authorize
|
||||
|
||||
FIELDS = tuple(QueueEscalationPolicy.DEFAULTS)
|
||||
# Сутки: всё, что дольше, — это не «позвать на помощь», а другая задача.
|
||||
MAX_MINUTES = 24 * 60
|
||||
|
||||
|
||||
def _payload(policy: QueueEscalationPolicy) -> dict:
|
||||
author = policy.updated_by
|
||||
return {
|
||||
**{field: getattr(policy, field) for field in FIELDS},
|
||||
"defaults": dict(QueueEscalationPolicy.DEFAULTS),
|
||||
"updatedAt": policy.updated_at.isoformat() if policy.updated_at else None,
|
||||
"updatedBy": (author.full_name or author.email) if author else "",
|
||||
}
|
||||
|
||||
|
||||
class QueuePolicyView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request: Request) -> Response:
|
||||
context = request.tenant_context
|
||||
if not authorize(context.membership, "settings.view", ResourceScope(context.organization_id)):
|
||||
return Response({"detail": t("settings.queue_policy_forbidden")}, status=403)
|
||||
return Response(_payload(policy_for(context.organization)))
|
||||
|
||||
def patch(self, request: Request) -> Response:
|
||||
context = request.tenant_context
|
||||
if not authorize(context.membership, "settings.manage", ResourceScope(context.organization_id)):
|
||||
return Response({"detail": t("settings.queue_policy_forbidden")}, status=403)
|
||||
policy = policy_for(context.organization)
|
||||
changed = []
|
||||
for field in FIELDS:
|
||||
if field not in request.data:
|
||||
continue
|
||||
value = request.data[field]
|
||||
if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= MAX_MINUTES:
|
||||
return Response({"detail": t("settings.queue_minutes_range")}, status=400)
|
||||
if getattr(policy, field) != value:
|
||||
setattr(policy, field, value)
|
||||
changed.append(field)
|
||||
if changed:
|
||||
policy.updated_at = timezone.now()
|
||||
policy.updated_by = context.actor_user
|
||||
policy.save(update_fields=[*changed, "updated_at", "updated_by"])
|
||||
return Response(_payload(policy))
|
||||
@@ -13,12 +13,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
from channels.layers import get_channel_layer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
from chatballs.realtime import publish
|
||||
|
||||
INBOX_EVENT = "inbox.changed"
|
||||
CONVERSATION_EVENT = "conversation.changed"
|
||||
@@ -32,27 +27,12 @@ def conversation_group(conversation_id: int) -> str:
|
||||
return f"conv.{conversation_id}"
|
||||
|
||||
|
||||
def _publish(group: str, payload: dict[str, object]) -> None:
|
||||
"""Оповещение — вспомогательный путь: его сбой не должен ронять запись.
|
||||
|
||||
Сообщение уже сохранено к моменту отправки; если канал недоступен, клиент
|
||||
узнает об изменении следующим опросом — он остаётся как запасной путь.
|
||||
"""
|
||||
layer = get_channel_layer()
|
||||
if layer is None:
|
||||
return
|
||||
try:
|
||||
async_to_sync(layer.group_send)(group, {"type": "fanout", "payload": payload})
|
||||
except Exception: # noqa: BLE001 — канал не должен ломать сохранение
|
||||
logger.warning("realtime fanout failed for %s", group, exc_info=True)
|
||||
|
||||
|
||||
def notify_inbox_changed(organization_id: int) -> None:
|
||||
_publish(inbox_group(organization_id), {"type": INBOX_EVENT})
|
||||
publish(inbox_group(organization_id), {"type": INBOX_EVENT})
|
||||
|
||||
|
||||
def notify_conversation_changed(conversation_id: int, *, organization_id: int) -> None:
|
||||
_publish(
|
||||
publish(
|
||||
conversation_group(conversation_id),
|
||||
{"type": CONVERSATION_EVENT, "conversationId": conversation_id},
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ from django.db.models import (
|
||||
Value,
|
||||
When,
|
||||
)
|
||||
from django.db.models.functions import Coalesce
|
||||
|
||||
from chatballs.api.pagination import SortKey
|
||||
from chatballs.conversations.models import (
|
||||
@@ -63,6 +64,11 @@ def order_conversations(
|
||||
Сортировка живёт на сервере вместе с окном: клиент видит не весь набор, и
|
||||
переставлять в браузере ему нечего. `waiting` — «ждущие человека первыми,
|
||||
дольше всех ждущий выше», остальные — по убыванию активности.
|
||||
|
||||
«Дольше всех ждущий» считается от waiting_since — момента, когда диалог
|
||||
встал в очередь. По времени последнего сообщения его считать нельзя: клиент,
|
||||
написавший повторно, двигал бы себя в конец очереди, и чем настойчивее он
|
||||
напоминал о себе, тем позже до него доходила очередь.
|
||||
"""
|
||||
if sort != "waiting":
|
||||
return queryset.order_by("-last_message_at", "-id"), ACTIVITY_KEYS
|
||||
@@ -72,7 +78,9 @@ def order_conversations(
|
||||
When(waits, then=Value(0)), default=Value(1), output_field=IntegerField()
|
||||
),
|
||||
_wait_at=Case(
|
||||
When(waits, then=F("last_message_at")),
|
||||
# Coalesce — страховка для строк, встававших в очередь до появления
|
||||
# waiting_since: без неё они ушли бы в конец очереди вместо начала.
|
||||
When(waits, then=Coalesce(F("waiting_since"), F("last_message_at"))),
|
||||
default=Value(_NOT_WAITING_AT),
|
||||
output_field=DateTimeField(),
|
||||
),
|
||||
|
||||
@@ -257,6 +257,17 @@ def conversation_payload(
|
||||
"isAssignedToViewer": bool(
|
||||
viewer_id and conversation.assigned_operator_id == viewer_id
|
||||
),
|
||||
# Ожидание (макет «Очередь и уведомления», кадры Q3 и Q4): с какого
|
||||
# момента диалог ждёт человека и с какого — конкретного человека.
|
||||
# Считать «сколько осталось» клиент должен сам: минута на сервере и
|
||||
# минута на экране расходятся, и показывать замерший счётчик хуже, чем
|
||||
# не показывать никакого.
|
||||
"waitingSince": (
|
||||
conversation.waiting_since.isoformat() if conversation.waiting_since else None
|
||||
),
|
||||
"assignedAt": (
|
||||
conversation.assigned_at.isoformat() if conversation.assigned_at else None
|
||||
),
|
||||
"group": (
|
||||
{"id": conversation.group_id, "name": conversation.group.name, "color": conversation.group.color}
|
||||
if conversation.group_id
|
||||
|
||||
@@ -13,9 +13,12 @@ from chatballs.conversations.models import (
|
||||
MessageKind,
|
||||
SystemEvent,
|
||||
)
|
||||
from chatballs.conversations.queue import QUEUE_FIELDS, enter_queue, leave_queue
|
||||
from chatballs.i18n import customer_language, t
|
||||
from chatballs.identity.models import EmployeeRole
|
||||
from chatballs.integrations.models import IntegrationProvider
|
||||
from chatballs.notifications.models import NotificationAudience, NotificationType
|
||||
from chatballs.notifications.services import notify
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
|
||||
|
||||
@@ -37,7 +40,7 @@ def _require_open(conversation: Conversation) -> None:
|
||||
|
||||
|
||||
|
||||
def _operator_label(operator) -> str:
|
||||
def operator_label(operator) -> str:
|
||||
|
||||
return getattr(operator, "full_name", "") or operator.email
|
||||
|
||||
@@ -101,7 +104,9 @@ def claim_locked_conversation(*, context: TenantContext, conversation: Conversat
|
||||
|
||||
conversation.expected_responder = ExpectedResponder.OPERATOR
|
||||
|
||||
conversation.save(update_fields=["control_mode", "assigned_operator", "expected_responder"])
|
||||
leave_queue(conversation)
|
||||
|
||||
conversation.save(update_fields=["control_mode", "assigned_operator", "expected_responder", "waiting_since"])
|
||||
|
||||
Message.objects.create(
|
||||
|
||||
@@ -111,9 +116,9 @@ def claim_locked_conversation(*, context: TenantContext, conversation: Conversat
|
||||
|
||||
system_event=SystemEvent.OPERATOR_TOOK,
|
||||
|
||||
system_params={"operator": _operator_label(operator)},
|
||||
system_params={"operator": operator_label(operator)},
|
||||
|
||||
text=f"Оператор {_operator_label(operator)} перехватил диалог",
|
||||
text=f"Оператор {operator_label(operator)} перехватил диалог",
|
||||
|
||||
)
|
||||
|
||||
@@ -147,7 +152,9 @@ def release_to_ai(*, context: TenantContext, conversation_id: int) -> Conversati
|
||||
|
||||
conversation.expected_responder = ExpectedResponder.AI
|
||||
|
||||
conversation.save(update_fields=["control_mode", "assigned_operator", "expected_responder"])
|
||||
leave_queue(conversation)
|
||||
|
||||
conversation.save(update_fields=["control_mode", "assigned_operator", "expected_responder", "waiting_since"])
|
||||
|
||||
Message.objects.create(
|
||||
conversation=conversation,
|
||||
@@ -176,13 +183,12 @@ def return_to_queue(*, context: TenantContext, conversation_id: int) -> Conversa
|
||||
|
||||
_require_open(conversation)
|
||||
|
||||
conversation.control_mode = ControlMode.PAUSED
|
||||
enter_queue(conversation)
|
||||
|
||||
conversation.assigned_operator = None
|
||||
|
||||
conversation.expected_responder = ExpectedResponder.OPERATOR
|
||||
|
||||
conversation.save(update_fields=["control_mode", "assigned_operator", "expected_responder"])
|
||||
conversation.save(update_fields=[*QUEUE_FIELDS, "assigned_operator"])
|
||||
|
||||
Message.objects.create(
|
||||
conversation=conversation,
|
||||
@@ -337,6 +343,8 @@ def close_conversation(*, context: TenantContext, conversation_id: int) -> Conve
|
||||
|
||||
conversation.expected_responder = ExpectedResponder.NOBODY
|
||||
|
||||
leave_queue(conversation)
|
||||
|
||||
conversation.save(
|
||||
|
||||
update_fields=[
|
||||
@@ -348,6 +356,7 @@ def close_conversation(*, context: TenantContext, conversation_id: int) -> Conve
|
||||
"assigned_operator",
|
||||
|
||||
"expected_responder",
|
||||
"waiting_since",
|
||||
|
||||
]
|
||||
|
||||
@@ -383,6 +392,8 @@ def mark_conversation_as_spam(
|
||||
|
||||
conversation.expected_responder = ExpectedResponder.NOBODY
|
||||
|
||||
leave_queue(conversation)
|
||||
|
||||
conversation.save(
|
||||
|
||||
update_fields=[
|
||||
@@ -394,6 +405,7 @@ def mark_conversation_as_spam(
|
||||
"assigned_operator",
|
||||
|
||||
"expected_responder",
|
||||
"waiting_since",
|
||||
|
||||
]
|
||||
|
||||
@@ -401,3 +413,53 @@ def mark_conversation_as_spam(
|
||||
|
||||
return conversation
|
||||
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def assign_operator(*, context: TenantContext, conversation_id: int, assignee) -> Conversation:
|
||||
"""Назначить ответственного за диалог (или снять назначение).
|
||||
|
||||
Назначение — не взятие: человек ещё не ответил и мог даже не увидеть
|
||||
диалог. Но из общей очереди диалог уходит — отвечать в нём, кроме
|
||||
назначенного и руководства, уже никто не может, — поэтому назначенного надо
|
||||
позвать лично и поставить срок. Не успел — диалог возвращается в общую
|
||||
очередь (chatballs.conversations.escalation).
|
||||
|
||||
Раньше эта операция молча писала внешний ключ: назначенный не узнавал,
|
||||
диалог продолжал числиться в общей очереди, а взять его оттуда было уже
|
||||
нельзя.
|
||||
"""
|
||||
conversation = Conversation.objects.select_for_update().get(
|
||||
id=conversation_id, organization=context.organization
|
||||
)
|
||||
_require_open(conversation)
|
||||
conversation.assigned_operator = assignee
|
||||
conversation.assigned_at = timezone.now() if assignee is not None else None
|
||||
conversation.save(update_fields=["assigned_operator", "assigned_at"])
|
||||
if assignee is None:
|
||||
return conversation
|
||||
Message.objects.create(
|
||||
conversation=conversation,
|
||||
author_type=MessageAuthor.SYSTEM,
|
||||
system_event=SystemEvent.ASSIGNED_TO,
|
||||
system_params={"operator": operator_label(assignee)},
|
||||
text=f"Диалог назначен на {operator_label(assignee)}",
|
||||
)
|
||||
# Себе назначил — сам и знает.
|
||||
if context.actor_user is not None and assignee.pk == context.actor_user.pk:
|
||||
return conversation
|
||||
contact_name = getattr(conversation.contact, "name", "") or t("conversations.guest")
|
||||
notify(
|
||||
context=context,
|
||||
type=NotificationType.DIALOG_ASSIGNED,
|
||||
audience=NotificationAudience.USER,
|
||||
recipient_user=assignee,
|
||||
title=f"Вам назначен диалог · {contact_name}",
|
||||
title_key="notifications.assigned_to_you",
|
||||
text_params={"contact": contact_name},
|
||||
target_id=conversation.id,
|
||||
source_type="Conversation",
|
||||
source_id=conversation.id,
|
||||
dedup_key=f"assign:{conversation.id}:{assignee.pk}",
|
||||
)
|
||||
return conversation
|
||||
@@ -8,11 +8,10 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from django.db.models import Count, Sum
|
||||
from django.db.models import Count
|
||||
from django.db.models.functions import TruncDate, TruncHour
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.ai.models import LlmInvocation
|
||||
from chatballs.channels.selectors import channels_in_organization
|
||||
from chatballs.conversations.models import (
|
||||
ControlMode,
|
||||
@@ -64,17 +63,6 @@ def _chart(
|
||||
return {"values": values, "labels": labels}
|
||||
|
||||
|
||||
def _ai_cost(
|
||||
org_id: int,
|
||||
start: datetime,
|
||||
end: datetime | None = None,
|
||||
) -> int:
|
||||
qs = LlmInvocation.objects.filter(channel__organization_id=org_id, created_at__gte=start)
|
||||
if end is not None:
|
||||
qs = qs.filter(created_at__lt=end)
|
||||
return qs.aggregate(total=Sum("cost_micros"))["total"] or 0
|
||||
|
||||
|
||||
def sales_overview_stats(context, period: str) -> dict:
|
||||
organization_id = context.organization_id
|
||||
now = timezone.now()
|
||||
@@ -105,8 +93,6 @@ def sales_overview_stats(context, period: str) -> dict:
|
||||
conversation__organization_id=organization_id,
|
||||
created_at__gte=start,
|
||||
).count(),
|
||||
"aiCostMicros": _ai_cost(organization_id, start),
|
||||
"aiCostPrevMicros": _ai_cost(organization_id, prev_start, start),
|
||||
}
|
||||
|
||||
open_by_channel = dict(open_qs.values_list("channel_id").annotate(c=Count("id")))
|
||||
|
||||
@@ -340,30 +340,34 @@ class ReplyTemplateTests(ChatExtrasTestCase):
|
||||
self.assertFalse(ReplyTemplate.objects.exists())
|
||||
|
||||
|
||||
class LaunchChecklistTests(TestCase):
|
||||
class OnboardingTests(TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.organization = Organization.objects.create(name="New", slug="launch-org")
|
||||
owner = HumanUser.objects.create_user(
|
||||
self.owner = HumanUser.objects.create_user(
|
||||
email="owner@launch.test", password="Password-123"
|
||||
)
|
||||
OrganizationMembership.objects.create(
|
||||
user=owner,
|
||||
self.membership = OrganizationMembership.objects.create(
|
||||
user=self.owner,
|
||||
organization=self.organization,
|
||||
role=EmployeeRole.OWNER,
|
||||
position_title="Owner",
|
||||
)
|
||||
self.client = APIClient()
|
||||
self.client.force_authenticate(owner)
|
||||
self.client.force_authenticate(self.owner)
|
||||
|
||||
def test_checklist_marks_steps_by_fact(self) -> None:
|
||||
initial = self.client.get("/api/v1/company/launch-checklist/").json()
|
||||
def test_steps_are_marked_by_fact(self) -> None:
|
||||
initial = self.client.get("/api/v1/company/onboarding/").json()
|
||||
self.assertEqual(
|
||||
initial,
|
||||
initial["steps"],
|
||||
{
|
||||
"agentCreated": False,
|
||||
"providerConnected": False,
|
||||
"agentActive": False,
|
||||
"knowledgeFilled": False,
|
||||
"connectionBound": False,
|
||||
"widgetPublished": False,
|
||||
"employeeInvited": False,
|
||||
"done": False,
|
||||
"platformConfigured": False,
|
||||
"firstConversation": False,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -393,5 +397,56 @@ class LaunchChecklistTests(TestCase):
|
||||
position_title="Operator",
|
||||
)
|
||||
|
||||
final = self.client.get("/api/v1/company/launch-checklist/").json()
|
||||
self.assertTrue(final["done"])
|
||||
final = self.client.get("/api/v1/company/onboarding/").json()
|
||||
self.assertTrue(final["steps"]["connectionBound"])
|
||||
self.assertTrue(final["steps"]["employeeInvited"])
|
||||
|
||||
def test_existing_member_has_not_dismissed_onboarding(self) -> None:
|
||||
"""Признак пустой у всех, кто заведён до появления онбординга."""
|
||||
|
||||
payload = self.client.get("/api/v1/company/onboarding/").json()
|
||||
self.assertIsNone(payload["dismissedAt"])
|
||||
self.assertIsNone(payload["completedAt"])
|
||||
|
||||
def test_dismiss_and_complete_and_restart(self) -> None:
|
||||
dismissed = self.client.post(
|
||||
"/api/v1/company/onboarding/", {"action": "dismiss"}, format="json"
|
||||
).json()
|
||||
self.assertIsNotNone(dismissed["dismissedAt"])
|
||||
self.assertIsNone(dismissed["completedAt"])
|
||||
|
||||
completed = self.client.post(
|
||||
"/api/v1/company/onboarding/", {"action": "complete"}, format="json"
|
||||
).json()
|
||||
self.assertIsNotNone(completed["completedAt"])
|
||||
|
||||
restarted = self.client.post(
|
||||
"/api/v1/company/onboarding/", {"action": "restart"}, format="json"
|
||||
).json()
|
||||
self.assertIsNone(restarted["dismissedAt"])
|
||||
self.assertIsNone(restarted["completedAt"])
|
||||
|
||||
def test_dismissal_is_personal(self) -> None:
|
||||
"""Закрытие одним администратором не прячет визард у второго."""
|
||||
|
||||
self.client.post(
|
||||
"/api/v1/company/onboarding/", {"action": "dismiss"}, format="json"
|
||||
)
|
||||
colleague = HumanUser.objects.create_user(
|
||||
email="admin@launch.test", password="Password-123"
|
||||
)
|
||||
OrganizationMembership.objects.create(
|
||||
user=colleague,
|
||||
organization=self.organization,
|
||||
role=EmployeeRole.ADMIN,
|
||||
position_title="Admin",
|
||||
)
|
||||
other = APIClient()
|
||||
other.force_authenticate(colleague)
|
||||
self.assertIsNone(other.get("/api/v1/company/onboarding/").json()["dismissedAt"])
|
||||
|
||||
def test_unknown_action_is_rejected(self) -> None:
|
||||
response = self.client.post(
|
||||
"/api/v1/company/onboarding/", {"action": "nope"}, format="json"
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
@@ -1,8 +1,15 @@
|
||||
"""Справочник выбора ответственного: ограниченная выдача и поиск на сервере."""
|
||||
"""Справочник выбора ответственного: ограниченная выдача, поиск и присутствие."""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest import mock
|
||||
|
||||
from django.core.cache import cache
|
||||
from django.test import TestCase
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.channels.models import Channel
|
||||
from chatballs.conversations.chat_extras_views import DIRECTORY_LIMIT
|
||||
from chatballs.conversations.models import Contact, Conversation, LifecycleState
|
||||
from chatballs.identity.bootstrap import bootstrap_owner
|
||||
from chatballs.identity.models import (
|
||||
EmployeeRole,
|
||||
@@ -10,6 +17,7 @@ from chatballs.identity.models import (
|
||||
Organization,
|
||||
OrganizationMembership,
|
||||
)
|
||||
from chatballs.presence import touch
|
||||
from chatballs.testing import TenantAPIClient as APIClient
|
||||
|
||||
|
||||
@@ -54,3 +62,65 @@ class ConversationDirectoryTests(TestCase):
|
||||
|
||||
def test_groups_are_returned_as_before(self) -> None:
|
||||
self.assertIn("groups", self._directory())
|
||||
|
||||
|
||||
class DirectoryPresenceTests(TestCase):
|
||||
"""Присутствие и загрузка в выборе ответственного (макет Q5).
|
||||
|
||||
Назначить отсутствующего можно — признак ничего не запрещает; он лишь
|
||||
отвечает на вопрос «кто сейчас за рабочим местом».
|
||||
"""
|
||||
|
||||
def setUp(self) -> None:
|
||||
cache.clear()
|
||||
self.organization = Organization.objects.create(name="Example", slug="directory-presence")
|
||||
self.owner = self._employee("owner@dir.test", EmployeeRole.OWNER)
|
||||
self.away = self._employee("away@dir.test", EmployeeRole.EMPLOYEE)
|
||||
self.client = APIClient()
|
||||
self.client.force_authenticate(self.owner.user)
|
||||
|
||||
def _employee(self, email: str, role: str) -> OrganizationMembership:
|
||||
user = HumanUser.objects.create_user(email=email, password="Password-123")
|
||||
return OrganizationMembership.objects.create(
|
||||
user=user, organization=self.organization, role=role, position_title="Specialist"
|
||||
)
|
||||
|
||||
def _rows(self) -> dict[int, dict]:
|
||||
response = self.client.get("/api/v1/conversations/directory/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
return {row["id"]: row for row in response.json()["employees"]}
|
||||
|
||||
def test_presence_is_reported_for_whoever_is_in_the_app(self) -> None:
|
||||
touch(self.organization.id, self.owner.user_id)
|
||||
rows = self._rows()
|
||||
self.assertTrue(rows[self.owner.user_id]["online"])
|
||||
self.assertIsNotNone(rows[self.owner.user_id]["lastSeenAt"])
|
||||
self.assertFalse(rows[self.away.user_id]["online"])
|
||||
self.assertIsNone(rows[self.away.user_id]["lastSeenAt"])
|
||||
|
||||
def test_long_gone_employee_is_not_online_but_remembered(self) -> None:
|
||||
with mock.patch(
|
||||
"chatballs.presence.timezone.now",
|
||||
return_value=timezone.now() - timedelta(minutes=25),
|
||||
):
|
||||
touch(self.organization.id, self.away.user_id)
|
||||
row = self._rows()[self.away.user_id]
|
||||
self.assertFalse(row["online"])
|
||||
self.assertIsNotNone(row["lastSeenAt"])
|
||||
|
||||
def test_load_counts_only_open_dialogs_of_that_person(self) -> None:
|
||||
channel = Channel.objects.create(
|
||||
organization=self.organization, code="dir-presence", name="Канал"
|
||||
)
|
||||
contact = Contact.objects.create(organization=self.organization, name="Клиент")
|
||||
for lifecycle in (LifecycleState.OPEN, LifecycleState.OPEN, LifecycleState.CLOSED):
|
||||
Conversation.objects.create(
|
||||
organization=self.organization,
|
||||
channel=channel,
|
||||
contact=contact,
|
||||
lifecycle=lifecycle,
|
||||
assigned_operator=self.owner.user,
|
||||
)
|
||||
rows = self._rows()
|
||||
self.assertEqual(rows[self.owner.user_id]["openDialogs"], 2)
|
||||
self.assertEqual(rows[self.away.user_id]["openDialogs"], 0)
|
||||
@@ -15,6 +15,7 @@ from chatballs.conversations.models import Contact, Conversation, MessageAuthor
|
||||
from chatballs.conversations.selectors import conversation_messages
|
||||
from chatballs.conversations.serializers import conversation_payload, message_payload
|
||||
from chatballs.conversations.transports import email as email_transport
|
||||
from chatballs.conversations.transports.errors import PollFailed
|
||||
from chatballs.identity.bootstrap import bootstrap_owner
|
||||
from chatballs.identity.models import Organization
|
||||
from chatballs.integrations.models import Integration, IntegrationKind, IntegrationProvider
|
||||
@@ -359,11 +360,11 @@ class EmailPollTests(TestCase):
|
||||
|
||||
with mock.patch.object(email_transport, "_imap_connect", side_effect=OSError("refused")):
|
||||
|
||||
messages, marker = email_transport.poll_updates(integration)
|
||||
with self.assertRaises(PollFailed):
|
||||
email_transport.poll_updates(integration)
|
||||
|
||||
self.assertEqual(messages, [])
|
||||
|
||||
self.assertEqual(marker, "7:99")
|
||||
# Курсор не сдвинулся: следующий удачный опрос продолжит с того же места.
|
||||
self.assertEqual(integration.poll_marker, "7:99")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Сбой опроса подключения: пауза с удвоением и тишина в журнале.
|
||||
|
||||
Раньше подключение с ненастоящим токеном писало предупреждение каждые три
|
||||
секунды. Теперь после сбоя оно пропускается с растущей паузой, журнал видит
|
||||
первый сбой, выход на максимальную паузу и восстановление, а курсор при
|
||||
сбое не двигается. Демо-подключения не опрашиваются вовсе.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest import mock
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from chatballs.channels.models import Channel
|
||||
from chatballs.conversations import poller
|
||||
from chatballs.conversations.transports import backoff, poll
|
||||
from chatballs.conversations.transports.errors import PollFailed
|
||||
from chatballs.identity.models import Organization
|
||||
from chatballs.integrations.models import Integration, IntegrationKind, IntegrationProvider
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
from chatballs.tenancy.database import tenant_atomic
|
||||
|
||||
|
||||
class PollBackoffTests(TestCase):
|
||||
def setUp(self) -> None:
|
||||
backoff.reset()
|
||||
self.addCleanup(backoff.reset)
|
||||
self.organization = Organization.objects.create(name="Poll", slug="poll-org")
|
||||
with tenant_atomic(self.organization.id):
|
||||
self.channel = Channel.objects.create(organization=self.organization, name="Main", code="main")
|
||||
self.integration = Integration.objects.create(
|
||||
organization=self.organization,
|
||||
kind=IntegrationKind.MESSENGER,
|
||||
provider=IntegrationProvider.TELEGRAM,
|
||||
name="Bot",
|
||||
secret="0000:not-a-token",
|
||||
channel=self.channel,
|
||||
poll_marker="41",
|
||||
)
|
||||
|
||||
def _fail(self, *_args, **_kwargs):
|
||||
raise PollFailed("HTTP Error 401: Unauthorized")
|
||||
|
||||
def test_failure_is_logged_once_and_then_skipped(self) -> None:
|
||||
with mock.patch.dict(poller.transports._POLL, {IntegrationProvider.TELEGRAM: self._fail}):
|
||||
with self.assertLogs("chatballs.conversations.transports.backoff", level="WARNING") as logs:
|
||||
self.assertEqual(poll(self.integration), ([], "41"))
|
||||
self.assertEqual(len(logs.output), 1)
|
||||
self.assertIn("401", logs.output[0])
|
||||
# Пока пауза не вышла, транспорт не вызывается и журнал молчит.
|
||||
with mock.patch.object(backoff, "_now", return_value=backoff._now()):
|
||||
with self.assertNoLogs("chatballs.conversations.transports.backoff", level="WARNING"):
|
||||
self.assertEqual(poll(self.integration), ([], "41"))
|
||||
self.assertTrue(backoff.should_skip(self.integration.id))
|
||||
|
||||
def test_delay_doubles_up_to_the_cap_and_recovery_is_logged(self) -> None:
|
||||
clock = [1000.0]
|
||||
with mock.patch.object(backoff, "_now", side_effect=lambda: clock[0]):
|
||||
with mock.patch.dict(poller.transports._POLL, {IntegrationProvider.TELEGRAM: self._fail}):
|
||||
delays = []
|
||||
for _ in range(10):
|
||||
poll(self.integration)
|
||||
state = backoff._failures[self.integration.id]
|
||||
delays.append(state.delay)
|
||||
clock[0] = state.next_attempt_at # ждём ровно до следующей попытки
|
||||
self.assertEqual(delays[:3], [6.0, 12.0, 24.0])
|
||||
self.assertEqual(delays[-1], backoff.MAX_DELAY_SECONDS)
|
||||
self.assertTrue(all(delay <= backoff.MAX_DELAY_SECONDS for delay in delays))
|
||||
|
||||
with mock.patch.dict(poller.transports._POLL, {IntegrationProvider.TELEGRAM: lambda _i: ([], "42")}):
|
||||
with self.assertLogs("chatballs.conversations.transports.backoff", level="INFO") as logs:
|
||||
self.assertEqual(poll(self.integration), ([], "42"))
|
||||
self.assertIn("recovered", logs.output[0])
|
||||
self.assertNotIn(self.integration.id, backoff._failures)
|
||||
|
||||
def test_demo_seed_connections_are_not_polled(self) -> None:
|
||||
with tenant_atomic(self.organization.id):
|
||||
Integration.objects.filter(pk=self.integration.pk).update(config={"demoSeed": True})
|
||||
context = TenantContext.for_resource(self.organization)
|
||||
with mock.patch("chatballs.conversations.poller.transports.poll") as polled:
|
||||
poller.poll_all_messengers(context)
|
||||
polled.assert_not_called()
|
||||
@@ -0,0 +1,246 @@
|
||||
"""Эскалация ждущих диалогов и личная очередь назначенного.
|
||||
|
||||
Регрессия, ради которой всё это заведено: про ждущий диалог операторов окликали
|
||||
ровно один раз, и дальше суточный dedup гарантировал тишину. Назначение при этом
|
||||
молча писало внешний ключ — назначенный не узнавал, а из общей очереди диалог
|
||||
уже ушёл.
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from django.core.cache import cache
|
||||
from django.test import TestCase
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.channels.models import Channel
|
||||
from chatballs.conversations.escalation import sweep_waiting_conversations
|
||||
from chatballs.conversations.models import (
|
||||
Contact,
|
||||
ControlMode,
|
||||
Conversation,
|
||||
ExpectedResponder,
|
||||
LifecycleState,
|
||||
SystemEvent,
|
||||
)
|
||||
from chatballs.conversations.queue_models import policy_for
|
||||
from chatballs.conversations.services import assign_operator
|
||||
from chatballs.identity.group_models import EmployeeGroup, EmployeeGroupMember
|
||||
from chatballs.identity.models import (
|
||||
EmployeeRole,
|
||||
HumanUser,
|
||||
Organization,
|
||||
OrganizationMembership,
|
||||
)
|
||||
from chatballs.notifications.models import Notification, NotificationAudience
|
||||
from chatballs.presence import touch
|
||||
from chatballs.testing import tenant_context_for
|
||||
|
||||
|
||||
class QueueTestBase(TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.organization = Organization.objects.create(name="Example", slug="queue-escalation")
|
||||
self.support = EmployeeGroup.objects.create(
|
||||
organization=self.organization, name="Поддержка"
|
||||
)
|
||||
self.owner = self._employee("owner@queue.test", EmployeeRole.OWNER)
|
||||
self.operator = self._employee("operator@queue.test", EmployeeRole.EMPLOYEE)
|
||||
EmployeeGroupMember.objects.create(
|
||||
organization=self.organization, group=self.support, employee=self.operator
|
||||
)
|
||||
self.context = tenant_context_for(self.owner.user, self.organization)
|
||||
self.policy = policy_for(self.organization)
|
||||
self.channel = Channel.objects.create(
|
||||
organization=self.organization, group=self.support, code="esc", name="Очередь"
|
||||
)
|
||||
self.conversation = self._waiting_conversation()
|
||||
# Обычный случай: смена на месте. Пустую смену проверяет
|
||||
# PresenceEscalationTests, и она её задаёт явно.
|
||||
cache.clear()
|
||||
touch(self.organization.id, self.operator.user_id)
|
||||
|
||||
def _employee(self, email: str, role: str) -> OrganizationMembership:
|
||||
user = HumanUser.objects.create_user(email=email, password="Password-123")
|
||||
return OrganizationMembership.objects.create(
|
||||
user=user, organization=self.organization, role=role, position_title="Specialist"
|
||||
)
|
||||
|
||||
def _waiting_conversation(self) -> Conversation:
|
||||
contact = Contact.objects.create(organization=self.organization, name="Клиент")
|
||||
return Conversation.objects.create(
|
||||
organization=self.organization,
|
||||
channel=self.channel,
|
||||
group=self.support,
|
||||
contact=contact,
|
||||
lifecycle=LifecycleState.OPEN,
|
||||
control_mode=ControlMode.PAUSED,
|
||||
expected_responder=ExpectedResponder.OPERATOR,
|
||||
waiting_since=timezone.now(),
|
||||
)
|
||||
|
||||
def _wait_for(self, minutes: int) -> None:
|
||||
Conversation.objects.filter(pk=self.conversation.pk).update(
|
||||
waiting_since=timezone.now() - timedelta(minutes=minutes)
|
||||
)
|
||||
|
||||
def _dedup_keys(self) -> set[str]:
|
||||
return set(
|
||||
Notification.objects.filter(organization=self.organization).values_list(
|
||||
"dedup_key", flat=True
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
|
||||
class QueueEscalationTests(QueueTestBase):
|
||||
def test_fresh_dialog_is_not_escalated(self) -> None:
|
||||
self.assertEqual(sweep_waiting_conversations(self.context), 0)
|
||||
self.assertEqual(self._dedup_keys(), set())
|
||||
|
||||
def test_reminder_goes_to_the_group_of_the_dialog(self) -> None:
|
||||
self._wait_for(self.policy.remind_after_minutes + 1)
|
||||
self.assertEqual(sweep_waiting_conversations(self.context), 1)
|
||||
reminder = Notification.objects.get(dedup_key=f"waiting:{self.conversation.id}:remind")
|
||||
self.assertEqual(reminder.audience, NotificationAudience.OPERATORS)
|
||||
self.assertEqual(reminder.audience_group_id, self.support.id)
|
||||
|
||||
def test_circle_widens_beyond_the_group(self) -> None:
|
||||
self._wait_for(self.policy.widen_after_minutes + 1)
|
||||
sweep_waiting_conversations(self.context)
|
||||
widened = Notification.objects.get(dedup_key=f"waiting:{self.conversation.id}:widen")
|
||||
self.assertIsNone(widened.audience_group_id)
|
||||
|
||||
def test_management_is_called_last(self) -> None:
|
||||
self._wait_for(self.policy.escalate_after_minutes + 1)
|
||||
sweep_waiting_conversations(self.context)
|
||||
management = Notification.objects.filter(
|
||||
dedup_key__startswith=f"waiting:{self.conversation.id}:management"
|
||||
)
|
||||
self.assertEqual(
|
||||
{item.recipient_user_id for item in management}, {self.owner.user_id}
|
||||
)
|
||||
|
||||
def test_second_sweep_does_not_repeat_itself(self) -> None:
|
||||
self._wait_for(self.policy.escalate_after_minutes + 1)
|
||||
first = sweep_waiting_conversations(self.context)
|
||||
second = sweep_waiting_conversations(self.context)
|
||||
self.assertGreater(first, 0)
|
||||
self.assertEqual(second, 0)
|
||||
|
||||
def test_assigned_dialog_is_not_escalated_to_everyone(self) -> None:
|
||||
assign_operator(
|
||||
context=self.context,
|
||||
conversation_id=self.conversation.id,
|
||||
assignee=self.operator.user,
|
||||
)
|
||||
self._wait_for(self.policy.escalate_after_minutes + 1)
|
||||
sweep_waiting_conversations(self.context)
|
||||
self.assertEqual(
|
||||
{key for key in self._dedup_keys() if key.startswith("waiting:")}, set()
|
||||
)
|
||||
|
||||
|
||||
class AssignmentTests(QueueTestBase):
|
||||
def test_assignment_notifies_the_assignee_and_writes_history(self) -> None:
|
||||
assign_operator(
|
||||
context=self.context,
|
||||
conversation_id=self.conversation.id,
|
||||
assignee=self.operator.user,
|
||||
)
|
||||
notification = Notification.objects.get(
|
||||
dedup_key=f"assign:{self.conversation.id}:{self.operator.user_id}"
|
||||
)
|
||||
self.assertEqual(notification.audience, NotificationAudience.USER)
|
||||
self.assertEqual(notification.recipient_user_id, self.operator.user_id)
|
||||
self.assertEqual(
|
||||
list(self.conversation.messages.values_list("system_event", flat=True)),
|
||||
[SystemEvent.ASSIGNED_TO],
|
||||
)
|
||||
|
||||
def test_assigning_to_yourself_does_not_ping_you(self) -> None:
|
||||
assign_operator(
|
||||
context=self.context,
|
||||
conversation_id=self.conversation.id,
|
||||
assignee=self.owner.user,
|
||||
)
|
||||
self.assertFalse(
|
||||
Notification.objects.filter(
|
||||
dedup_key=f"assign:{self.conversation.id}:{self.owner.user_id}"
|
||||
).exists()
|
||||
)
|
||||
|
||||
def test_unclaimed_assignment_returns_the_dialog_to_the_queue(self) -> None:
|
||||
assign_operator(
|
||||
context=self.context,
|
||||
conversation_id=self.conversation.id,
|
||||
assignee=self.operator.user,
|
||||
)
|
||||
Conversation.objects.filter(pk=self.conversation.pk).update(
|
||||
assigned_at=timezone.now()
|
||||
- timedelta(minutes=self.policy.assignment_timeout_minutes + 1)
|
||||
)
|
||||
sweep_waiting_conversations(self.context)
|
||||
|
||||
self.conversation.refresh_from_db()
|
||||
self.assertIsNone(self.conversation.assigned_operator_id)
|
||||
self.assertIsNone(self.conversation.assigned_at)
|
||||
# Ожидание не обнулилось: клиент ждёт с того же момента, что и ждал.
|
||||
self.assertIsNotNone(self.conversation.waiting_since)
|
||||
self.assertIn(
|
||||
SystemEvent.ASSIGNMENT_EXPIRED,
|
||||
set(self.conversation.messages.values_list("system_event", flat=True)),
|
||||
)
|
||||
|
||||
|
||||
class PresenceEscalationTests(QueueTestBase):
|
||||
"""Присутствие сокращает ожидание, но ничего не запрещает."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
# Начинаем с пустой смены: за рабочим местом нет никого.
|
||||
cache.clear()
|
||||
|
||||
def test_circle_widens_at_the_first_threshold_when_nobody_is_online(self) -> None:
|
||||
self._wait_for(self.policy.remind_after_minutes + 1)
|
||||
sweep_waiting_conversations(self.context)
|
||||
self.assertTrue(
|
||||
Notification.objects.filter(
|
||||
dedup_key=f"waiting:{self.conversation.id}:widen"
|
||||
).exists()
|
||||
)
|
||||
|
||||
def test_present_operator_keeps_the_second_threshold(self) -> None:
|
||||
touch(self.organization.id, self.operator.user_id)
|
||||
self._wait_for(self.policy.remind_after_minutes + 1)
|
||||
sweep_waiting_conversations(self.context)
|
||||
# Напомнили группе, но круг не расширили: в группе есть кому ответить.
|
||||
self.assertTrue(
|
||||
Notification.objects.filter(
|
||||
dedup_key=f"waiting:{self.conversation.id}:remind"
|
||||
).exists()
|
||||
)
|
||||
self.assertFalse(
|
||||
Notification.objects.filter(
|
||||
dedup_key=f"waiting:{self.conversation.id}:widen"
|
||||
).exists()
|
||||
)
|
||||
|
||||
def test_presence_never_delays_the_wider_circle(self) -> None:
|
||||
touch(self.organization.id, self.operator.user_id)
|
||||
self._wait_for(self.policy.widen_after_minutes + 1)
|
||||
sweep_waiting_conversations(self.context)
|
||||
self.assertTrue(
|
||||
Notification.objects.filter(
|
||||
dedup_key=f"waiting:{self.conversation.id}:widen"
|
||||
).exists()
|
||||
)
|
||||
|
||||
def test_operator_of_another_group_does_not_count_as_present(self) -> None:
|
||||
outsider = self._employee("outsider@queue.test", EmployeeRole.EMPLOYEE)
|
||||
touch(self.organization.id, outsider.user_id)
|
||||
self._wait_for(self.policy.remind_after_minutes + 1)
|
||||
sweep_waiting_conversations(self.context)
|
||||
self.assertTrue(
|
||||
Notification.objects.filter(
|
||||
dedup_key=f"waiting:{self.conversation.id}:widen"
|
||||
).exists()
|
||||
)
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Очередь к оператору: с какого момента идёт ожидание и в каком порядке разбирают.
|
||||
|
||||
Регрессия, ради которой заведён waiting_since: «дольше всех ждущий» считался по
|
||||
времени последнего сообщения, поэтому клиент, напомнивший о себе, уезжал в конец
|
||||
очереди. Чем настойчивее человек, тем позже до него доходили руки.
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest import mock
|
||||
|
||||
from django.test import TestCase
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.ai.models import AIAgent
|
||||
from chatballs.channels.models import Channel
|
||||
from chatballs.conversations.ingest import ingest_inbound
|
||||
from chatballs.conversations.models import ControlMode, Conversation
|
||||
from chatballs.conversations.selectors import order_conversations
|
||||
from chatballs.conversations.services import (
|
||||
claim_conversation,
|
||||
close_conversation,
|
||||
return_to_queue,
|
||||
)
|
||||
from chatballs.conversations.transports.base import InboundMessage
|
||||
from chatballs.identity.bootstrap import bootstrap_owner
|
||||
from chatballs.identity.models import HumanUser, Organization
|
||||
from chatballs.integrations.models import Integration, IntegrationKind, IntegrationProvider
|
||||
from chatballs.notifications.models import Notification, NotificationType
|
||||
from chatballs.testing import tenant_context_for
|
||||
|
||||
|
||||
class QueueTestBase(TestCase):
|
||||
def setUp(self) -> None:
|
||||
bootstrap_owner(email="owner@example.com", password="temporary-password")
|
||||
self.organization = Organization.objects.get(slug="demo")
|
||||
self.owner = HumanUser.objects.get(email="owner@example.com")
|
||||
self.context = tenant_context_for(self.owner, self.organization)
|
||||
# Канал без активного агента: каждый входящий сразу создаёт очередь.
|
||||
self.channel = Channel.objects.create(
|
||||
organization=self.organization, code="queue-order", name="Очередь"
|
||||
)
|
||||
self.integration = Integration.objects.create(
|
||||
organization=self.organization,
|
||||
kind=IntegrationKind.MESSENGER,
|
||||
provider=IntegrationProvider.TELEGRAM,
|
||||
name="queue-bot",
|
||||
channel=self.channel,
|
||||
)
|
||||
|
||||
def _ingest(self, external_id: str, chat_id: str, text: str) -> None:
|
||||
inbound = InboundMessage(
|
||||
external_id=external_id,
|
||||
user_id=chat_id,
|
||||
chat_id=chat_id,
|
||||
text=text,
|
||||
display_name=chat_id,
|
||||
)
|
||||
with (
|
||||
mock.patch("chatballs.conversations.ingest.run_channel_turn"),
|
||||
mock.patch("chatballs.conversations.ingest.transports.send_reply"),
|
||||
):
|
||||
ingest_inbound(self.integration, inbound)
|
||||
|
||||
def _waiting_order(self) -> list[int]:
|
||||
ordered, _ = order_conversations(
|
||||
Conversation.objects.filter(organization=self.organization), "waiting"
|
||||
)
|
||||
return list(ordered.values_list("id", flat=True))
|
||||
|
||||
|
||||
|
||||
class QueueOrderTests(QueueTestBase):
|
||||
def test_new_dialog_without_agent_starts_waiting(self) -> None:
|
||||
self._ingest("m-1", "chat-1", "Здравствуйте")
|
||||
conversation = self.channel.conversations.get()
|
||||
self.assertEqual(conversation.control_mode, ControlMode.PAUSED)
|
||||
self.assertIsNotNone(conversation.waiting_since)
|
||||
|
||||
def test_reminder_from_customer_does_not_restart_the_wait(self) -> None:
|
||||
self._ingest("m-1", "chat-1", "Здравствуйте")
|
||||
conversation = self.channel.conversations.get()
|
||||
started = conversation.waiting_since
|
||||
|
||||
self._ingest("m-2", "chat-1", "Ну что там?")
|
||||
|
||||
conversation.refresh_from_db()
|
||||
self.assertEqual(conversation.waiting_since, started)
|
||||
# Свежесть диалога при этом обновилась — ожидание и активность разные вещи.
|
||||
self.assertGreater(conversation.last_message_at, started)
|
||||
|
||||
def test_longest_waiting_goes_first_even_after_a_reminder(self) -> None:
|
||||
self._ingest("a-1", "chat-a", "Первый вопрос")
|
||||
first = Conversation.objects.get(external_chat_id="chat-a")
|
||||
# Первый диалог ждёт заметно дольше второго.
|
||||
Conversation.objects.filter(pk=first.pk).update(
|
||||
waiting_since=timezone.now() - timedelta(hours=2)
|
||||
)
|
||||
self._ingest("b-1", "chat-b", "Второй вопрос")
|
||||
second = Conversation.objects.get(external_chat_id="chat-b")
|
||||
|
||||
# …и именно он напоминает о себе, двигая своё последнее сообщение вперёд.
|
||||
self._ingest("a-2", "chat-a", "Всё ещё жду")
|
||||
|
||||
self.assertEqual(self._waiting_order(), [first.id, second.id])
|
||||
|
||||
def test_claim_ends_the_wait_and_return_to_queue_starts_a_new_one(self) -> None:
|
||||
self._ingest("m-1", "chat-1", "Здравствуйте")
|
||||
conversation = self.channel.conversations.get()
|
||||
first_wait = conversation.waiting_since
|
||||
|
||||
claimed = claim_conversation(context=self.context, conversation_id=conversation.id)
|
||||
self.assertEqual(claimed.control_mode, ControlMode.HUMAN)
|
||||
self.assertIsNone(claimed.waiting_since)
|
||||
|
||||
returned = return_to_queue(context=self.context, conversation_id=conversation.id)
|
||||
self.assertEqual(returned.control_mode, ControlMode.PAUSED)
|
||||
self.assertIsNotNone(returned.waiting_since)
|
||||
# Ожидание началось заново: диалог успел побывать у оператора.
|
||||
self.assertGreater(returned.waiting_since, first_wait)
|
||||
|
||||
def test_closed_dialog_leaves_the_queue(self) -> None:
|
||||
self._ingest("z-1", "chat-z", "Вопрос")
|
||||
conversation = self.channel.conversations.get()
|
||||
self.assertIsNotNone(conversation.waiting_since)
|
||||
|
||||
closed = close_conversation(context=self.context, conversation_id=conversation.id)
|
||||
self.assertIsNone(closed.waiting_since)
|
||||
|
||||
|
||||
class NewDialogNotificationTests(QueueTestBase):
|
||||
"""«Новый диалог» и «клиент запросил оператора» — разные события.
|
||||
|
||||
Диалог начинается и на канале с работающим агентом, где человека никто не
|
||||
звал. Назвать такой оклик просьбой о человеке — соврать тому, кто на него
|
||||
подписан.
|
||||
"""
|
||||
|
||||
def _last_type(self) -> str:
|
||||
return (
|
||||
Notification.objects.filter(organization=self.organization)
|
||||
.order_by("-id")
|
||||
.values_list("type", flat=True)
|
||||
.first()
|
||||
)
|
||||
|
||||
def test_dialog_without_an_agent_asks_for_a_person(self) -> None:
|
||||
self._ingest("n-1", "chat-n", "Здравствуйте")
|
||||
self.assertEqual(self._last_type(), NotificationType.OPERATOR_REQUESTED)
|
||||
|
||||
def test_dialog_handled_by_the_agent_is_just_a_new_dialog(self) -> None:
|
||||
agent = AIAgent.objects.create(
|
||||
organization=self.organization,
|
||||
channel=self.channel,
|
||||
name="Консультант",
|
||||
is_active=True,
|
||||
)
|
||||
self.assertTrue(agent.is_active)
|
||||
with mock.patch(
|
||||
"chatballs.conversations.ingest.run_channel_turn",
|
||||
return_value=mock.Mock(text="Здравствуйте!"),
|
||||
), mock.patch("chatballs.conversations.ingest.transports.send_reply"):
|
||||
ingest_inbound(
|
||||
self.integration,
|
||||
InboundMessage(
|
||||
external_id="a-1",
|
||||
user_id="chat-a",
|
||||
chat_id="chat-a",
|
||||
text="Здравствуйте",
|
||||
display_name="chat-a",
|
||||
),
|
||||
)
|
||||
self.assertEqual(self._last_type(), NotificationType.NEW_DIALOG)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Сроки очереди через API (макет Q2).
|
||||
|
||||
До этого пороги правились только в служебной админке — то есть де-факто никем.
|
||||
"""
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from chatballs.conversations.queue_models import QueueEscalationPolicy
|
||||
from chatballs.identity.models import (
|
||||
EmployeeRole,
|
||||
HumanUser,
|
||||
Organization,
|
||||
OrganizationMembership,
|
||||
)
|
||||
from chatballs.testing import TenantAPIClient as APIClient
|
||||
|
||||
URL = "/api/v1/conversations/queue-policy/"
|
||||
|
||||
|
||||
class QueuePolicyApiTests(TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.organization = Organization.objects.create(name="Example", slug="queue-policy")
|
||||
self.owner = self._employee("owner@policy.test", EmployeeRole.OWNER)
|
||||
self.operator = self._employee("operator@policy.test", EmployeeRole.EMPLOYEE)
|
||||
self.client = APIClient()
|
||||
self.client.force_authenticate(self.owner.user)
|
||||
|
||||
def _employee(self, email: str, role: str) -> OrganizationMembership:
|
||||
user = HumanUser.objects.create_user(email=email, password="Password-123")
|
||||
return OrganizationMembership.objects.create(
|
||||
user=user, organization=self.organization, role=role, position_title="Specialist"
|
||||
)
|
||||
|
||||
def test_first_read_returns_usual_delays(self) -> None:
|
||||
response = self.client.get(URL)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
payload = response.json()
|
||||
self.assertEqual(payload["remind_after_minutes"], 5)
|
||||
self.assertEqual(payload["assignment_timeout_minutes"], 10)
|
||||
self.assertEqual(payload["defaults"], payload["defaults"] | {"widen_after_minutes": 15})
|
||||
self.assertIsNone(payload["updatedAt"])
|
||||
|
||||
def test_saving_remembers_who_and_when(self) -> None:
|
||||
response = self.client.patch(URL, {"remind_after_minutes": 3}, format="json")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
payload = response.json()
|
||||
self.assertEqual(payload["remind_after_minutes"], 3)
|
||||
self.assertEqual(payload["updatedBy"], self.owner.user.full_name or self.owner.user.email)
|
||||
self.assertIsNotNone(payload["updatedAt"])
|
||||
self.assertEqual(QueueEscalationPolicy.objects.get().remind_after_minutes, 3)
|
||||
|
||||
def test_nonsense_values_are_refused(self) -> None:
|
||||
for value in (0, -5, 10000, "быстро", True):
|
||||
with self.subTest(value=value):
|
||||
response = self.client.patch(URL, {"widen_after_minutes": value}, format="json")
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(QueueEscalationPolicy.objects.get().widen_after_minutes, 15)
|
||||
|
||||
def test_operator_reads_but_does_not_change(self) -> None:
|
||||
self.client.force_authenticate(self.operator.user)
|
||||
self.assertEqual(self.client.get(URL).status_code, 403)
|
||||
self.assertEqual(
|
||||
self.client.patch(URL, {"remind_after_minutes": 1}, format="json").status_code, 403
|
||||
)
|
||||
@@ -3,7 +3,6 @@ from unittest import mock
|
||||
|
||||
from django.test import TestCase, override_settings
|
||||
|
||||
from chatballs.ai.limits import LimitExceeded
|
||||
from chatballs.ai.models import AIAgent, AIAgentStatus
|
||||
from chatballs.ai.provider.base import ProviderError
|
||||
from chatballs.channels.models import Channel
|
||||
@@ -42,10 +41,9 @@ def _messenger_connection(channel):
|
||||
)
|
||||
|
||||
|
||||
class IngestLimitHandlingTests(TestCase):
|
||||
"""При срабатывании дневного лимита стоимости (LimitExceeded) диалог не должен
|
||||
«зависать»: его передают оператору с fallback-ответом клиенту (как при сбое
|
||||
провайдера). См. ingest.ingest_inbound.
|
||||
class IngestProviderFailureTests(TestCase):
|
||||
"""При сбое провайдера диалог не должен «зависать»: его передают оператору с
|
||||
fallback-ответом клиенту. См. ingest.ingest_inbound.
|
||||
"""
|
||||
|
||||
def setUp(self) -> None:
|
||||
@@ -63,13 +61,13 @@ class IngestLimitHandlingTests(TestCase):
|
||||
external_id="ext-1", user_id="user-1", chat_id="chat-1", text="Здравствуйте", display_name="Гость"
|
||||
)
|
||||
|
||||
def test_limit_exceeded_hands_off_to_operator(self) -> None:
|
||||
def test_provider_failure_hands_off_to_operator(self) -> None:
|
||||
from chatballs.conversations.ingest import ingest_inbound
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"chatballs.conversations.ingest.run_channel_turn",
|
||||
side_effect=LimitExceeded("Channel daily AI cost limit reached"),
|
||||
side_effect=ProviderError("provider is down"),
|
||||
),
|
||||
mock.patch("chatballs.conversations.ingest.transports.send_reply", return_value=True) as send,
|
||||
):
|
||||
@@ -423,7 +421,7 @@ class WebchatContactTests(TestCase):
|
||||
)
|
||||
self.assertTrue(
|
||||
Notification.objects.filter(
|
||||
type=NotificationType.DIALOG_WAITING,
|
||||
type=NotificationType.OPERATOR_REQUESTED,
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
target_id=str(conversation.id),
|
||||
).exists()
|
||||
@@ -431,7 +429,7 @@ class WebchatContactTests(TestCase):
|
||||
self.assertEqual(
|
||||
set(
|
||||
Notification.objects.filter(
|
||||
type=NotificationType.INTEGRATION_ERROR,
|
||||
type=NotificationType.AI_STOPPED,
|
||||
audience=NotificationAudience.USER,
|
||||
target_id=str(conversation.id),
|
||||
).values_list("recipient_user__email", flat=True)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from chatballs.conversations.transports import backoff
|
||||
from chatballs.conversations.transports import email as _email
|
||||
from chatballs.conversations.transports import max as _max
|
||||
from chatballs.conversations.transports import telegram as _telegram
|
||||
from chatballs.conversations.transports.errors import PollFailed
|
||||
from chatballs.i18n import t
|
||||
from chatballs.integrations.models import IntegrationProvider
|
||||
|
||||
@@ -51,7 +53,22 @@ SUPPORTED_PROVIDERS = tuple(_POLL.keys())
|
||||
|
||||
|
||||
def poll(integration):
|
||||
return _POLL[integration.provider](integration)
|
||||
"""Опрос подключения с паузой после сбоя (transports.backoff).
|
||||
|
||||
Сбой транспорта не роняет цикл и не пишется в журнал на каждой попытке:
|
||||
подключение пропускается с растущей паузой, а журнал видит только смену
|
||||
состояния. Курсор при сбое не двигается.
|
||||
"""
|
||||
|
||||
if backoff.should_skip(integration.id):
|
||||
return [], integration.poll_marker
|
||||
try:
|
||||
result = _POLL[integration.provider](integration)
|
||||
except PollFailed as error:
|
||||
backoff.record_failure(integration, error)
|
||||
return [], integration.poll_marker
|
||||
backoff.record_success(integration)
|
||||
return result
|
||||
|
||||
|
||||
def send_reply(integration, *, chat_id: str, user_id: str, text: str) -> bool:
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Пауза между попытками опроса подключения после сбоя.
|
||||
|
||||
Воркер опрашивает мессенджеры каждые три секунды. Подключение с отозванным
|
||||
токеном или недоступным сервером отвечало ошибкой на каждый цикл и писало
|
||||
её в журнал двадцать раз в минуту — журнал переставал быть читаемым, а
|
||||
чужой сервер получал бессмысленный поток запросов. Теперь после сбоя
|
||||
подключение пропускается с растущей паузой, а в журнал попадают только
|
||||
изменения состояния: первый сбой, выход на максимальную паузу и
|
||||
восстановление.
|
||||
|
||||
Состояние живёт в памяти процесса: воркер один, а после перезапуска первая
|
||||
попытка всё равно нужна.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Первая пауза — два цикла опроса, дальше удвоение до четверти часа.
|
||||
FIRST_DELAY_SECONDS = 6.0
|
||||
MAX_DELAY_SECONDS = 900.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Failure:
|
||||
failures: int
|
||||
next_attempt_at: float
|
||||
delay: float
|
||||
|
||||
|
||||
_failures: dict[int, _Failure] = {}
|
||||
|
||||
|
||||
def _now() -> float:
|
||||
return time.monotonic()
|
||||
|
||||
|
||||
def should_skip(integration_id: int) -> bool:
|
||||
state = _failures.get(integration_id)
|
||||
return state is not None and _now() < state.next_attempt_at
|
||||
|
||||
|
||||
def record_failure(integration, error: object) -> None:
|
||||
previous = _failures.get(integration.id)
|
||||
failures = (previous.failures if previous else 0) + 1
|
||||
delay = min(FIRST_DELAY_SECONDS * 2 ** (failures - 1), MAX_DELAY_SECONDS)
|
||||
_failures[integration.id] = _Failure(failures=failures, next_attempt_at=_now() + delay, delay=delay)
|
||||
if failures == 1:
|
||||
logger.warning(
|
||||
"%s poll failed for integration %s: %s (next attempt in %.0fs)",
|
||||
integration.provider, integration.id, error, delay,
|
||||
)
|
||||
elif delay >= MAX_DELAY_SECONDS and (previous is None or previous.delay < MAX_DELAY_SECONDS):
|
||||
logger.warning(
|
||||
"%s poll keeps failing for integration %s: %s (retrying every %.0f min)",
|
||||
integration.provider, integration.id, error, MAX_DELAY_SECONDS / 60,
|
||||
)
|
||||
|
||||
|
||||
def record_success(integration) -> None:
|
||||
state = _failures.pop(integration.id, None)
|
||||
if state is not None:
|
||||
logger.info(
|
||||
"%s poll recovered for integration %s after %s failure(s)",
|
||||
integration.provider, integration.id, state.failures,
|
||||
)
|
||||
|
||||
|
||||
def reset() -> None:
|
||||
"""Для тестов: забыть все сбои."""
|
||||
|
||||
_failures.clear()
|
||||
@@ -26,6 +26,7 @@ from chatballs.conversations.transports.base import (
|
||||
guess_content_type,
|
||||
safe_filename,
|
||||
)
|
||||
from chatballs.conversations.transports.errors import PollFailed
|
||||
from chatballs.i18n import customer_language, t
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -135,8 +136,7 @@ def poll_updates(integration) -> tuple[list[InboundMessage], str]:
|
||||
try:
|
||||
client = _imap_connect(integration)
|
||||
except (imaplib.IMAP4.error, OSError, TimeoutError) as error:
|
||||
logger.warning("Email IMAP poll failed for integration %s: %s", integration.id, error)
|
||||
return [], integration.poll_marker
|
||||
raise PollFailed(str(error)) from error
|
||||
try:
|
||||
client.select("INBOX", readonly=True)
|
||||
validity = _status_value(client, "UIDVALIDITY")
|
||||
@@ -162,8 +162,7 @@ def poll_updates(integration) -> tuple[list[InboundMessage], str]:
|
||||
new_marker = f"{validity}:{uids[-1]}" if uids else integration.poll_marker
|
||||
return messages, new_marker
|
||||
except (imaplib.IMAP4.error, OSError, TimeoutError) as error:
|
||||
logger.warning("Email IMAP poll failed for integration %s: %s", integration.id, error)
|
||||
return [], integration.poll_marker
|
||||
raise PollFailed(str(error)) from error
|
||||
finally:
|
||||
try:
|
||||
client.logout()
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
class PollFailed(Exception):
|
||||
"""Опрос подключения не удался: сеть, авторизация, ответ не разобран.
|
||||
|
||||
Транспорт не пишет об этом в журнал сам — решение, когда повторить и что
|
||||
записать, принимает слой пауз между попытками (``transports.backoff``).
|
||||
"""
|
||||
@@ -27,6 +27,7 @@ from chatballs.conversations.transports.base import (
|
||||
request_json_multipart,
|
||||
safe_filename,
|
||||
)
|
||||
from chatballs.conversations.transports.errors import PollFailed
|
||||
from chatballs.i18n import customer_language, t
|
||||
from chatballs.integrations.checks import DEFAULT_MAX_BASE_URL
|
||||
from chatballs.integrations.outbound import host_of
|
||||
@@ -242,8 +243,7 @@ def poll_updates(integration) -> tuple[list[InboundMessage], str]:
|
||||
try:
|
||||
data = request_json(url, headers={"Authorization": token, "Content-Type": "application/json"}, proxy_url=_proxy(integration))
|
||||
except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException, json.JSONDecodeError) as error:
|
||||
logger.warning("MAX poll failed for integration %s: %s", integration.id, error)
|
||||
return [], integration.poll_marker
|
||||
raise PollFailed(str(error)) from error
|
||||
updates = data.get("updates") or []
|
||||
messages = [m for m in (_normalize(u) for u in updates) if m is not None]
|
||||
new_marker = data.get("marker")
|
||||
|
||||
@@ -23,6 +23,7 @@ from chatballs.conversations.transports.base import (
|
||||
request_json_multipart,
|
||||
safe_filename,
|
||||
)
|
||||
from chatballs.conversations.transports.errors import PollFailed
|
||||
from chatballs.i18n import customer_language, t
|
||||
from chatballs.integrations.checks import DEFAULT_TELEGRAM_BASE_URL
|
||||
from chatballs.integrations.outbound import host_of
|
||||
@@ -124,8 +125,7 @@ def poll_updates(integration) -> tuple[list[InboundMessage], str]:
|
||||
try:
|
||||
data = request_json(url, proxy_url=_proxy(integration))
|
||||
except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException, json.JSONDecodeError) as error:
|
||||
logger.warning("Telegram poll failed for integration %s: %s", integration.id, error)
|
||||
return [], integration.poll_marker
|
||||
raise PollFailed(str(error)) from error
|
||||
if not data.get("ok"):
|
||||
return [], integration.poll_marker
|
||||
updates = data.get("result") or []
|
||||
|
||||
@@ -3,6 +3,7 @@ from django.urls import path
|
||||
from chatballs.conversations import (
|
||||
attachment_views,
|
||||
chat_extras_views,
|
||||
queue_policy_views,
|
||||
reporting_views,
|
||||
views,
|
||||
voice_views,
|
||||
@@ -30,6 +31,7 @@ urlpatterns = [
|
||||
path("<int:conversation_id>/labels/", chat_extras_views.ConversationLabelsView.as_view(), name="conversation-labels"),
|
||||
path("<int:conversation_id>/archive/", chat_extras_views.ConversationArchiveView.as_view(), name="conversation-archive"),
|
||||
path("counters/", chat_extras_views.ConversationCountersView.as_view(), name="conversation-counters"),
|
||||
path("queue-policy/", queue_policy_views.QueuePolicyView.as_view(), name="conversation-queue-policy"),
|
||||
path("directory/", chat_extras_views.ConversationDirectoryView.as_view(), name="conversation-directory"),
|
||||
path("labels/", chat_extras_views.LabelListView.as_view(), name="conversation-label-list"),
|
||||
path("labels/<int:label_id>/", chat_extras_views.LabelDetailView.as_view(), name="conversation-label-detail"),
|
||||
|
||||
@@ -30,6 +30,7 @@ from chatballs.conversations.serializers import (
|
||||
)
|
||||
from chatballs.conversations.services import (
|
||||
ClaimError,
|
||||
assign_operator,
|
||||
claim_conversation,
|
||||
close_conversation,
|
||||
mark_conversation_as_spam,
|
||||
@@ -87,6 +88,21 @@ class ConversationListView(ConversationViewBase):
|
||||
items = items.filter(
|
||||
lifecycle=LifecycleState.OPEN, control_mode=ControlMode.PAUSED
|
||||
)
|
||||
# Две вкладки ожидания (макет «Очередь и уведомления», кадр Q3): общая
|
||||
# очередь — диалоги без ответственного, их берёт кто угодно; «на мне» —
|
||||
# назначенные лично и ждущие, пока их возьмут.
|
||||
if params.get("queue") == "1":
|
||||
items = items.filter(
|
||||
lifecycle=LifecycleState.OPEN,
|
||||
control_mode=ControlMode.PAUSED,
|
||||
assigned_operator__isnull=True,
|
||||
)
|
||||
if params.get("waitingOnMe") == "1":
|
||||
items = items.filter(
|
||||
lifecycle=LifecycleState.OPEN,
|
||||
control_mode=ControlMode.PAUSED,
|
||||
assigned_operator_id=request.user.id,
|
||||
)
|
||||
query = params.get("q", "").strip()
|
||||
if query:
|
||||
from django.contrib.postgres.search import SearchQuery, SearchVector
|
||||
@@ -469,8 +485,11 @@ class ConversationAssigneeView(ConversationViewBase):
|
||||
if membership is None:
|
||||
return Response({"detail": t("admin.employee_not_found")}, status=400)
|
||||
assignee = membership.user
|
||||
conversation.assigned_operator = assignee
|
||||
conversation.save(update_fields=["assigned_operator"])
|
||||
conversation = assign_operator(
|
||||
context=request.tenant_context,
|
||||
conversation_id=conversation.id,
|
||||
assignee=assignee,
|
||||
)
|
||||
self._audit(request, "assignee_changed", conversation)
|
||||
return Response(
|
||||
{
|
||||
|
||||
@@ -6,6 +6,7 @@ from django.core.management.base import BaseCommand
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.calls.maintenance import expire_stale_calls
|
||||
from chatballs.conversations.escalation import sweep_waiting_conversations
|
||||
from chatballs.conversations.maintenance import close_stale_conversations
|
||||
from chatballs.conversations.poller import poll_all_messengers
|
||||
from chatballs.events.handlers import dispatch
|
||||
@@ -15,12 +16,16 @@ from chatballs.notifications.binding import poll_notifier_bots
|
||||
from chatballs.tenancy.context import TenantActorKind, TenantContext
|
||||
from chatballs.tenancy.database import tenant_atomic
|
||||
from chatballs.tenancy.lookup import iter_organizations
|
||||
from chatballs.updates.services import check_for_updates
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MESSENGER_POLL_INTERVAL = 3.0 # seconds between messenger long-poll cycles
|
||||
MAINTENANCE_INTERVAL = 3600.0 # seconds between maintenance cycles (auto-close stale dialogs)
|
||||
CALL_SWEEP_INTERVAL = 10.0 # seconds between call timeout sweeps (invite expiry, stuck connect)
|
||||
# Пороги очереди задаются в минутах, поэтому раз в полминуты — с запасом:
|
||||
# проверка дешёвая, а повтор гасится dedup-ключом уровня.
|
||||
QUEUE_SWEEP_INTERVAL = 30.0 # seconds between waiting-queue escalation sweeps
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
@@ -38,6 +43,7 @@ class Command(BaseCommand):
|
||||
last_poll = 0.0
|
||||
last_maintenance = 0.0
|
||||
last_call_sweep = 0.0
|
||||
last_queue_sweep = 0.0
|
||||
while True:
|
||||
try:
|
||||
event = claim_next_outbox_event()
|
||||
@@ -90,8 +96,22 @@ class Command(BaseCommand):
|
||||
expire_stale_calls(context)
|
||||
except Exception: # pragma: no cover
|
||||
logger.exception("Call sweep cycle failed")
|
||||
if now - last_queue_sweep >= QUEUE_SWEEP_INTERVAL:
|
||||
last_queue_sweep = now
|
||||
try:
|
||||
for context in self._tenant_contexts():
|
||||
with tenant_atomic(context):
|
||||
sweep_waiting_conversations(context)
|
||||
except Exception: # pragma: no cover
|
||||
logger.exception("Waiting queue sweep cycle failed")
|
||||
if now - last_maintenance >= MAINTENANCE_INTERVAL:
|
||||
last_maintenance = now
|
||||
# Канал релизов спрашивается не чаще раза в несколько часов:
|
||||
# интервал держит сама проверка по времени последнего ответа.
|
||||
try:
|
||||
check_for_updates()
|
||||
except Exception: # pragma: no cover
|
||||
logger.exception("Update check cycle failed")
|
||||
try:
|
||||
for context in self._tenant_contexts():
|
||||
with tenant_atomic(context):
|
||||
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
|
||||
MESSAGES: dict[str, object] = {
|
||||
"admin.choose_logo_file": "Choose a logo file",
|
||||
"admin.currency_rub_only": "Only the Russian rouble (RUB) is supported",
|
||||
"admin.employee_not_found": "Operator not found",
|
||||
"admin.group_name_taken": "A group with this name already exists",
|
||||
"admin.group_not_found": "Group not found",
|
||||
@@ -55,6 +54,8 @@ MESSAGES: dict[str, object] = {
|
||||
"conversations.not_found": "Conversation not found",
|
||||
"conversations.note_too_long": "The note is longer than 4000 characters",
|
||||
"conversations.restore_admin_only": "Only an administrator can restore a conversation",
|
||||
"conversations.system.assigned_to": "Conversation assigned to {operator}",
|
||||
"conversations.system.assignment_expired": "{operator} did not pick the conversation up — it is back in the queue",
|
||||
"conversations.system.ai_handed_over": "AI handed the conversation to an operator",
|
||||
"conversations.system.ai_unavailable": "AI is unavailable — the conversation was handed to an operator",
|
||||
"conversations.system.call_accepted": "The customer accepted the call invitation",
|
||||
@@ -97,11 +98,23 @@ MESSAGES: dict[str, object] = {
|
||||
"notifications.new_dialog_body": "{contact} · {provider}: {preview}",
|
||||
"notifications.new_message": "New message · {contact}",
|
||||
"notifications.operator_needed": "An operator is needed · {contact}",
|
||||
"notifications.still_waiting": "Conversation is still waiting · {contact}",
|
||||
"notifications.still_waiting_body": "Nobody has picked this conversation up. Open it if you can reply.",
|
||||
"notifications.waiting_unattended": "Nobody is picking this conversation up · {contact}",
|
||||
"notifications.waiting_unattended_body": "The customer has been waiting longer than usual and the queue is not being worked.",
|
||||
"notifications.assigned_to_you": "A conversation was assigned to you · {contact}",
|
||||
"notifications.assignment_expired": "Conversation is unassigned again · {contact}",
|
||||
"notifications.voice_without_transcript": "A voice message without a transcript",
|
||||
"onboarding.membership_required": "Onboarding is available to organization members",
|
||||
"onboarding.unknown_action": "Unknown onboarding action",
|
||||
"portals.article_not_found": "Article not found",
|
||||
"portals.file_field_required": "A file is required in the file field (multipart/form-data)",
|
||||
"portals.file_not_found": "File not found",
|
||||
"portals.helpful_must_be_boolean": "helpful must be a boolean",
|
||||
"portals.installation_domain_missing": (
|
||||
"The installation address has no domain: set one in Settings, "
|
||||
"otherwise there is nowhere to host the portal"
|
||||
),
|
||||
"portals.invalid_article": "Invalid article",
|
||||
"portals.invalid_article_data": "Invalid article data",
|
||||
"portals.invalid_category": "Invalid category",
|
||||
@@ -111,7 +124,7 @@ MESSAGES: dict[str, object] = {
|
||||
"portals.invalid_section": "Invalid section",
|
||||
"portals.not_found": "Portal not found",
|
||||
"portals.section_not_found": "Section not found",
|
||||
"profile.accent_hex": "The accent is a HEX colour like #1677ff",
|
||||
"profile.accent_hex": "The accent is a HEX colour like #0f9b8e",
|
||||
"profile.choose_photo_file": "Choose a photo file",
|
||||
"profile.link_not_found": "Link not found",
|
||||
"profile.notification_bot_not_found": "Notification bot not found",
|
||||
@@ -213,6 +226,7 @@ MESSAGES: dict[str, object] = {
|
||||
"audit.action_identity_employee_invited": "Operator invited",
|
||||
"audit.action_identity_invitation_accepted": "Organization invitation accepted",
|
||||
"audit.action_identity_invitation_revoked": "Operator invitation revoked",
|
||||
"audit.action_updates_install_requested": "Installation update started",
|
||||
"audit.action_identity_employee_groups_changed": "Operator groups changed",
|
||||
"audit.action_identity_employee_password_reset": "Operator password reset",
|
||||
"audit.action_identity_employee_privileged_action_denied": "Privileged action denied",
|
||||
@@ -246,6 +260,7 @@ MESSAGES: dict[str, object] = {
|
||||
"audit.action_integrations_integration_created": "Integration added",
|
||||
"audit.action_integrations_integration_deleted": "Integration deleted",
|
||||
"audit.action_integrations_integration_updated": "Integration changed",
|
||||
"audit.action_organization_created": "Organization created from the interface",
|
||||
"audit.action_organization_owner_activated": "Organization owner activated",
|
||||
"audit.action_organization_owner_invitation_requested": "Owner invitation sent",
|
||||
"audit.action_organization_provisioned": "Organization created",
|
||||
@@ -331,13 +346,21 @@ MESSAGES: dict[str, object] = {
|
||||
"identity.invalid_credentials": "Invalid credentials",
|
||||
"identity.invalid_totp_code": "Invalid TOTP code",
|
||||
"identity.invitation_email_mismatch": "Invitation email does not match the account",
|
||||
"identity.organization_create_forbidden": "Only the installation administrator and organization owners or administrators can create organizations",
|
||||
"identity.invitation_invalid": "Invitation is invalid or has expired",
|
||||
"identity.invitation_account_exists": "An account with this address already exists. Sign in with it",
|
||||
"updates.nothing_to_install": "The latest version is already installed",
|
||||
"updates.updater_offline": "The update service is not running, so updating from the interface is unavailable",
|
||||
"updates.install_in_progress": "An update is already in progress",
|
||||
"identity.role_conflict": "User already has a different role in this organization",
|
||||
"identity.token_required": "token is required",
|
||||
"identity.totp_challenge_inactive": "TOTP challenge is not active",
|
||||
"notifications.ids_list_or_all": "ids must be a list or use all=true",
|
||||
"notifications.push_types_list": "pushTypes must be a list",
|
||||
"notifications.enabled_bool": "enabled must be true or false",
|
||||
"settings.queue_minutes_range": "The delay is set in minutes, from 1 to 1440",
|
||||
"settings.queue_policy_forbidden": "Only someone who manages settings can change these delays",
|
||||
"notifications.unknown_transport": "Unknown delivery channel",
|
||||
"platform.idempotency_key_required": "Idempotency-Key header is required",
|
||||
"portals.articles_non_empty": "articles must be a non-empty list",
|
||||
"profile.current_password_invalid": "Current password is invalid",
|
||||
@@ -355,7 +378,8 @@ MESSAGES: dict[str, object] = {
|
||||
"api.expected_record_id": "{name}: a record identifier is expected",
|
||||
"settings.storage_unavailable": "The storage is unavailable: {error}",
|
||||
"admin.actor_system": "System",
|
||||
"admin.image_formats": "PNG, JPEG and WebP are supported",
|
||||
"admin.image_formats": "PNG, JPEG, WebP and SVG are supported",
|
||||
"admin.svg_logo_unsafe": "SVG must not contain scripts, event handlers or external links",
|
||||
"admin.logo_too_large": "The logo must not exceed 2 MB",
|
||||
"calls.calls_off_entry_point": "Calls are switched off for this entry point",
|
||||
"calls.failure_code_required": "FAILED needs a normalized failure_code",
|
||||
@@ -469,10 +493,12 @@ MESSAGES: dict[str, object] = {
|
||||
"ai.unexpected_provider_response": "Unexpected provider response: {error}",
|
||||
"settings.base_url_rejected": "Base URL: {error}",
|
||||
"settings.proxy_url_rejected": "Proxy: {error}",
|
||||
"notifications.type_dialog_waiting": "A dialog is waiting for an operator",
|
||||
"notifications.type_dialog_new_message": "A new message in a dialog",
|
||||
"notifications.type_release_published": "An agent release was published",
|
||||
"notifications.type_integration_error": "Integration error",
|
||||
"notifications.type_new_dialog": "A new conversation",
|
||||
"notifications.type_operator_requested": "A customer asked for a person",
|
||||
"notifications.type_dialog_new_message": "A new message in my conversation",
|
||||
"notifications.type_dialog_assigned": "A conversation was assigned to me",
|
||||
"notifications.type_dialog_waiting_long": "A conversation has been waiting a long time",
|
||||
"notifications.type_ai_stopped": "AI stopped by an error",
|
||||
"integrations.check_no_connection": "No connection: {error}",
|
||||
"integrations.check_api_key_missing": "The API key is not set",
|
||||
"integrations.check_base_url_missing": "Base URL is not set",
|
||||
|
||||
@@ -8,7 +8,6 @@ from __future__ import annotations
|
||||
|
||||
MESSAGES: dict[str, object] = {
|
||||
"admin.choose_logo_file": "Выберите файл логотипа",
|
||||
"admin.currency_rub_only": "Поддерживается только российский рубль (RUB)",
|
||||
"admin.employee_not_found": "Сотрудник не найден",
|
||||
"admin.group_name_taken": "Группа с таким именем уже есть",
|
||||
"admin.group_not_found": "Группа не найдена",
|
||||
@@ -60,6 +59,8 @@ MESSAGES: dict[str, object] = {
|
||||
"conversations.note_too_long": "Заметка длиннее 4000 символов",
|
||||
"conversations.restore_admin_only": "Восстановить диалог может только администратор",
|
||||
"conversations.system.ai_handed_over": "AI передал диалог оператору",
|
||||
"conversations.system.assigned_to": "Диалог назначен на {operator}",
|
||||
"conversations.system.assignment_expired": "{operator} не взял диалог — он вернулся в очередь",
|
||||
"conversations.system.ai_unavailable": "AI недоступен — диалог передан оператору",
|
||||
"conversations.system.call_accepted": "Клиент принял приглашение на звонок",
|
||||
"conversations.system.call_cancelled": "Сотрудник отменил приглашение на звонок",
|
||||
@@ -102,10 +103,22 @@ MESSAGES: dict[str, object] = {
|
||||
"notifications.new_message": "Новое сообщение · {contact}",
|
||||
"notifications.operator_needed": "Нужен оператор · {contact}",
|
||||
"notifications.voice_without_transcript": "Голосовое без расшифровки",
|
||||
"notifications.still_waiting": "Диалог всё ещё ждёт · {contact}",
|
||||
"notifications.still_waiting_body": "Диалог никто не взял. Откройте его, если можете ответить.",
|
||||
"notifications.waiting_unattended": "Диалог никто не берёт · {contact}",
|
||||
"notifications.waiting_unattended_body": "Клиент ждёт ответа дольше обычного, и очередь не разбирают.",
|
||||
"notifications.assigned_to_you": "Вам назначен диалог · {contact}",
|
||||
"notifications.assignment_expired": "Диалог снова ничей · {contact}",
|
||||
"onboarding.membership_required": "Онбординг доступен участнику организации",
|
||||
"onboarding.unknown_action": "Неизвестное действие онбординга",
|
||||
"portals.article_not_found": "Статья не найдена",
|
||||
"portals.file_field_required": "Нужен файл в поле file (multipart/form-data)",
|
||||
"portals.file_not_found": "Файл не найден",
|
||||
"portals.helpful_must_be_boolean": "helpful должен быть boolean",
|
||||
"portals.installation_domain_missing": (
|
||||
"Адрес установки задан без домена: укажите домен в «Настройках», "
|
||||
"иначе портал негде разместить"
|
||||
),
|
||||
"portals.invalid_article": "Некорректная статья",
|
||||
"portals.invalid_article_data": "Некорректные данные статьи",
|
||||
"portals.invalid_category": "Некорректная категория",
|
||||
@@ -115,7 +128,7 @@ MESSAGES: dict[str, object] = {
|
||||
"portals.invalid_section": "Некорректный раздел",
|
||||
"portals.not_found": "Портал не найден",
|
||||
"portals.section_not_found": "Раздел не найден",
|
||||
"profile.accent_hex": "Акцент — HEX-цвет вида #1677ff",
|
||||
"profile.accent_hex": "Акцент — HEX-цвет вида #0f9b8e",
|
||||
"profile.choose_photo_file": "Выберите файл фото",
|
||||
"profile.link_not_found": "Привязка не найдена",
|
||||
"profile.notification_bot_not_found": "Бот уведомлений не найден",
|
||||
@@ -217,6 +230,7 @@ MESSAGES: dict[str, object] = {
|
||||
"audit.action_identity_employee_invited": "Отправлено приглашение сотруднику",
|
||||
"audit.action_identity_invitation_accepted": "Принято приглашение в организацию",
|
||||
"audit.action_identity_invitation_revoked": "Отозвано приглашение сотрудника",
|
||||
"audit.action_updates_install_requested": "Запущено обновление установки",
|
||||
"audit.action_identity_employee_groups_changed": "Изменены группы сотрудника",
|
||||
"audit.action_identity_employee_password_reset": "Сброшен пароль сотрудника",
|
||||
"audit.action_identity_employee_privileged_action_denied": "Отказано в привилегированном действии",
|
||||
@@ -250,6 +264,7 @@ MESSAGES: dict[str, object] = {
|
||||
"audit.action_integrations_integration_created": "Добавлена интеграция",
|
||||
"audit.action_integrations_integration_deleted": "Удалена интеграция",
|
||||
"audit.action_integrations_integration_updated": "Изменена интеграция",
|
||||
"audit.action_organization_created": "Создана организация из интерфейса",
|
||||
"audit.action_organization_owner_activated": "Активирован владелец организации",
|
||||
"audit.action_organization_owner_invitation_requested": "Отправлено приглашение владельцу",
|
||||
"audit.action_organization_provisioned": "Создана организация",
|
||||
@@ -335,13 +350,21 @@ MESSAGES: dict[str, object] = {
|
||||
"identity.invalid_credentials": "Неверный email или пароль",
|
||||
"identity.invalid_totp_code": "Неверный код",
|
||||
"identity.invitation_email_mismatch": "Приглашение выписано на другой адрес",
|
||||
"identity.organization_create_forbidden": "Создавать организации могут администратор установки и владельцы или администраторы организаций",
|
||||
"identity.invitation_invalid": "Приглашение недействительно или истекло",
|
||||
"identity.invitation_account_exists": "Учётная запись с этим адресом уже есть — войдите под ней",
|
||||
"updates.nothing_to_install": "Установлена последняя версия",
|
||||
"updates.updater_offline": "Сервис обновления не запущен — обновление из интерфейса недоступно",
|
||||
"updates.install_in_progress": "Обновление уже идёт",
|
||||
"identity.role_conflict": "У пользователя уже другая роль в этой организации",
|
||||
"identity.token_required": "Нужен токен",
|
||||
"identity.totp_challenge_inactive": "Проверка кода уже неактуальна — войдите заново",
|
||||
"notifications.ids_list_or_all": "ids — список, либо all=true",
|
||||
"notifications.push_types_list": "pushTypes — список",
|
||||
"notifications.enabled_bool": "enabled — да или нет",
|
||||
"settings.queue_minutes_range": "Срок указывается в минутах: от 1 до 1440",
|
||||
"settings.queue_policy_forbidden": "Менять сроки может тот, кто управляет настройками",
|
||||
"notifications.unknown_transport": "Неизвестный способ доставки",
|
||||
"platform.idempotency_key_required": "Нужен заголовок Idempotency-Key",
|
||||
"portals.articles_non_empty": "articles — непустой список",
|
||||
"profile.current_password_invalid": "Текущий пароль неверен",
|
||||
@@ -359,7 +382,8 @@ MESSAGES: dict[str, object] = {
|
||||
"api.expected_record_id": "{name}: ожидается идентификатор записи",
|
||||
"settings.storage_unavailable": "Хранилище недоступно: {error}",
|
||||
"admin.actor_system": "Система",
|
||||
"admin.image_formats": "Поддерживаются PNG, JPEG и WebP",
|
||||
"admin.image_formats": "Поддерживаются PNG, JPEG, WebP и SVG",
|
||||
"admin.svg_logo_unsafe": "В SVG не должно быть скриптов, обработчиков событий и внешних ссылок",
|
||||
"admin.logo_too_large": "Размер логотипа не должен превышать 2 МБ",
|
||||
"calls.calls_off_entry_point": "Звонки отключены для этой точки входа",
|
||||
"calls.failure_code_required": "Для FAILED требуется нормализованный failure_code",
|
||||
@@ -473,10 +497,12 @@ MESSAGES: dict[str, object] = {
|
||||
"ai.unexpected_provider_response": "Неожиданный ответ провайдера: {error}",
|
||||
"settings.base_url_rejected": "Base URL: {error}",
|
||||
"settings.proxy_url_rejected": "Прокси: {error}",
|
||||
"notifications.type_dialog_waiting": "Диалог ждёт оператора",
|
||||
"notifications.type_dialog_new_message": "Новое сообщение в диалоге",
|
||||
"notifications.type_release_published": "Опубликован релиз агента",
|
||||
"notifications.type_integration_error": "Ошибка интеграции",
|
||||
"notifications.type_new_dialog": "Новый диалог",
|
||||
"notifications.type_operator_requested": "Клиент запросил оператора",
|
||||
"notifications.type_dialog_new_message": "Новое сообщение в моём диалоге",
|
||||
"notifications.type_dialog_assigned": "Диалог назначили на меня",
|
||||
"notifications.type_dialog_waiting_long": "Диалог долго ждёт человека",
|
||||
"notifications.type_ai_stopped": "AI остановлен ошибкой",
|
||||
"integrations.check_no_connection": "Нет связи: {error}",
|
||||
"integrations.check_api_key_missing": "Не указан API-ключ",
|
||||
"integrations.check_base_url_missing": "Не указан Base URL",
|
||||
|
||||
@@ -35,7 +35,7 @@ class HumanUserAdmin(UserAdmin):
|
||||
|
||||
@admin.register(Organization)
|
||||
class OrganizationAdmin(admin.ModelAdmin):
|
||||
list_display = ["slug", "name", "currency", "timezone"]
|
||||
list_display = ["slug", "name", "timezone"]
|
||||
search_fields = ["slug", "name"]
|
||||
|
||||
|
||||
|
||||
@@ -43,7 +43,6 @@ def organization_settings_payload(organization: Organization) -> dict[str, objec
|
||||
return {
|
||||
"name": organization.name,
|
||||
"timezone": organization.timezone,
|
||||
"currency": organization.currency,
|
||||
# Пустая строка доезжает до интерфейса как есть: там это отдельный
|
||||
# пункт «Как в установке», а не отсутствие значения.
|
||||
"language": organization.language,
|
||||
|
||||
@@ -11,6 +11,7 @@ from django.db import transaction
|
||||
|
||||
from chatballs.i18n import t
|
||||
from chatballs.i18n.languages import normalize_language
|
||||
from chatballs.identity.logo_svg import SVG_CONTENT_TYPE, looks_like_svg, svg_is_safe
|
||||
from chatballs.identity.models import Organization
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
from chatballs.tenancy.storage import adjust_storage_usage
|
||||
@@ -27,17 +28,18 @@ MAX_LOGO_BYTES = 2 * 1024 * 1024
|
||||
class OrganizationSettingsInput:
|
||||
name: str
|
||||
timezone: str
|
||||
currency: str
|
||||
# Пустая строка — «как в установке»: организация не обязана выбирать язык,
|
||||
# и владелец, который его не трогал, не должен получить жёсткий русский
|
||||
# после того, как язык установки сменили.
|
||||
language: str = ""
|
||||
|
||||
|
||||
def _validate_input(data: OrganizationSettingsInput) -> OrganizationSettingsInput:
|
||||
def validate_organization_settings(data: OrganizationSettingsInput) -> OrganizationSettingsInput:
|
||||
"""Имя, часовой пояс и язык организации — одни правила для «Настроек» и
|
||||
для страницы создания организации."""
|
||||
|
||||
name = data.name.strip()
|
||||
timezone = data.timezone.strip()
|
||||
currency = data.currency.strip().upper()
|
||||
language = normalize_language(data.language)
|
||||
if data.language.strip() and not language:
|
||||
raise ValidationError({"language": t("settings.language_unsupported")})
|
||||
@@ -51,13 +53,7 @@ def _validate_input(data: OrganizationSettingsInput) -> OrganizationSettingsInpu
|
||||
raise ValidationError(
|
||||
{"timezone": t("admin.invalid_timezone")}
|
||||
) from error
|
||||
if currency != "RUB":
|
||||
raise ValidationError(
|
||||
{"currency": t("admin.currency_rub_only")}
|
||||
)
|
||||
return OrganizationSettingsInput(
|
||||
name=name, timezone=timezone, currency=currency, language=language
|
||||
)
|
||||
return OrganizationSettingsInput(name=name, timezone=timezone, language=language)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
@@ -66,15 +62,14 @@ def update_organization_settings(
|
||||
context: TenantContext,
|
||||
data: OrganizationSettingsInput,
|
||||
) -> Organization:
|
||||
clean = _validate_input(data)
|
||||
clean = validate_organization_settings(data)
|
||||
organization = Organization.objects.select_for_update().get(
|
||||
pk=context.organization_id
|
||||
)
|
||||
organization.name = clean.name
|
||||
organization.timezone = clean.timezone
|
||||
organization.currency = clean.currency
|
||||
organization.language = clean.language
|
||||
organization.save(update_fields=["name", "timezone", "currency", "language"])
|
||||
organization.save(update_fields=["name", "timezone", "language"])
|
||||
return organization
|
||||
|
||||
|
||||
@@ -85,6 +80,8 @@ def _image_type(data: bytes) -> tuple[str, str] | None:
|
||||
return "image/jpeg", ".jpg"
|
||||
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return "image/webp", ".webp"
|
||||
if looks_like_svg(data):
|
||||
return SVG_CONTENT_TYPE, ".svg"
|
||||
return None
|
||||
|
||||
|
||||
@@ -102,6 +99,10 @@ def replace_organization_logo(
|
||||
detected = _image_type(data)
|
||||
if detected is None:
|
||||
raise ValidationError({"file": t("admin.image_formats")})
|
||||
if detected[0] == SVG_CONTENT_TYPE and not svg_is_safe(data):
|
||||
# Скрипты, внешние ссылки и обработчики событий в логотипе не нужны:
|
||||
# файл отклоняется целиком, а не переписывается молча.
|
||||
raise ValidationError({"file": t("admin.svg_logo_unsafe")})
|
||||
content_type, suffix = detected
|
||||
organization = Organization.objects.select_for_update().get(
|
||||
pk=context.organization_id
|
||||
|
||||
@@ -74,7 +74,6 @@ class OrganizationSettingsView(APIView):
|
||||
data=OrganizationSettingsInput(
|
||||
name=str(body.get("name", organization.name)),
|
||||
timezone=str(body.get("timezone", organization.timezone)),
|
||||
currency=str(body.get("currency", organization.currency)),
|
||||
language=str(body.get("language", organization.language)),
|
||||
),
|
||||
)
|
||||
@@ -107,11 +106,18 @@ class OrganizationLogoView(APIView):
|
||||
organization = request.tenant_context.organization
|
||||
if not organization.logo:
|
||||
return Response({"detail": t("admin.logo_not_uploaded")}, status=404)
|
||||
return FileResponse(
|
||||
response = FileResponse(
|
||||
organization.logo.open("rb"),
|
||||
content_type=organization.logo_content_type or "application/octet-stream",
|
||||
filename="organization-logo",
|
||||
)
|
||||
# Логотип показывается через <img>, но адрес можно открыть и напрямую.
|
||||
# SVG проверен при загрузке; заголовки — второй рубеж: в контексте
|
||||
# документа ему нельзя ни исполнять скрипты, ни ходить наружу, а
|
||||
# браузеру нельзя угадывать тип.
|
||||
response["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox"
|
||||
response["X-Content-Type-Options"] = "nosniff"
|
||||
return response
|
||||
|
||||
def post(self, request: Request) -> Response:
|
||||
upload = request.FILES.get("file")
|
||||
@@ -286,37 +292,100 @@ def _audit_actors(base) -> list[dict[str, object]]:
|
||||
return actors
|
||||
|
||||
|
||||
class LaunchChecklistView(APIView):
|
||||
"""Чек-лист «Запуск» (SPEC-CHATBALLS-0031 §5, дизайн-базлайн v2): три шага с
|
||||
автоотметкой по факту. Скрытие блока — предпочтение клиента (localStorage)."""
|
||||
class OnboardingView(APIView):
|
||||
"""Состояние онбординга «Начало работы» для текущего человека.
|
||||
|
||||
Шаги отмечаются по факту, а не по нажатию «Далее»: визард — проводник, а
|
||||
не чек-лист с галочками вручную. Признаки «закрыл» и «прошёл» — на членстве
|
||||
в организации: у каждого человека свои, и один администратор не прячет
|
||||
визард команде.
|
||||
"""
|
||||
|
||||
permission_classes = [HasCapability]
|
||||
required_capability = "settings.view"
|
||||
|
||||
def get(self, request: Request) -> Response:
|
||||
from chatballs.channels.models import Channel
|
||||
from chatballs.identity.models import OrganizationMembership
|
||||
from chatballs.integrations.models import Integration, IntegrationKind
|
||||
membership = request.tenant_context.membership
|
||||
return Response(
|
||||
{
|
||||
"steps": onboarding_steps(request.tenant_context.organization_id),
|
||||
"dismissedAt": _isoformat(membership.onboarding_dismissed_at if membership else None),
|
||||
"completedAt": _isoformat(membership.onboarding_completed_at if membership else None),
|
||||
}
|
||||
)
|
||||
|
||||
organization_id = request.tenant_context.organization_id
|
||||
agent_created = Channel.objects.filter(organization_id=organization_id).exists()
|
||||
connection_bound = Integration.objects.filter(
|
||||
def post(self, request: Request) -> Response:
|
||||
"""Закрыть визард или отметить его пройденным.
|
||||
|
||||
Тело ``{"action": "dismiss" | "complete" | "restart"}``. «Заново»
|
||||
снимает оба признака: визард снова открывается по ссылке и пилюле.
|
||||
"""
|
||||
|
||||
membership = request.tenant_context.membership
|
||||
if membership is None:
|
||||
return Response({"detail": t("onboarding.membership_required")}, status=403)
|
||||
action = str(request.data.get("action") or "dismiss")
|
||||
now = django_timezone.now()
|
||||
if action == "dismiss":
|
||||
membership.onboarding_dismissed_at = now
|
||||
elif action == "complete":
|
||||
membership.onboarding_dismissed_at = now
|
||||
membership.onboarding_completed_at = now
|
||||
elif action == "restart":
|
||||
membership.onboarding_dismissed_at = None
|
||||
membership.onboarding_completed_at = None
|
||||
else:
|
||||
return Response({"detail": t("onboarding.unknown_action")}, status=400)
|
||||
membership.save(update_fields=["onboarding_dismissed_at", "onboarding_completed_at"])
|
||||
return Response(
|
||||
{
|
||||
"steps": onboarding_steps(request.tenant_context.organization_id),
|
||||
"dismissedAt": _isoformat(membership.onboarding_dismissed_at),
|
||||
"completedAt": _isoformat(membership.onboarding_completed_at),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _isoformat(value: datetime | None) -> str | None:
|
||||
return value.isoformat() if value is not None else None
|
||||
|
||||
|
||||
def onboarding_steps(organization_id: int) -> dict[str, bool]:
|
||||
"""Восемь фактов настройки установки, каждый — один запрос на существование."""
|
||||
|
||||
from chatballs.ai.models import AIAgent, AIAgentStatus, Knowledge
|
||||
from chatballs.conversations.models import Conversation
|
||||
from chatballs.identity import instance_settings
|
||||
from chatballs.identity.models import Organization, OrganizationMembership
|
||||
from chatballs.integrations.models import Integration, IntegrationKind
|
||||
from chatballs.webchat.models import WebChatWidget, WebChatWidgetStatus
|
||||
|
||||
organization = Organization.objects.filter(pk=organization_id).first()
|
||||
return {
|
||||
"providerConnected": Integration.objects.filter(
|
||||
organization_id=organization_id,
|
||||
kind=IntegrationKind.LLM_PROVIDER,
|
||||
).exists(),
|
||||
"agentActive": AIAgent.objects.filter(
|
||||
organization_id=organization_id,
|
||||
status=AIAgentStatus.ACTIVE,
|
||||
).exists(),
|
||||
"knowledgeFilled": Knowledge.objects.filter(organization_id=organization_id).exists(),
|
||||
"connectionBound": Integration.objects.filter(
|
||||
organization_id=organization_id,
|
||||
kind=IntegrationKind.MESSENGER,
|
||||
channel__isnull=False,
|
||||
).exists()
|
||||
employee_invited = (
|
||||
OrganizationMembership.objects.filter(
|
||||
organization_id=organization_id
|
||||
).count()
|
||||
> 1
|
||||
or request.tenant_context.organization.invitations.exists()
|
||||
)
|
||||
return Response(
|
||||
{
|
||||
"agentCreated": agent_created,
|
||||
"connectionBound": connection_bound,
|
||||
"employeeInvited": employee_invited,
|
||||
"done": agent_created and connection_bound and employee_invited,
|
||||
}
|
||||
)
|
||||
).exists(),
|
||||
"widgetPublished": WebChatWidget.objects.filter(
|
||||
organization_id=organization_id,
|
||||
status=WebChatWidgetStatus.PUBLISHED,
|
||||
).exists(),
|
||||
"employeeInvited": (
|
||||
OrganizationMembership.objects.filter(organization_id=organization_id).count() > 1
|
||||
or (organization is not None and organization.invitations.exists())
|
||||
),
|
||||
# Шаг про саму установку, а не про организацию: домен и исходящая почта
|
||||
# общие для всех организаций на сервере.
|
||||
"platformConfigured": bool(instance_settings.public_host()) and instance_settings.email_is_configured(),
|
||||
"firstConversation": Conversation.objects.filter(organization_id=organization_id).exists(),
|
||||
}
|
||||
@@ -81,6 +81,7 @@ AUDIT_ACTION_LABELS: dict[str, str] = {
|
||||
"identity.employee_invited": "audit.action_identity_employee_invited",
|
||||
"identity.invitation_accepted": "audit.action_identity_invitation_accepted",
|
||||
"identity.invitation_revoked": "audit.action_identity_invitation_revoked",
|
||||
"updates.install_requested": "audit.action_updates_install_requested",
|
||||
"identity.employee_updated": "audit.action_identity_employee_updated",
|
||||
"identity.employee_blocked": "audit.action_identity_employee_blocked",
|
||||
"identity.employee_unblocked": "audit.action_identity_employee_unblocked",
|
||||
@@ -110,6 +111,7 @@ AUDIT_ACTION_LABELS: dict[str, str] = {
|
||||
"administration.instance_updated": "audit.action_administration_instance_updated",
|
||||
# --- Организация ---
|
||||
"organization.provisioned": "audit.action_organization_provisioned",
|
||||
"organization.created": "audit.action_organization_created",
|
||||
"organization.owner_activated": "audit.action_organization_owner_activated",
|
||||
"organization.owner_invitation_requested": "audit.action_organization_owner_invitation_requested",
|
||||
# --- Интеграции и каналы ---
|
||||
|
||||
@@ -17,7 +17,8 @@ from chatballs.identity.avatars import delete_user_avatar, replace_user_avatar
|
||||
from chatballs.identity.instance_settings import default_language
|
||||
from chatballs.identity.models import HumanUser, OrganizationMembership
|
||||
from chatballs.identity.sessions import list_user_sessions
|
||||
from chatballs.tenancy.ingress import user_requires_totp
|
||||
from chatballs.tenancy.database import tenant_atomic
|
||||
from chatballs.tenancy.ingress import membership_routes_for_user, user_requires_totp
|
||||
|
||||
|
||||
class ProfileUpdateView(APIView):
|
||||
@@ -289,10 +290,20 @@ def _request_organization_language(request: Request) -> str:
|
||||
context = getattr(request, "tenant_context", None)
|
||||
if context is not None:
|
||||
return context.organization.language or ""
|
||||
membership = (
|
||||
OrganizationMembership.objects.select_related("organization")
|
||||
.filter(user=request.user, blocked_at__isnull=True)
|
||||
.order_by("created_at", "id")
|
||||
.first()
|
||||
)
|
||||
return membership.organization.language if membership is not None else ""
|
||||
# Членства роли app без контекста не видны: сначала каталог входа, затем
|
||||
# каждое членство читается в контексте своей организации — как в
|
||||
# identity.auth.common._user_payload.
|
||||
oldest: tuple[object, int, str] | None = None
|
||||
for route in membership_routes_for_user(request.user.id):
|
||||
with tenant_atomic(route.organization_id):
|
||||
membership = (
|
||||
OrganizationMembership.objects.select_related("organization")
|
||||
.filter(id=route.resource_id, user=request.user, blocked_at__isnull=True)
|
||||
.first()
|
||||
)
|
||||
if membership is None:
|
||||
continue
|
||||
key = (membership.created_at, membership.id, membership.organization.language or "")
|
||||
if oldest is None or key[:2] < oldest[:2]:
|
||||
oldest = key
|
||||
return oldest[2] if oldest is not None else ""
|
||||
@@ -28,7 +28,6 @@ def bootstrap_owner(*, email: str, password: str, full_name: str = "") -> Bootst
|
||||
defaults={
|
||||
"name": "Demo",
|
||||
"timezone": "Europe/Moscow",
|
||||
"currency": "RUB",
|
||||
},
|
||||
)
|
||||
from chatballs.ai.knowledge_categories import ensure_uncategorized_category
|
||||
|
||||
@@ -23,9 +23,9 @@ urlpatterns = [
|
||||
name="organization-logo",
|
||||
),
|
||||
path(
|
||||
"launch-checklist/",
|
||||
administration_views.LaunchChecklistView.as_view(),
|
||||
name="launch-checklist",
|
||||
"onboarding/",
|
||||
administration_views.OnboardingView.as_view(),
|
||||
name="onboarding",
|
||||
),
|
||||
path("demo/", demo_views.DemoDataView.as_view(), name="organization-demo-data"),
|
||||
path("administration/communication/", feature_views.CommunicationSettingsView.as_view(), name="communication-settings"),
|
||||
|
||||
@@ -30,9 +30,6 @@
|
||||
"how-to-measure",
|
||||
"lead-times"
|
||||
],
|
||||
"limits": {
|
||||
"dailyCostUsd": 300
|
||||
},
|
||||
"createdDaysAgo": 41
|
||||
},
|
||||
{
|
||||
@@ -53,7 +50,6 @@
|
||||
"returns-and-exchanges",
|
||||
"your-account"
|
||||
],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 30,
|
||||
"policy": {
|
||||
"allow_anonymous_sessions": true,
|
||||
@@ -78,7 +74,6 @@
|
||||
"your-account",
|
||||
"returns-and-exchanges"
|
||||
],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 28,
|
||||
"policy": {
|
||||
"allow_anonymous_sessions": true,
|
||||
@@ -96,7 +91,6 @@
|
||||
"instructions": "",
|
||||
"knowledge": [],
|
||||
"portalArticles": [],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 3
|
||||
},
|
||||
{
|
||||
@@ -113,7 +107,6 @@
|
||||
"pricing"
|
||||
],
|
||||
"portalArticles": [],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 180
|
||||
}
|
||||
],
|
||||
@@ -378,7 +371,6 @@
|
||||
80,
|
||||
260
|
||||
],
|
||||
"costMicrosPerToken": 0.6,
|
||||
"failuresTotal": 3
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@
|
||||
],
|
||||
"notifications": [
|
||||
{
|
||||
"type": "DIALOG_WAITING",
|
||||
"type": "OPERATOR_REQUESTED",
|
||||
"level": "WARNING",
|
||||
"title": "Dmitry Orlov is waiting for an operator",
|
||||
"body": "Web Chat: the client asked for a member of staff. Waiting 6 min.",
|
||||
@@ -107,7 +107,7 @@
|
||||
"minutesAgo": 4
|
||||
},
|
||||
{
|
||||
"type": "INTEGRATION_ERROR",
|
||||
"type": "AI_STOPPED",
|
||||
"level": "CRITICAL",
|
||||
"title": "Telegram · delivery bot: connection error",
|
||||
"body": "401 Unauthorized: bot token was revoked in @BotFather. Check the token in the connection settings.",
|
||||
@@ -116,7 +116,7 @@
|
||||
"minutesAgo": 4200
|
||||
},
|
||||
{
|
||||
"type": "RELEASE_PUBLISHED",
|
||||
"type": "DIALOG_ASSIGNED",
|
||||
"level": "SUCCESS",
|
||||
"title": "Chatballs update: voice messages",
|
||||
"body": "Operators can send voice messages to Telegram and MAX, and incoming ones are transcribed with a single button.",
|
||||
@@ -136,9 +136,9 @@
|
||||
"connection": "tg",
|
||||
"externalChatId": "482900010",
|
||||
"pushTypes": [
|
||||
"DIALOG_WAITING",
|
||||
"OPERATOR_REQUESTED",
|
||||
"DIALOG_NEW_MESSAGE",
|
||||
"INTEGRATION_ERROR"
|
||||
"AI_STOPPED"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -146,7 +146,7 @@
|
||||
"connection": "tg",
|
||||
"externalChatId": "482900011",
|
||||
"pushTypes": [
|
||||
"DIALOG_WAITING"
|
||||
"OPERATOR_REQUESTED"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -30,9 +30,6 @@
|
||||
"kak-snyat-merki",
|
||||
"sroki-dostavki"
|
||||
],
|
||||
"limits": {
|
||||
"dailyCostUsd": 300
|
||||
},
|
||||
"createdDaysAgo": 41
|
||||
},
|
||||
{
|
||||
@@ -53,7 +50,6 @@
|
||||
"vozvrat-i-obmen",
|
||||
"lichnyj-kabinet"
|
||||
],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 30,
|
||||
"policy": {
|
||||
"allow_anonymous_sessions": true,
|
||||
@@ -78,7 +74,6 @@
|
||||
"lichnyj-kabinet",
|
||||
"vozvrat-i-obmen"
|
||||
],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 28,
|
||||
"policy": {
|
||||
"allow_anonymous_sessions": true,
|
||||
@@ -96,7 +91,6 @@
|
||||
"instructions": "",
|
||||
"knowledge": [],
|
||||
"portalArticles": [],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 3
|
||||
},
|
||||
{
|
||||
@@ -113,7 +107,6 @@
|
||||
"pricing"
|
||||
],
|
||||
"portalArticles": [],
|
||||
"limits": {},
|
||||
"createdDaysAgo": 180
|
||||
}
|
||||
],
|
||||
@@ -378,7 +371,6 @@
|
||||
80,
|
||||
260
|
||||
],
|
||||
"costMicrosPerToken": 0.6,
|
||||
"failuresTotal": 3
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@
|
||||
],
|
||||
"notifications": [
|
||||
{
|
||||
"type": "DIALOG_WAITING",
|
||||
"type": "OPERATOR_REQUESTED",
|
||||
"level": "WARNING",
|
||||
"title": "Дмитрий Орлов ждёт оператора",
|
||||
"body": "Web Chat: клиент попросил сотрудника. Ждёт 6 мин.",
|
||||
@@ -107,7 +107,7 @@
|
||||
"minutesAgo": 4
|
||||
},
|
||||
{
|
||||
"type": "INTEGRATION_ERROR",
|
||||
"type": "AI_STOPPED",
|
||||
"level": "CRITICAL",
|
||||
"title": "Telegram · бот доставки: ошибка подключения",
|
||||
"body": "401 Unauthorized: bot token was revoked in @BotFather. Проверьте токен в настройках подключения.",
|
||||
@@ -116,7 +116,7 @@
|
||||
"minutesAgo": 4200
|
||||
},
|
||||
{
|
||||
"type": "RELEASE_PUBLISHED",
|
||||
"type": "DIALOG_ASSIGNED",
|
||||
"level": "SUCCESS",
|
||||
"title": "Обновление Chatballs: голосовые сообщения",
|
||||
"body": "Операторы могут отправлять голосовые в Telegram и MAX, входящие расшифровываются одной кнопкой.",
|
||||
@@ -136,9 +136,9 @@
|
||||
"connection": "tg",
|
||||
"externalChatId": "482900010",
|
||||
"pushTypes": [
|
||||
"DIALOG_WAITING",
|
||||
"OPERATOR_REQUESTED",
|
||||
"DIALOG_NEW_MESSAGE",
|
||||
"INTEGRATION_ERROR"
|
||||
"AI_STOPPED"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -146,7 +146,7 @@
|
||||
"connection": "tg",
|
||||
"externalChatId": "482900011",
|
||||
"pushTypes": [
|
||||
"DIALOG_WAITING"
|
||||
"OPERATOR_REQUESTED"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -82,7 +82,6 @@ def _ensure_agent(context: TenantContext, refs: DemoRefs, item: dict, llm: Integ
|
||||
agent.persona = item.get("persona", "")
|
||||
agent.tone = item.get("tone", "")
|
||||
agent.instructions = item.get("instructions", "")
|
||||
agent.limits = item.get("limits", {})
|
||||
if agent.status in ("ACTIVE", "DISABLED"):
|
||||
agent.provider_integration = llm
|
||||
agent.model = (llm.config or {}).get("default_model", "demo")
|
||||
@@ -115,7 +114,8 @@ def _ensure_connection(context: TenantContext, refs: DemoRefs, item: dict, curre
|
||||
provider=item["provider"],
|
||||
name=item["name"],
|
||||
secret=item.get("secret", ""),
|
||||
config=item.get("config", {}),
|
||||
# Токены демо-подключений ненастоящие: воркер их не опрашивает.
|
||||
config={**item.get("config", {}), "demoSeed": True},
|
||||
),
|
||||
)
|
||||
Integration.objects.filter(pk=integration.pk).update(
|
||||
@@ -255,7 +255,6 @@ def _generate_usage(refs: DemoRefs, spec: dict | None, current) -> None:
|
||||
prompt_tokens=prompt,
|
||||
completion_tokens=0 if failed else completion,
|
||||
total_tokens=prompt + (0 if failed else completion),
|
||||
cost_micros=0 if failed else int((prompt + completion) * spec["costMicrosPerToken"]),
|
||||
latency_ms=random.randint(900, 4200),
|
||||
status=LlmInvocationStatus.ERROR if failed else LlmInvocationStatus.SUCCESS,
|
||||
error="Provider timeout after 30s" if failed else "",
|
||||
@@ -273,7 +272,6 @@ def _generate_usage(refs: DemoRefs, spec: dict | None, current) -> None:
|
||||
prompt_tokens=tokens,
|
||||
completion_tokens=0,
|
||||
total_tokens=tokens,
|
||||
cost_micros=int(tokens * 0.02),
|
||||
latency_ms=random.randint(200, 900),
|
||||
status=LlmInvocationStatus.SUCCESS,
|
||||
)
|
||||
|
||||
@@ -18,6 +18,7 @@ from chatballs.calls.models import (
|
||||
ParticipantConnectionState,
|
||||
ParticipantSide,
|
||||
)
|
||||
from chatballs.conversations.queue_models import policy_for
|
||||
from chatballs.identity.demo_seed import manifest
|
||||
from chatballs.identity.demo_seed.loaders.common import backdate, moment, now
|
||||
from chatballs.identity.demo_seed.refs import DemoRefs
|
||||
@@ -28,7 +29,9 @@ from chatballs.notifications.models import (
|
||||
NotificationAudience,
|
||||
NotificationLevel,
|
||||
NotificationRead,
|
||||
NotificationTransport,
|
||||
)
|
||||
from chatballs.notifications.preferences import update_preference
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
|
||||
FINISHED = {
|
||||
@@ -44,6 +47,9 @@ FINISHED = {
|
||||
def load(context: TenantContext, refs: DemoRefs) -> None:
|
||||
data = manifest.load("operations", refs.language)
|
||||
current = now()
|
||||
# Пороги очереди — данные организации, а не установки: демо-организация
|
||||
# заводит их со значениями по умолчанию, как завела бы живая.
|
||||
policy_for(refs.organization)
|
||||
for item in data.get("calls", []):
|
||||
_ensure_call(refs, item, current)
|
||||
for item in data.get("notifications", []):
|
||||
@@ -55,9 +61,15 @@ def load(context: TenantContext, refs: DemoRefs) -> None:
|
||||
defaults={
|
||||
"organization": refs.organization,
|
||||
"external_chat_id": item["externalChatId"],
|
||||
"push_types": item.get("pushTypes", []),
|
||||
},
|
||||
)
|
||||
update_preference(
|
||||
organization_id=refs.organization.id,
|
||||
user_id=refs.users[item["user"]].id,
|
||||
transport=NotificationTransport.MESSENGER,
|
||||
enabled=True,
|
||||
types=item.get("pushTypes", []),
|
||||
)
|
||||
for item in data.get("messengerBindingCodes", []):
|
||||
MessengerBindingCode.objects.get_or_create(
|
||||
code=item["code"],
|
||||
|
||||
@@ -72,8 +72,12 @@ class InstanceSettings(models.Model):
|
||||
|
||||
|
||||
_CACHE_TTL_SECONDS = 10.0
|
||||
# Перечитать кэш при промахе по хосту можно не чаще раза в секунду на процесс:
|
||||
# иначе поток запросов с чужим Host превращался бы в поток запросов к базе.
|
||||
_MISS_REFRESH_SECONDS = 1.0
|
||||
_lock = threading.Lock()
|
||||
_cached: tuple[float, tuple[str, str]] | None = None
|
||||
_last_miss_refresh = 0.0
|
||||
|
||||
|
||||
def invalidate_cache() -> None:
|
||||
@@ -112,6 +116,31 @@ def accepted_hosts() -> tuple[str, ...]:
|
||||
return tuple(host for host in _hosts() if host)
|
||||
|
||||
|
||||
def host_is_accepted(host: str) -> bool:
|
||||
"""Свой ли это адрес — с перечитыванием кэша при промахе.
|
||||
|
||||
Кэш живёт в каждом процессе gunicorn отдельно. Мастер первого запуска или
|
||||
смена адреса в «Настройках» сбрасывают его только там, где выполнялись;
|
||||
соседний процесс до 10 секунд отвечал бы «Invalid host» на адрес, который
|
||||
установка уже считает своим. Поэтому промах — повод перечитать строку, но
|
||||
не чаще раза в секунду.
|
||||
"""
|
||||
|
||||
global _last_miss_refresh
|
||||
if not host:
|
||||
return False
|
||||
known = {normalize_domain(item) for item in accepted_hosts()}
|
||||
if host in known:
|
||||
return True
|
||||
now = time.monotonic()
|
||||
with _lock:
|
||||
if now - _last_miss_refresh < _MISS_REFRESH_SECONDS:
|
||||
return False
|
||||
_last_miss_refresh = now
|
||||
invalidate_cache()
|
||||
return host in {normalize_domain(item) for item in accepted_hosts()}
|
||||
|
||||
|
||||
def default_language() -> str:
|
||||
"""Язык установки: экраны до входа и умолчание для организаций.
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from django.urls import path
|
||||
|
||||
from chatballs.identity import instance_views
|
||||
from chatballs.tenancy import storage_views
|
||||
from chatballs.updates import views as update_views
|
||||
|
||||
urlpatterns = [
|
||||
path("settings/", instance_views.InstanceAddressView.as_view(), name="instance-settings"),
|
||||
@@ -25,4 +26,8 @@ urlpatterns = [
|
||||
storage_views.StorageMigrateView.as_view(),
|
||||
name="instance-storage-migrate",
|
||||
),
|
||||
# Обновления установки: состояние, проверка канала, установка по кнопке.
|
||||
path("update/", update_views.UpdateStateView.as_view(), name="instance-update"),
|
||||
path("update/check/", update_views.UpdateCheckView.as_view(), name="instance-update-check"),
|
||||
path("update/install/", update_views.UpdateInstallView.as_view(), name="instance-update-install"),
|
||||
]
|
||||
@@ -25,6 +25,7 @@ from chatballs.identity.models import (
|
||||
)
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
from chatballs.tenancy.database import tenant_atomic
|
||||
from chatballs.tenancy.ingress import invitation_route
|
||||
|
||||
# Приглашение существующего пользователя в организацию: письмо отправляет
|
||||
# воркер по этому событию (identity.event_handlers).
|
||||
@@ -204,14 +205,37 @@ def register_and_accept(*, token: str, full_name: str, password: str) -> Accepte
|
||||
|
||||
|
||||
def pending_invitation_for_token(token: str) -> OrganizationInvitation | None:
|
||||
return _invitation_for_token(token, accepted=False)
|
||||
|
||||
|
||||
def _invitation_for_token(token: str, *, accepted: bool) -> OrganizationInvitation | None:
|
||||
"""Приглашение по токену из письма — без tenant-контекста на входе.
|
||||
|
||||
Ссылка /join приходит до входа в организацию, а таблица приглашений и
|
||||
строка организации роли app без контекста не видны (tenancy/0003, 0033).
|
||||
Организацию находит security-barrier каталог по хэшу токена (tenancy/0035),
|
||||
и приглашение читается уже в её контексте — вместе с организацией, чтобы
|
||||
вызывающий код мог обращаться к ней и после выхода из контекста.
|
||||
"""
|
||||
|
||||
if not token:
|
||||
return None
|
||||
return OrganizationInvitation.objects.filter(
|
||||
token_hash=_token_hash(token),
|
||||
accepted_at__isnull=True,
|
||||
token_hash = _token_hash(token)
|
||||
route = invitation_route(token_hash)
|
||||
if route is None:
|
||||
return None
|
||||
query = OrganizationInvitation.objects.select_related("organization").filter(
|
||||
id=route.resource_id,
|
||||
organization_id=route.organization_id,
|
||||
token_hash=token_hash,
|
||||
revoked_at__isnull=True,
|
||||
expires_at__gt=timezone.now(),
|
||||
).first()
|
||||
)
|
||||
if accepted:
|
||||
query = query.filter(accepted_at__isnull=False)
|
||||
else:
|
||||
query = query.filter(accepted_at__isnull=True, expires_at__gt=timezone.now())
|
||||
with tenant_atomic(route.organization_id):
|
||||
return query.first()
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
@@ -314,16 +338,13 @@ def _already_accepted_for(
|
||||
) -> AcceptedInvitation | None:
|
||||
"""Idempotent re-accept: if this token was already accepted by the same user,
|
||||
return the existing result instead of raising (SPEC-HUB-0021 §11/§15)."""
|
||||
invitation = OrganizationInvitation.objects.filter(
|
||||
token_hash=_token_hash(token),
|
||||
accepted_at__isnull=False,
|
||||
revoked_at__isnull=True,
|
||||
).first()
|
||||
invitation = _invitation_for_token(token, accepted=True)
|
||||
if invitation is None:
|
||||
return None
|
||||
membership = OrganizationMembership.objects.filter(
|
||||
user=user, organization=invitation.organization
|
||||
).first()
|
||||
with tenant_atomic(invitation.organization_id):
|
||||
membership = OrganizationMembership.objects.filter(
|
||||
user=user, organization=invitation.organization
|
||||
).first()
|
||||
if membership is None:
|
||||
return None
|
||||
return AcceptedInvitation(
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Проверка SVG-логотипа организации.
|
||||
|
||||
SVG — это XML с возможностью исполнять скрипты и тянуть внешние ресурсы.
|
||||
Логотип отдаётся с адреса самого приложения, поэтому опасный файл принимать
|
||||
нельзя даже с защитными заголовками при отдаче: файл проверяется при загрузке
|
||||
и отклоняется целиком, а не «чистится» — переписывать чужую графику молча
|
||||
хуже, чем попросить другой файл.
|
||||
|
||||
Отклоняется: DOCTYPE и сущности, элементы script/foreignObject/iframe/
|
||||
embed/object/audio/video, атрибуты-обработчики on*, ссылки javascript: и
|
||||
data:text, внешние адреса в href/xlink:href и в url() внутри стилей.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
SVG_CONTENT_TYPE = "image/svg+xml"
|
||||
|
||||
_FORBIDDEN_TAGS = frozenset({"script", "foreignobject", "iframe", "embed", "object", "audio", "video"})
|
||||
_HREF_ATTRIBUTES = frozenset({"href", "{http://www.w3.org/1999/xlink}href"})
|
||||
_DECLARATION = re.compile(rb"<!\s*(DOCTYPE|ENTITY)", re.IGNORECASE)
|
||||
_EXTERNAL_URL = re.compile(r"url\(\s*['\"]?\s*(?!#|data:image/)", re.IGNORECASE)
|
||||
|
||||
|
||||
def looks_like_svg(data: bytes) -> bool:
|
||||
head = data.lstrip(b"\xef\xbb\xbf \t\r\n")[:4096].lower()
|
||||
if head.startswith(b"<svg"):
|
||||
return True
|
||||
return head.startswith((b"<?xml", b"<!--")) and b"<svg" in head
|
||||
|
||||
|
||||
def _local(name: str) -> str:
|
||||
return name.rsplit("}", 1)[-1].lower()
|
||||
|
||||
|
||||
def _dangerous_value(value: str) -> bool:
|
||||
compact = re.sub(r"\s+", "", value).lower()
|
||||
return compact.startswith("javascript:") or compact.startswith("data:text") or compact.startswith("vbscript:")
|
||||
|
||||
|
||||
def svg_is_safe(data: bytes) -> bool:
|
||||
if _DECLARATION.search(data):
|
||||
return False
|
||||
try:
|
||||
root = ET.fromstring(data)
|
||||
except ET.ParseError:
|
||||
return False
|
||||
if _local(root.tag) != "svg":
|
||||
return False
|
||||
for element in root.iter():
|
||||
tag = _local(element.tag) if isinstance(element.tag, str) else ""
|
||||
if tag in _FORBIDDEN_TAGS:
|
||||
return False
|
||||
for name, value in element.attrib.items():
|
||||
local = _local(name)
|
||||
if local.startswith("on"):
|
||||
return False
|
||||
if _dangerous_value(value):
|
||||
return False
|
||||
if name in _HREF_ATTRIBUTES or local == "href":
|
||||
stripped = value.strip()
|
||||
if stripped and not (stripped.startswith("#") or stripped.lower().startswith("data:image/")):
|
||||
return False
|
||||
if local == "style" and _EXTERNAL_URL.search(value):
|
||||
return False
|
||||
if tag == "style" and element.text and (
|
||||
"@import" in element.text.lower() or _EXTERNAL_URL.search(element.text)
|
||||
):
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,25 @@
|
||||
# Онбординг «Начало работы» показывается всем, кто его ещё не закрыл, включая
|
||||
# тех, кто работает в установке давно. Признак закрытия — на членстве человека
|
||||
# в организации: у каждого он свой, и закрытие одним администратором не прячет
|
||||
# визард у остальных. NULL по умолчанию, поэтому существующие записи считаются
|
||||
# «не закрывал» и увидят визард при следующем входе.
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("identity", "0037_invitation_membership_fields"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="organizationmembership",
|
||||
name="onboarding_dismissed_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="organizationmembership",
|
||||
name="onboarding_completed_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Валюта организации удалена: поле принимало только RUB, не читалось нигде и
|
||||
# ни одна сумма в продукте в ней не считалась. Осталось от эпохи CRM и пережило
|
||||
# пивот в поддержку. Расход на модель — единственные деньги в системе — тоже
|
||||
# снят вместе с лимитами.
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("identity", "0038_membership_onboarding_dismissed_at"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name="organization",
|
||||
name="currency",
|
||||
),
|
||||
]
|
||||
@@ -75,7 +75,7 @@ class HumanUser(AbstractUser):
|
||||
# без этой отметки принимался бы второй раз ещё полторы минуты.
|
||||
totp_last_counter = models.BigIntegerField(default=0)
|
||||
# Внешний вид — глобальная настройка пользователя (не membership):
|
||||
# тема и акцентный HEX-цвет; пустой акцент — дефолтный синий #1677ff.
|
||||
# тема и акцентный HEX-цвет; пустой акцент — цвет продукта #0f9b8e.
|
||||
ui_theme = models.CharField(max_length=8, choices=UiTheme.choices, default=UiTheme.SYSTEM)
|
||||
ui_accent = models.CharField(max_length=9, blank=True)
|
||||
# Язык интерфейса — тоже глобальная настройка пользователя, а не
|
||||
@@ -125,7 +125,6 @@ class Organization(models.Model):
|
||||
default=OrganizationStatus.ACTIVE,
|
||||
)
|
||||
timezone = models.CharField(max_length=64, default="Europe/Moscow")
|
||||
currency = models.CharField(max_length=3, default="RUB")
|
||||
# Язык рабочего места по умолчанию: на нём организация открывается всем,
|
||||
# кто не выбрал свой в профиле. Стоит рядом с часовым поясом и валютой —
|
||||
# это такой же региональный параметр организации, и в «Настройках» они
|
||||
@@ -184,6 +183,14 @@ class OrganizationMembership(models.Model):
|
||||
phone = models.CharField(max_length=32, blank=True)
|
||||
totp_required = models.BooleanField(default=False)
|
||||
blocked_at = models.DateTimeField(null=True, blank=True)
|
||||
# Онбординг закрыт этим человеком в этой организации. Признак живёт на
|
||||
# членстве, а не на организации: иначе первый же закрывший спрятал бы
|
||||
# визард всей команде. NULL — не закрывал, значит увидит при следующем
|
||||
# входе, включая тех, кто работает в системе давно.
|
||||
onboarding_dismissed_at = models.DateTimeField(null=True, blank=True)
|
||||
# Визард пройден до конца. Отдельно от «закрыл»: закрыть можно на первом
|
||||
# шаге, и тогда возвращаться к настройке ещё есть зачем.
|
||||
onboarding_completed_at = models.DateTimeField(null=True, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Создание организации человеком из интерфейса.
|
||||
|
||||
Кнопка «Добавить организацию» в переключателе (дизайн-базлайн v2, A1) ведёт
|
||||
на страницу с полями организации; тот, кто её заполнил, становится владельцем
|
||||
новой организации и сразу в неё переключается. Это второй путь появления
|
||||
организации рядом с платформенным провижинингом (platform.provisioning_service):
|
||||
там оператор заводит организацию для чужого владельца по e-mail, здесь человек
|
||||
заводит её себе.
|
||||
|
||||
Кто может: администратор установки и любой, у кого есть роль владельца или
|
||||
администратора хотя бы в одной организации. Сотрудник, работающий только в
|
||||
чате, чужую установку организациями не засевает.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from django.db import transaction
|
||||
from django.utils.text import slugify
|
||||
|
||||
from chatballs.ai.knowledge_categories import ensure_uncategorized_category
|
||||
from chatballs.events.services import DomainEvent, enqueue_event
|
||||
from chatballs.i18n import t
|
||||
from chatballs.i18n.audience import customer_language
|
||||
from chatballs.identity.administration_services import (
|
||||
OrganizationSettingsInput,
|
||||
validate_organization_settings,
|
||||
)
|
||||
from chatballs.identity.audit import record_audit_event
|
||||
from chatballs.identity.models import (
|
||||
EmployeeRole,
|
||||
HumanUser,
|
||||
Organization,
|
||||
OrganizationMembership,
|
||||
OrganizationStatus,
|
||||
)
|
||||
from chatballs.tenancy.context import TenantActorKind, TenantContext
|
||||
from chatballs.tenancy.database import tenant_atomic
|
||||
from chatballs.tenancy.ingress import membership_routes_for_user
|
||||
from chatballs.tenancy.lookup import organization_route_by_slug, reserve_organization_id
|
||||
|
||||
MANAGER_ROLES = frozenset({EmployeeRole.OWNER, EmployeeRole.ADMIN})
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CreatedOrganization:
|
||||
organization: Organization
|
||||
membership: OrganizationMembership
|
||||
|
||||
|
||||
def can_create_organization(user: HumanUser) -> bool:
|
||||
"""Администратор установки или менеджер (владелец/администратор) где-либо."""
|
||||
|
||||
if not user.is_active:
|
||||
return False
|
||||
if user.is_instance_admin:
|
||||
return True
|
||||
for route in membership_routes_for_user(user.id):
|
||||
with tenant_atomic(route.organization_id):
|
||||
role = (
|
||||
OrganizationMembership.objects.filter(
|
||||
id=route.resource_id, user=user, blocked_at__isnull=True
|
||||
)
|
||||
.values_list("role", flat=True)
|
||||
.first()
|
||||
)
|
||||
if role in MANAGER_ROLES:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def unique_organization_slug(name: str) -> str:
|
||||
"""Слаг из имени, уникальный среди организаций установки.
|
||||
|
||||
Проверка идёт через каталог организаций: роль app без контекста строк
|
||||
организаций не видит (tenancy/0033).
|
||||
"""
|
||||
|
||||
base = slugify(name)[:40].strip("-") or "organization"
|
||||
candidate = base
|
||||
suffix = 2
|
||||
while organization_route_by_slug(candidate) is not None:
|
||||
candidate = f"{base}-{suffix}"
|
||||
suffix += 1
|
||||
return candidate
|
||||
|
||||
|
||||
def create_organization(
|
||||
*, data: OrganizationSettingsInput, owner: HumanUser
|
||||
) -> CreatedOrganization:
|
||||
"""Создать организацию и сделать человека её владельцем — одной транзакцией.
|
||||
|
||||
Порядок тот же, что у мастера первого запуска (identity.setup): id
|
||||
выделяется заранее, строка вставляется уже в контексте этого id — иначе
|
||||
роль app не увидит собственную вставку (tenancy/0033, политика 0035).
|
||||
"""
|
||||
|
||||
clean = validate_organization_settings(data)
|
||||
with transaction.atomic():
|
||||
organization_id = reserve_organization_id()
|
||||
with tenant_atomic(organization_id):
|
||||
organization = Organization(
|
||||
id=organization_id,
|
||||
name=clean.name,
|
||||
slug=unique_organization_slug(clean.name),
|
||||
status=OrganizationStatus.ACTIVE,
|
||||
timezone=clean.timezone,
|
||||
language=clean.language,
|
||||
)
|
||||
organization.save(force_insert=True)
|
||||
ensure_uncategorized_category(organization)
|
||||
membership = OrganizationMembership.objects.create(
|
||||
user=owner,
|
||||
organization=organization,
|
||||
role=EmployeeRole.OWNER,
|
||||
# Должность — текстом на языке организации, как в провижининге.
|
||||
position_title=t("setup.owner_position", language=customer_language(organization)),
|
||||
totp_required=False,
|
||||
)
|
||||
record_audit_event(
|
||||
action="organization.created",
|
||||
actor=owner,
|
||||
organization=organization,
|
||||
object_type="Organization",
|
||||
object_id=str(organization.public_id),
|
||||
payload={"organizationName": organization.name},
|
||||
)
|
||||
enqueue_event(
|
||||
DomainEvent(
|
||||
aggregate_type="Organization",
|
||||
aggregate_id=str(organization.public_id),
|
||||
event_type="organization.provisioned",
|
||||
payload={},
|
||||
tenant_context=TenantContext.for_resource(
|
||||
organization,
|
||||
actor_kind=TenantActorKind.SYSTEM,
|
||||
actor_user=owner,
|
||||
),
|
||||
)
|
||||
)
|
||||
return CreatedOrganization(organization=organization, membership=membership)
|
||||
@@ -0,0 +1,12 @@
|
||||
from django.urls import path
|
||||
|
||||
from chatballs.identity import organization_views
|
||||
|
||||
urlpatterns = [
|
||||
path("", organization_views.OrganizationCreateView.as_view(), name="organization-create"),
|
||||
path(
|
||||
"options/",
|
||||
organization_views.OrganizationCreateOptionsView.as_view(),
|
||||
name="organization-create-options",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Создание организации из интерфейса: /api/v1/organizations/ без uuid в адресе.
|
||||
|
||||
Организации ещё нет, поэтому tenant middleware этот путь не трогает: контекст
|
||||
открывает сам сервис вокруг вставки. Ответ повторяет форму ответа приглашения
|
||||
(auth.invitations): обновлённая учётная запись со списком членств и публичный
|
||||
id организации, в которую интерфейсу переключиться.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.request import Request
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from chatballs.i18n import t
|
||||
from chatballs.identity.administration_payloads import (
|
||||
administration_languages,
|
||||
administration_timezones,
|
||||
)
|
||||
from chatballs.identity.administration_services import OrganizationSettingsInput
|
||||
from chatballs.identity.auth.common import _user_payload, validation_response
|
||||
from chatballs.identity.organization_creation import (
|
||||
can_create_organization,
|
||||
create_organization,
|
||||
)
|
||||
|
||||
|
||||
def _forbidden() -> Response:
|
||||
return Response({"detail": t("identity.organization_create_forbidden")}, status=403)
|
||||
|
||||
|
||||
class OrganizationCreateOptionsView(APIView):
|
||||
"""Справочники для формы: часовые пояса и языки, как в «Настройках»."""
|
||||
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request: Request) -> Response:
|
||||
if not can_create_organization(request.user):
|
||||
return _forbidden()
|
||||
return Response(
|
||||
{
|
||||
"timezones": administration_timezones(),
|
||||
"languages": administration_languages(),
|
||||
"currencies": ["RUB"],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class OrganizationCreateView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def post(self, request: Request) -> Response:
|
||||
if not can_create_organization(request.user):
|
||||
return _forbidden()
|
||||
body = request.data if isinstance(request.data, dict) else {}
|
||||
try:
|
||||
created = create_organization(
|
||||
data=OrganizationSettingsInput(
|
||||
name=str(body.get("name", "")),
|
||||
timezone=str(body.get("timezone", "") or "Europe/Moscow"),
|
||||
language=str(body.get("language", "")),
|
||||
),
|
||||
owner=request.user,
|
||||
)
|
||||
except ValidationError as error:
|
||||
return validation_response(error)
|
||||
return Response(
|
||||
{
|
||||
"user": _user_payload(request.user),
|
||||
"organizationPublicId": str(created.organization.public_id),
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
@@ -15,6 +15,12 @@ from chatballs.identity.models import EmployeeRole, OrganizationMembership
|
||||
# сохраняется; scope-модель и отделы упразднены.
|
||||
|
||||
|
||||
# Руководство организации: видит всё независимо от групп. Набор один и тот же
|
||||
# в проверке доступа, в видимости диалогов и в подборе получателей уведомлений,
|
||||
# поэтому записан здесь один раз.
|
||||
MANAGEMENT_ROLES = frozenset({EmployeeRole.OWNER, EmployeeRole.ADMIN})
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ResourceScope:
|
||||
organization_id: int
|
||||
@@ -47,6 +53,18 @@ def authorize(actor, capability: str, resource_scope: ResourceScope) -> bool:
|
||||
return capability in _role_capabilities(profile.role)
|
||||
|
||||
|
||||
def roles_with_capability(capability: str) -> frozenset[str]:
|
||||
"""Роли, которым право выдано.
|
||||
|
||||
Нужна там, где получателей ищут пачкой: спрашивать authorize() по одному
|
||||
сотруднику — это запрос в базу на каждого, то есть сотня запросов на сотню
|
||||
рабочих мест. Право выводится из роли, значит и отбирать можно по роли.
|
||||
"""
|
||||
return frozenset(
|
||||
role for role in EmployeeRole.values if capability in _role_capabilities(role)
|
||||
)
|
||||
|
||||
|
||||
def has_capability_any_scope(actor, capability: str) -> bool:
|
||||
profile = _active_membership(actor)
|
||||
if profile is None:
|
||||
@@ -56,7 +74,7 @@ def has_capability_any_scope(actor, capability: str) -> bool:
|
||||
|
||||
def can_administer_access(actor) -> bool:
|
||||
profile = _active_membership(actor)
|
||||
return profile is not None and profile.role in {EmployeeRole.OWNER, EmployeeRole.ADMIN}
|
||||
return profile is not None and profile.role in MANAGEMENT_ROLES
|
||||
|
||||
|
||||
def conversation_visibility(actor) -> dict | None:
|
||||
@@ -69,7 +87,7 @@ def conversation_visibility(actor) -> dict | None:
|
||||
profile = _active_membership(actor)
|
||||
if profile is None:
|
||||
return {"none": True}
|
||||
if profile.role in {EmployeeRole.OWNER, EmployeeRole.ADMIN}:
|
||||
if profile.role in MANAGEMENT_ROLES:
|
||||
return None
|
||||
from chatballs.identity.group_models import member_group_ids
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@ class AdministrationApiTests(TestCase):
|
||||
name="Example",
|
||||
slug="administration",
|
||||
timezone="Europe/Moscow",
|
||||
currency="RUB",
|
||||
)
|
||||
self.owner = HumanUser.objects.create_user(
|
||||
email="owner@administration.test",
|
||||
@@ -60,7 +59,6 @@ class AdministrationApiTests(TestCase):
|
||||
{
|
||||
"name": "Example",
|
||||
"timezone": "Europe/Moscow",
|
||||
"currency": "RUB",
|
||||
# Пустой язык — «как в установке»: организация своего не выбрала.
|
||||
"language": "",
|
||||
"logoUrl": None,
|
||||
@@ -78,7 +76,6 @@ class AdministrationApiTests(TestCase):
|
||||
{
|
||||
"name": "Новая компания",
|
||||
"timezone": "Asia/Yekaterinburg",
|
||||
"currency": "rub",
|
||||
},
|
||||
format="json",
|
||||
)
|
||||
@@ -87,7 +84,6 @@ class AdministrationApiTests(TestCase):
|
||||
self.organization.refresh_from_db()
|
||||
self.assertEqual(self.organization.name, "Новая компания")
|
||||
self.assertEqual(self.organization.timezone, "Asia/Yekaterinburg")
|
||||
self.assertEqual(self.organization.currency, "RUB")
|
||||
|
||||
def test_invalid_timezone_is_rejected(self) -> None:
|
||||
response = self.client.patch(
|
||||
@@ -99,16 +95,6 @@ class AdministrationApiTests(TestCase):
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn("timezone", response.json()["errors"])
|
||||
|
||||
def test_only_ruble_currency_is_accepted(self) -> None:
|
||||
response = self.client.patch(
|
||||
"/api/v1/company/administration/",
|
||||
{"currency": "USD"},
|
||||
format="json",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn("российский рубль", response.json()["errors"]["currency"])
|
||||
|
||||
def test_logo_upload_download_and_delete(self) -> None:
|
||||
png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
|
||||
uploaded = self.client.post(
|
||||
@@ -172,16 +158,16 @@ class AdministrationApiTests(TestCase):
|
||||
"/api/v1/company/administration/logo/",
|
||||
{
|
||||
"file": SimpleUploadedFile(
|
||||
"logo.svg",
|
||||
b"<svg></svg>",
|
||||
content_type="image/svg+xml",
|
||||
"logo.txt",
|
||||
b"not an image at all",
|
||||
content_type="text/plain",
|
||||
)
|
||||
},
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn("PNG, JPEG и WebP", response.json()["detail"])
|
||||
self.assertIn("PNG, JPEG, WebP и SVG", response.json()["detail"])
|
||||
|
||||
def test_audit_returns_readable_label_next_to_the_action_code(self) -> None:
|
||||
record_audit_event(
|
||||
|
||||
@@ -12,9 +12,12 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.test import TestCase
|
||||
|
||||
from chatballs.identity import instance_settings
|
||||
from chatballs.identity.bootstrap import bootstrap_owner
|
||||
from chatballs.identity.instance_settings import (
|
||||
InstanceSettings,
|
||||
@@ -201,3 +204,51 @@ class InstanceSettingsAccessTests(TestCase):
|
||||
f"/api/v1/organizations/{self.result.organization.public_id}/company/administration/instance/"
|
||||
)
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
|
||||
class StaleHostCacheTests(TestCase):
|
||||
"""Адрес, записанный мастером в одном процессе, принимает и соседний.
|
||||
|
||||
Кэш адреса живёт в каждом процессе gunicorn по 10 секунд. Соседний процесс
|
||||
с устаревшим кэшем отвечал «Invalid host» на первый же запрос после
|
||||
мастера — в интерфейсе это «Ошибка загрузки», исчезавшая после обновления
|
||||
страницы. Промах по хосту теперь перечитывает кэш.
|
||||
"""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.result = bootstrap_owner(email="cache-owner@example.com", password=PASSWORD)
|
||||
self.client = TenantAPIClient()
|
||||
self.client.force_authenticate(self.result.owner)
|
||||
# Строка настроек должна существовать: update() ниже её не создаёт.
|
||||
InstanceSettings.load()
|
||||
self.addCleanup(invalidate_cache)
|
||||
|
||||
def _stale_cache_with_no_host(self) -> None:
|
||||
# Соседний процесс: только что прочитал пустой адрес, TTL ещё не вышел.
|
||||
instance_settings._cached = (time.monotonic(), ("", ""))
|
||||
instance_settings._last_miss_refresh = 0.0
|
||||
|
||||
def test_host_written_by_another_process_is_accepted_at_once(self) -> None:
|
||||
self._stale_cache_with_no_host()
|
||||
# Запись мимо save(): invalidate_cache() в этом процессе не вызывается,
|
||||
# как и в реальности, где мастер отработал в другом воркере.
|
||||
InstanceSettings.objects.filter(pk=InstanceSettings.SINGLETON_PK).update(
|
||||
public_host="crm.example.test"
|
||||
)
|
||||
|
||||
response = self.client.get("/api/v1/auth/session/", HTTP_HOST="crm.example.test")
|
||||
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
|
||||
def test_unknown_host_does_not_reread_more_than_once_a_second(self) -> None:
|
||||
InstanceSettings.objects.filter(pk=InstanceSettings.SINGLETON_PK).update(
|
||||
public_host="crm.example.test"
|
||||
)
|
||||
self._stale_cache_with_no_host()
|
||||
self.assertEqual(self.client.get("/api/v1/auth/session/", HTTP_HOST="evil.example").status_code, 400)
|
||||
# Первый промах перечитал кэш и уже знает настоящий адрес.
|
||||
self.assertEqual(set(accepted_hosts()), {"crm.example.test"})
|
||||
# Второй промах в ту же секунду базу не трогает: кэш подменён, но не перечитан.
|
||||
instance_settings._cached = (time.monotonic(), ("", ""))
|
||||
self.assertEqual(self.client.get("/api/v1/auth/session/", HTTP_HOST="evil.example").status_code, 400)
|
||||
self.assertEqual(accepted_hosts(), ())
|
||||
@@ -0,0 +1,77 @@
|
||||
"""SVG-логотип организации: принимается чистый, отклоняется опасный.
|
||||
|
||||
Логотип отдаётся с адреса приложения, поэтому SVG проверяется при загрузке
|
||||
(скрипты, обработчики, внешние ссылки), а при отдаче получает защитные
|
||||
заголовки как второй рубеж.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.test import TestCase
|
||||
|
||||
from chatballs.identity.bootstrap import bootstrap_owner
|
||||
from chatballs.identity.logo_svg import svg_is_safe
|
||||
from chatballs.testing import TenantAPIClient
|
||||
|
||||
CLEAN_SVG = b"""<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 64 64">
|
||||
<defs><linearGradient id="g"><stop offset="0" stop-color="#1677ff"/><stop offset="1" stop-color="#003eb3"/></linearGradient></defs>
|
||||
<style>.mark { fill: url(#g); }</style>
|
||||
<circle class="mark" cx="32" cy="32" r="30"/>
|
||||
<use xlink:href="#mark"/>
|
||||
</svg>
|
||||
"""
|
||||
|
||||
|
||||
class SvgSafetyTests(TestCase):
|
||||
def test_clean_svg_is_accepted(self) -> None:
|
||||
self.assertTrue(svg_is_safe(CLEAN_SVG))
|
||||
|
||||
def test_dangerous_svg_is_rejected(self) -> None:
|
||||
samples = {
|
||||
"script": b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
|
||||
"handler": b'<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"><rect/></svg>',
|
||||
"javascript href": b'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:href="javascript:alert(1)"><rect/></a></svg>',
|
||||
"external image": b'<svg xmlns="http://www.w3.org/2000/svg"><image href="https://evil.example/t.png"/></svg>',
|
||||
"foreignObject": b'<svg xmlns="http://www.w3.org/2000/svg"><foreignObject><div>x</div></foreignObject></svg>',
|
||||
"external css": b'<svg xmlns="http://www.w3.org/2000/svg"><style>@import url(https://evil.example/a.css);</style></svg>',
|
||||
"style url": b'<svg xmlns="http://www.w3.org/2000/svg"><rect style="fill:url(http://evil.example/x)"/></svg>',
|
||||
"doctype entity": b'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY x "y">]><svg xmlns="http://www.w3.org/2000/svg"/>',
|
||||
"not svg": b'<html><body>hi</body></html>',
|
||||
"broken xml": b'<svg xmlns="http://www.w3.org/2000/svg"><rect></svg>',
|
||||
}
|
||||
for name, sample in samples.items():
|
||||
with self.subTest(name):
|
||||
self.assertFalse(svg_is_safe(sample))
|
||||
|
||||
|
||||
class SvgLogoApiTests(TestCase):
|
||||
def setUp(self) -> None:
|
||||
result = bootstrap_owner(email="svg-owner@example.com", password="temporary-password")
|
||||
self.client = TenantAPIClient()
|
||||
self.client.force_authenticate(result.owner)
|
||||
|
||||
def _upload(self, data: bytes):
|
||||
return self.client.post(
|
||||
"/api/v1/company/administration/logo/",
|
||||
{"file": SimpleUploadedFile("logo.svg", data, content_type="image/svg+xml")},
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
def test_svg_logo_round_trip_with_protective_headers(self) -> None:
|
||||
uploaded = self._upload(CLEAN_SVG)
|
||||
|
||||
self.assertEqual(uploaded.status_code, 200, uploaded.content)
|
||||
downloaded = self.client.get("/api/v1/company/administration/logo/")
|
||||
self.assertEqual(downloaded.status_code, 200)
|
||||
self.assertEqual(downloaded["Content-Type"], "image/svg+xml")
|
||||
self.assertIn("sandbox", downloaded["Content-Security-Policy"])
|
||||
self.assertEqual(downloaded["X-Content-Type-Options"], "nosniff")
|
||||
self.assertEqual(b"".join(downloaded.streaming_content), CLEAN_SVG)
|
||||
|
||||
def test_svg_with_script_is_refused_with_a_field_error(self) -> None:
|
||||
response = self._upload(b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn("file", response.json()["errors"])
|
||||
@@ -4,6 +4,14 @@ from django.test import TransactionTestCase
|
||||
|
||||
|
||||
class MembershipMigrationTests(TransactionTestCase):
|
||||
"""Перенос сотрудников на членства (identity/0012) не теряет идентификаторы.
|
||||
|
||||
Тест уводит базу к состоянию до переноса, поэтому обязан вернуть её обратно
|
||||
за собой. Иначе всё, что запускается после него в той же сессии, работает
|
||||
на схеме годичной давности: откат по identity утягивает и зависимые
|
||||
миграции других приложений, и чем их больше, тем разрушительнее последствия.
|
||||
"""
|
||||
|
||||
migrate_from = [("identity", "0011_enforce_capability_registry")]
|
||||
migrate_to = [("identity", "0012_membership_identity")]
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Создание организации из интерфейса: кнопка «Добавить организацию» (A1)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from django.test import TestCase, override_settings
|
||||
|
||||
from chatballs.ai.models import KnowledgeCategory
|
||||
from chatballs.identity.models import (
|
||||
AuditEvent,
|
||||
EmployeeRole,
|
||||
HumanUser,
|
||||
Organization,
|
||||
OrganizationMembership,
|
||||
)
|
||||
from chatballs.testing import TenantAPIClient
|
||||
|
||||
URL = "/api/v1/organizations/"
|
||||
|
||||
|
||||
@override_settings(ROOT_URLCONF="chatballs_backend.urls_app")
|
||||
class OrganizationCreationTests(TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.first = Organization.objects.create(name="Ателье Норд", slug="atelie-nord")
|
||||
self.owner = HumanUser.objects.create_user(
|
||||
email="owner@example.test", password="Owner-pass-123!", full_name="Елена"
|
||||
)
|
||||
OrganizationMembership.objects.create(
|
||||
organization=self.first,
|
||||
user=self.owner,
|
||||
role=EmployeeRole.OWNER,
|
||||
position_title="Владелец",
|
||||
)
|
||||
self.employee = HumanUser.objects.create_user(
|
||||
email="employee@example.test", password="Emp-pass-1234!", full_name="Иван"
|
||||
)
|
||||
OrganizationMembership.objects.create(
|
||||
organization=self.first,
|
||||
user=self.employee,
|
||||
role=EmployeeRole.EMPLOYEE,
|
||||
position_title="Оператор",
|
||||
)
|
||||
|
||||
def _post(self, user: HumanUser, **body):
|
||||
client = TenantAPIClient()
|
||||
client.force_login(user)
|
||||
return client.post(
|
||||
URL,
|
||||
data=json.dumps({"name": "Вторая компания", "timezone": "Europe/Moscow", **body}),
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
def test_owner_creates_organization_and_becomes_its_owner(self) -> None:
|
||||
response = self._post(self.owner, language="en")
|
||||
|
||||
self.assertEqual(response.status_code, 201, response.content)
|
||||
payload = response.json()
|
||||
created = Organization.objects.get(public_id=payload["organizationPublicId"])
|
||||
self.assertEqual(created.name, "Вторая компания")
|
||||
self.assertEqual(created.language, "en")
|
||||
self.assertEqual(created.status, "ACTIVE")
|
||||
membership = OrganizationMembership.objects.get(organization=created, user=self.owner)
|
||||
self.assertEqual(membership.role, EmployeeRole.OWNER)
|
||||
self.assertTrue(KnowledgeCategory.objects.filter(organization=created).exists())
|
||||
# Список членств в ответе уже содержит новую организацию: интерфейсу
|
||||
# есть куда переключиться без повторного запроса сессии.
|
||||
self.assertEqual(
|
||||
{item["organizationPublicId"] for item in payload["user"]["memberships"]},
|
||||
{str(self.first.public_id), str(created.public_id)},
|
||||
)
|
||||
self.assertTrue(
|
||||
AuditEvent.objects.filter(
|
||||
organization=created, action="organization.created", actor=self.owner
|
||||
).exists()
|
||||
)
|
||||
|
||||
def test_same_name_gets_a_distinct_slug(self) -> None:
|
||||
first = self._post(self.owner).json()["organizationPublicId"]
|
||||
second = self._post(self.owner).json()["organizationPublicId"]
|
||||
|
||||
slugs = set(Organization.objects.filter(public_id__in=[first, second]).values_list("slug", flat=True))
|
||||
self.assertEqual(len(slugs), 2)
|
||||
|
||||
def test_employee_cannot_create_organizations(self) -> None:
|
||||
response = self._post(self.employee)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(Organization.objects.count(), 1)
|
||||
|
||||
def test_instance_admin_without_memberships_can_create(self) -> None:
|
||||
admin = HumanUser.objects.create_user(
|
||||
email="admin@example.test", password="Admin-pass-123!", is_instance_admin=True
|
||||
)
|
||||
|
||||
response = self._post(admin)
|
||||
|
||||
self.assertEqual(response.status_code, 201, response.content)
|
||||
created = Organization.objects.get(public_id=response.json()["organizationPublicId"])
|
||||
self.assertTrue(OrganizationMembership.objects.filter(organization=created, user=admin, role=EmployeeRole.OWNER).exists())
|
||||
|
||||
def test_empty_name_is_a_field_error(self) -> None:
|
||||
response = self._post(self.owner, name=" ")
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn("name", response.json()["errors"])
|
||||
self.assertEqual(Organization.objects.count(), 1)
|
||||
|
||||
def test_anonymous_is_rejected(self) -> None:
|
||||
response = TenantAPIClient().post(URL, data=json.dumps({"name": "X"}), content_type="application/json")
|
||||
|
||||
self.assertIn(response.status_code, {401, 403})
|
||||
|
||||
def test_options_list_timezones_and_languages(self) -> None:
|
||||
client = TenantAPIClient()
|
||||
client.force_login(self.owner)
|
||||
|
||||
response = client.get(f"{URL}options/")
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn("Europe/Moscow", response.json()["timezones"])
|
||||
self.assertTrue(response.json()["languages"])
|
||||
@@ -50,6 +50,8 @@ COVERAGE_EXEMPT = {
|
||||
# Настройки установки (адрес, по которому её открывают) — тоже одна
|
||||
# строка на инстанс: их пишет мастер первого запуска, а не демо.
|
||||
("identity", "instancesettings"),
|
||||
# Состояние обновлений установки — одна строка на инстанс (updates/0001).
|
||||
("updates", "updatestate"),
|
||||
}
|
||||
COVERAGE_EXEMPT_APPS = {"platform", "events"}
|
||||
|
||||
|
||||
@@ -12,13 +12,19 @@ import secrets
|
||||
from datetime import timedelta
|
||||
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
|
||||
from chatballs.conversations import transports
|
||||
from chatballs.conversations.transports.base import InboundMessage
|
||||
from chatballs.i18n import customer_language, first_chosen, normalize_language, t
|
||||
from chatballs.integrations.models import Integration, IntegrationKind, IntegrationProvider
|
||||
from chatballs.notifications.models import MessengerBinding, MessengerBindingCode
|
||||
from chatballs.notifications.models import (
|
||||
MessengerBinding,
|
||||
MessengerBindingCode,
|
||||
NotificationTransport,
|
||||
)
|
||||
from chatballs.notifications.preferences import update_preference
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -39,7 +45,11 @@ def notifier_integrations(context):
|
||||
provider__in=(IntegrationProvider.TELEGRAM, IntegrationProvider.MAX),
|
||||
config__purpose=NOTIFIER_PURPOSE,
|
||||
).exclude(secret="")
|
||||
return qs.filter(organization=context.organization)
|
||||
# Демо-подключения из демо-набора не опрашиваются: токены ненастоящие.
|
||||
# Отсутствие ключа в JSON — тоже «не демо», поэтому isnull, а не exclude.
|
||||
return qs.filter(organization=context.organization).filter(
|
||||
Q(config__demoSeed__isnull=True) | Q(config__demoSeed=False)
|
||||
)
|
||||
|
||||
|
||||
def deep_link(integration: Integration, code: str) -> str:
|
||||
@@ -105,6 +115,13 @@ def handle_notifier_inbound(integration: Integration, inbound: InboundMessage) -
|
||||
integration=integration,
|
||||
defaults={"external_chat_id": inbound.chat_id or inbound.user_id},
|
||||
)
|
||||
# Привязка — и есть согласие получать: до неё звать было просто некуда.
|
||||
update_preference(
|
||||
organization_id=integration.organization_id,
|
||||
user_id=binding_code.user_id,
|
||||
transport=NotificationTransport.MESSENGER,
|
||||
enabled=True,
|
||||
)
|
||||
binding_code.delete()
|
||||
# Подтверждение читает конкретный сотрудник — язык берём из его профиля.
|
||||
done = t(
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
"""Доставка уведомлений в мессенджеры через сервисных ботов.
|
||||
|
||||
Событие notifications.notification_created кладётся в outbox из notify() и
|
||||
обрабатывается worker'ом: аудитория разворачивается в получателей (зеркало
|
||||
selectors.visible_for), их привязки получают сообщение через транспорт бота.
|
||||
обрабатывается worker'ом: аудитория разворачивается в получателей
|
||||
(chatballs.notifications.recipients), их привязки получают сообщение через
|
||||
транспорт бота.
|
||||
|
||||
Отправка best-effort: сбой одной привязки логируется и не валит событие.
|
||||
"""
|
||||
|
||||
@@ -12,15 +14,13 @@ import logging
|
||||
|
||||
from chatballs.conversations import transports
|
||||
from chatballs.identity.instance_settings import public_base_url
|
||||
from chatballs.identity.models import OrganizationMembership
|
||||
from chatballs.notifications.models import (
|
||||
MessengerBinding,
|
||||
Notification,
|
||||
NotificationAudience,
|
||||
NotificationLevel,
|
||||
)
|
||||
from chatballs.notifications.selectors import visible_for
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
from chatballs.notifications.preferences import messenger_types
|
||||
from chatballs.notifications.recipients import recipient_user_ids
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -34,21 +34,6 @@ _LEVEL_MARK = {
|
||||
}
|
||||
|
||||
|
||||
def _recipient_user_ids(notification: Notification) -> list[int]:
|
||||
if notification.audience == NotificationAudience.USER:
|
||||
return [notification.recipient_user_id] if notification.recipient_user_id else []
|
||||
profiles = OrganizationMembership.objects.filter(
|
||||
organization_id=notification.organization_id,
|
||||
blocked_at__isnull=True,
|
||||
user__is_active=True,
|
||||
).select_related("user")
|
||||
return [
|
||||
profile.user_id
|
||||
for profile in profiles
|
||||
if visible_for(TenantContext.for_membership(profile)).filter(id=notification.id).exists()
|
||||
]
|
||||
|
||||
|
||||
def _message_text(notification: Notification) -> str:
|
||||
mark = _LEVEL_MARK.get(notification.level, "🔔")
|
||||
lines = [f"{mark} {notification.title}"]
|
||||
@@ -60,8 +45,14 @@ def _message_text(notification: Notification) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def deliver_notification(notification: Notification) -> int:
|
||||
user_ids = _recipient_user_ids(notification)
|
||||
def deliver_notification(notification: Notification, *, user_ids: list[int] | None = None) -> int:
|
||||
"""Рассылает уведомление в привязанные мессенджеры.
|
||||
|
||||
Получателей можно передать готовыми: тот же список нужен и оповещению
|
||||
открытого приложения, а считать его дважды на каждое уведомление незачем.
|
||||
"""
|
||||
if user_ids is None:
|
||||
user_ids = recipient_user_ids(notification)
|
||||
if not user_ids:
|
||||
return 0
|
||||
bindings = (
|
||||
@@ -71,7 +62,10 @@ def deliver_notification(notification: Notification) -> int:
|
||||
text = _message_text(notification)
|
||||
sent = 0
|
||||
for binding in bindings:
|
||||
if notification.type not in (binding.push_types or []):
|
||||
allowed = messenger_types(
|
||||
organization_id=notification.organization_id, user_id=binding.user_id
|
||||
)
|
||||
if notification.type not in allowed:
|
||||
continue
|
||||
try:
|
||||
if transports.send_reply(binding.integration, chat_id=binding.external_chat_id, user_id="", text=text):
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from chatballs.events.handlers import register
|
||||
from chatballs.notifications.delivery import NOTIFICATION_CREATED, deliver_notification
|
||||
from chatballs.notifications.models import Notification
|
||||
from chatballs.notifications.realtime import notify_notifications_changed
|
||||
from chatballs.notifications.recipients import recipient_user_ids
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
|
||||
|
||||
@@ -11,5 +13,11 @@ def handle_notification_created(payload: dict, context: TenantContext | None) ->
|
||||
notification = Notification.objects.filter(
|
||||
pk=payload.get("notificationId"), organization=context.organization
|
||||
).first()
|
||||
if notification is not None:
|
||||
deliver_notification(notification)
|
||||
if notification is None:
|
||||
return
|
||||
# Получатели считаются один раз на оба пути доставки.
|
||||
user_ids = recipient_user_ids(notification)
|
||||
# Сначала те, кто сидит в приложении: это мгновенно и ничего не стоит.
|
||||
# Мессенджер — следом, он медленнее и ходит наружу.
|
||||
notify_notifications_changed(user_ids)
|
||||
deliver_notification(notification, user_ids=user_ids)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Граница видимости уведомления — та же, что у диалога.
|
||||
|
||||
Раньше уведомления фильтровались только правом «видеть диалоги», а сами диалоги
|
||||
— ещё и группой (ADR-CHATBALLS-0043 §4). Из-за расхождения оператор одной группы
|
||||
получал оклик с именем клиента и куском переписки по диалогу другой группы и,
|
||||
перейдя по нему, упирался в «диалог не найден».
|
||||
|
||||
Старые записи остаются с NULL: группу диалога, из которого они родились, задним
|
||||
числом восстанавливать нечем, а NULL здесь означает прежнее поведение — видно
|
||||
всем, кого пропускает аудитория.
|
||||
"""
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('identity', '0020_employeegroup_employeegroupmember_and_more'),
|
||||
('notifications', '0010_i18n_events'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='notification',
|
||||
name='audience_group',
|
||||
field=models.ForeignKey(
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name='notifications',
|
||||
to='identity.employeegroup',
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Настройка оклика уезжает из привязки к мессенджеру в отдельную сущность.
|
||||
|
||||
Пока транспорт был один, список типов на привязке работал. Со вторым (браузер) в
|
||||
профиле оказались бы два списка галочек про одно и то же, и человек, отключивший
|
||||
«новое сообщение», продолжал бы получать его с другой стороны.
|
||||
|
||||
Порядок операций здесь важен: сначала новая таблица, потом перенос, и только
|
||||
потом удаление старого поля. Django сгенерировал обратный порядок — в нём
|
||||
настройки всех, кто подключил бота, молча обнулились бы.
|
||||
"""
|
||||
|
||||
import chatballs.notifications.models
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
MESSENGER = "MESSENGER"
|
||||
|
||||
|
||||
def carry_over_push_types(apps, schema_editor):
|
||||
MessengerBinding = apps.get_model("notifications", "MessengerBinding")
|
||||
NotificationPreference = apps.get_model("notifications", "NotificationPreference")
|
||||
rows = []
|
||||
seen = set()
|
||||
for binding in MessengerBinding.objects.all().iterator():
|
||||
# Мессенджер у сотрудника один на организацию, но привязок в базе могло
|
||||
# остаться несколько: берём первую и не плодим дубли под уникальным ключом.
|
||||
key = (binding.organization_id, binding.user_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
rows.append(
|
||||
NotificationPreference(
|
||||
organization_id=binding.organization_id,
|
||||
user_id=binding.user_id,
|
||||
transport=MESSENGER,
|
||||
# Привязка существует — значит, согласие получать уже дано.
|
||||
enabled=True,
|
||||
types=binding.push_types or [],
|
||||
)
|
||||
)
|
||||
NotificationPreference.objects.bulk_create(rows, ignore_conflicts=True)
|
||||
|
||||
|
||||
def restore_push_types(apps, schema_editor):
|
||||
MessengerBinding = apps.get_model("notifications", "MessengerBinding")
|
||||
NotificationPreference = apps.get_model("notifications", "NotificationPreference")
|
||||
by_user = {
|
||||
(preference.organization_id, preference.user_id): preference.types
|
||||
for preference in NotificationPreference.objects.filter(transport=MESSENGER)
|
||||
}
|
||||
for binding in MessengerBinding.objects.all().iterator():
|
||||
types = by_user.get((binding.organization_id, binding.user_id))
|
||||
if types is not None:
|
||||
binding.push_types = types
|
||||
binding.save(update_fields=["push_types"])
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('identity', '0039_remove_organization_currency'),
|
||||
('notifications', '0011_notification_audience_group'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='NotificationPreference',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('transport', models.CharField(choices=[('BROWSER', 'Браузер'), ('MESSENGER', 'Мессенджер')], max_length=16)),
|
||||
('enabled', models.BooleanField(default=False)),
|
||||
('types', models.JSONField(blank=True, default=chatballs.notifications.models.default_push_types)),
|
||||
('organization', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='notification_preferences', to='identity.organization')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notification_preferences', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'constraints': [models.UniqueConstraint(fields=('organization', 'user', 'transport'), name='uniq_notification_preference')],
|
||||
},
|
||||
),
|
||||
migrations.RunPython(carry_over_push_types, restore_push_types),
|
||||
migrations.RemoveField(
|
||||
model_name='messengerbinding',
|
||||
name='push_types',
|
||||
),
|
||||
]
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
"""Набор типов событий — из макета «Очередь и уведомления», фрейм Q1.
|
||||
|
||||
Раньше «клиент запросил оператора» и «диалог долго ждёт» были одним типом
|
||||
DIALOG_WAITING, и отписаться от второго, не потеряв первое, было нельзя. Теперь
|
||||
это разные события, и к ним добавилось «диалог назначили на меня».
|
||||
|
||||
Старые записи разделяются по dedup_key — единственному, что о них известно
|
||||
задним числом: ключи эскалации начинаются с «waiting:», ключи назначения — с
|
||||
«assign:». Всё остальное, что было DIALOG_WAITING, — это просьба о человеке.
|
||||
|
||||
Выбор сотрудника в настройках переносится по тому же соответствию, иначе человек после
|
||||
обновления молча перестал бы получать то, на что подписан.
|
||||
"""
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
# Старый код -> новый. RELEASE_PUBLISHED не переносится: он был заделом на
|
||||
# будущее, никогда не отправлялся и в новом наборе ему места нет.
|
||||
OLD_TO_NEW = {
|
||||
"DIALOG_WAITING": "OPERATOR_REQUESTED",
|
||||
"INTEGRATION_ERROR": "AI_STOPPED",
|
||||
}
|
||||
|
||||
SPLIT_BY_DEDUP_PREFIX = (
|
||||
("waiting:", "DIALOG_WAITING_LONG"),
|
||||
("assign:", "DIALOG_ASSIGNED"),
|
||||
)
|
||||
|
||||
|
||||
def forward(apps, schema_editor):
|
||||
Notification = apps.get_model("notifications", "Notification")
|
||||
for old, new in OLD_TO_NEW.items():
|
||||
Notification.objects.filter(type=old).update(type=new)
|
||||
for prefix, new in SPLIT_BY_DEDUP_PREFIX:
|
||||
Notification.objects.filter(
|
||||
type="OPERATOR_REQUESTED", dedup_key__startswith=prefix
|
||||
).update(type=new)
|
||||
_remap_preferences(apps, {**OLD_TO_NEW})
|
||||
|
||||
|
||||
def backward(apps, schema_editor):
|
||||
Notification = apps.get_model("notifications", "Notification")
|
||||
reverse = {
|
||||
"OPERATOR_REQUESTED": "DIALOG_WAITING",
|
||||
"DIALOG_WAITING_LONG": "DIALOG_WAITING",
|
||||
"DIALOG_ASSIGNED": "DIALOG_WAITING",
|
||||
"AI_STOPPED": "INTEGRATION_ERROR",
|
||||
}
|
||||
for new, old in reverse.items():
|
||||
Notification.objects.filter(type=new).update(type=old)
|
||||
_remap_preferences(apps, reverse)
|
||||
|
||||
|
||||
def _remap_preferences(apps, mapping):
|
||||
"""Подписки сотрудников: коды внутри JSON-списка."""
|
||||
NotificationPreference = apps.get_model("notifications", "NotificationPreference")
|
||||
for preference in NotificationPreference.objects.all().iterator():
|
||||
types = preference.types or []
|
||||
moved = [mapping.get(code, code) for code in types]
|
||||
# Дубли возможны, когда два старых кода сходятся в один новый.
|
||||
unique = list(dict.fromkeys(moved))
|
||||
if unique != types:
|
||||
preference.types = unique
|
||||
preference.save(update_fields=["types"])
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('notifications', '0012_notification_preference'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(forward, backward),
|
||||
migrations.AlterField(
|
||||
model_name='notification',
|
||||
name='type',
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
('OPERATOR_REQUESTED', 'Клиент запросил оператора'),
|
||||
('DIALOG_NEW_MESSAGE', 'Новое сообщение в моём диалоге'),
|
||||
('DIALOG_ASSIGNED', 'Диалог назначили на меня'),
|
||||
('DIALOG_WAITING_LONG', 'Диалог долго ждёт человека'),
|
||||
('AI_STOPPED', 'AI остановлен ошибкой или лимитом'),
|
||||
],
|
||||
max_length=32,
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
"""«Новый диалог» — отдельное событие (макет Q1, дополнение владельца).
|
||||
|
||||
В присланном наборе такого типа не было, и оклик о новом диалоге попал в
|
||||
«клиент запросил оператора». Но диалог начинается и на канале с работающим
|
||||
агентом, где человека никто не звал: называть это просьбой о человеке — врать.
|
||||
|
||||
Старые записи узнаются по dedup_key «dialog:» — так помечены именно оклики о
|
||||
новом диалоге. Разделить их по тому, был ли тогда доступен агент, задним числом
|
||||
нельзя, поэтому все они становятся «новым диалогом»: это верно для
|
||||
подавляющего большинства (канал с агентом — обычный случай) и, в отличие от
|
||||
обратного, ничего не приписывает клиенту.
|
||||
|
||||
Подписки: кому приходило «клиент запросил оператора», тому добавляется и «новый
|
||||
диалог». До этой миграции это было одно событие, и человек не должен молча
|
||||
перестать получать половину того, на что был подписан.
|
||||
"""
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def forward(apps, schema_editor):
|
||||
Notification = apps.get_model("notifications", "Notification")
|
||||
Notification.objects.filter(
|
||||
type="OPERATOR_REQUESTED", dedup_key__startswith="dialog:"
|
||||
).update(type="NEW_DIALOG")
|
||||
NotificationPreference = apps.get_model("notifications", "NotificationPreference")
|
||||
for preference in NotificationPreference.objects.all().iterator():
|
||||
types = preference.types or []
|
||||
if "OPERATOR_REQUESTED" in types and "NEW_DIALOG" not in types:
|
||||
preference.types = ["NEW_DIALOG", *types]
|
||||
preference.save(update_fields=["types"])
|
||||
|
||||
|
||||
def backward(apps, schema_editor):
|
||||
Notification = apps.get_model("notifications", "Notification")
|
||||
Notification.objects.filter(type="NEW_DIALOG").update(type="OPERATOR_REQUESTED")
|
||||
NotificationPreference = apps.get_model("notifications", "NotificationPreference")
|
||||
for preference in NotificationPreference.objects.all().iterator():
|
||||
types = preference.types or []
|
||||
if "NEW_DIALOG" in types:
|
||||
kept = [code for code in types if code != "NEW_DIALOG"]
|
||||
preference.types = kept if "OPERATOR_REQUESTED" in kept else ["OPERATOR_REQUESTED", *kept]
|
||||
preference.save(update_fields=["types"])
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('notifications', '0013_notification_types_from_baseline'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='notification',
|
||||
name='type',
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
('NEW_DIALOG', 'Новый диалог'),
|
||||
('OPERATOR_REQUESTED', 'Клиент запросил оператора'),
|
||||
('DIALOG_NEW_MESSAGE', 'Новое сообщение в моём диалоге'),
|
||||
('DIALOG_ASSIGNED', 'Диалог назначили на меня'),
|
||||
('DIALOG_WAITING_LONG', 'Диалог долго ждёт человека'),
|
||||
('AI_STOPPED', 'AI остановлен ошибкой или лимитом'),
|
||||
],
|
||||
max_length=32,
|
||||
),
|
||||
),
|
||||
migrations.RunPython(forward, backward),
|
||||
]
|
||||
@@ -8,11 +8,24 @@ from chatballs.tenancy.models import TenantRelationModel
|
||||
|
||||
|
||||
class NotificationType(models.TextChoices):
|
||||
DIALOG_WAITING = "DIALOG_WAITING", "Диалог ждёт оператора"
|
||||
DIALOG_NEW_MESSAGE = "DIALOG_NEW_MESSAGE", "Новое сообщение в диалоге"
|
||||
# Задел на будущее (добавляются записью в реестр notifications.services.TYPE_META):
|
||||
RELEASE_PUBLISHED = "RELEASE_PUBLISHED", "Опубликован релиз агента"
|
||||
INTEGRATION_ERROR = "INTEGRATION_ERROR", "Ошибка интеграции"
|
||||
"""Что произошло. Набор — из макета «Очередь и уведомления», фрейм Q1.
|
||||
|
||||
Это ровно тот список, который сотрудник видит галочками в профиле, поэтому
|
||||
типы разделены по смыслу для человека, а не по месту в коде. «Клиент
|
||||
запросил оператора» и «диалог долго ждёт» раньше были одним типом, и
|
||||
отписаться от второго, не потеряв первое, было нельзя.
|
||||
|
||||
«Новый диалог» стоит отдельно от «клиент запросил оператора» по той же
|
||||
причине: диалог может начаться и на канале с работающим агентом, где
|
||||
человека никто не звал, и называть такой оклик просьбой о человеке — врать.
|
||||
"""
|
||||
|
||||
NEW_DIALOG = "NEW_DIALOG", "Новый диалог"
|
||||
OPERATOR_REQUESTED = "OPERATOR_REQUESTED", "Клиент запросил оператора"
|
||||
DIALOG_NEW_MESSAGE = "DIALOG_NEW_MESSAGE", "Новое сообщение в моём диалоге"
|
||||
DIALOG_ASSIGNED = "DIALOG_ASSIGNED", "Диалог назначили на меня"
|
||||
DIALOG_WAITING_LONG = "DIALOG_WAITING_LONG", "Диалог долго ждёт человека"
|
||||
AI_STOPPED = "AI_STOPPED", "AI остановлен ошибкой или лимитом"
|
||||
|
||||
|
||||
class NotificationLevel(models.TextChoices):
|
||||
@@ -47,6 +60,17 @@ class Notification(models.Model):
|
||||
target_route = models.CharField(max_length=64, blank=True)
|
||||
target_id = models.CharField(max_length=64, blank=True)
|
||||
audience = models.CharField(max_length=16, choices=NotificationAudience.choices, default=NotificationAudience.ALL)
|
||||
# Граница видимости уведомления (ADR-CHATBALLS-0043 §4). Уведомление о диалоге
|
||||
# видно тем же, кому виден сам диалог: иначе оператор чужой группы получает
|
||||
# оклик с именем клиента и куском переписки, а открыть диалог не может.
|
||||
# NULL — видно всем, кого пропускает аудитория.
|
||||
audience_group = models.ForeignKey(
|
||||
"identity.EmployeeGroup",
|
||||
on_delete=models.SET_NULL,
|
||||
related_name="notifications",
|
||||
null=True,
|
||||
blank=True,
|
||||
)
|
||||
recipient_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name="direct_notifications")
|
||||
source_type = models.CharField(max_length=64, blank=True)
|
||||
source_id = models.CharField(max_length=64, blank=True)
|
||||
@@ -72,8 +96,57 @@ class NotificationRead(TenantRelationModel):
|
||||
|
||||
|
||||
def default_push_types() -> list[str]:
|
||||
# Дефолт: диалоговые события (новый диалог / ждёт оператора / новое сообщение).
|
||||
return [NotificationType.DIALOG_WAITING, NotificationType.DIALOG_NEW_MESSAGE]
|
||||
# Дефолт — то, что касается лично и требует действия: позвали человека,
|
||||
# написали в мой диалог, назначили на меня. «Долго ждёт» и сбой AI —
|
||||
# подписка по желанию, иначе оклик обесценивается.
|
||||
# «Новый диалог» сюда не входит: диалог, которым занимается агент, лично
|
||||
# никого не касается. Кому он нужен — включит галочкой.
|
||||
return [
|
||||
NotificationType.OPERATOR_REQUESTED,
|
||||
NotificationType.DIALOG_NEW_MESSAGE,
|
||||
NotificationType.DIALOG_ASSIGNED,
|
||||
]
|
||||
|
||||
|
||||
class NotificationTransport(models.TextChoices):
|
||||
BROWSER = "BROWSER", "Браузер"
|
||||
MESSENGER = "MESSENGER", "Мессенджер"
|
||||
|
||||
|
||||
class NotificationPreference(models.Model):
|
||||
"""Куда и о чём окликать сотрудника.
|
||||
|
||||
Одна настройка на все транспорты. Браузер и бот в мессенджере отвечают на
|
||||
один и тот же вопрос — «о чём меня звать», — и второй такой же список
|
||||
галочек в профиле означал бы два расходящихся ответа на него. Новый
|
||||
транспорт (почта, мобильное приложение) — это строка здесь, а не ещё одна
|
||||
таблица настроек.
|
||||
|
||||
Разрешение самого браузера тут не хранится: оно живёт в браузере, своё на
|
||||
каждом устройстве, и сервер его ни выдать, ни отозвать не может. Здесь
|
||||
только намерение человека — хочет ли он, чтобы его окликали.
|
||||
"""
|
||||
|
||||
organization = models.ForeignKey(
|
||||
"identity.Organization", on_delete=models.PROTECT, related_name="notification_preferences"
|
||||
)
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_preferences"
|
||||
)
|
||||
transport = models.CharField(max_length=16, choices=NotificationTransport.choices)
|
||||
enabled = models.BooleanField(default=False)
|
||||
# Подмножество NotificationType; пустой список — не звать вовсе.
|
||||
types = models.JSONField(default=default_push_types, blank=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=["organization", "user", "transport"], name="uniq_notification_preference"
|
||||
)
|
||||
]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"pref:{self.user_id}/{self.transport}"
|
||||
|
||||
|
||||
class MessengerBinding(TenantRelationModel):
|
||||
@@ -87,8 +160,8 @@ class MessengerBinding(TenantRelationModel):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="messenger_bindings")
|
||||
integration = models.ForeignKey("integrations.Integration", on_delete=models.CASCADE, related_name="messenger_bindings")
|
||||
external_chat_id = models.CharField(max_length=128)
|
||||
# Типы уведомлений, которые доставляются в мессенджер (подмножество NotificationType).
|
||||
push_types = models.JSONField(default=default_push_types, blank=True)
|
||||
# Типы событий живут не здесь, а в NotificationPreference: вопрос «о чём
|
||||
# звать» один на все транспорты, и ответ на него обязан быть один.
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Настройки оклика сотрудника: о чём звать и каким транспортом.
|
||||
|
||||
Раньше список типов жил на привязке к мессенджеру. Пока транспорт был один, это
|
||||
работало; со вторым (браузер) в профиле появились бы два списка галочек про одно
|
||||
и то же, и человек, отключивший «новое сообщение», продолжал бы получать его с
|
||||
другой стороны. Поэтому список вынесен из привязки и заведён на транспорт.
|
||||
|
||||
Про `enabled` важно не ошибиться: это согласие получать, и у двух транспортов оно
|
||||
выражено по-разному. У мессенджера согласие — сама привязка бота: она есть, и
|
||||
звать есть куда; нет — и `enabled` ничего не спасёт. У браузера предъявить нечего,
|
||||
кроме намерения человека, поэтому его и храним. Отсюда две разные функции ниже:
|
||||
доставка в мессенджер спрашивает только типы (получателей она уже отобрала по
|
||||
наличию привязки), а браузер — типы вместе с согласием.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from chatballs.notifications.models import (
|
||||
NotificationPreference,
|
||||
NotificationTransport,
|
||||
NotificationType,
|
||||
default_push_types,
|
||||
)
|
||||
|
||||
|
||||
def preference_for(
|
||||
*, organization_id: int, user_id: int, transport: str
|
||||
) -> NotificationPreference:
|
||||
"""Настройка транспорта; при первом обращении заводится с дефолтами."""
|
||||
preference, _ = NotificationPreference.objects.get_or_create(
|
||||
organization_id=organization_id,
|
||||
user_id=user_id,
|
||||
transport=transport,
|
||||
defaults={"enabled": False, "types": default_push_types()},
|
||||
)
|
||||
return preference
|
||||
|
||||
|
||||
def preference_types(*, organization_id: int, user_id: int, transport: str) -> list[str]:
|
||||
"""Типы, выбранные для транспорта. Без строки — дефолтный набор.
|
||||
|
||||
Согласие не проверяется: у мессенджера его подтверждает привязка, и
|
||||
отсутствие строки настроек не повод замолчать.
|
||||
"""
|
||||
preference = NotificationPreference.objects.filter(
|
||||
organization_id=organization_id, user_id=user_id, transport=transport
|
||||
).first()
|
||||
if preference is None:
|
||||
return default_push_types()
|
||||
return list(preference.types or [])
|
||||
|
||||
|
||||
def enabled_types(*, organization_id: int, user_id: int, transport: str) -> list[str]:
|
||||
"""Типы транспорта, который человек включил. Не включил — пустой список."""
|
||||
preference = NotificationPreference.objects.filter(
|
||||
organization_id=organization_id, user_id=user_id, transport=transport
|
||||
).first()
|
||||
if preference is None or not preference.enabled:
|
||||
return []
|
||||
return list(preference.types or [])
|
||||
|
||||
|
||||
def update_preference(
|
||||
*,
|
||||
organization_id: int,
|
||||
user_id: int,
|
||||
transport: str,
|
||||
enabled: bool | None = None,
|
||||
types: list[str] | None = None,
|
||||
) -> NotificationPreference:
|
||||
preference = preference_for(
|
||||
organization_id=organization_id, user_id=user_id, transport=transport
|
||||
)
|
||||
fields = []
|
||||
if enabled is not None and preference.enabled != enabled:
|
||||
preference.enabled = enabled
|
||||
fields.append("enabled")
|
||||
if types is not None:
|
||||
# Чужие коды в список не пускаем: он приходит из браузера.
|
||||
allowed = [code for code in types if code in NotificationType.values]
|
||||
if preference.types != allowed:
|
||||
preference.types = allowed
|
||||
fields.append("types")
|
||||
if fields:
|
||||
preference.save(update_fields=fields)
|
||||
return preference
|
||||
|
||||
|
||||
def messenger_types(*, organization_id: int, user_id: int) -> list[str]:
|
||||
return preference_types(
|
||||
organization_id=organization_id,
|
||||
user_id=user_id,
|
||||
transport=NotificationTransport.MESSENGER,
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Оповещение сотрудника о том, что у него появились уведомления.
|
||||
|
||||
Событие адресное — в сокет каждого получателя отдельно. Группа организации, на
|
||||
которой живут события инбокса, здесь не годится: уведомления сотрудник видит не
|
||||
все, и рассылка на организацию означала бы, что о чужих он как минимум узнаёт.
|
||||
|
||||
Как и у диалогов, событие несёт только повод перезапросить: ни текста, ни
|
||||
идентификаторов. Содержимое клиент забирает обычным запросом, где и живёт
|
||||
проверка видимости — канал о ней не знает и потому не может в ней ошибиться.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
from chatballs.realtime import publish
|
||||
|
||||
NOTIFICATIONS_EVENT = "notifications.changed"
|
||||
|
||||
|
||||
def user_group(user_id: int) -> str:
|
||||
return f"user.{user_id}"
|
||||
|
||||
|
||||
def notify_notifications_changed(user_ids: Iterable[int]) -> None:
|
||||
for user_id in set(user_ids):
|
||||
publish(user_group(user_id), {"type": NOTIFICATIONS_EVENT})
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Кому адресовано уведомление.
|
||||
|
||||
Ответ нужен двум транспортам сразу — сокету открытого приложения и боту в
|
||||
мессенджере, — поэтому он считается здесь один раз, а не в каждом из них.
|
||||
|
||||
Раньше получатели искались перебором: для каждого сотрудника организации
|
||||
выполнялся отдельный запрос `visible_for(...).exists()`. На сотню рабочих мест
|
||||
это сотня запросов на каждое входящее сообщение — терпимо, только пока
|
||||
уведомления доставляются раз в пятнадцать секунд. Здесь два запроса независимо
|
||||
от размера организации: право выводится из роли, членство в группе — одним
|
||||
IN-условием.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from django.db.models import Q
|
||||
|
||||
from chatballs.identity.models import OrganizationMembership
|
||||
from chatballs.identity.policy import MANAGEMENT_ROLES, roles_with_capability
|
||||
from chatballs.notifications.models import Notification, NotificationAudience
|
||||
|
||||
# Аудитория — это право её читать. Зеркало notifications.selectors.visible_for:
|
||||
# расходиться этим двум таблицам нельзя, иначе уведомление придёт тому, кто его
|
||||
# потом не увидит в списке, или наоборот.
|
||||
AUDIENCE_CAPABILITY = {
|
||||
NotificationAudience.ALL: "company.view",
|
||||
NotificationAudience.OPERATORS: "conversations.view",
|
||||
NotificationAudience.OWNER: "employees.manage_privileged",
|
||||
}
|
||||
|
||||
|
||||
def audience_user_ids(
|
||||
*,
|
||||
organization_id: int,
|
||||
audience: str,
|
||||
group_id: int | None = None,
|
||||
recipient_user_id: int | None = None,
|
||||
) -> list[int]:
|
||||
"""Кого охватывает такая аудитория.
|
||||
|
||||
Отдельно от уведомления, потому что спросить это нужно и до него: очередь
|
||||
выясняет, есть ли вообще кому заметить ждущий диалог, ещё не решив, звать ли.
|
||||
"""
|
||||
if audience == NotificationAudience.USER:
|
||||
return [recipient_user_id] if recipient_user_id else []
|
||||
capability = AUDIENCE_CAPABILITY.get(audience)
|
||||
if capability is None:
|
||||
return []
|
||||
memberships = OrganizationMembership.objects.filter(
|
||||
organization_id=organization_id,
|
||||
role__in=roles_with_capability(capability),
|
||||
blocked_at__isnull=True,
|
||||
user__is_active=True,
|
||||
)
|
||||
if group_id is not None:
|
||||
# Та же граница, что у диалога: руководство видит всё, остальные — свою
|
||||
# группу (chatballs.identity.policy.conversation_visibility).
|
||||
memberships = memberships.filter(
|
||||
Q(role__in=MANAGEMENT_ROLES) | Q(group_links__group_id=group_id)
|
||||
).distinct()
|
||||
return list(memberships.values_list("user_id", flat=True))
|
||||
|
||||
|
||||
def recipient_user_ids(notification: Notification) -> list[int]:
|
||||
"""Идентификаторы сотрудников, которым это уведомление адресовано."""
|
||||
return audience_user_ids(
|
||||
organization_id=notification.organization_id,
|
||||
audience=notification.audience,
|
||||
group_id=notification.audience_group_id,
|
||||
recipient_user_id=notification.recipient_user_id,
|
||||
)
|
||||
@@ -1,7 +1,12 @@
|
||||
from django.db.models import Q, QuerySet
|
||||
|
||||
from chatballs.identity.policy import ResourceScope, authorize
|
||||
from chatballs.identity.policy import (
|
||||
ResourceScope,
|
||||
authorize,
|
||||
conversation_visibility,
|
||||
)
|
||||
from chatballs.notifications.models import Notification, NotificationAudience
|
||||
from chatballs.notifications.recipients import AUDIENCE_CAPABILITY
|
||||
from chatballs.tenancy.context import TenantContext
|
||||
|
||||
|
||||
@@ -11,16 +16,25 @@ def visible_for(context: TenantContext) -> QuerySet[Notification]:
|
||||
return Notification.objects.none()
|
||||
user = context.actor_user
|
||||
organization_scope = ResourceScope(profile.organization_id)
|
||||
audiences = []
|
||||
if authorize(profile, "company.view", organization_scope):
|
||||
audiences.append(NotificationAudience.ALL)
|
||||
if authorize(profile, "conversations.view", organization_scope):
|
||||
audiences.append(NotificationAudience.OPERATORS)
|
||||
if authorize(profile, "employees.manage_privileged", organization_scope):
|
||||
audiences.append(NotificationAudience.OWNER)
|
||||
audiences = [
|
||||
audience
|
||||
for audience, capability in AUDIENCE_CAPABILITY.items()
|
||||
if authorize(profile, capability, organization_scope)
|
||||
]
|
||||
by_audience = Q(audience__in=audiences)
|
||||
scope = conversation_visibility(profile)
|
||||
if scope is not None:
|
||||
# Уведомление о диалоге группы читает тот же, кому виден сам диалог.
|
||||
# Предикат намеренно взят тот же (ADR-CHATBALLS-0043 §4): два разных
|
||||
# ответа на вопрос «кому это видно» — дефект, а не гибкость. Раньше
|
||||
# уведомления фильтровались только правом, и оператор чужой группы
|
||||
# получал оклик с именем клиента и куском переписки по диалогу, который
|
||||
# не может открыть.
|
||||
by_audience &= Q(audience_group__isnull=True) | Q(
|
||||
audience_group_id__in=scope.get("group_ids") or ()
|
||||
)
|
||||
return Notification.objects.filter(organization_id=profile.organization_id).filter(
|
||||
Q(audience__in=audiences)
|
||||
| Q(audience=NotificationAudience.USER, recipient_user=user)
|
||||
by_audience | Q(audience=NotificationAudience.USER, recipient_user=user)
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -20,25 +20,35 @@ from chatballs.notifications.selectors import unread_for
|
||||
# каждый сотрудник читает его на своём языке. Ярлык TextChoices остаётся
|
||||
# английским/русским значением модели и до человека не доходит.
|
||||
TYPE_META: dict[str, dict] = {
|
||||
NotificationType.DIALOG_WAITING: {
|
||||
NotificationType.NEW_DIALOG: {
|
||||
"level": NotificationLevel.INFO,
|
||||
"route": "chat",
|
||||
"label": "notifications.type_new_dialog",
|
||||
},
|
||||
NotificationType.OPERATOR_REQUESTED: {
|
||||
"level": NotificationLevel.WARNING,
|
||||
"route": "chat",
|
||||
"label": "notifications.type_dialog_waiting",
|
||||
"label": "notifications.type_operator_requested",
|
||||
},
|
||||
NotificationType.DIALOG_NEW_MESSAGE: {
|
||||
"level": NotificationLevel.INFO,
|
||||
"route": "chat",
|
||||
"label": "notifications.type_dialog_new_message",
|
||||
},
|
||||
NotificationType.RELEASE_PUBLISHED: {
|
||||
"level": NotificationLevel.SUCCESS,
|
||||
"route": "agents",
|
||||
"label": "notifications.type_release_published",
|
||||
NotificationType.DIALOG_ASSIGNED: {
|
||||
"level": NotificationLevel.INFO,
|
||||
"route": "chat",
|
||||
"label": "notifications.type_dialog_assigned",
|
||||
},
|
||||
NotificationType.INTEGRATION_ERROR: {
|
||||
NotificationType.DIALOG_WAITING_LONG: {
|
||||
"level": NotificationLevel.WARNING,
|
||||
"route": "chat",
|
||||
"label": "notifications.type_dialog_waiting_long",
|
||||
},
|
||||
NotificationType.AI_STOPPED: {
|
||||
"level": NotificationLevel.CRITICAL,
|
||||
"route": "integrations",
|
||||
"label": "notifications.type_integration_error",
|
||||
"route": "agents",
|
||||
"label": "notifications.type_ai_stopped",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -48,6 +58,7 @@ def notify(
|
||||
context,
|
||||
type: str,
|
||||
audience: str,
|
||||
audience_group=None,
|
||||
title: str,
|
||||
body: str = "",
|
||||
title_key: str = "",
|
||||
@@ -71,6 +82,7 @@ def notify(
|
||||
organization=organization,
|
||||
type=type,
|
||||
audience=audience,
|
||||
audience_group=audience_group,
|
||||
title=title,
|
||||
body=body,
|
||||
title_key=title_key,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Уведомление о диалоге видно тем же, кому виден сам диалог.
|
||||
|
||||
Регрессия: уведомления фильтровались только правом «видеть диалоги», а диалоги —
|
||||
ещё и группой (ADR-CHATBALLS-0043 §4). Оператор чужой группы получал оклик с
|
||||
именем клиента и куском переписки, а открыть диалог не мог.
|
||||
"""
|
||||
|
||||
from django.test import TestCase
|
||||
|
||||
from chatballs.identity.group_models import EmployeeGroup, EmployeeGroupMember
|
||||
from chatballs.identity.models import (
|
||||
EmployeeRole,
|
||||
HumanUser,
|
||||
Organization,
|
||||
OrganizationMembership,
|
||||
)
|
||||
from chatballs.notifications.models import NotificationAudience, NotificationType
|
||||
from chatballs.notifications.recipients import recipient_user_ids
|
||||
from chatballs.notifications.selectors import visible_for
|
||||
from chatballs.notifications.services import notify
|
||||
from chatballs.testing import tenant_context_for
|
||||
|
||||
|
||||
class NotificationGroupVisibilityTests(TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.organization = Organization.objects.create(name="Example", slug="notify-groups")
|
||||
self.support = EmployeeGroup.objects.create(
|
||||
organization=self.organization, name="Поддержка"
|
||||
)
|
||||
self.sales = EmployeeGroup.objects.create(organization=self.organization, name="Продажи")
|
||||
self.owner = self._employee("owner@notify.test", EmployeeRole.OWNER)
|
||||
self.insider = self._employee("insider@notify.test", EmployeeRole.EMPLOYEE)
|
||||
self.outsider = self._employee("outsider@notify.test", EmployeeRole.EMPLOYEE)
|
||||
EmployeeGroupMember.objects.create(
|
||||
organization=self.organization, group=self.support, employee=self.insider
|
||||
)
|
||||
EmployeeGroupMember.objects.create(
|
||||
organization=self.organization, group=self.sales, employee=self.outsider
|
||||
)
|
||||
self.context = tenant_context_for(self.owner.user, self.organization)
|
||||
|
||||
def _employee(self, email: str, role: str) -> OrganizationMembership:
|
||||
user = HumanUser.objects.create_user(email=email, password="Password-123")
|
||||
return OrganizationMembership.objects.create(
|
||||
user=user, organization=self.organization, role=role, position_title="Specialist"
|
||||
)
|
||||
|
||||
def _visible_ids(self, membership: OrganizationMembership) -> set[int]:
|
||||
context = tenant_context_for(membership.user, self.organization)
|
||||
return set(visible_for(context).values_list("id", flat=True))
|
||||
|
||||
def _waiting(self, group: EmployeeGroup | None):
|
||||
return notify(
|
||||
context=self.context,
|
||||
type=NotificationType.OPERATOR_REQUESTED,
|
||||
audience=NotificationAudience.OPERATORS,
|
||||
audience_group=group,
|
||||
title="Нужен оператор",
|
||||
)
|
||||
|
||||
def test_group_notification_reaches_only_that_group_and_management(self) -> None:
|
||||
notification = self._waiting(self.support)
|
||||
self.assertIn(notification.id, self._visible_ids(self.insider))
|
||||
self.assertNotIn(notification.id, self._visible_ids(self.outsider))
|
||||
self.assertIn(notification.id, self._visible_ids(self.owner))
|
||||
|
||||
def test_notification_without_group_stays_visible_to_everyone(self) -> None:
|
||||
notification = self._waiting(None)
|
||||
for membership in (self.insider, self.outsider, self.owner):
|
||||
self.assertIn(notification.id, self._visible_ids(membership))
|
||||
|
||||
def test_recipients_match_what_the_list_shows(self) -> None:
|
||||
"""Доставка и список обязаны отвечать одинаково.
|
||||
|
||||
Иначе уведомление уходит в мессенджер тому, кто потом не находит его в
|
||||
приложении, или наоборот.
|
||||
"""
|
||||
for group in (self.support, None):
|
||||
notification = self._waiting(group)
|
||||
delivered = set(recipient_user_ids(notification))
|
||||
listed = {
|
||||
membership.user_id
|
||||
for membership in (self.owner, self.insider, self.outsider)
|
||||
if notification.id in self._visible_ids(membership)
|
||||
}
|
||||
self.assertEqual(delivered, listed)
|
||||
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user