v1.7.0: refactor max_bot to flat structure, add VCF+UserModel+NLP history context, portal pages and proxy fixes

- Refactored max_bot from nested packages to flat module structure
- Q2: Extended BotUser model (patronymic, email, org, address, vcf_raw, contact_hash, phone_verified, email_verified, last_interaction, total_conversations, total_tickets)
- Q2: VCF parser (FN, N, TEL, EMAIL, ORG, ADR), upsert on re-contact, NLP history context (_get_user_history_context -> YandexGPT)
- Q1: Broadcast preview modal with 10s confirmation timer
- Q3: CSS var(--white)->var(--bg-card), var(--text)->var(--text-primary)
- Q4: bot_settings showNotification(), editable max_bot_id
- Q5: Webhook secret passthrough via X-Max-Bot-Api-Secret
- Masking sensitive keys, dialog_cleared handler, migrate via _add_column_if_not_exists()
- Rate limit (asyncio.sleep 0.5 per 10), dead code removed, conv.intent context in contact.py
- Portal pages: bot_consent, bot_kb (edit), bot_settings, bot_test, bot_tickets, portal_settings
- Tests: 21/21 passing, added test_yandex_gpt.py, test_email_sender.py
- Deploy: deploy_full.sh, schema.sql, seed_knowledge_base.sql
This commit is contained in:
2026-05-29 02:30:30 +03:00
parent 493e0b37a1
commit 72b6879f4b
234 changed files with 26768 additions and 6240 deletions
+34 -118
View File
@@ -1,129 +1,45 @@
import time
from typing import Optional
from typing import Optional, Dict
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.models import BotSetting, BotFeature, BotResponseTemplate, BotCategory
from app.database import async_session
from app.models import BotSetting
class SettingsCache:
_cache: dict = {}
_features: dict = {}
_templates: dict = {}
_categories: list = []
_last_update: float = 0
TTL = 300 # 5 minutes
def __init__(self):
self._cache: dict[str, str] = {}
self._loaded = False
@classmethod
async def refresh(cls, db: AsyncSession):
now = time.time()
if now - cls._last_update < cls.TTL and cls._cache:
return
async def _load(self):
async with async_session() as db:
result = await db.execute(select(BotSetting))
rows = result.scalars().all()
self._cache = {row.key: row.value or "" for row in rows}
self._loaded = True
result = await db.execute(select(BotSetting))
cls._cache = {row.key: row.value for row in result.scalars().all()}
async def get(self, key: str, default: str = "") -> str:
if not self._loaded:
await self._load()
return self._cache.get(key, default)
result = await db.execute(select(BotFeature).where(BotFeature.enabled == True))
cls._features = {row.feature_key: row for row in result.scalars().all()}
async def set(self, key: str, value: str) -> bool:
async with async_session() as db:
result = await db.execute(select(BotSetting).where(BotSetting.key == key))
setting = result.scalar_one_or_none()
if setting:
setting.value = value
else:
db.add(BotSetting(key=key, value=value))
await db.commit()
self._cache[key] = value
return True
result = await db.execute(select(BotFeature))
all_features = {row.feature_key: row for row in result.scalars().all()}
async def get_all(self) -> Dict[str, str]:
if not self._loaded:
await self._load()
return dict(self._cache)
result = await db.execute(select(BotResponseTemplate))
cls._templates = {row.template_key: row.template_text for row in result.scalars().all()}
def invalidate(self):
self._loaded = False
result = await db.execute(
select(BotCategory).where(BotCategory.active == True).order_by(BotCategory.sort_order)
)
cls._categories = result.scalars().all()
cls._last_update = now
@classmethod
def get(cls, key: str, default: str = "") -> str:
return cls._cache.get(key, default)
@classmethod
def get_int(cls, key: str, default: int = 0) -> int:
val = cls._cache.get(key, str(default))
try:
return int(val)
except (ValueError, TypeError):
return default
@classmethod
def get_list(cls, key: str, default: list = None) -> list:
val = cls._cache.get(key, "")
if not val:
return default or []
return [x.strip() for x in val.split(",")]
@classmethod
def get_all(cls) -> dict:
return dict(cls._cache)
@classmethod
def is_feature_enabled(cls, feature_key: str) -> bool:
return feature_key in cls._features
@classmethod
def get_enabled_features(cls) -> dict:
return dict(cls._features)
@classmethod
def get_template(cls, key: str, default: str = "") -> str:
return cls._templates.get(key, default)
@classmethod
def get_all_templates(cls) -> dict:
return dict(cls._templates)
@classmethod
def get_categories(cls) -> list:
return list(cls._categories)
@classmethod
def get_bot_token(cls) -> str:
return cls._cache.get("bot_token", "")
@classmethod
def get_assistant_name(cls) -> str:
return cls._cache.get("assistant_name", "София")
@classmethod
def is_work_hours(cls) -> bool:
import datetime
import pytz
tz_name = cls._cache.get("timezone", "Europe/Moscow")
try:
tz = pytz.timezone(tz_name)
except Exception:
tz = pytz.timezone("Europe/Moscow")
now = datetime.datetime.now(tz)
work_days = cls.get_list("work_days", ["1", "2", "3", "4", "5"])
weekday = str(now.isoweekday())
if weekday not in work_days:
return False
start = cls.get_int("work_hours_start", 9)
end = cls.get_int("work_hours_end", 18)
return start <= now.hour < end
@classmethod
def get_work_hours_str(cls) -> str:
start = cls.get_int("work_hours_start", 9)
end = cls.get_int("work_hours_end", 18)
return f"{start}:00-{end}:00"
@classmethod
def get_phones(cls) -> list:
phones = []
p1 = cls._cache.get("phone_1", "")
p2 = cls._cache.get("phone_2", "")
if p1:
phones.append(p1)
if p2:
phones.append(p2)
return phones
@classmethod
def get_email(cls) -> str:
return cls._cache.get("support_email", "")
settings_cache = SettingsCache()