From d378b5c77070f9ac3eb26de5311a98adb068af12 Mon Sep 17 00:00:00 2001 From: anor Date: Thu, 1 Oct 2026 00:58:22 +1000 Subject: [PATCH] =?UTF-8?q?test:=20=D0=BF=D1=80=D0=BE=D0=B1=D0=BD=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=20=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D1=8B=D0=BC=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D1=82=D0=B5=D0=BB=D1=8F=D0=BC=20=E2=80=94=20=D0=BE=D0=B4?= =?UTF-8?q?=D0=B8=D0=BD=20=D0=B4=D0=B8=D0=B0=D0=BB=D0=BE=D0=B3=20=D0=B8=20?= =?UTF-8?q?=D0=BF=D1=8F=D1=82=D1=8C=20=D0=B2=D0=BE=D0=BF=D1=80=D0=BE=D1=81?= =?UTF-8?q?=D0=BE=D0=B2=20(=D0=BA=D1=80=D0=B0=D1=81=D0=BD=D1=8B=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/TASK.md | 20 ++++ tests/test_trial_access.py | 205 +++++++++++++++++++++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 tests/test_trial_access.py diff --git a/docs/TASK.md b/docs/TASK.md index a11e6cb..d5691ee 100644 --- a/docs/TASK.md +++ b/docs/TASK.md @@ -1,3 +1,23 @@ +# TASK 2026-10-01 — пробный доступ новым пользователям + +Решение Хозяина 01.10.2026: новым пользователям один чат и 5 вопросов. Уточнено ответами: +новые = зарегистрированные после выката (нынешние 10 учёток не задеты); 5 вопросов на всё +время; после пятого — «Пробный доступ закончился, напишите на info@infosmeta.ru». + +### Приёмка +Готово когда: +- `auth.register_user` ставит учётке `users.trial = 1`; прежние учётки `trial = 0`; + админ по роли и владелец под пробный режим не попадают никогда; +- у пробного человека вопрос (`/api/chat`) после TRIAL_QUESTIONS (5) принятых вопросов за всё + время — 402 «Пробный доступ закончился: 5 вопросов из 5. …»; загрузка и демо-смета — тоже 402; +- все записи пробного человека (вопрос, загрузка, tus, демо, дата сметы) идут только в его первый + диалог; вопрос из другого диалога — 409 с `trial_tab`, страница открывает его диалог и + повторяет вопрос туда; загрузка/демо/дата в другой диалог — 403 с текстом; +- страница у пробного человека прячет «Новый чат» и «Новый диалог», при входе из нового + браузера открывает его диалог; значок: «Осталось: N из 5 вопр.», при нуле «Пробный доступ + закончился»; окно по щелчку объясняет ограничения; +- админка: статус «Пробный · задано N из 5», кнопка «Снять пробный» / «Сделать пробным». + # TASK 2026-09-30 — пределы загрузки, «только просмотр», таймаут зайки Повод: zakaz@smetashop.pro 30.09.2026 шесть раз подряд получил маску сбоя. Зайка молчала diff --git a/tests/test_trial_access.py b/tests/test_trial_access.py new file mode 100644 index 0000000..7fd37e1 --- /dev/null +++ b/tests/test_trial_access.py @@ -0,0 +1,205 @@ +"""Пробный доступ новым пользователям (решение Хозяина 01.10.2026). + +Новая учётка — один диалог и пять вопросов на всё время. Прежние учётки не задеты; +админ и владелец под пробный режим не попадают никогда. +""" + +import base64 +import importlib +import os +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + +NEW = "novichok@x" +OLD = "stary@x" + + +@pytest.fixture() +def env(tmp_path, monkeypatch): + monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) + monkeypatch.setenv("DATA_DIR", str(tmp_path / "data")) + monkeypatch.setenv("AI_BACKEND", "claude") + monkeypatch.setenv("SESSION_SECRET", "test-secret") + monkeypatch.setenv("TRIAL_QUESTIONS", "5") + monkeypatch.delenv("AGENT_OWNER_EMAILS", raising=False) + monkeypatch.delenv("SMTP_HOST", raising=False) + monkeypatch.chdir(ROOT) + import db, auth, claude_bridge, quotas, main + for m in (db, auth, claude_bridge, quotas, main): + importlib.reload(m) + db.init_db() + db.create_user(OLD, "h") + res = auth.register_user(NEW, "Пароль-надёжный-123", "") + assert res.get("ok"), res + from fastapi.testclient import TestClient + return db, auth, main, TestClient(main.app) + + +def _h(auth, user, tab, role="user"): + return {"Authorization": "Bearer " + auth._make_token(user, role), "X-Tab-Id": tab} + + +def _asked(db, user, n): + for _ in range(n): + db.log_action(user, "chat", "POST", "/api/chat", None, None, 200) + + +def _first_dialog(db, user, tab="t-first"): + db.save_message(user, tab, "user", "первый вопрос") + return tab + + +# --- кто пробный --- + +def test_registration_marks_new_user_as_trial(env): + db, auth, main, client = env + assert db.get_user_by_email(NEW)["trial"] == 1 + assert db.get_user_by_email(OLD)["trial"] == 0 + + +def test_admin_and_owner_never_trial(env, monkeypatch): + db, auth, main, client = env + db.set_trial(OLD, True) + db.set_user_role(OLD, "admin") + assert main._trial_state(OLD) is None + monkeypatch.setenv("AGENT_OWNER_EMAILS", NEW) + assert main._trial_state(NEW) is None + + +# --- пять вопросов --- + +def test_fifth_question_allowed_sixth_refused(env): + db, auth, main, client = env + tab = _first_dialog(db, NEW) + _asked(db, NEW, 4) + main._refuse_if_trial_over(NEW) # пятый ещё можно + _asked(db, NEW, 1) + r = client.post("/api/chat", headers=_h(auth, NEW, tab), json={"message": "ещё", "tab_id": tab}) + assert r.status_code == 402 + assert "Пробный доступ закончился" in r.json()["detail"] + assert "5 вопросов из 5" in r.json()["detail"] + + +def test_old_user_not_limited_by_trial(env): + db, auth, main, client = env + _asked(db, OLD, 50) + main._refuse_if_trial_over(OLD) # не бросает + assert main._trial_state(OLD) is None + + +def test_trial_over_blocks_uploads_and_demo(env): + db, auth, main, client = env + tab = _first_dialog(db, NEW) + _asked(db, NEW, 5) + h = _h(auth, NEW, tab) + r = client.post("/api/upload", headers=h, files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")}) + assert r.status_code == 402 + assert client.post("/api/demo-file", headers=h, json={"tab_id": tab}).status_code == 402 + + +# --- один диалог --- + +def test_question_from_other_dialog_redirected_to_trial_dialog(env): + db, auth, main, client = env + tab = _first_dialog(db, NEW) + r = client.post("/api/chat", headers=_h(auth, NEW, "t-second"), + json={"message": "вопрос", "tab_id": "t-second"}) + assert r.status_code == 409 + assert r.json()["trial_tab"] == tab + assert not [s for s in db.list_sessions(NEW) if s["tab_id"] == "t-second"] + + +def test_first_write_defines_the_dialog(env): + db, auth, main, client = env + assert main._trial_state(NEW)["tab"] is None # ещё ни одного диалога + r = client.post("/api/upload", headers=_h(auth, NEW, "t-a"), + files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")}) + assert r.status_code == 200 + assert main._trial_state(NEW)["tab"] == "t-a" + + +def test_upload_demo_date_into_other_dialog_refused(env): + db, auth, main, client = env + _first_dialog(db, NEW) + h = _h(auth, NEW, "t-second") + r = client.post("/api/upload", headers=h, files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")}) + assert r.status_code == 403 and "один диалог" in r.json()["detail"] + assert client.post("/api/demo-file", headers=h, json={"tab_id": "t-second"}).status_code == 403 + r = client.post("/api/sessions/t-second/date", headers=h, json={"date": "2026-01-01"}) + assert r.status_code == 403 + meta = "filename {},tab_id {}".format(base64.b64encode(b"a.pdf").decode(), + base64.b64encode(b"t-second").decode()) + r = client.post("/api/tus", headers={**h, "Tus-Resumable": "1.0.0", "Upload-Length": "10", + "Upload-Metadata": meta}) + assert r.status_code == 403 + + +def test_old_user_can_open_many_dialogs(env): + db, auth, main, client = env + _first_dialog(db, OLD) + r = client.post("/api/upload", headers=_h(auth, OLD, "t-second"), + files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")}) + assert r.status_code == 200 + + +# --- что видит человек --- + +def test_limits_report_trial(env): + db, auth, main, client = env + _first_dialog(db, NEW) + _asked(db, NEW, 2) + d = client.get("/api/limits", headers=_h(auth, NEW, "t-first")).json() + assert d["trial"] == {"used": 2, "limit": 5, "tab": "t-first"} + d = client.get("/api/limits", headers=_h(auth, OLD, "x")).json() + assert "trial" not in d + + +def test_page_handles_trial(): + html = open(os.path.join(ROOT, "static", "chat.html"), encoding="utf-8").read() + assert "if (b.trial) {" in html # значок + assert "d.trial_tab" in html # переход в пробный диалог и повтор + assert "function applyTrial()" in html # прячет «Новый чат», открывает диалог + + +# --- админка --- + +def test_admin_toggles_trial_and_sees_count(env): + db, auth, main, client = env + db.create_user("boss@x", "h", role="admin") + ah = _h(auth, "boss@x", "x", "admin") + _asked(db, NEW, 3) + rows = client.get("/api/admin/users", headers=ah).json() + rows = rows["users"] if isinstance(rows, dict) else rows + me = [u for u in rows if u["email"] == NEW][0] + assert me["trial"] == 1 and me["trial_used"] == 3 + r = client.post("/api/admin/users/trial", headers=ah, json={"email": NEW, "trial": False}) + assert r.status_code == 200 + assert db.get_user_by_email(NEW)["trial"] == 0 + r = client.post("/api/admin/users/trial", headers=ah, json={"email": NEW, "trial": "no"}) + assert r.status_code == 400 + r = client.post("/api/admin/users/trial", headers=ah, json={"email": "nobody@x", "trial": True}) + assert r.status_code == 404 + r = client.post("/api/admin/users/trial", headers=_h(auth, NEW, "x"), json={"email": NEW, "trial": False}) + assert r.status_code == 403 + + +def test_stream_balance_event_uses_same_view(): + # Событие остатка после ответа обязано нести пробный режим, иначе значок после первого же + # ответа вернулся бы к суточному остатку. + src = open(os.path.join(ROOT, "main.py"), encoding="utf-8").read() + assert "_balance = await asyncio.to_thread(_person_view, user)" in src + assert "quotas.person_snapshot, user)" not in src + + +def test_first_dialog_is_the_earliest(env): + # Если в базе у человека окажутся записи в двух диалогах (например, пробный режим + # включили уже работавшему), его диалог — самый первый, а не последний. + db, auth, main, client = env + db.save_message(NEW, "t-early", "user", "раз") + db.save_message(NEW, "t-late", "user", "два") + assert db.first_dialog(NEW) == "t-early"