Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
716002dcaf | ||
|
|
5dbe1427eb | ||
|
|
054789049f |
No files matched your search
@@ -3,6 +3,8 @@ import struct
|
||||
|
||||
import requests
|
||||
|
||||
from ai_core.net_safety import public_url_error
|
||||
|
||||
from config import PIAPI_API_KEY, PIAPI_IMAGE_MODEL, get_proxies
|
||||
|
||||
PIAPI_IMAGE_URL = "https://api.piapi.ai/v1/images/generations"
|
||||
@@ -253,7 +255,11 @@ class ImageGenerator:
|
||||
if item.get("b64_json"):
|
||||
return base64.b64decode(item["b64_json"])
|
||||
if item.get("url"):
|
||||
img_response = requests.get(item["url"], proxies=self.proxies, timeout=120)
|
||||
# Ссылку прислал провайдер (возможно, «свой») — скачиваем только из публичного интернета, без редиректов
|
||||
url_error = public_url_error(item["url"], allow_http=True)
|
||||
if url_error:
|
||||
raise RuntimeError(f"Провайдер вернул недопустимую ссылку на картинку: {url_error}")
|
||||
img_response = requests.get(item["url"], proxies=self.proxies, timeout=120, allow_redirects=False)
|
||||
img_response.raise_for_status()
|
||||
return img_response.content
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Проверка адресов, к которым сервер ходит по указанию пользователя (свой ИИ-провайдер, ссылки на картинки).
|
||||
Без неё через «свой провайдер» можно заставить сервер обратиться во внутреннюю сеть (SSRF)."""
|
||||
import ipaddress
|
||||
import socket
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
def public_url_error(url: str, allow_http: bool = False):
|
||||
"""None — адрес публичный и допустимый, иначе текст ошибки для пользователя."""
|
||||
try:
|
||||
parsed = urlparse((url or "").strip())
|
||||
except ValueError:
|
||||
return "Некорректный адрес."
|
||||
schemes = ("https", "http") if allow_http else ("https",)
|
||||
if parsed.scheme not in schemes:
|
||||
return "Адрес должен начинаться с https://."
|
||||
host = parsed.hostname
|
||||
if not host:
|
||||
return "В адресе нет домена."
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, parsed.port or 443, proto=socket.IPPROTO_TCP)
|
||||
except (socket.gaierror, UnicodeError):
|
||||
return f"Домен {host} не найден."
|
||||
for info in infos:
|
||||
ip = ipaddress.ip_address(info[4][0].split("%")[0])
|
||||
if not ip.is_global or ip.is_multicast:
|
||||
return f"Адрес {host} ведёт во внутреннюю сеть — такие адреса запрещены."
|
||||
return None
|
||||
|
||||
|
||||
def is_public_url(url: str) -> bool:
|
||||
return public_url_error(url) is None
|
||||
+82
-51
@@ -2,7 +2,16 @@ import random
|
||||
import os
|
||||
import json
|
||||
import requests
|
||||
from config import PIAPI_API_KEY, PIAPI_MODEL, get_proxies
|
||||
from config import (
|
||||
PIAPI_API_KEY,
|
||||
PIAPI_MODEL,
|
||||
QWEN_API_KEY,
|
||||
QWEN_BASE_URL,
|
||||
QWEN_MAX_TOKENS,
|
||||
QWEN_MODEL,
|
||||
QWEN_TIMEOUT,
|
||||
get_proxies,
|
||||
)
|
||||
|
||||
PIAPI_URL = "https://api.piapi.ai/v1/chat/completions"
|
||||
|
||||
@@ -15,6 +24,10 @@ class ContentGenerator:
|
||||
Если не передан — используются глобальные настройки PiAPI из config."""
|
||||
print("🔄 Инициализация ContentGenerator...")
|
||||
|
||||
# Общие параметры для всех провайдеров
|
||||
self.timeout = QWEN_TIMEOUT
|
||||
self.max_tokens = QWEN_MAX_TOKENS
|
||||
|
||||
if provider_settings and provider_settings.get("api_key"):
|
||||
# Per-user настройки
|
||||
self.api_key = provider_settings["api_key"]
|
||||
@@ -27,6 +40,16 @@ class ContentGenerator:
|
||||
# Это нужно для доступа из России к зарубежным API
|
||||
self.proxies = get_proxies()
|
||||
print(f"✅ Провайдер: {self.provider_type} | модель: {self.model} | прокси: {'да' if self.proxies else 'нет'}")
|
||||
elif QWEN_API_KEY and QWEN_BASE_URL:
|
||||
# Глобальные настройки: Qwen по умолчанию
|
||||
self.api_key = QWEN_API_KEY
|
||||
self.base_url = QWEN_BASE_URL.rstrip("/")
|
||||
self.model = QWEN_MODEL
|
||||
self.use_piapi = True
|
||||
self.chat_url = self.base_url + "/chat/completions"
|
||||
self.provider_type = "qwen"
|
||||
self.proxies = get_proxies()
|
||||
print(f"✅ Qwen подключен (по умолчанию) | модель: {self.model}")
|
||||
elif PIAPI_API_KEY:
|
||||
# Глобальные настройки из config
|
||||
self.api_key = PIAPI_API_KEY
|
||||
@@ -184,28 +207,47 @@ class ContentGenerator:
|
||||
Пост должен быть уникальным и интересным.
|
||||
"""
|
||||
|
||||
response = requests.post(
|
||||
self.chat_url,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}"
|
||||
},
|
||||
json={
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "Ты профессиональный копирайтер. Пиши ярко, полезно и вовлекающе."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"temperature": 0.9,
|
||||
"max_tokens": 500
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=30
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return self._post_chat({
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "Ты профессиональный копирайтер. Пиши ярко, полезно и вовлекающе."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"temperature": 0.9,
|
||||
"max_tokens": self.max_tokens,
|
||||
})
|
||||
|
||||
return data["choices"][0]["message"]["content"].strip()
|
||||
def _post_chat(self, payload):
|
||||
"""POST /chat/completions с повтором, если content пуст из-за лимита токенов.
|
||||
|
||||
Qwen сначала «размышляет», и reasoning входит в max_tokens: на маленьком
|
||||
лимите ответ приходит пустым с finish_reason='length'. Тогда один раз
|
||||
удваиваем лимит и повторяем.
|
||||
"""
|
||||
payload = dict(payload)
|
||||
payload.setdefault("max_tokens", self.max_tokens)
|
||||
for attempt in range(2):
|
||||
response = requests.post(
|
||||
self.chat_url,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
},
|
||||
json=payload,
|
||||
proxies=self.proxies,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
choice = (data.get("choices") or [{}])[0]
|
||||
content = ((choice.get("message") or {}).get("content") or "").strip()
|
||||
if content:
|
||||
return content
|
||||
if choice.get("finish_reason") == "length" and attempt == 0:
|
||||
payload["max_tokens"] = min(int(payload["max_tokens"]) * 2, 32768)
|
||||
continue
|
||||
return content
|
||||
return ""
|
||||
|
||||
def generate_post_with_style(self, business_type, business_description, platform, style, wishes):
|
||||
"""Генерирует пост с учётом стиля и пожеланий пользователя"""
|
||||
@@ -241,28 +283,17 @@ class ContentGenerator:
|
||||
Напиши только текст поста, без лишних пояснений.
|
||||
"""
|
||||
|
||||
response = requests.post(
|
||||
self.chat_url,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}"
|
||||
},
|
||||
json={
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "Ты профессиональный копирайтер. Точно следуешь стилю и пожеланиям клиента."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"temperature": 0.9,
|
||||
"max_tokens": 500
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=30
|
||||
)
|
||||
response.raise_for_status()
|
||||
post = response.json()["choices"][0]["message"]["content"].strip()
|
||||
post = self._post_chat({
|
||||
"model": self.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "Ты профессиональный копирайтер. Точно следуешь стилю и пожеланиям клиента."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"temperature": 0.9,
|
||||
"max_tokens": self.max_tokens,
|
||||
})
|
||||
if post and len(post) > 20:
|
||||
print("✅ Пост в стиле сгенерирован через PiAPI!")
|
||||
print("✅ Пост в стиле сгенерирован через API!")
|
||||
return post
|
||||
except Exception as e:
|
||||
print(f"⚠️ Ошибка PiAPI: {e}, использую шаблоны")
|
||||
@@ -422,7 +453,7 @@ class ContentGenerator:
|
||||
"max_tokens": 4000
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=90
|
||||
timeout=self.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
msg = response.json()["choices"][0]["message"]
|
||||
@@ -484,7 +515,7 @@ class ContentGenerator:
|
||||
"max_tokens": 4000
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=90
|
||||
timeout=self.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
post = response.json()["choices"][0]["message"]["content"].strip()
|
||||
@@ -494,8 +525,8 @@ class ContentGenerator:
|
||||
except Exception as e:
|
||||
print(f"⚠️ Ошибка API при модификации: {e}")
|
||||
|
||||
# Если ИИ не сработал — возвращаем оригинал с пометкой
|
||||
return f"{original_post}\n\n💬 [ИИ не смог изменить пост: {instruction}]"
|
||||
# ИИ не ответил — пост не трогаем: ошибка уходит в задачу, интерфейс покажет её и предложит повторить
|
||||
raise RuntimeError("ИИ не смог изменить пост. Проверьте настройки провайдера в разделе «ИИ» и повторите.")
|
||||
|
||||
def _generate_template_brand_post(self, brand_data, platform, wishes):
|
||||
"""Простой пост из медиа-образа без обращения к ИИ (запасной вариант)."""
|
||||
@@ -579,7 +610,7 @@ class ContentGenerator:
|
||||
"max_tokens": 1000
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=60
|
||||
timeout=self.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
raw = response.json()["choices"][0]["message"]["content"].strip()
|
||||
@@ -720,7 +751,7 @@ class ContentGenerator:
|
||||
"response_format": {"type": "json_object"}
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=60
|
||||
timeout=self.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
content = response.json()["choices"][0]["message"]["content"].strip()
|
||||
@@ -771,7 +802,7 @@ class ContentGenerator:
|
||||
"response_format": {"type": "json_object"}
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=30
|
||||
timeout=self.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
content = response.json()["choices"][0]["message"]["content"].strip()
|
||||
@@ -865,7 +896,7 @@ Tone of Voice: {tov_description}
|
||||
"response_format": {"type": "json_object"}
|
||||
},
|
||||
proxies=self.proxies,
|
||||
timeout=30
|
||||
timeout=self.timeout
|
||||
)
|
||||
response.raise_for_status()
|
||||
content = response.json()["choices"][0]["message"]["content"].strip()
|
||||
|
||||
+36
-15
@@ -140,16 +140,33 @@ def analyze_posts_with_ai(posts: list, provider_settings: dict = None) -> dict:
|
||||
base_url = provider_settings.get("base_url", "https://api.piapi.ai/v1")
|
||||
model = provider_settings.get("text_model", "gpt-4o")
|
||||
else:
|
||||
from config import PIAPI_API_KEY, PIAPI_MODEL
|
||||
api_key = PIAPI_API_KEY
|
||||
base_url = "https://api.piapi.ai/v1"
|
||||
model = PIAPI_MODEL
|
||||
from config import PIAPI_API_KEY, PIAPI_MODEL, QWEN_API_KEY, QWEN_BASE_URL, QWEN_MODEL
|
||||
if QWEN_API_KEY and QWEN_BASE_URL:
|
||||
api_key = QWEN_API_KEY
|
||||
base_url = QWEN_BASE_URL
|
||||
model = QWEN_MODEL
|
||||
else:
|
||||
api_key = PIAPI_API_KEY
|
||||
base_url = "https://api.piapi.ai/v1"
|
||||
model = PIAPI_MODEL
|
||||
|
||||
if not api_key:
|
||||
return {"error": "AI-провайдер не настроен. Настройте ИИ в разделе «ИИ»."}
|
||||
|
||||
chat_url = base_url.rstrip("/") + "/chat/completions"
|
||||
proxies = get_proxies()
|
||||
from config import QWEN_TIMEOUT
|
||||
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "Ты эксперт по брендингу. Отвечаешь только валидным JSON."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"temperature": 0.3,
|
||||
"max_tokens": 2000,
|
||||
"response_format": {"type": "json_object"}
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
@@ -158,19 +175,23 @@ def analyze_posts_with_ai(posts: list, provider_settings: dict = None) -> dict:
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {api_key}"
|
||||
},
|
||||
json={
|
||||
"model": model,
|
||||
"messages": [
|
||||
{"role": "system", "content": "Ты эксперт по брендингу. Отвечаешь только валидным JSON."},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"temperature": 0.3,
|
||||
"max_tokens": 2000,
|
||||
"response_format": {"type": "json_object"}
|
||||
},
|
||||
json=payload,
|
||||
proxies=proxies,
|
||||
timeout=90
|
||||
timeout=QWEN_TIMEOUT
|
||||
)
|
||||
# Не все OpenAI-совместимые серверы поддерживают response_format — повторяем без него
|
||||
if response.status_code == 400 and "response_format" in payload:
|
||||
payload.pop("response_format", None)
|
||||
response = requests.post(
|
||||
chat_url,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {api_key}"
|
||||
},
|
||||
json=payload,
|
||||
proxies=proxies,
|
||||
timeout=QWEN_TIMEOUT
|
||||
)
|
||||
response.raise_for_status()
|
||||
content = response.json()["choices"][0]["message"]["content"].strip()
|
||||
|
||||
|
||||
@@ -48,6 +48,12 @@ def _md_to_html(text: str) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def _scrub(err) -> str:
|
||||
"""Текст ошибки без токена бота: requests кладёт полный URL запроса (с токеном) в исключение."""
|
||||
text = str(err)
|
||||
return text.replace(TOKEN, "<token>") if TOKEN else text
|
||||
|
||||
|
||||
def _api_call(method, params):
|
||||
"""Вызывает Telegram Bot API метод. Возвращает (ok, result_or_error)."""
|
||||
try:
|
||||
@@ -62,7 +68,7 @@ def _api_call(method, params):
|
||||
return True, data.get("result", {})
|
||||
return False, data.get("description", "Неизвестная ошибка")
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
return False, _scrub(e)
|
||||
|
||||
|
||||
def resolve_chat(username_or_id):
|
||||
@@ -83,12 +89,14 @@ def resolve_chat(username_or_id):
|
||||
chat_type = result.get("type", "unknown")
|
||||
title = result.get("title") or result.get("first_name", "") or result.get("username", "")
|
||||
username = result.get("username", "")
|
||||
description = result.get("description", "") or ""
|
||||
|
||||
return {
|
||||
"chat_id": chat_id,
|
||||
"title": title,
|
||||
"username": username,
|
||||
"type": chat_type,
|
||||
"description": description,
|
||||
}
|
||||
|
||||
|
||||
@@ -183,4 +191,4 @@ def _api_call_send_photo(chat_id, image_bytes, caption):
|
||||
|
||||
return True, data.get("result", {})
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
return False, _scrub(e)
|
||||
+321
-101
@@ -2,8 +2,8 @@ from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Depends, FastAPI, Form, HTTPException, Query, Request
|
||||
@@ -13,6 +13,7 @@ from fastapi.templating import Jinja2Templates
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from ai_core.image_generator import IMAGE_SIZES, IMAGE_TEMPLATES, STYLE_PRESETS, ImageGenerator, detect_ext, get_sizes_for_model
|
||||
from ai_core.net_safety import public_url_error
|
||||
from ai_core.neural_network import ContentGenerator
|
||||
from ai_core.social_analyzer import analyze_posts_with_ai, detect_platform, fetch_telegram_posts
|
||||
from ai_core.telegram_publisher import (
|
||||
@@ -22,10 +23,12 @@ from ai_core.telegram_publisher import (
|
||||
)
|
||||
from ai_core.tenchat_publisher import publish_post as publish_post_tenchat
|
||||
from cabinet_service.brand_doc_generator import generate_brand_docx
|
||||
from config import SECRET_KEY
|
||||
from config import SECRET_KEY, QWEN_BASE_URL, QWEN_MODEL
|
||||
from database import (
|
||||
add_post_revision,
|
||||
count_user_tasks,
|
||||
create_task,
|
||||
fail_unfinished_tasks,
|
||||
create_web_user,
|
||||
delete_brand_survey,
|
||||
delete_channel,
|
||||
@@ -79,14 +82,165 @@ MEDIA_DIR = BASE_DIR / "media"
|
||||
MEDIA_DIR.mkdir(exist_ok=True)
|
||||
|
||||
app = FastAPI(title="Личный кабинет")
|
||||
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
|
||||
# На сервере с https задайте SESSION_COOKIE_SECURE=1 в .env — cookie сессии не уйдёт по http
|
||||
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, same_site="lax",
|
||||
https_only=os.getenv("SESSION_COOKIE_SECURE", "0") == "1",
|
||||
max_age=14 * 24 * 3600)
|
||||
|
||||
_UNSAFE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def security_middleware(request: Request, call_next):
|
||||
# CSRF: изменяющий запрос браузера должен прийти с нашего же сайта. Браузер всегда шлёт Origin
|
||||
# (или хотя бы Referer) у POST-форм и fetch, подделать их со стороннего сайта нельзя.
|
||||
if request.method in _UNSAFE_METHODS:
|
||||
source = request.headers.get("origin") or request.headers.get("referer")
|
||||
if source:
|
||||
from urllib.parse import urlparse
|
||||
# Origin: null шлют песочницы iframe и file:// — тоже чужой источник
|
||||
if source == "null" or urlparse(source).netloc != request.headers.get("host", ""):
|
||||
return JSONResponse({"error": "Запрос отклонён: он пришёл с другого сайта."}, status_code=403)
|
||||
response = await call_next(request)
|
||||
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
||||
response.headers.setdefault("X-Frame-Options", "DENY")
|
||||
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
if request.headers.get("x-forwarded-proto") == "https" or request.url.scheme == "https":
|
||||
response.headers.setdefault("Strict-Transport-Security", "max-age=31536000")
|
||||
return response
|
||||
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
|
||||
app.mount("/media", StaticFiles(directory=str(MEDIA_DIR)), name="media")
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
|
||||
|
||||
def plural(n, forms):
|
||||
"""Склонение по числу: plural(3, ['день', 'дня', 'дней']) -> 'дня'."""
|
||||
n = abs(int(n or 0))
|
||||
a, b = n % 100, n % 10
|
||||
if 10 < a < 20:
|
||||
return forms[2]
|
||||
if 1 < b < 5:
|
||||
return forms[1]
|
||||
if b == 1:
|
||||
return forms[0]
|
||||
return forms[2]
|
||||
|
||||
|
||||
_PATRONYMIC_ENDINGS = ("вич", "вна", "чна", "ична", "инична", "оглы", "кызы")
|
||||
_SURNAME_ENDINGS = ("ов", "ова", "ев", "ева", "ёв", "ёва", "ин", "ина", "ын", "ына", "ский", "ская", "цкий", "цкая",
|
||||
"ской", "енко", "ук", "юк", "чук", "ых", "их", "ко")
|
||||
# Частые имена: окончания вроде «-ина» есть и у имён (Ирина), и у фамилий (Котина), поэтому сначала — словарь
|
||||
_FIRST_NAMES = set("""
|
||||
александр алексей анатолий андрей антон аркадий арсений артём артем артур богдан борис вадим валентин валерий василий
|
||||
виктор виталий владимир владислав всеволод вячеслав геннадий георгий герман глеб григорий давид даниил данил денис
|
||||
дмитрий евгений егор захар иван игнат игорь илья кирилл константин лев леонид максим марк матвей михаил назар никита
|
||||
николай олег павел пётр петр платон роман ростислав руслан савелий семён семен сергей станислав степан тимофей тимур
|
||||
фёдор федор филипп эдуард юрий ян ярослав рашид рустам тарас остап богдан мирон
|
||||
александра алина алиса алла анастасия ангелина анна антонина арина валентина валерия варвара вера вероника виктория
|
||||
галина дарья диана ева евгения екатерина елена елизавета жанна зарина зинаида злата инна ирина карина кира кристина
|
||||
ксения лариса лидия лилия любовь людмила маргарита марина мария милана надежда наталья наталия нина оксана олеся ольга
|
||||
полина раиса регина светлана софия софья стефания таисия тамара татьяна ульяна элина эльвира юлия яна ярослава
|
||||
саша шура лёша леша дима женя ваня вова володя коля костя миша паша петя серёжа сережа слава толя юра
|
||||
аня валя варя галя даша катя ксюша лена лиза люба люда маша надя наташа оля поля света соня таня юля
|
||||
""".split())
|
||||
|
||||
|
||||
def first_name(full_name):
|
||||
"""Имя для обращения из поля «Имя»: «Котова Ирина Сергеевна» → «Ирина», «Анна Тестова» → «Анна».
|
||||
В обращении имя стоит в именительном падеже, склонять его не нужно. В поле вписано название
|
||||
организации (есть кавычки) — имени нет, обращение без имени."""
|
||||
raw = str(full_name or "")
|
||||
if any(q in raw for q in "«»\"„“"):
|
||||
return ""
|
||||
words = [w for w in raw.replace(",", " ").split() if w.replace("-", "").isalpha()]
|
||||
if not words:
|
||||
return ""
|
||||
low = [w.lower() for w in words]
|
||||
|
||||
def cap(w):
|
||||
return "-".join(p[:1].upper() + p[1:].lower() for p in w.split("-"))
|
||||
# Слово из словаря имён — оно и есть имя
|
||||
for i, w in enumerate(low):
|
||||
if w in _FIRST_NAMES or w.split("-")[0] in _FIRST_NAMES:
|
||||
return cap(words[i])
|
||||
# Есть отчество — имя стоит перед ним
|
||||
for i, w in enumerate(low):
|
||||
if i > 0 and w.endswith(_PATRONYMIC_ENDINGS):
|
||||
return cap(words[i - 1])
|
||||
# Первое слово похоже на фамилию, второе — нет: «Котова Ирина»
|
||||
if len(words) >= 2 and low[0].endswith(_SURNAME_ENDINGS) and not low[1].endswith(_SURNAME_ENDINGS):
|
||||
return cap(words[1])
|
||||
return cap(words[0])
|
||||
|
||||
|
||||
def greeting_for_hour(hour=None):
|
||||
"""Приветствие по времени суток: утро 5–11, день 11–17, вечер 17–23, ночь 23–5.
|
||||
Без аргумента — по часам сервера; на странице скрипт уточняет по часам пользователя."""
|
||||
if hour is None:
|
||||
from datetime import datetime
|
||||
hour = datetime.now().hour
|
||||
if 5 <= hour < 11:
|
||||
return "Доброе утро"
|
||||
if 11 <= hour < 17:
|
||||
return "Добрый день"
|
||||
if 17 <= hour < 23:
|
||||
return "Добрый вечер"
|
||||
return "Доброй ночи"
|
||||
|
||||
|
||||
# SQLite хранит CURRENT_TIMESTAMP в UTC; показываем по Москве (DISPLAY_TZ_OFFSET — смещение в часах)
|
||||
DISPLAY_TZ_OFFSET = int(os.getenv("DISPLAY_TZ_OFFSET", "3"))
|
||||
|
||||
|
||||
def local_dt(value, fmt="%d.%m.%Y %H:%M"):
|
||||
"""«2026-10-28 10:49:12» (UTC) → «28.10.2026 13:49». Непонятное значение возвращается как есть."""
|
||||
from datetime import datetime, timedelta
|
||||
raw = str(value or "")
|
||||
try:
|
||||
dt = datetime.strptime(raw[:19], "%Y-%m-%d %H:%M:%S")
|
||||
except ValueError:
|
||||
return raw
|
||||
return (dt + timedelta(hours=DISPLAY_TZ_OFFSET)).strftime(fmt)
|
||||
|
||||
|
||||
templates.env.filters["local_dt"] = local_dt
|
||||
templates.env.filters["first_name"] = first_name
|
||||
templates.env.globals["greeting_for_hour"] = greeting_for_hour
|
||||
|
||||
# Компоненты дизайн-системы (иконки, логотип) доступны во всех шаблонах как ui.*
|
||||
templates.env.globals["plural"] = plural
|
||||
# Числа с неразрывным пробелом между разрядами: 4096 -> «4 096»
|
||||
templates.env.filters["num"] = lambda n: "{:,}".format(int(n or 0)).replace(",", " ")
|
||||
templates.env.globals["ui"] = templates.env.get_template("_ui.html").module
|
||||
|
||||
content_gen = ContentGenerator()
|
||||
image_gen = ImageGenerator()
|
||||
|
||||
# Фоновые задачи (генерации через ИИ) — общий пул потоков вместо потока на каждый запрос:
|
||||
# сколько бы задач ни пришло, одновременно к провайдеру идут не больше TASK_WORKERS.
|
||||
TASK_WORKERS = int(os.getenv("TASK_WORKERS", "4"))
|
||||
TASK_ACTIVE_LIMIT = int(os.getenv("TASK_ACTIVE_LIMIT", "2")) # незавершённых задач на пользователя
|
||||
TASK_HOURLY_LIMIT = int(os.getenv("TASK_HOURLY_LIMIT", "60")) # задач на пользователя в час
|
||||
task_pool = ThreadPoolExecutor(max_workers=TASK_WORKERS, thread_name_prefix="task")
|
||||
fail_unfinished_tasks()
|
||||
|
||||
# Загрузка картинок: только настоящие изображения и не больше 10 МБ
|
||||
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def is_image(data: bytes) -> bool:
|
||||
"""PNG, JPEG, WebP или GIF по сигнатуре файла — расширению и MIME из браузера не доверяем."""
|
||||
return (data[:8] == b"\x89PNG\r\n\x1a\n" or data[:3] == b"\xff\xd8\xff"
|
||||
or (data[:4] == b"RIFF" and data[8:12] == b"WEBP") or data[:4] == b"GIF8")
|
||||
|
||||
|
||||
def to_int(value, default=None):
|
||||
"""int из поля формы или query; мусор — default, а не 500."""
|
||||
try:
|
||||
return int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def get_user_content_gen(user: dict) -> ContentGenerator:
|
||||
"""Возвращает ContentGenerator с настройками text-провайдера пользователя."""
|
||||
@@ -145,6 +299,9 @@ def flash(request: Request, message: str):
|
||||
def render(request: Request, template: str, status_code: int = 200, **context):
|
||||
context.setdefault("user", None)
|
||||
context["flash_message"] = request.session.pop("flash", None)
|
||||
# Активный медиа-образ — для карточки внизу боковой навигации
|
||||
if context["user"] and "active_persona" not in context:
|
||||
context["active_persona"] = get_latest_brand_survey_for_user(context["user"]["id"])
|
||||
return templates.TemplateResponse(request, template, context, status_code=status_code)
|
||||
|
||||
|
||||
@@ -161,14 +318,21 @@ def health():
|
||||
|
||||
@app.get("/")
|
||||
def root(request: Request):
|
||||
# Посадочная страница с описанием сервиса
|
||||
return render(request, "landing.html")
|
||||
if request.session.get("user_id"):
|
||||
return RedirectResponse("/dashboard", status_code=303)
|
||||
return RedirectResponse("/login", status_code=303)
|
||||
|
||||
|
||||
@app.get("/presentation-tz")
|
||||
def presentation_tz(request: Request):
|
||||
# Техническое задание на создание презентации сервиса
|
||||
return render(request, "presentation_tz.html")
|
||||
@app.get("/presentation.{ext}")
|
||||
def presentation_file(ext: str):
|
||||
# Готовая презентация лежит в корне проекта (её собирает deploy/generate_presentation.py)
|
||||
if ext not in ("pdf", "pptx"):
|
||||
raise HTTPException(status_code=404)
|
||||
path = BASE_DIR.parent / f"ИИ_Пресс-секретарь_презентация.{ext}"
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="Презентация ещё не собрана")
|
||||
from fastapi.responses import FileResponse
|
||||
return FileResponse(path, filename=path.name)
|
||||
|
||||
|
||||
# === РЕГИСТРАЦИЯ ===
|
||||
@@ -193,6 +357,8 @@ def register_submit(
|
||||
errors = []
|
||||
if len(password) < 8:
|
||||
errors.append("Пароль должен быть не короче 8 символов.")
|
||||
if len(password.encode("utf-8")) > 72:
|
||||
errors.append("Пароль слишком длинный: не больше 72 байт (около 36 русских или 72 латинских символов).")
|
||||
if password != password_confirm:
|
||||
errors.append("Пароли не совпадают.")
|
||||
if "@" not in email or "." not in email.split("@")[-1]:
|
||||
@@ -210,8 +376,8 @@ def register_submit(
|
||||
password_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
user_id = create_web_user(email, password_hash, name, phone)
|
||||
request.session["user_id"] = user_id
|
||||
flash(request, "Регистрация завершена! Добро пожаловать.")
|
||||
return RedirectResponse("/dashboard", status_code=303)
|
||||
flash(request, "Регистрация завершена. Начните с медиа-образа — посты пишутся на его основе.")
|
||||
return RedirectResponse("/survey", status_code=303)
|
||||
|
||||
|
||||
# === ВХОД / ВЫХОД ===
|
||||
@@ -230,6 +396,7 @@ def login_submit(request: Request, email: str = Form(...), password: str = Form(
|
||||
valid = (
|
||||
user is not None
|
||||
and user["password_hash"]
|
||||
and len(password.encode("utf-8")) <= 72
|
||||
and bcrypt.checkpw(password.encode("utf-8"), user["password_hash"].encode("utf-8"))
|
||||
)
|
||||
if not valid:
|
||||
@@ -253,7 +420,19 @@ def logout(request: Request):
|
||||
@app.get("/dashboard")
|
||||
def dashboard(request: Request, user: dict = Depends(current_user)):
|
||||
latest_survey = get_latest_brand_survey_for_user(user["id"])
|
||||
return render(request, "dashboard.html", user=user, latest_survey=latest_survey)
|
||||
recent_posts = get_posts_for_user(user["id"], limit=3)
|
||||
for p in recent_posts:
|
||||
p["images"] = get_post_images(p["id"], user["id"])
|
||||
all_posts = get_posts_for_user(user["id"], limit=10000)
|
||||
counters = {
|
||||
"posts": len(all_posts),
|
||||
"images": len(get_media_for_user(user["id"], limit=10000)),
|
||||
"published": sum(1 for p in all_posts if p.get("published")),
|
||||
"surveys": len(get_brand_surveys_for_user(user["id"])),
|
||||
}
|
||||
return render(request, "dashboard.html", user=user, latest_survey=latest_survey,
|
||||
active_persona=latest_survey, recent_posts=recent_posts,
|
||||
counters=counters, platform_label=platform_label)
|
||||
|
||||
|
||||
@app.get("/profile/edit")
|
||||
@@ -282,20 +461,21 @@ def profile_edit_submit(
|
||||
def provider_form(request: Request, user: dict = Depends(current_user)):
|
||||
provider = get_provider_settings(user["id"])
|
||||
return render(request, "provider.html", user=user,
|
||||
provider=provider, provider_presets=PROVIDER_PRESETS)
|
||||
provider=provider, provider_presets=PROVIDER_PRESETS,
|
||||
default_text={"base_url": QWEN_BASE_URL or "", "model": QWEN_MODEL})
|
||||
|
||||
|
||||
@app.post("/provider")
|
||||
def provider_submit(
|
||||
request: Request,
|
||||
# Text provider
|
||||
text_provider_type: str = Form(...),
|
||||
text_provider_type: str = Form(""),
|
||||
text_api_key: str = Form(""),
|
||||
text_base_url: str = Form(""),
|
||||
text_model: str = Form(""),
|
||||
text_use_global: str = Form(""),
|
||||
# Image provider
|
||||
image_provider_type: str = Form(...),
|
||||
image_provider_type: str = Form(""),
|
||||
image_api_key: str = Form(""),
|
||||
image_base_url: str = Form(""),
|
||||
image_model: str = Form(""),
|
||||
@@ -304,14 +484,18 @@ def provider_submit(
|
||||
):
|
||||
errors = []
|
||||
|
||||
# «Стандартные настройки» — это Qwen сервиса, отдельный провайдер выбирать не нужно
|
||||
if text_use_global and text_provider_type not in PROVIDER_PRESETS:
|
||||
text_provider_type = "qwen"
|
||||
|
||||
# Валидация text-провайдера
|
||||
if text_provider_type not in PROVIDER_PRESETS:
|
||||
errors.append("Выберите провайдера для текста.")
|
||||
text_preset = PROVIDER_PRESETS.get(text_provider_type, {})
|
||||
if not text_use_global and text_preset.get("needs_key") and not text_api_key.strip():
|
||||
errors.append("Укажите API ключ для текстового провайдера или выберите «Использовать глобальные настройки».")
|
||||
if not text_use_global and text_provider_type == "custom" and not text_base_url.strip():
|
||||
errors.append("Для кастомного текстового провайдера укажите Base URL.")
|
||||
if not text_use_global and text_provider_type in ("custom", "qwen") and not (text_base_url.strip() or text_preset.get("base_url")):
|
||||
errors.append("Для этого текстового провайдера укажите Base URL.")
|
||||
|
||||
# Валидация image-провайдера
|
||||
if image_provider_type not in PROVIDER_PRESETS:
|
||||
@@ -321,6 +505,12 @@ def provider_submit(
|
||||
errors.append("Укажите API ключ для провайдера изображений или выберите «Использовать глобальные настройки».")
|
||||
if not image_use_global and image_provider_type == "custom" and not image_base_url.strip():
|
||||
errors.append("Для кастомного image-провайдера укажите Base URL.")
|
||||
# Свой адрес провайдера — только публичный https: сервер отправляет на него запросы и показывает ответ
|
||||
for label, use_global, base in (("текстового", text_use_global, text_base_url), ("image-", image_use_global, image_base_url)):
|
||||
if not use_global and base.strip():
|
||||
url_error = public_url_error(base)
|
||||
if url_error:
|
||||
errors.append(f"Base URL {label}провайдера: {url_error}")
|
||||
if not image_preset.get("supports_images", True) and not image_use_global:
|
||||
errors.append(f"Провайдер «{image_preset.get('name')}» не поддерживает генерацию изображений. Выберите другой.")
|
||||
|
||||
@@ -328,11 +518,14 @@ def provider_submit(
|
||||
return render(
|
||||
request, "provider.html", status_code=400,
|
||||
user=user, provider_presets=PROVIDER_PRESETS, errors=errors,
|
||||
default_text={"base_url": QWEN_BASE_URL or "", "model": QWEN_MODEL},
|
||||
form={
|
||||
"text_provider_type": text_provider_type, "text_api_key": text_api_key,
|
||||
"text_base_url": text_base_url, "text_model": text_model,
|
||||
"text_use_global": text_use_global,
|
||||
"image_provider_type": image_provider_type, "image_api_key": image_api_key,
|
||||
"image_base_url": image_base_url, "image_model": image_model,
|
||||
"image_use_global": image_use_global,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -571,12 +764,13 @@ async def post_image_upload(request: Request, post_id: int, user: dict = Depends
|
||||
flash(request, "Выберите файлы для загрузки.")
|
||||
return RedirectResponse(f"/posts/{post_id}", status_code=303)
|
||||
|
||||
uploaded = 0
|
||||
uploaded = skipped = 0
|
||||
for upload in files:
|
||||
if not upload or not upload.filename:
|
||||
continue
|
||||
raw = await upload.read()
|
||||
if not raw:
|
||||
raw = await upload.read(MAX_IMAGE_BYTES + 1)
|
||||
if not raw or len(raw) > MAX_IMAGE_BYTES or not is_image(raw):
|
||||
skipped += 1
|
||||
continue
|
||||
ext = detect_ext(raw)
|
||||
filename = f"{uuid.uuid4().hex}{ext}"
|
||||
@@ -584,10 +778,11 @@ async def post_image_upload(request: Request, post_id: int, user: dict = Depends
|
||||
save_post_image(post_id, user["id"], filename, source="upload")
|
||||
uploaded += 1
|
||||
|
||||
note = f" Пропущено файлов: {skipped} — нужны JPG, PNG, WebP или GIF до 10 МБ." if skipped else ""
|
||||
if uploaded:
|
||||
flash(request, f"Загружено изображений: {uploaded}")
|
||||
flash(request, f"Загружено изображений: {uploaded}.{note}")
|
||||
else:
|
||||
flash(request, "Не удалось загрузить изображения.")
|
||||
flash(request, "Не удалось загрузить изображения." + note)
|
||||
return RedirectResponse(f"/posts/{post_id}", status_code=303)
|
||||
|
||||
|
||||
@@ -642,8 +837,8 @@ def plan_form(request: Request, user: dict = Depends(current_user)):
|
||||
|
||||
|
||||
@app.post("/plan")
|
||||
def plan_submit(request: Request, days: int = Form(7), user: dict = Depends(current_user)):
|
||||
days = max(1, min(days, 14))
|
||||
def plan_submit(request: Request, days: str = Form("7"), user: dict = Depends(current_user)):
|
||||
days = max(1, min(to_int(days, 7), 14))
|
||||
user_gen = get_user_content_gen(user)
|
||||
latest = get_latest_brand_survey_for_user(user["id"])
|
||||
if latest:
|
||||
@@ -664,8 +859,8 @@ def plan_status_submit(
|
||||
user: dict = Depends(current_user),
|
||||
):
|
||||
try:
|
||||
update_plan_status(user["id"], item_id, status)
|
||||
flash(request, "Статус пункта обновлён.")
|
||||
found = update_plan_status(user["id"], item_id, status)
|
||||
flash(request, "Статус пункта обновлён." if found else "Пункт плана не найден.")
|
||||
except ValueError:
|
||||
flash(request, "Недопустимый статус.")
|
||||
return RedirectResponse("/plan", status_code=303)
|
||||
@@ -673,8 +868,8 @@ def plan_status_submit(
|
||||
|
||||
@app.post("/plan/{item_id}/delete")
|
||||
def plan_item_delete(request: Request, item_id: int, user: dict = Depends(current_user)):
|
||||
delete_plan_item(user["id"], item_id)
|
||||
flash(request, "Пункт плана удалён.")
|
||||
found = delete_plan_item(user["id"], item_id)
|
||||
flash(request, "Пункт плана удалён." if found else "Пункт плана не найден.")
|
||||
return RedirectResponse("/plan", status_code=303)
|
||||
|
||||
|
||||
@@ -694,7 +889,10 @@ def delete_account_submit(
|
||||
):
|
||||
if confirm != "yes":
|
||||
return RedirectResponse("/dashboard", status_code=303)
|
||||
delete_user_by_id(user["id"])
|
||||
for filename in delete_user_by_id(user["id"]):
|
||||
fp = MEDIA_DIR / filename
|
||||
if fp.exists():
|
||||
fp.unlink()
|
||||
request.session.clear()
|
||||
return RedirectResponse("/login", status_code=303)
|
||||
|
||||
@@ -740,9 +938,9 @@ def image_generate_submit(
|
||||
if not prompt:
|
||||
return render(
|
||||
request, "image_generate.html", status_code=400,
|
||||
user=user, sizes=sizes, styles=STYLE_PRESETS,
|
||||
user=user, sizes=sizes, styles=STYLE_PRESETS, templates=IMAGE_TEMPLATES,
|
||||
form={"prompt": prompt, "size": size, "style": style},
|
||||
errors=["Опиши, что нужно нарисовать."],
|
||||
errors=["Опишите, что нужно нарисовать."],
|
||||
)
|
||||
|
||||
user_img_gen = get_user_image_gen(user)
|
||||
@@ -752,7 +950,7 @@ def image_generate_submit(
|
||||
except Exception as e:
|
||||
return render(
|
||||
request, "image_generate.html", status_code=502,
|
||||
user=user, sizes=sizes, styles=STYLE_PRESETS,
|
||||
user=user, sizes=sizes, styles=STYLE_PRESETS, templates=IMAGE_TEMPLATES,
|
||||
form={"prompt": prompt, "size": size, "style": style},
|
||||
errors=[f"Ошибка генерации картинки: {e}"],
|
||||
)
|
||||
@@ -824,10 +1022,10 @@ async def survey_import_submit(request: Request, user: dict = Depends(current_us
|
||||
)
|
||||
# Поддерживаем два формата: {"data": {...}, "title": "..."} или просто {...}
|
||||
if isinstance(data, dict) and "data" in data and isinstance(data["data"], dict):
|
||||
title = (data.get("title") or "Импортированный образ").strip()[:200]
|
||||
title = str(data.get("title") or "Импортированный образ").strip()[:200]
|
||||
survey_data = data["data"]
|
||||
elif isinstance(data, dict):
|
||||
title = (data.get("client_name") or data.get("title") or "Импортированный образ").strip()[:200]
|
||||
title = str(data.get("client_name") or data.get("title") or "Импортированный образ").strip()[:200]
|
||||
survey_data = data
|
||||
else:
|
||||
return render(
|
||||
@@ -879,7 +1077,7 @@ async def survey_import_submit(request: Request, user: dict = Depends(current_us
|
||||
errors=["Не удалось разобрать документ. Проверьте, что PiAPI ключ настроен, и попробуйте снова."],
|
||||
)
|
||||
|
||||
title = (survey_data.get("client_name") or "Импортированный образ").strip()[:200]
|
||||
title = str(survey_data.get("client_name") or "Импортированный образ").strip()[:200]
|
||||
survey_id = save_brand_survey(user["id"], title, survey_data)
|
||||
flash(request, f"Медиа-образ «{title}» импортирован из .docx.")
|
||||
return RedirectResponse(f"/surveys/{survey_id}", status_code=303)
|
||||
@@ -892,8 +1090,13 @@ async def survey_import_submit(request: Request, user: dict = Depends(current_us
|
||||
|
||||
@app.post("/survey/submit")
|
||||
async def survey_submit(request: Request, user: dict = Depends(current_user)):
|
||||
body = await request.json()
|
||||
title = (body.get("title") or "Без названия").strip()[:200]
|
||||
try:
|
||||
body = await request.json()
|
||||
except ValueError:
|
||||
body = None
|
||||
if not isinstance(body, dict) or not isinstance(body.get("data") or {}, dict):
|
||||
return JSONResponse({"ok": False, "error": "Некорректные данные анкеты."}, status_code=400)
|
||||
title = str(body.get("title") or "Без названия").strip()[:200] or "Без названия"
|
||||
data = body.get("data") or {}
|
||||
survey_id = save_brand_survey(user["id"], title, data)
|
||||
return {"id": survey_id, "ok": True}
|
||||
@@ -993,9 +1196,37 @@ def channel_add_submit(
|
||||
form={"chat_input": chat_input},
|
||||
)
|
||||
|
||||
# 4. Сохраняем
|
||||
save_channel(user["id"], chat_id, title, username, chat_type)
|
||||
flash(request, f"Канал «{title}» добавлен.")
|
||||
# 4. Бот общий, поэтому «бот — админ» не доказывает, что канал ваш.
|
||||
# Владелец подтверждает канал кодом в его описании: менять описание могут только админы канала.
|
||||
pending = {"chat_id": chat_id, "title": title, "username": username, "type": chat_type,
|
||||
"code": "press-" + uuid.uuid4().hex[:8]}
|
||||
request.session["channel_verify"] = pending
|
||||
return render(request, "channel_add.html", user=user, verify=pending)
|
||||
|
||||
|
||||
@app.post("/channels/verify")
|
||||
def channel_verify_submit(request: Request, user: dict = Depends(current_user)):
|
||||
pending = request.session.get("channel_verify")
|
||||
if not pending:
|
||||
flash(request, "Проверка устарела. Добавьте канал ещё раз.")
|
||||
return RedirectResponse("/channels/add", status_code=303)
|
||||
|
||||
info = resolve_chat(str(pending["chat_id"]))
|
||||
if "error" in info:
|
||||
return render(request, "channel_add.html", status_code=400, user=user, verify=pending,
|
||||
errors=[f"Не удалось проверить канал: {info['error']}"])
|
||||
if pending["code"] not in (info.get("description") or ""):
|
||||
return render(request, "channel_add.html", status_code=400, user=user, verify=pending,
|
||||
errors=["Код не найден в описании канала. Сохраните описание в Telegram и проверьте ещё раз."])
|
||||
is_admin, admin_error = check_bot_is_admin(pending["chat_id"])
|
||||
if not is_admin:
|
||||
return render(request, "channel_add.html", status_code=400, user=user, verify=pending,
|
||||
errors=[admin_error or "Бот не админ в этом чате."])
|
||||
|
||||
request.session.pop("channel_verify", None)
|
||||
if not is_channel_already_added(user["id"], pending["chat_id"]):
|
||||
save_channel(user["id"], pending["chat_id"], info["title"], info["username"], info["type"])
|
||||
flash(request, f"Канал «{info['title']}» подключён. Код из описания можно удалить.")
|
||||
return RedirectResponse("/channels", status_code=303)
|
||||
|
||||
|
||||
@@ -1121,12 +1352,7 @@ def _run_post_generation(task_id, user_id, platform, style, wishes, survey_id, p
|
||||
gen = ContentGenerator(provider_settings=settings) if settings and settings.get("api_key") else content_gen
|
||||
content = gen.generate_post_from_brand_profile(brand_data, platform, style, wishes)
|
||||
post_id = save_post_for_user(user_id, platform, content, style, wishes)
|
||||
# Если пост создан из плана — ставим статус «опубликовано»
|
||||
if plan_id:
|
||||
try:
|
||||
update_plan_status(user_id, int(plan_id), "published")
|
||||
except (ValueError, Exception) as e:
|
||||
print(f"⚠️ Не удалось обновить статус плана {plan_id}: {e}")
|
||||
# Пост из плана — пока только черновик: «Опубликовано» пункт получает вручную в плане
|
||||
update_task_status(task_id, 'done', result_json=json.dumps({"post_id": post_id, "content": content}))
|
||||
except Exception as e:
|
||||
update_task_status(task_id, 'error', error=str(e))
|
||||
@@ -1204,7 +1430,7 @@ def _run_social_analysis(task_id, user_id, url, manual_posts):
|
||||
|
||||
if not posts:
|
||||
update_task_status(task_id, 'error',
|
||||
error="Не удалось загрузить посты. Для VK и Tenchat вставьте тексты постов вручную (по 2+ постов через пустую строку).")
|
||||
error="Не удалось загрузить посты. Для VK и TenChat вставьте тексты постов вручную (по 2+ постов через пустую строку).")
|
||||
return
|
||||
|
||||
# AI-анализ
|
||||
@@ -1320,86 +1546,80 @@ def _run_post_image_generation(task_id, user_id, post_id, template_key=None, cus
|
||||
update_task_status(task_id, 'error', error=str(e))
|
||||
|
||||
|
||||
TASK_TYPES = {
|
||||
"generate_post", "generate_plan", "generate_image", "generate_post_image", "analyze_post_image",
|
||||
"generate_post_image_with_concept", "analyze_social_profile", "modify_post",
|
||||
}
|
||||
POST_TASKS = {"generate_post_image", "analyze_post_image", "generate_post_image_with_concept", "modify_post"}
|
||||
|
||||
|
||||
def _task_error(message, status_code=400):
|
||||
return JSONResponse({"error": message}, status_code=status_code)
|
||||
|
||||
|
||||
@app.post("/api/tasks")
|
||||
async def api_start_task(request: Request, user: dict = Depends(current_user)):
|
||||
"""Запускает фоновую задачу. Возвращает task_id."""
|
||||
uid = user["id"]
|
||||
form = await request.form()
|
||||
task_type_val = form.get("task_type", "")
|
||||
task_id = create_task(uid, task_type_val)
|
||||
if task_type_val not in TASK_TYPES:
|
||||
return _task_error("Неизвестный тип задачи.")
|
||||
|
||||
# Лимиты: каждая задача — платный запрос к ИИ через общий ключ
|
||||
if count_user_tasks(uid, 15, active_only=True) >= TASK_ACTIVE_LIMIT:
|
||||
return _task_error("Дождитесь окончания текущих генераций и повторите.", 429)
|
||||
if count_user_tasks(uid, 60) >= TASK_HOURLY_LIMIT:
|
||||
return _task_error("Достигнут лимит генераций на этот час. Повторите позже.", 429)
|
||||
|
||||
post_id = None
|
||||
if task_type_val in POST_TASKS:
|
||||
post_id = to_int(form.get("post_id"))
|
||||
if not post_id or not get_post_by_id_for_user(post_id, uid):
|
||||
return _task_error("Пост не найден.", 404)
|
||||
|
||||
if task_type_val == "generate_post":
|
||||
platform = form.get("platform", "telegram")
|
||||
style = form.get("style", "")
|
||||
wishes = form.get("wishes", "")
|
||||
survey_id = form.get("survey_id", "")
|
||||
plan_id = form.get("plan_id", "") or None
|
||||
t = threading.Thread(target=_run_post_generation, args=(task_id, uid, platform, style, wishes, survey_id, plan_id), daemon=True)
|
||||
t.start()
|
||||
job = (_run_post_generation, form.get("platform", "telegram"), form.get("style", ""),
|
||||
form.get("wishes", ""), to_int(form.get("survey_id")), form.get("plan_id", "") or None)
|
||||
|
||||
elif task_type_val == "generate_plan":
|
||||
days = int(form.get("days", 7))
|
||||
days = max(1, min(days, 14))
|
||||
t = threading.Thread(target=_run_plan_generation, args=(task_id, uid, days), daemon=True)
|
||||
t.start()
|
||||
days = max(1, min(to_int(form.get("days"), 7), 14))
|
||||
job = (_run_plan_generation, days)
|
||||
|
||||
elif task_type_val == "generate_image":
|
||||
prompt = form.get("prompt", "")
|
||||
size = form.get("size", "square")
|
||||
style = form.get("style", "none")
|
||||
ref_file = form.get("reference_image")
|
||||
ref_bytes = None
|
||||
if ref_file and hasattr(ref_file, "read"):
|
||||
ref_bytes = await ref_file.read()
|
||||
ref_bytes = await ref_file.read(MAX_IMAGE_BYTES + 1)
|
||||
if len(ref_bytes) < 100:
|
||||
ref_bytes = None # слишком маленький, пропускаем
|
||||
t = threading.Thread(target=_run_image_generation, args=(task_id, uid, prompt, size, style, ref_bytes), daemon=True)
|
||||
t.start()
|
||||
ref_bytes = None # пустой файл — генерируем без образца
|
||||
elif len(ref_bytes) > MAX_IMAGE_BYTES or not is_image(ref_bytes):
|
||||
return _task_error("Образец должен быть картинкой JPG, PNG, WebP или GIF до 10 МБ.")
|
||||
job = (_run_image_generation, form.get("prompt", ""), form.get("size", "square"),
|
||||
form.get("style", "none"), ref_bytes)
|
||||
|
||||
elif task_type_val == "generate_post_image":
|
||||
post_id = int(form.get("post_id", 0))
|
||||
template_key = form.get("template_key", "") or None
|
||||
t = threading.Thread(target=_run_post_image_generation, args=(task_id, uid, post_id, template_key), daemon=True)
|
||||
t.start()
|
||||
job = (_run_post_image_generation, post_id, form.get("template_key", "") or None)
|
||||
|
||||
elif task_type_val == "analyze_post_image":
|
||||
post_id = int(form.get("post_id", 0))
|
||||
t = threading.Thread(target=_run_analyze_post_image, args=(task_id, uid, post_id), daemon=True)
|
||||
t.start()
|
||||
job = (_run_analyze_post_image, post_id)
|
||||
|
||||
elif task_type_val == "generate_post_image_with_concept":
|
||||
post_id = int(form.get("post_id", 0))
|
||||
concept_prompt = form.get("concept_prompt", "")
|
||||
concept_style = form.get("concept_style", "none")
|
||||
concept_size = form.get("concept_size", "square")
|
||||
t = threading.Thread(
|
||||
target=_run_post_image_generation,
|
||||
args=(task_id, uid, post_id),
|
||||
kwargs={"custom_prompt": concept_prompt, "custom_style": concept_style, "custom_size": concept_size},
|
||||
daemon=True,
|
||||
)
|
||||
t.start()
|
||||
job = (lambda task_id, uid_, pid: _run_post_image_generation(
|
||||
task_id, uid_, pid,
|
||||
custom_prompt=form.get("concept_prompt", ""),
|
||||
custom_style=form.get("concept_style", "none"),
|
||||
custom_size=form.get("concept_size", "square"),
|
||||
), post_id)
|
||||
|
||||
elif task_type_val == "analyze_social_profile":
|
||||
url = form.get("url", "")
|
||||
manual_posts = form.get("manual_posts", "")
|
||||
t = threading.Thread(
|
||||
target=_run_social_analysis,
|
||||
args=(task_id, uid, url, manual_posts),
|
||||
daemon=True,
|
||||
)
|
||||
t.start()
|
||||
job = (_run_social_analysis, form.get("url", ""), form.get("manual_posts", ""))
|
||||
|
||||
elif task_type_val == "modify_post":
|
||||
post_id = int(form.get("post_id", 0))
|
||||
instruction = form.get("instruction", "")
|
||||
t = threading.Thread(
|
||||
target=_run_modify_post,
|
||||
args=(task_id, uid, post_id, instruction),
|
||||
daemon=True,
|
||||
)
|
||||
t.start()
|
||||
else: # modify_post
|
||||
job = (_run_modify_post, post_id, form.get("instruction", ""))
|
||||
|
||||
task_id = create_task(uid, task_type_val)
|
||||
task_pool.submit(job[0], task_id, uid, *job[1:])
|
||||
return {"task_id": task_id, "status": "pending"}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg viewBox="0 0 5669.29 5669.29" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="fg137" x1="1189.35" y1="5684.39" x2="4479.95" y2="-15.1" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#1d71b8"/><stop offset="1" stop-color="#009fe3"/></linearGradient><linearGradient id="fg14a" x1="2583.32" y1="3977.34" x2="3684.12" y2="2070.69" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#009fe3"/><stop offset="1" stop-color="#312783"/></linearGradient><linearGradient id="fg14b" x1="1783.3" y1="3867.5" x2="2693.66" y2="2290.71" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#009fe3"/><stop offset="1" stop-color="#312783"/></linearGradient><linearGradient id="fg14c" x1="2671.48" y1="3177.09" x2="2908.46" y2="2766.62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#009fe3"/><stop offset="1" stop-color="#312783"/></linearGradient></defs><rect width="5669.29" height="5669.29" rx="1589.68" ry="1589.68" fill="url(#fg137)"/><path fill="#fff" d="M3720.19,2839.18l-572.18,1154.71-60.86,122.81-329.71-882.38c-1.19-3.17-2.33-6.37-3.44-9.59l71.95-505.75c42.35-78.96,97.59-152.06,163.21-211.45l541.2-489.89,66.89,74.35,87.56,97.32c124.93,138.85,141.13,436.45,35.38,649.87Z"/><path fill="#fff" d="M4723.87,3339.65l-1093.38,989.71c-87.45,79.16-182.61,115.97-254.55,98.46-48.02-11.69-83.39-47.1-105.12-105.25l-26.86-71.89c.21-.42.41-.83.62-1.25l654.81-1321.45c67.88-136.98,99.36-301.15,88.64-462.25-11.04-166.03-65.93-311.7-154.54-410.19l-87.97-97.77,404.13-365.81c87.45-79.16,182.61-115.97,254.55-98.46,48.02,11.69,83.39,47.1,105.11,105.25l419.71,1123.26c65.38,174.96-28.57,457.81-205.15,617.64Z"/><path fill="url(#fg14a)" d="M3056.27,2581.67l540.98-489.68-66.89-74.35-66.89-74.34-541.42,490.09c-34.48,31.22-66.75,66.01-96.33,103.64,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77,298.85,799.81c15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81-296.9-794.57c-65.37-174.97,28.58-457.81,205.16-617.65Z"/><path fill="#fff" d="M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-356.23,718.89c-124.39,251.03-101.72,591.81,50.64,761.15l574.59,638.64,18.48-128.96-518.73-576.56ZM3684.81,2189.31l-87.56-97.32-66.89-74.35-66.89-74.34-580.67-645.4c-36.29-40.34-75.92-60.7-118.03-60.7-6.06,0-12.17.42-18.34,1.27-73.35,10.06-148.41,79.17-200.79,184.86l-212.3,428.44,153.87,88.2c114.94,65.89,212.58,187.13,274.93,341.4,33.16,82.06,54.57,168.96,63.58,255.66,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77-105.14,733.41,109,121.15c36.29,40.34,75.92,60.7,118.03,60.7,6.06,0,12.17-.42,18.34-1.27,55.4-7.6,111.78-48.89,158.62-114.18,15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81,572.18-1154.71c105.75-213.42,89.55-511.02-35.38-649.87Z"/><path fill="url(#fg14b)" d="M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-86.92-49.82-358.91,724.31c-67.88,136.98-99.36,301.15-88.64,462.25,11.04,166.02,65.93,311.7,154.54,410.19l628.59,698.66c3.6-15.21,6.59-31.04,8.94-47.42l11.4-79.49,18.48-128.96-518.73-576.56Z"/><path fill="#fff" d="M2624.35,2719.79l-179.41,1251.42-18.48,128.96-11.4,79.49c-2.35,16.38-5.34,32.21-8.94,47.42-22.07,93.22-66.84,162.99-124.06,190.91-18.29,8.93-37.5,13.39-57.54,13.38-28.6,0-58.89-9.09-90.56-27.24l-1040.33-596.3c-162.04-92.88-270.39-370.53-236.59-606.3l209.28-1459.87c16.74-116.76,66.46-205.86,133-238.33,18.3-8.92,37.51-13.38,57.55-13.38,28.6,0,58.88,9.09,90.56,27.24l723.11,414.48,86.92,49.82,86.91,49.82,143.38,82.18c162.05,92.88,270.39,370.53,236.6,606.3Z"/><path fill="url(#fg14c)" d="M2754,3224.73l68.32-476.56c1.39-9.67,2.6-19.4,3.63-29.19l-71.95,505.75Z"/></svg>
|
||||
|
After Width: | Height: | Size: 3.6 KiB |
@@ -0,0 +1,658 @@
|
||||
/* ИИ Пресс-секретарь — компоненты. Все значения из tokens.css. */
|
||||
|
||||
.ps-icon { display: block; flex: none; }
|
||||
|
||||
:where(.ps-btn, .ps-iconbtn, .ps-chip, .ps-seg-opt, .ps-switch, .ps-tab, .ps-card-title button):focus-visible {
|
||||
outline: 3px solid var(--focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ---------- Logo ---------- */
|
||||
.ps-logo { display: inline-flex; align-items: center; gap: calc(var(--ps-logo-size, 40px) * 0.28); color: var(--ink); }
|
||||
.ps-logo-mark { display: block; flex: none; }
|
||||
.ps-logo-mark svg { display: block; width: 100%; height: 100%; }
|
||||
.ps-logo--mono .ps-logo-mark { color: var(--brand); }
|
||||
.ps-logo--white, .ps-logo--white .ps-logo-mark { color: #ffffff; }
|
||||
.ps-logo-word {
|
||||
display: inline-flex; align-items: center; gap: 0.32em; white-space: nowrap;
|
||||
font: 600 calc(var(--ps-logo-size, 40px) * 0.5)/1 var(--font-display); letter-spacing: -0.02em;
|
||||
}
|
||||
.ps-logo-ai {
|
||||
font-size: max(12px, 0.6em); font-weight: 700; letter-spacing: 0.04em; line-height: 1;
|
||||
padding: 0.24em 0.42em 0.2em; border-radius: 0.42em;
|
||||
background: var(--indigo-tint); color: var(--indigo);
|
||||
}
|
||||
.ps-logo--mono .ps-logo-ai { background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-logo--white .ps-logo-ai { background: #ffffff; color: var(--logo-deep); }
|
||||
|
||||
/* ---------- Button ---------- */
|
||||
.ps-btn {
|
||||
--_h: var(--control-md);
|
||||
position: relative; display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2);
|
||||
min-height: var(--_h); padding: 0 var(--space-5); border: 0; border-radius: var(--radius-pill);
|
||||
font: 500 15px/20px var(--font-text); letter-spacing: -0.005em; white-space: nowrap; text-decoration: none;
|
||||
cursor: pointer; -webkit-tap-highlight-color: transparent;
|
||||
transition: transform var(--dur-tap) var(--ease-standard), background-color var(--dur-tap) var(--ease-standard), box-shadow var(--dur-move) var(--ease-soft);
|
||||
}
|
||||
.ps-btn:active:not(:disabled) { transform: scale(0.97); }
|
||||
.ps-btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.ps-btn.is-loading { opacity: 1; cursor: progress; }
|
||||
.ps-btn--sm { --_h: var(--control-sm); padding: 0 var(--space-4); font-size: 13px; gap: var(--space-1); }
|
||||
.ps-btn--sm::before { content: ""; position: absolute; inset: -4px 0; }
|
||||
.ps-btn--lg { --_h: var(--control-lg); padding: 0 var(--space-6); font-size: 17px; font-weight: 600; }
|
||||
.ps-btn--block { display: flex; width: 100%; }
|
||||
.ps-btn--primary { background: var(--brand); color: var(--on-brand); box-shadow: var(--shadow-1); }
|
||||
.ps-btn--primary:hover:not(:disabled) { background: var(--brand-pressed); box-shadow: var(--shadow-2); }
|
||||
.ps-btn--secondary { background: var(--surface-raised); color: var(--brand); box-shadow: inset 0 0 0 1px var(--border-strong); }
|
||||
.ps-btn--secondary:hover:not(:disabled) { background: var(--brand-tint); }
|
||||
.ps-btn--quiet { background: transparent; color: var(--brand); }
|
||||
.ps-btn--quiet:hover:not(:disabled) { background: var(--brand-tint); }
|
||||
.ps-btn--glass {
|
||||
background: var(--surface-glass); color: var(--ink);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass)) saturate(180%); backdrop-filter: blur(var(--blur-glass)) saturate(180%);
|
||||
box-shadow: inset 0 0 0 1px var(--hairline), var(--shadow-1);
|
||||
}
|
||||
.ps-btn--danger { background: var(--danger-tint); color: var(--danger); }
|
||||
.ps-spinner {
|
||||
width: 16px; height: 16px; border-radius: 50%; border: 2px solid currentColor; border-right-color: transparent;
|
||||
animation: ps-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
/* ---------- Icon button ---------- */
|
||||
.ps-iconbtn {
|
||||
display: inline-grid; place-items: center; flex: none;
|
||||
width: var(--target-min); height: var(--target-min); padding: 0; border: 0; border-radius: var(--radius-pill);
|
||||
background: transparent; color: var(--ink-secondary); cursor: pointer; -webkit-tap-highlight-color: transparent;
|
||||
transition: transform var(--dur-tap) var(--ease-standard), background-color var(--dur-tap) var(--ease-standard), color var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-iconbtn:hover:not(:disabled) { background: var(--surface-sunken); color: var(--ink); }
|
||||
.ps-iconbtn:active:not(:disabled) { transform: scale(0.92); }
|
||||
.ps-iconbtn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.ps-iconbtn--tinted { background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-iconbtn--tinted:hover:not(:disabled) { background: var(--brand-tint); color: var(--brand-pressed); }
|
||||
.ps-iconbtn--filled { background: var(--brand); color: var(--on-brand); box-shadow: var(--shadow-1); }
|
||||
.ps-iconbtn--filled:hover:not(:disabled) { background: var(--brand-pressed); color: var(--on-brand); }
|
||||
.ps-iconbtn--filled:disabled { background: var(--surface-sunken); color: var(--ink-tertiary); box-shadow: none; opacity: 1; }
|
||||
.ps-iconbtn--glass {
|
||||
background: var(--surface-glass); color: var(--ink);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass)) saturate(180%); backdrop-filter: blur(var(--blur-glass)) saturate(180%);
|
||||
box-shadow: inset 0 0 0 1px var(--hairline), var(--shadow-1);
|
||||
}
|
||||
|
||||
/* ---------- Suggestion chip ---------- */
|
||||
.ps-chip {
|
||||
position: relative; display: inline-flex; align-items: center; gap: var(--space-2);
|
||||
min-height: var(--control-sm); padding: 0 var(--space-4); border: 0; border-radius: var(--radius-pill);
|
||||
background: var(--surface-raised); color: var(--ink); box-shadow: inset 0 0 0 1px var(--hairline);
|
||||
font: 500 15px/20px var(--font-text); cursor: pointer; white-space: nowrap;
|
||||
transition: background-color var(--dur-tap) var(--ease-standard), box-shadow var(--dur-tap) var(--ease-standard), transform var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-chip::before { content: ""; position: absolute; inset: -4px 0; }
|
||||
.ps-chip .ps-icon { color: var(--brand); }
|
||||
.ps-chip:hover { background: var(--brand-tint); }
|
||||
.ps-chip:active { transform: scale(0.96); }
|
||||
.ps-chip.is-selected { background: var(--brand-tint); color: var(--brand); box-shadow: inset 0 0 0 1.5px var(--brand); }
|
||||
.ps-chip--sm { font-size: 13px; line-height: 18px; padding: 0 var(--space-3); min-height: 32px; gap: var(--space-1); }
|
||||
.ps-chip--sm::before { inset: -6px 0; }
|
||||
|
||||
/* ---------- Text field ---------- */
|
||||
.ps-field { display: grid; gap: var(--space-2); min-width: 0; }
|
||||
.ps-field-top { display: flex; justify-content: space-between; align-items: baseline; gap: var(--space-2); }
|
||||
.ps-field-label { font: 500 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-field-count { font: 400 12px/16px var(--font-text); color: var(--ink-tertiary); font-variant-numeric: tabular-nums; }
|
||||
.ps-field-control {
|
||||
box-sizing: border-box; width: 100%; min-height: var(--control-md); padding: 11px var(--space-4); margin: 0;
|
||||
border: 0; border-radius: var(--radius-sm); background: var(--surface-raised); color: var(--ink);
|
||||
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||
font: 400 16px/22px var(--font-text); resize: vertical; outline: none;
|
||||
transition: box-shadow var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-field-control::placeholder { color: var(--ink-tertiary); }
|
||||
.ps-field-control:hover { box-shadow: inset 0 0 0 1px var(--ink-secondary); }
|
||||
.ps-field-control:focus { box-shadow: inset 0 0 0 2px var(--brand), 0 0 0 4px var(--brand-tint); }
|
||||
.ps-field-control:disabled { background: var(--surface-sunken); color: var(--ink-tertiary); box-shadow: none; }
|
||||
.ps-field.is-error .ps-field-control { box-shadow: inset 0 0 0 2px var(--danger); }
|
||||
.ps-field-hint { display: flex; gap: 6px; align-items: flex-start; margin: 0; font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-field-hint .ps-icon { margin-top: 1px; }
|
||||
.ps-field.is-error .ps-field-hint { color: var(--danger); }
|
||||
|
||||
/* ---------- Prompt composer ---------- */
|
||||
.ps-composer {
|
||||
display: grid; gap: var(--space-1); padding: 6px; border-radius: var(--radius-xl);
|
||||
background: var(--surface-raised); box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline);
|
||||
transition: box-shadow var(--dur-move) var(--ease-soft);
|
||||
}
|
||||
.ps-composer:focus-within { box-shadow: var(--shadow-2), inset 0 0 0 1.5px var(--brand); }
|
||||
.ps-composer-suggest { display: flex; flex-wrap: wrap; gap: var(--space-2); padding: var(--space-2) var(--space-2) var(--space-2); }
|
||||
.ps-composer-row { display: flex; align-items: flex-end; gap: var(--space-1); }
|
||||
.ps-composer-input {
|
||||
flex: 1; min-width: 0; min-height: var(--target-min); max-height: 200px; padding: 10px var(--space-3); margin: 0;
|
||||
border: 0; background: transparent; color: var(--ink); resize: none; outline: none;
|
||||
font: 400 16px/24px var(--font-text);
|
||||
}
|
||||
.ps-composer-input::placeholder { color: var(--ink-tertiary); }
|
||||
.ps-composer-row > .ps-iconbtn--filled, .ps-composer-row > .ps-iconbtn--tinted { animation: ps-pop var(--dur-move) var(--ease-spring); }
|
||||
.ps-composer-note { margin: 0; padding: 0 12px 4px; font: 400 12px/16px var(--font-text); color: var(--ink-tertiary); text-align: center; }
|
||||
|
||||
/* ---------- Segmented control ---------- */
|
||||
.ps-seg {
|
||||
position: relative; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr;
|
||||
padding: 4px; border-radius: var(--radius-md); background: var(--surface-sunken); min-height: var(--control-md);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.ps-seg-thumb {
|
||||
position: absolute; top: 4px; bottom: 4px; left: 4px; width: calc((100% - 8px) / var(--ps-seg-n));
|
||||
border-radius: var(--radius-sm); background: var(--surface-raised); box-shadow: var(--shadow-1);
|
||||
transform: translateX(calc(100% * var(--ps-seg-i)));
|
||||
transition: transform var(--dur-snappy) var(--spring-snappy);
|
||||
}
|
||||
.ps-seg-opt {
|
||||
position: relative; z-index: 1; min-height: 36px; padding: 0 var(--space-3); border: 0; border-radius: var(--radius-sm);
|
||||
background: transparent; color: var(--ink-secondary); font: 500 15px/20px var(--font-text); cursor: pointer;
|
||||
transition: color var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-seg-opt[aria-checked="true"] { color: var(--ink); font-weight: 600; }
|
||||
|
||||
/* ---------- Switch ---------- */
|
||||
.ps-switch {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: var(--space-4);
|
||||
width: 100%; min-height: var(--target-min); padding: 0; border: 0; background: none; color: var(--ink);
|
||||
text-align: left; cursor: pointer; font: inherit;
|
||||
}
|
||||
.ps-switch:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.ps-switch-text { display: grid; gap: 2px; }
|
||||
.ps-switch-label { font: 500 15px/20px var(--font-text); }
|
||||
.ps-switch-desc { font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-switch-track {
|
||||
position: relative; flex: none; width: 51px; height: 31px; border-radius: var(--radius-pill);
|
||||
background: var(--border-strong); transition: background-color var(--dur-move) var(--ease-standard);
|
||||
}
|
||||
.ps-switch-knob {
|
||||
position: absolute; top: 2px; left: 2px; width: 27px; height: 27px; border-radius: 50%;
|
||||
background: var(--surface-raised); box-shadow: var(--shadow-1);
|
||||
transition: transform var(--dur-bouncy) var(--spring-bouncy), width var(--dur-snappy) var(--spring-snappy);
|
||||
}
|
||||
.ps-switch[aria-checked="true"] .ps-switch-track { background: var(--brand); }
|
||||
.ps-switch[aria-checked="true"] .ps-switch-knob { transform: translateX(20px); }
|
||||
.ps-switch:active .ps-switch-knob { width: 31px; }
|
||||
.ps-switch[aria-checked="true"]:active .ps-switch-knob { transform: translateX(16px); }
|
||||
|
||||
/* ---------- Message ---------- */
|
||||
.ps-msg { display: flex; gap: var(--space-3); align-items: flex-start; max-width: 640px; animation: ps-rise var(--dur-smooth) var(--spring-smooth); }
|
||||
.ps-msg--user { flex-direction: row-reverse; margin-left: auto; }
|
||||
.ps-msg-avatar { flex: none; margin-top: 2px; }
|
||||
.ps-msg-body { display: grid; gap: var(--space-2); min-width: 0; }
|
||||
.ps-msg--user .ps-msg-body { justify-items: end; }
|
||||
.ps-msg-meta { display: flex; align-items: center; gap: 6px; font: 500 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-msg-author { color: var(--ink); font-weight: 600; }
|
||||
.ps-msg-meta time { font-size: 12px; color: var(--ink-tertiary); }
|
||||
.ps-ai-tag {
|
||||
padding: 1px 8px; border-radius: 6px; background: var(--indigo-tint); color: var(--indigo);
|
||||
font: 700 12px/16px var(--font-display); letter-spacing: 0.04em;
|
||||
}
|
||||
.ps-msg-bubble {
|
||||
padding: var(--space-3) var(--space-4); border-radius: var(--radius-lg);
|
||||
font: 400 16px/24px var(--font-text); color: var(--ink); overflow-wrap: anywhere;
|
||||
}
|
||||
.ps-msg--ai .ps-msg-bubble { background: var(--surface-raised); border-top-left-radius: 6px; box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); }
|
||||
.ps-msg--user .ps-msg-bubble { background: var(--brand-tint); border-top-right-radius: 6px; }
|
||||
.ps-msg-bubble > p { margin: 0; }
|
||||
.ps-msg-bubble > p + p { margin-top: var(--space-3); }
|
||||
.ps-msg-actions { display: flex; flex-wrap: wrap; gap: 2px; margin-left: -6px; }
|
||||
.ps-caret { display: inline-block; width: 2px; height: 1.05em; margin-left: 2px; vertical-align: -0.15em; border-radius: 1px; background: var(--brand); animation: ps-blink 1s steps(2, start) infinite; }
|
||||
|
||||
/* ---------- Thinking — «Веер» ---------- */
|
||||
.ps-thinking {
|
||||
display: inline-flex; align-items: center; gap: 10px; padding: 8px 16px 8px 10px; border-radius: var(--radius-pill);
|
||||
background: var(--indigo-tint); color: var(--indigo); font: 500 15px/20px var(--font-text);
|
||||
}
|
||||
.ps-fan { position: relative; display: block; width: 30px; height: 26px; flex: none; }
|
||||
.ps-fan i {
|
||||
position: absolute; left: 10.5px; top: 4px; width: 9px; height: 17px; border-radius: 3px 4px 3px 4px;
|
||||
transform: rotate(calc(var(--r) * 0.3));
|
||||
background: currentColor; transform-origin: 50% 100%;
|
||||
animation: ps-fan var(--dur-think) var(--ease-soft) infinite;
|
||||
}
|
||||
.ps-fan i:nth-child(1) { --r: -36deg; opacity: 0.45; }
|
||||
.ps-fan i:nth-child(2) { --r: 0deg; opacity: 0.7; animation-delay: 80ms; }
|
||||
.ps-fan i:nth-child(3) { --r: 36deg; animation-delay: 160ms; }
|
||||
|
||||
/* ---------- Status badge ---------- */
|
||||
.ps-badge {
|
||||
display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 8px 0 6px; border-radius: var(--radius-xs);
|
||||
font: 500 13px/18px var(--font-text); white-space: nowrap;
|
||||
}
|
||||
.ps-badge--neutral { background: var(--surface-sunken); color: var(--ink-secondary); }
|
||||
.ps-badge--ai { background: var(--indigo-tint); color: var(--indigo); }
|
||||
.ps-badge--warning { background: var(--warning-tint); color: var(--warning); }
|
||||
.ps-badge--success { background: var(--success-tint); color: var(--success); }
|
||||
.ps-badge--danger { background: var(--danger-tint); color: var(--danger); }
|
||||
|
||||
/* ---------- Draft card ---------- */
|
||||
.ps-card {
|
||||
position: relative; display: grid; gap: var(--space-3); padding: var(--space-5); min-width: 0;
|
||||
border-radius: var(--radius-lg); background: var(--surface-raised);
|
||||
box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline);
|
||||
transition: transform var(--dur-move) var(--ease-soft), box-shadow var(--dur-move) var(--ease-soft);
|
||||
}
|
||||
.ps-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-2), inset 0 0 0 1px var(--hairline); }
|
||||
.ps-card:active { transform: scale(0.99); }
|
||||
.ps-card:has(.ps-card-title button:focus-visible) { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.ps-card-top { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); }
|
||||
.ps-card-channels { font: 500 12px/16px var(--font-text); letter-spacing: 0.04em; text-transform: uppercase; color: var(--ink-tertiary); }
|
||||
.ps-card-title { margin: 0; font: 600 20px/26px var(--font-display); letter-spacing: -0.01em; color: var(--ink); text-wrap: balance; }
|
||||
.ps-card-title button { all: unset; cursor: pointer; }
|
||||
.ps-card-title button::after { content: ""; position: absolute; inset: 0; border-radius: inherit; }
|
||||
.ps-card-title button:focus-visible { outline: none; }
|
||||
.ps-card-excerpt {
|
||||
margin: 0; font: 400 15px/22px var(--font-text); color: var(--ink-secondary);
|
||||
display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;
|
||||
}
|
||||
.ps-card-foot { display: flex; align-items: center; gap: var(--space-3); font: 500 13px/18px var(--font-text); color: var(--ink-tertiary); }
|
||||
.ps-card-len { font-family: var(--font-text); font-weight: 400; font-variant-numeric: tabular-nums; }
|
||||
.ps-card-chev { margin-left: auto; color: var(--ink-tertiary); transition: transform var(--dur-move) var(--ease-soft); }
|
||||
.ps-card:hover .ps-card-chev { transform: translateX(3px); color: var(--brand); }
|
||||
|
||||
/* ---------- Toast ---------- */
|
||||
.ps-toast {
|
||||
display: flex; align-items: flex-start; gap: var(--space-3); max-width: 420px; padding: var(--space-3) var(--space-2) var(--space-3) var(--space-3);
|
||||
border-radius: var(--radius-lg); background: var(--surface-glass); color: var(--ink);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass)) saturate(180%); backdrop-filter: blur(var(--blur-glass)) saturate(180%);
|
||||
box-shadow: var(--shadow-float), inset 0 0 0 1px var(--hairline);
|
||||
animation: ps-rise var(--dur-smooth) var(--spring-smooth);
|
||||
}
|
||||
.ps-toast-icon { display: grid; place-items: center; width: 32px; height: 32px; flex: none; border-radius: 50%; }
|
||||
.ps-toast--info .ps-toast-icon { background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-toast--success .ps-toast-icon { background: var(--success-tint); color: var(--success); }
|
||||
.ps-toast--warning .ps-toast-icon { background: var(--warning-tint); color: var(--warning); }
|
||||
.ps-toast--danger .ps-toast-icon { background: var(--danger-tint); color: var(--danger); }
|
||||
.ps-toast--ai .ps-toast-icon { background: var(--indigo-tint); color: var(--indigo); }
|
||||
.ps-toast-text { flex: 1; min-width: 0; display: grid; gap: 2px; padding-top: 5px; }
|
||||
.ps-toast-title { margin: 0; font: 600 15px/20px var(--font-text); }
|
||||
.ps-toast-body { margin: 0; font: 400 15px/22px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-toast-action { justify-self: start; margin: 4px 0 0 -12px; }
|
||||
.ps-toast > .ps-iconbtn { margin-top: -6px; }
|
||||
|
||||
/* ---------- Tab bar ---------- */
|
||||
.ps-tabbar {
|
||||
display: inline-flex; gap: 2px; padding: 6px; border-radius: var(--radius-xl);
|
||||
background: var(--surface-glass);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass)) saturate(180%); backdrop-filter: blur(var(--blur-glass)) saturate(180%);
|
||||
box-shadow: var(--shadow-float), inset 0 0 0 1px var(--hairline);
|
||||
}
|
||||
.ps-tab {
|
||||
display: grid; justify-items: center; gap: 2px; min-width: 72px; min-height: 52px; padding: 6px 10px 4px;
|
||||
border: 0; border-radius: var(--radius-lg); background: transparent; color: var(--ink-tertiary); cursor: pointer;
|
||||
transition: background-color var(--dur-move) var(--ease-soft), color var(--dur-tap) var(--ease-standard), transform var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-tab:hover { color: var(--ink-secondary); }
|
||||
.ps-tab:active { transform: scale(0.94); }
|
||||
.ps-tab.is-active { background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-tab-icon { position: relative; }
|
||||
.ps-tab-label { font: 600 12px/16px var(--font-text); }
|
||||
.ps-tab-badge {
|
||||
position: absolute; top: -4px; right: -10px; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box;
|
||||
border-radius: var(--radius-pill); background: var(--brand); color: var(--on-brand);
|
||||
font: 700 12px/18px var(--font-text); text-align: center; box-shadow: 0 0 0 2px var(--surface-raised);
|
||||
}
|
||||
|
||||
.ps-badge--brand { background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-spinner--sm { width: 12px; height: 12px; border-width: 2px; }
|
||||
.ps-card-img { display: inline-flex; align-items: center; gap: 4px; font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* ---------- Side navigation ---------- */
|
||||
.ps-sidenav {
|
||||
box-sizing: border-box; display: flex; flex-direction: column; gap: var(--space-4); width: 264px; min-height: 100%; flex: none;
|
||||
padding: var(--space-5) var(--space-3); background: var(--surface-raised); box-shadow: inset -1px 0 0 var(--hairline);
|
||||
}
|
||||
.ps-sidenav-logo { padding: 0 var(--space-3) var(--space-2); }
|
||||
.ps-sidenav-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; }
|
||||
.ps-sidenav-item {
|
||||
display: flex; align-items: center; gap: var(--space-3); width: 100%; min-height: var(--target-min); padding: 0 var(--space-3);
|
||||
border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--ink-secondary);
|
||||
font: 500 15px/20px var(--font-text); text-align: left; cursor: pointer;
|
||||
transition: background-color var(--dur-tap) var(--ease-standard), color var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-sidenav-item:hover { background: var(--surface-sunken); color: var(--ink); }
|
||||
.ps-sidenav-item.is-active { background: var(--brand-tint); color: var(--brand); font-weight: 600; }
|
||||
.ps-sidenav-item:focus-visible, .ps-sidenav-persona:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.ps-sidenav-badge { margin-left: auto; min-width: 20px; height: 20px; padding: 0 6px; box-sizing: border-box; border-radius: var(--radius-pill); background: var(--brand); color: var(--on-brand); font: 600 12px/20px var(--font-text); text-align: center; }
|
||||
.ps-sidenav-persona {
|
||||
margin-top: auto; display: flex; align-items: center; gap: var(--space-3); width: 100%; padding: var(--space-3);
|
||||
border: 0; border-radius: var(--radius-md); background: var(--surface-sunken); color: var(--ink); text-align: left; cursor: pointer; font: inherit;
|
||||
}
|
||||
.ps-sidenav-persona-icon { display: grid; place-items: center; width: 36px; height: 36px; flex: none; border-radius: var(--radius-sm); background: var(--indigo-tint); color: var(--indigo); }
|
||||
.ps-sidenav-persona-text { flex: 1; min-width: 0; display: grid; gap: 2px; }
|
||||
.ps-sidenav-persona-cap { font: 500 12px/16px var(--font-text); color: var(--ink-tertiary); }
|
||||
.ps-sidenav-persona-name { font: 600 15px/20px var(--font-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* ---------- Stat card ---------- */
|
||||
.ps-stat {
|
||||
display: grid; grid-template-columns: auto 1fr; align-items: center; column-gap: var(--space-3); row-gap: var(--space-2);
|
||||
padding: var(--space-5); border-radius: var(--radius-lg); background: var(--surface-raised);
|
||||
box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); min-width: 0;
|
||||
}
|
||||
.ps-stat-icon { display: grid; place-items: center; width: 36px; height: 36px; border-radius: var(--radius-sm); background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-stat-label { font: 500 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-stat-value { grid-column: 1 / -1; font: 700 34px/40px var(--font-display); letter-spacing: -0.02em; color: var(--ink); font-variant-numeric: tabular-nums; }
|
||||
.ps-stat-note { grid-column: 1 / -1; font: 400 13px/18px var(--font-text); color: var(--ink-tertiary); }
|
||||
|
||||
/* ---------- Choice cards ---------- */
|
||||
.ps-choices { display: grid; gap: 8px; min-width: 0; }
|
||||
.ps-choices-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr)); gap: var(--space-3); }
|
||||
.ps-choices-grid.is-compact { grid-template-columns: repeat(auto-fit, minmax(min(100%, 136px), 1fr)); gap: var(--space-2); }
|
||||
.ps-choice {
|
||||
container-type: inline-size; display: block; min-width: 0; min-height: var(--target-min); padding: var(--inset-card); border: 0;
|
||||
border-radius: var(--radius-lg); background: var(--surface-raised); color: var(--ink); text-align: left; cursor: pointer; font: inherit;
|
||||
box-shadow: inset 0 0 0 1px var(--hairline);
|
||||
transition: box-shadow var(--dur-tap) var(--ease-standard), background-color var(--dur-tap) var(--ease-standard), transform var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-choice:hover { box-shadow: inset 0 0 0 1px var(--border-strong); }
|
||||
.ps-choice:active { transform: scale(0.98); }
|
||||
.ps-choice:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.ps-choice.is-selected { background: var(--brand-tint); box-shadow: inset 0 0 0 2px var(--brand); }
|
||||
.ps-choice:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
/* Иконка, текст и галочка — три колонки сетки. Ничего не лежит поверх текста. */
|
||||
.ps-choice-body {
|
||||
display: grid; grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "icon text check";
|
||||
align-items: start; column-gap: var(--gap-row); row-gap: var(--space-3);
|
||||
}
|
||||
.ps-choice-body.no-icon { grid-template-columns: minmax(0, 1fr) auto; grid-template-areas: "text check"; }
|
||||
.ps-choice-icon { grid-area: icon; display: grid; place-items: center; width: var(--tile-md); height: var(--tile-md); border-radius: var(--radius-sm); background: var(--surface-sunken); color: var(--ink-secondary); }
|
||||
.ps-choice.is-selected .ps-choice-icon { background: var(--surface-raised); color: var(--brand); }
|
||||
.ps-choice-text { grid-area: text; display: grid; gap: 2px; min-width: 0; align-self: center; }
|
||||
.ps-choice-kicker { font: 600 12px/16px var(--font-text); letter-spacing: 0.04em; text-transform: uppercase; color: var(--indigo); }
|
||||
.ps-choice-title { font: 600 15px/20px var(--font-text); color: var(--ink); overflow-wrap: break-word; hyphens: manual; }
|
||||
.ps-choice-desc { font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-choice-check {
|
||||
grid-area: check; display: grid; place-items: center; width: 22px; height: 22px; border-radius: 50%;
|
||||
box-shadow: inset 0 0 0 1.5px var(--border-strong); color: transparent;
|
||||
transition: background-color var(--dur-move) var(--ease-spring), transform var(--dur-move) var(--ease-spring);
|
||||
}
|
||||
.ps-choice.is-selected .ps-choice-check { background: var(--brand); color: var(--on-brand); box-shadow: none; }
|
||||
/* Узкая карточка: иконка и галочка — верхний ряд, текст — на всю ширину ниже. */
|
||||
@container (max-width: 210px) {
|
||||
.ps-choice-body { grid-template-columns: auto 1fr auto; grid-template-areas: "icon . check" "text text text"; }
|
||||
.ps-choice-body.no-icon { grid-template-columns: 1fr auto; grid-template-areas: "text check"; }
|
||||
.ps-choice-text { align-self: start; }
|
||||
}
|
||||
.ps-choices-grid.is-compact .ps-choice { padding: var(--inset-control); }
|
||||
.ps-choices-grid.is-compact .ps-choice-body { align-items: center; column-gap: var(--gap-icon); }
|
||||
.ps-choices-grid.is-compact .ps-choice-icon { width: var(--tile-sm); height: var(--tile-sm); }
|
||||
.ps-choices-grid.is-compact .ps-choice-desc { font-size: 12px; line-height: 16px; }
|
||||
.ps-choices-grid.is-compact .ps-choice-check { width: 18px; height: 18px; }
|
||||
.ps-choices-grid.is-compact .ps-choice-check .ps-icon { width: 12px; height: 12px; }
|
||||
.ps-choices-grid.is-compact .ps-choice.is-selected .ps-choice-title { font-weight: 700; }
|
||||
/* Компактная карточка уже 160px: индикатор не помещается рядом с текстом — выбор показывают рамка 2px и жирный заголовок. */
|
||||
@container (max-width: 159px) {
|
||||
.ps-choices-grid.is-compact .ps-choice-check { display: none; }
|
||||
.ps-choices-grid.is-compact .ps-choice-body.no-icon { grid-template-columns: minmax(0, 1fr); grid-template-areas: "text"; }
|
||||
}
|
||||
|
||||
/* ---------- Pillar ---------- */
|
||||
.ps-pillar {
|
||||
display: inline-flex; align-items: center; gap: 6px; height: 24px; padding: 0 8px; border-radius: var(--radius-xs);
|
||||
font: 500 13px/18px var(--font-text); white-space: nowrap;
|
||||
}
|
||||
.ps-pillar-mark { width: 8px; height: 8px; background: currentColor; flex: none; }
|
||||
.ps-pillar--1 { background: var(--pillar-1-tint); color: var(--pillar-1); }
|
||||
.ps-pillar--1 .ps-pillar-mark { border-radius: 50%; }
|
||||
.ps-pillar--2 { background: var(--pillar-2-tint); color: var(--pillar-2); }
|
||||
.ps-pillar--2 .ps-pillar-mark { border-radius: 2px; }
|
||||
.ps-pillar--3 { background: var(--pillar-3-tint); color: var(--pillar-3); }
|
||||
.ps-pillar--3 .ps-pillar-mark { width: 7px; height: 7px; border-radius: 1px; transform: rotate(45deg); }
|
||||
|
||||
/* ---------- Post preview ---------- */
|
||||
.ps-post {
|
||||
display: grid; gap: var(--space-4); padding: var(--space-5); border-radius: var(--radius-xl); background: var(--surface-raised);
|
||||
box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); min-width: 0;
|
||||
}
|
||||
.ps-post-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); }
|
||||
.ps-post-head > .ps-btn, .ps-post-head > .ps-iconbtn { margin-left: auto; }
|
||||
.ps-post-platform { display: inline-flex; align-items: center; gap: 6px; font: 600 15px/20px var(--font-text); color: var(--ink); }
|
||||
.ps-post-platform .ps-icon { color: var(--brand); }
|
||||
.ps-post-tag { padding: 2px 8px; border-radius: var(--radius-xs); background: var(--surface-sunken); font: 500 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-post-image { overflow: hidden; border-radius: var(--radius-lg); aspect-ratio: 16 / 9; max-width: 100%; }
|
||||
.ps-post-image > * { width: 100%; height: 100%; }
|
||||
.ps-post-text { font: 400 16px/25px var(--font-text); color: var(--ink); overflow-wrap: anywhere; }
|
||||
.ps-post-text p { margin: 0; white-space: pre-line; }
|
||||
.ps-post-text p + p { margin-top: 12px; }
|
||||
.ps-post-foot { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2) var(--space-4); padding-top: var(--space-3); box-shadow: inset 0 1px 0 var(--hairline); }
|
||||
.ps-post-count { font: 500 13px/18px var(--font-text); color: var(--ink-tertiary); font-variant-numeric: tabular-nums; }
|
||||
.ps-post-count.is-over { color: var(--danger); }
|
||||
.ps-post-note { display: inline-flex; align-items: center; gap: 6px; font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-post-note.is-danger { color: var(--danger); }
|
||||
.ps-post-actions { display: flex; flex-wrap: wrap; gap: var(--space-2); margin-left: auto; }
|
||||
|
||||
/* ---------- Version history ---------- */
|
||||
.ps-history { list-style: none; margin: 0; padding: 0; display: grid; }
|
||||
.ps-history-item { position: relative; display: grid; grid-template-columns: 20px 1fr auto; align-items: center; gap: var(--space-3); min-height: 52px; }
|
||||
.ps-history-item::before { content: ""; position: absolute; left: 9px; top: 0; bottom: 0; width: 2px; background: var(--hairline); }
|
||||
.ps-history-item:first-child::before { top: 50%; }
|
||||
.ps-history-item:last-child::before { bottom: 50%; }
|
||||
.ps-history-item:only-child::before { display: none; }
|
||||
.ps-history-dot { position: relative; width: 12px; height: 12px; margin-left: 4px; border-radius: 50%; background: var(--surface-raised); box-shadow: inset 0 0 0 2px var(--border-strong); }
|
||||
.ps-history-item.is-active .ps-history-dot { background: var(--brand); box-shadow: 0 0 0 4px var(--brand-tint); }
|
||||
.ps-history-text { display: grid; gap: 2px; min-width: 0; }
|
||||
.ps-history-title { font: 500 15px/20px var(--font-text); color: var(--ink); }
|
||||
.ps-history-meta { font: 400 12px/16px var(--font-text); color: var(--ink-tertiary); font-variant-numeric: tabular-nums; }
|
||||
.ps-history-current { font: 600 13px/18px var(--font-text); color: var(--brand); padding: 0 var(--space-3); }
|
||||
|
||||
/* ---------- Plan day ---------- */
|
||||
.ps-planday {
|
||||
display: grid; grid-template-columns: 56px 1fr auto; align-items: center; gap: var(--space-4);
|
||||
padding: var(--space-3) var(--space-4) var(--space-3) var(--space-3); border-radius: var(--radius-lg); background: var(--surface-raised);
|
||||
box-shadow: inset 0 0 0 1px var(--hairline);
|
||||
}
|
||||
.ps-planday-date { display: grid; justify-items: center; padding: 6px 0; border-radius: var(--radius-md); background: var(--surface-sunken); }
|
||||
.ps-planday-num { font: 700 22px/26px var(--font-display); color: var(--ink); font-variant-numeric: tabular-nums; }
|
||||
.ps-planday-wd { font: 500 12px/16px var(--font-text); color: var(--ink-tertiary); }
|
||||
.ps-planday-body { display: grid; gap: var(--space-2); min-width: 0; }
|
||||
.ps-planday-meta { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-2); }
|
||||
.ps-planday-platform { display: inline-flex; align-items: center; gap: 4px; font: 500 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-planday-idea { margin: 0; font: 400 15px/22px var(--font-text); color: var(--ink); }
|
||||
.ps-planday.is-done .ps-planday-date { background: var(--success-tint); }
|
||||
@media (max-width: 560px) {
|
||||
.ps-planday { grid-template-columns: 48px 1fr; }
|
||||
.ps-planday-action { grid-column: 2; }
|
||||
}
|
||||
|
||||
/* ---------- Image presets ---------- */
|
||||
.ps-presets { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: var(--space-3); }
|
||||
.ps-preset {
|
||||
display: grid; gap: 6px; padding: 6px 6px 10px; border: 0; border-radius: var(--radius-md); background: var(--surface-raised);
|
||||
box-shadow: inset 0 0 0 1px var(--hairline); color: var(--ink); cursor: pointer; font: inherit;
|
||||
transition: box-shadow var(--dur-tap) var(--ease-standard), transform var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-preset:hover { box-shadow: inset 0 0 0 1px var(--border-strong); }
|
||||
.ps-preset:active { transform: scale(0.97); }
|
||||
.ps-preset:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.ps-preset.is-selected { background: var(--brand-tint); box-shadow: inset 0 0 0 2px var(--brand); }
|
||||
.ps-preset-art { display: block; aspect-ratio: 4 / 3; overflow: hidden; border-radius: var(--radius-sm); }
|
||||
.ps-preset-art svg { display: block; width: 100%; height: 100%; }
|
||||
.ps-preset-art .t { fill: var(--brand-tint); }
|
||||
.ps-preset-art .b { fill: var(--logo-deep); }
|
||||
.ps-preset-art .a { fill: var(--brand-bright); }
|
||||
.ps-preset-art .c { fill: var(--ink-tertiary); }
|
||||
.ps-preset-art .s { fill: var(--surface-raised); }
|
||||
.ps-preset.is-selected .ps-preset-art .t { fill: var(--surface-raised); }
|
||||
.ps-preset-label { font: 500 13px/18px var(--font-text); text-align: center; }
|
||||
|
||||
/* ---------- Drop zone ---------- */
|
||||
.ps-drop {
|
||||
position: relative; display: grid; justify-items: center; gap: var(--space-2); padding: var(--space-6) var(--space-4); text-align: center;
|
||||
border-radius: var(--radius-lg); background: var(--surface-sunken); box-shadow: inset 0 0 0 1.5px var(--border-strong);
|
||||
cursor: pointer; transition: background-color var(--dur-tap) var(--ease-standard), box-shadow var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-drop:hover, .ps-drop.is-over { background: var(--brand-tint); box-shadow: inset 0 0 0 2px var(--brand); }
|
||||
.ps-drop:focus-within { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.ps-drop-input { position: absolute; width: 1px; height: 1px; opacity: 0; }
|
||||
.ps-drop-icon { display: grid; place-items: center; width: 44px; height: 44px; border-radius: 50%; background: var(--surface-raised); color: var(--brand); box-shadow: var(--shadow-1); }
|
||||
.ps-drop-title { font: 600 15px/20px var(--font-text); color: var(--ink); }
|
||||
.ps-drop-hint { font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
|
||||
/* ---------- Channel ---------- */
|
||||
.ps-channel { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3); padding: var(--space-3) var(--space-4); border-radius: var(--radius-lg); background: var(--surface-raised); box-shadow: inset 0 0 0 1px var(--hairline); }
|
||||
.ps-channel-avatar { display: grid; place-items: center; width: 44px; height: 44px; flex: none; border-radius: 50%; background: var(--brand-tint); color: var(--brand); font: 700 17px/1 var(--font-display); }
|
||||
.ps-channel-text { flex: 1; min-width: 140px; display: grid; gap: 2px; }
|
||||
.ps-channel-title { font: 600 15px/20px var(--font-text); color: var(--ink); }
|
||||
.ps-channel-meta { font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-channel-actions { display: flex; align-items: center; gap: var(--space-1); }
|
||||
|
||||
/* ---------- Progress & stepper ---------- */
|
||||
.ps-progress { display: grid; gap: var(--space-2); }
|
||||
.ps-progress-label { display: flex; justify-content: space-between; font: 500 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-progress-value { font-variant-numeric: tabular-nums; color: var(--ink); }
|
||||
.ps-progress-track { height: 8px; border-radius: var(--radius-pill); background: var(--surface-sunken); overflow: hidden; }
|
||||
.ps-progress-fill { display: block; height: 100%; border-radius: inherit; background: var(--brand); transition: width var(--dur-sheet) var(--ease-soft); }
|
||||
.ps-stepper { display: grid; gap: var(--space-3); }
|
||||
.ps-stepper-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--space-3); }
|
||||
.ps-stepper-count { font: 600 13px/18px var(--font-text); color: var(--brand); font-variant-numeric: tabular-nums; }
|
||||
.ps-stepper-title { font: 600 22px/28px var(--font-display); color: var(--ink); }
|
||||
.ps-stepper-track { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 4px; }
|
||||
.ps-stepper-seg { height: 6px; border-radius: var(--radius-pill); background: var(--surface-sunken); transition: background-color var(--dur-move) var(--ease-standard); }
|
||||
.ps-stepper-seg.is-done { background: var(--brand); }
|
||||
.ps-stepper-seg.is-current { background: var(--brand-bright); }
|
||||
|
||||
/* ---------- Persona card ---------- */
|
||||
.ps-persona {
|
||||
display: grid; gap: var(--space-3); padding: var(--space-5); border-radius: var(--radius-lg); background: var(--surface-raised);
|
||||
box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); min-width: 0; align-content: start;
|
||||
}
|
||||
.ps-persona.is-active { box-shadow: var(--shadow-2), inset 0 0 0 2px var(--brand); }
|
||||
.ps-persona-top { display: flex; align-items: center; gap: var(--space-3); }
|
||||
.ps-persona-icon { display: grid; place-items: center; width: 40px; height: 40px; flex: none; border-radius: var(--radius-sm); background: var(--indigo-tint); color: var(--indigo); }
|
||||
.ps-persona-type { flex: 1; font: 500 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-persona-name { margin: 0; font: 600 20px/26px var(--font-display); color: var(--ink); }
|
||||
.ps-persona-sum { margin: 0; font: 400 15px/22px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-persona-actions { display: flex; flex-wrap: wrap; gap: var(--space-1); }
|
||||
|
||||
/* ---------- Select, secret, slider ---------- */
|
||||
.ps-select { position: relative; }
|
||||
.ps-select-control { appearance: none; -webkit-appearance: none; padding-right: 40px; cursor: pointer; resize: none; }
|
||||
.ps-select-chev { position: absolute; right: 12px; top: 50%; margin-top: -9px; color: var(--ink-secondary); pointer-events: none; }
|
||||
.ps-secret { position: relative; }
|
||||
.ps-secret-control { padding-right: 52px; letter-spacing: 0.02em; }
|
||||
.ps-secret > .ps-iconbtn { position: absolute; right: 0; top: 0; }
|
||||
.ps-slider-value { font: 600 15px/20px var(--font-text); color: var(--brand); font-variant-numeric: tabular-nums; }
|
||||
.ps-slider { -webkit-appearance: none; appearance: none; width: 100%; height: var(--target-min); margin: 0; background: transparent; cursor: pointer; }
|
||||
.ps-slider::-webkit-slider-runnable-track { height: 6px; border-radius: var(--radius-pill); background: linear-gradient(to right, var(--brand) var(--ps-pct), var(--surface-sunken) var(--ps-pct)); }
|
||||
.ps-slider::-moz-range-track { height: 6px; border-radius: var(--radius-pill); background: linear-gradient(to right, var(--brand) var(--ps-pct), var(--surface-sunken) var(--ps-pct)); }
|
||||
.ps-slider::-webkit-slider-thumb { -webkit-appearance: none; width: 28px; height: 28px; margin-top: -11px; border-radius: 50%; background: var(--surface-raised); box-shadow: var(--shadow-2), inset 0 0 0 1px var(--hairline); transition: transform var(--dur-tap) var(--ease-spring); }
|
||||
.ps-slider::-moz-range-thumb { width: 28px; height: 28px; border: 0; border-radius: 50%; background: var(--surface-raised); box-shadow: var(--shadow-2); }
|
||||
.ps-slider:active::-webkit-slider-thumb { transform: scale(1.12); }
|
||||
.ps-slider:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; border-radius: var(--radius-sm); }
|
||||
.ps-slider-scale { display: flex; justify-content: space-between; font: 400 12px/16px var(--font-text); color: var(--ink-tertiary); margin-top: -6px; }
|
||||
|
||||
/* ---------- Empty state ---------- */
|
||||
.ps-empty { display: grid; justify-items: center; gap: var(--space-3); padding: var(--space-8) var(--space-4); text-align: center; }
|
||||
.ps-empty-icon { display: grid; place-items: center; width: 64px; height: 64px; border-radius: var(--radius-lg); background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-empty-title { margin: 0; font: 600 20px/26px var(--font-display); color: var(--ink); }
|
||||
.ps-empty-text { margin: 0; max-width: 40ch; font: 400 15px/22px var(--font-text); color: var(--ink-secondary); }
|
||||
|
||||
/* ---------- Provider card ---------- */
|
||||
.ps-provider { display: grid; gap: var(--space-4); padding: var(--space-5); border-radius: var(--radius-xl); background: var(--surface-raised); box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); }
|
||||
.ps-provider-head { display: flex; flex-wrap: wrap; align-items: flex-start; gap: var(--space-3); }
|
||||
.ps-provider-icon { display: grid; place-items: center; width: 44px; height: 44px; flex: none; border-radius: var(--radius-sm); background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-provider-text { flex: 1; display: grid; gap: 2px; min-width: 160px; }
|
||||
.ps-provider-title { margin: 0; font: 600 20px/26px var(--font-display); color: var(--ink); }
|
||||
.ps-provider-desc { font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-provider-body { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: var(--space-4); }
|
||||
|
||||
/* ---------- Экраны-образцы ---------- */
|
||||
.ps-shell { display: flex; min-height: 100%; background: var(--surface); }
|
||||
.ps-main { flex: 1; min-width: 0; overflow-y: auto; display: grid; align-content: start; gap: var(--stack-section); padding: var(--page-gutter); }
|
||||
.ps-main-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: var(--space-4); }
|
||||
.ps-h1 { margin: 0; font: 700 34px/40px var(--font-display); letter-spacing: -0.015em; color: var(--ink); text-wrap: balance; }
|
||||
.ps-h2 { margin: 0; font: 600 22px/28px var(--font-display); color: var(--ink); }
|
||||
.ps-lead { margin: var(--stack-text) 0 0; font: 400 15px/22px var(--font-text); color: var(--ink-secondary); }
|
||||
.ps-panel { display: grid; gap: var(--stack-group); padding: var(--inset-panel); border-radius: var(--radius-xl); background: var(--surface-raised); box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); align-content: start; min-width: 0; }
|
||||
|
||||
/* ---------- Quick action tile ---------- */
|
||||
.ps-action {
|
||||
display: grid; justify-items: start; align-content: start; gap: 4px; min-width: 0; padding: var(--inset-card);
|
||||
border: 0; border-radius: var(--radius-lg); background: var(--surface-raised); color: var(--ink); text-align: left; cursor: pointer; font: inherit;
|
||||
box-shadow: inset 0 0 0 1px var(--hairline);
|
||||
transition: box-shadow var(--dur-tap) var(--ease-standard), transform var(--dur-tap) var(--ease-standard);
|
||||
}
|
||||
.ps-action:hover { box-shadow: inset 0 0 0 1px var(--border-strong), var(--shadow-1); }
|
||||
.ps-action:active { transform: scale(0.98); }
|
||||
.ps-action:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.ps-action-icon { display: grid; place-items: center; width: var(--tile-md); height: var(--tile-md); margin-bottom: var(--space-2); border-radius: var(--radius-sm); background: var(--brand-tint); color: var(--brand); }
|
||||
.ps-action-title { font: 600 15px/20px var(--font-text); }
|
||||
.ps-action-desc { font: 400 13px/18px var(--font-text); color: var(--ink-secondary); }
|
||||
|
||||
/* ---------- Адаптивные сетки экранов ---------- */
|
||||
.ps-grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap: var(--space-6); align-items: stretch; }
|
||||
.ps-grid-3 { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr)); gap: var(--stack-group); }
|
||||
.ps-grid-4 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr)); gap: var(--stack-group); }
|
||||
.ps-grid-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 160px), 1fr)); gap: var(--space-3); }
|
||||
.ps-split { display: grid; grid-template-columns: minmax(0, 1fr) var(--ps-aside, 320px); gap: var(--space-6); align-items: start; }
|
||||
.ps-split.ps-split--start { grid-template-columns: var(--ps-aside, 320px) minmax(0, 1fr); }
|
||||
@media (max-width: 1023px) {
|
||||
.ps-sidenav { width: 76px; padding-inline: var(--space-3); }
|
||||
.ps-sidenav-logo .ps-logo-word, .ps-sidenav-persona-text, .ps-sidenav-persona > .ps-icon { display: none; }
|
||||
.ps-sidenav-logo { padding: 0 6px var(--space-2); }
|
||||
.ps-sidenav-item { justify-content: center; padding: 0; }
|
||||
.ps-sidenav-item > span:not(.ps-sidenav-badge) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.ps-sidenav-persona { justify-content: center; padding: var(--space-2); }
|
||||
.ps-main { padding: var(--space-6); }
|
||||
}
|
||||
@media (max-width: 899px) {
|
||||
.ps-split, .ps-split.ps-split--start { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@media (max-width: 599px) {
|
||||
.ps-sidenav { display: none; }
|
||||
.ps-main { padding: var(--space-4); gap: var(--space-6); }
|
||||
.ps-h1 { font-size: 28px; line-height: 34px; }
|
||||
}
|
||||
|
||||
/* ---------- Отклик на нажатие ----------
|
||||
Состояние меняется в первый кадр. Вниз — за 90 мс, обратно — пружиной spring-bouncy.
|
||||
Анимации — переходы (transition), а не ключевые кадры: любое движение можно прервать новым нажатием. */
|
||||
.ps-btn, .ps-iconbtn, .ps-chip, .ps-tab, .ps-choice, .ps-preset, .ps-action, .ps-sidenav-item, .ps-card, .ps-drop {
|
||||
transition-property: transform, background-color, box-shadow, color, opacity;
|
||||
transition-duration: var(--dur-bouncy), var(--dur-tap), var(--dur-smooth), var(--dur-tap), var(--dur-tap);
|
||||
transition-timing-function: var(--spring-bouncy), var(--ease-standard), var(--spring-smooth), var(--ease-standard), var(--ease-standard);
|
||||
}
|
||||
.ps-btn:active, .ps-iconbtn:active, .ps-chip:active, .ps-tab:active, .ps-choice:active, .ps-preset:active, .ps-action:active, .ps-sidenav-item:active, .ps-card:active {
|
||||
transition-duration: 90ms, var(--dur-tap), var(--dur-smooth), var(--dur-tap), var(--dur-tap);
|
||||
transition-timing-function: cubic-bezier(0.2, 0, 0, 1), var(--ease-standard), var(--spring-smooth), var(--ease-standard), var(--ease-standard);
|
||||
}
|
||||
.ps-sidenav-item:active { transform: scale(0.97); }
|
||||
.ps-action:hover, .ps-choice:hover:not(.is-selected) { transform: translateY(-1px); }
|
||||
|
||||
/* ---------- Непрерывные углы (squircle) ----------
|
||||
Где браузер умеет corner-shape, углы становятся «яблочными» суперэллипсами.
|
||||
Суперэллипс визуально острее круга, поэтому радиусы × 1,25 — концентричность сохраняется. */
|
||||
@supports (corner-shape: squircle) {
|
||||
:root { --radius-sm: 15px; --radius-md: 20px; --radius-lg: 28px; --radius-xl: 35px; }
|
||||
.ps-panel, .ps-card, .ps-post, .ps-persona, .ps-provider, .ps-stat, .ps-choice, .ps-action, .ps-channel, .ps-planday,
|
||||
.ps-drop, .ps-toast, .ps-tabbar, .ps-composer, .ps-msg-bubble, .ps-preset, .ps-field-control, .ps-seg, .ps-seg-thumb,
|
||||
.ps-sidenav-item, .ps-sidenav-persona, .ps-empty-icon, .ps-action-icon, .ps-stat-icon, .ps-choice-icon, .ps-persona-icon, .ps-provider-icon, .ps-tab {
|
||||
corner-shape: squircle;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Motion ---------- */
|
||||
@keyframes ps-spin { to { transform: rotate(360deg); } }
|
||||
@keyframes ps-blink { to { visibility: hidden; } }
|
||||
@keyframes ps-rise { from { transform: translateY(8px) scale(0.98); } }
|
||||
@keyframes ps-pop { from { transform: scale(0.6); opacity: 0; } }
|
||||
@keyframes ps-fan {
|
||||
0%, 100% { transform: rotate(calc(var(--r) * 0.3)) skewY(0deg); }
|
||||
35%, 70% { transform: rotate(var(--r)) skewY(-6deg); }
|
||||
}
|
||||
@keyframes ps-pulse { 50% { opacity: 0.35; } }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ps-msg, .ps-toast, .ps-composer-row > .ps-iconbtn { animation: none; }
|
||||
.ps-btn, .ps-iconbtn, .ps-chip, .ps-tab, .ps-choice, .ps-preset, .ps-action, .ps-sidenav-item, .ps-card, .ps-drop { transition-duration: 1ms !important; }
|
||||
.ps-action:hover, .ps-choice:hover:not(.is-selected) { transform: none; }
|
||||
.ps-fan i { animation: ps-pulse 1.6s ease-in-out infinite; transform: rotate(var(--r)); }
|
||||
.ps-card:hover, .ps-card:active, .ps-btn:active:not(:disabled), .ps-iconbtn:active:not(:disabled) { transform: none; }
|
||||
.ps-seg-thumb, .ps-switch-knob { transition-duration: 1ms; }
|
||||
}
|
||||
@media (prefers-reduced-transparency: reduce) {
|
||||
.ps-tabbar, .ps-toast, .ps-btn--glass, .ps-iconbtn--glass { background: var(--surface-raised); -webkit-backdrop-filter: none; backdrop-filter: none; }
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
Copyright 2026 The Donbass Project Authors.
|
||||
Portions copyright 2021 The Onest Project Authors (https://github.com/simpals/onest).
|
||||
|
||||
Donbass is a derivative of Onest, created under the terms of the SIL Open Font
|
||||
License, Version 1.1. Modifications: renaming, weight-range selection,
|
||||
per-weight tracking adjustments, and the addition of 10-degree oblique styles.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,155 @@
|
||||
/* ИИ Пресс-секретарь — «жидкое стекло»: блик за курсором и смена темы кругом от кнопки.
|
||||
Подключается в base.html и landing.html. Уважает «Уменьшить движение». */
|
||||
(function () {
|
||||
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
function isDark() {
|
||||
var t = document.documentElement.getAttribute('data-theme');
|
||||
if (t) return t === 'dark';
|
||||
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
}
|
||||
function syncLabels() {
|
||||
document.querySelectorAll('[data-theme-label]').forEach(function (el) {
|
||||
el.textContent = isDark() ? 'Светлая тема' : 'Тёмная тема';
|
||||
});
|
||||
}
|
||||
function applyTheme(next) {
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
try { localStorage.setItem('theme', next); } catch (e) {}
|
||||
syncLabels();
|
||||
}
|
||||
|
||||
/* Смена темы: новая тема раскрывается кругом из точки нажатия */
|
||||
document.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('[data-theme-toggle]');
|
||||
if (!btn) return;
|
||||
var next = isDark() ? 'light' : 'dark';
|
||||
if (!document.startViewTransition || reduce) { applyTheme(next); return; }
|
||||
var r = btn.getBoundingClientRect();
|
||||
var x = r.left + r.width / 2, y = r.top + r.height / 2;
|
||||
var radius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y));
|
||||
document.documentElement.classList.add('is-theme-switch');
|
||||
var t = document.startViewTransition(function () { applyTheme(next); });
|
||||
t.ready.then(function () {
|
||||
document.documentElement.animate(
|
||||
{ clipPath: ['circle(0 at ' + x + 'px ' + y + 'px)', 'circle(' + radius + 'px at ' + x + 'px ' + y + 'px)'] },
|
||||
{ duration: 520, easing: 'cubic-bezier(0.32, 0.72, 0, 1)', pseudoElement: '::view-transition-new(root)' }
|
||||
);
|
||||
}).catch(function () {});
|
||||
function done() { document.documentElement.classList.remove('is-theme-switch'); }
|
||||
t.finished.then(done, done);
|
||||
});
|
||||
document.addEventListener('DOMContentLoaded', syncLabels);
|
||||
|
||||
/* Навигация: одна плашка на всё меню. При нажатии пункт становится активным в тот же кадр,
|
||||
плашка едет к нему пружиной, а раздел тем временем загружается — ничего не ждёт анимацию. */
|
||||
function placeIndicator(nav, item, animate) {
|
||||
var ind = nav.querySelector('.app-nav-indicator');
|
||||
if (!ind || !item) return;
|
||||
var n = nav.getBoundingClientRect(), r = item.getBoundingClientRect();
|
||||
ind.classList.toggle('no-anim', !animate);
|
||||
ind.style.setProperty('--nav-y', (r.top - n.top) + 'px');
|
||||
ind.style.height = r.height + 'px';
|
||||
ind.style.left = (r.left - n.left) + 'px';
|
||||
ind.style.width = r.width + 'px';
|
||||
ind.style.right = 'auto';
|
||||
ind.classList.add('is-ready');
|
||||
if (!animate) { void ind.offsetWidth; ind.classList.remove('no-anim'); }
|
||||
}
|
||||
function placeTab(bar, tab, animate) {
|
||||
var ind = bar.querySelector('.app-tab-indicator');
|
||||
if (!ind || !tab) return;
|
||||
var b = bar.getBoundingClientRect(), r = tab.getBoundingClientRect();
|
||||
ind.classList.toggle('no-anim', !animate);
|
||||
ind.style.setProperty('--tab-x', (r.left - b.left) + 'px');
|
||||
ind.style.setProperty('--tab-w', r.width + 'px');
|
||||
ind.classList.add('is-ready');
|
||||
if (!animate) { void ind.offsetWidth; ind.classList.remove('no-anim'); }
|
||||
}
|
||||
function setActive(list, el) {
|
||||
list.forEach(function (x) { x.classList.toggle('is-active', x === el); if (x === el) x.setAttribute('aria-current', 'page'); else x.removeAttribute('aria-current'); });
|
||||
}
|
||||
function initNav() {
|
||||
var nav = document.querySelector('[data-nav]');
|
||||
if (nav) {
|
||||
var items = Array.prototype.slice.call(nav.querySelectorAll('a.ps-sidenav-item'));
|
||||
placeIndicator(nav, nav.querySelector('.ps-sidenav-item.is-active'), false);
|
||||
nav.addEventListener('pointerdown', function (e) {
|
||||
var a = e.target.closest('a.ps-sidenav-item');
|
||||
if (!a || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
|
||||
setActive(items, a); placeIndicator(nav, a, !reduce);
|
||||
});
|
||||
nav.addEventListener('keydown', function (e) {
|
||||
var a = e.target.closest('a.ps-sidenav-item');
|
||||
if (a && e.key === 'Enter') { setActive(items, a); placeIndicator(nav, a, !reduce); }
|
||||
});
|
||||
window.addEventListener('resize', function () { placeIndicator(nav, nav.querySelector('.ps-sidenav-item.is-active'), false); });
|
||||
}
|
||||
var bar = document.querySelector('[data-tabs]');
|
||||
if (bar) {
|
||||
var tabs = Array.prototype.slice.call(bar.querySelectorAll('.ps-tab'));
|
||||
placeTab(bar, bar.querySelector('.ps-tab.is-active'), false);
|
||||
bar.addEventListener('pointerdown', function (e) {
|
||||
var t = e.target.closest('a.ps-tab');
|
||||
if (!t || e.button !== 0) return;
|
||||
setActive(tabs, t); placeTab(bar, t, !reduce);
|
||||
});
|
||||
window.addEventListener('resize', function () { placeTab(bar, bar.querySelector('.ps-tab.is-active'), false); });
|
||||
}
|
||||
/* Большой заголовок → компактная стеклянная панель, когда заголовок ушёл под край */
|
||||
var cb = document.querySelector('[data-compactbar]');
|
||||
var h1 = document.querySelector('.ps-main-head h1');
|
||||
if (cb && h1 && 'IntersectionObserver' in window) {
|
||||
new IntersectionObserver(function (en) {
|
||||
var stuck = !en[0].isIntersecting && en[0].boundingClientRect.top < 0;
|
||||
cb.classList.toggle('is-stuck', stuck);
|
||||
cb.setAttribute('aria-hidden', stuck ? 'false' : 'true');
|
||||
}, { rootMargin: '-52px 0px 0px 0px', threshold: 0 }).observe(h1);
|
||||
}
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initNav); else initNav();
|
||||
/* Возврат «Назад» из кэша страниц — плашку на место без анимации */
|
||||
window.addEventListener('pageshow', function (e) {
|
||||
if (!e.persisted) return;
|
||||
var nav = document.querySelector('[data-nav]'), bar = document.querySelector('[data-tabs]');
|
||||
var path = location.pathname;
|
||||
if (nav) {
|
||||
var cur = nav.querySelector('a.ps-sidenav-item[aria-current]');
|
||||
/* после «Назад» активен пункт текущего адреса, а не нажатый перед уходом */
|
||||
nav.querySelectorAll('a.ps-sidenav-item').forEach(function (a) {
|
||||
(a.getAttribute('data-prefixes') || a.getAttribute('href')).split(' ').forEach(function (p) {
|
||||
if (path === p || path.indexOf(p + '/') === 0) cur = a;
|
||||
});
|
||||
});
|
||||
if (cur) { setActive(Array.prototype.slice.call(nav.querySelectorAll('a.ps-sidenav-item')), cur); placeIndicator(nav, cur, false); }
|
||||
}
|
||||
if (bar) {
|
||||
var tabs = Array.prototype.slice.call(bar.querySelectorAll('a.ps-tab')), hit = null;
|
||||
tabs.forEach(function (t) {
|
||||
(t.getAttribute('data-prefixes') || '').split(' ').forEach(function (p) { if (p && (path === p || path.indexOf(p + '/') === 0)) hit = t; });
|
||||
});
|
||||
var more = bar.querySelector('button.ps-tab');
|
||||
var target = hit || more;
|
||||
Array.prototype.slice.call(bar.querySelectorAll('.ps-tab')).forEach(function (t) {
|
||||
t.classList.toggle('is-active', t === target);
|
||||
if (t === target && t.tagName === 'A') t.setAttribute('aria-current', 'page'); else t.removeAttribute('aria-current');
|
||||
});
|
||||
placeTab(bar, target, false);
|
||||
}
|
||||
});
|
||||
|
||||
/* Блик на стекле: светлое пятно следует за курсором */
|
||||
if (reduce) return;
|
||||
document.addEventListener('pointermove', function (e) {
|
||||
var g = e.target.closest && e.target.closest('.app-glass');
|
||||
if (!g) return;
|
||||
var r = g.getBoundingClientRect();
|
||||
g.style.setProperty('--glass-x', (e.clientX - r.left) + 'px');
|
||||
g.style.setProperty('--glass-y', (e.clientY - r.top) + 'px');
|
||||
g.classList.add('is-lit');
|
||||
}, { passive: true });
|
||||
document.addEventListener('pointerout', function (e) {
|
||||
var g = e.target.closest && e.target.closest('.app-glass');
|
||||
if (g && !g.contains(e.relatedTarget)) g.classList.remove('is-lit');
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,174 @@
|
||||
/* ИИ Пресс-секретарь — фон первого экрана лендинга.
|
||||
Направление — сдержанность: один крупный целый знак справа, как одноцветная версия логотипа
|
||||
(листы одного тона, тени приглушают лист, а не вырезают его). Знак покачивается ±2,5°, дышит масштабом ±2,5%, раз в цикл по нему проходит блик.
|
||||
Фактура — сетка 12 колонок по контейнеру. Время суток (data-daypart у .lp-hero) меняет свет градиента
|
||||
и раскрытие веера; ночью — редкие звёзды. Левая половина под текстом остаётся чистой.
|
||||
Всё движение — синусы одной фазы цикла (24 с), поэтому цикл бесшовный.
|
||||
?t=N замораживает кадр (для проверки), «Уменьшить движение» — один статичный кадр, пауза вне экрана и на скрытой вкладке. */
|
||||
(function () {
|
||||
var hero = document.querySelector('.lp-hero');
|
||||
var canvas = hero && hero.querySelector('.lp-bg');
|
||||
if (!canvas || !canvas.getContext) return;
|
||||
var ctx = canvas.getContext('2d');
|
||||
var off = document.createElement('canvas'); // слой знака: собираем без нахлёста, кладём с одной прозрачностью
|
||||
var PERIOD = 24; // секунд в цикле
|
||||
var TAU = Math.PI * 2;
|
||||
var reduce = window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
var freeze = new URLSearchParams(location.search).get('t');
|
||||
|
||||
/* Параметры суток: градиент (3 точки), раскрытие веера, свет, плотность постов */
|
||||
var DAY = {
|
||||
morning: { g: ['#56c6f2', '#1d71b8', '#1b5fa6'], open: 0.62, breathe: 0.22, sun: 1, horizon: 0, posts: 3, laps: 1, stars: 0, windows: 0 },
|
||||
day: { g: ['#009fe3', '#1d71b8', '#1a63aa'], open: 0.92, breathe: 0.08, sun: 0, horizon: 0, posts: 6, laps: 2, stars: 0, windows: 0 },
|
||||
evening: { g: ['#1590d8', '#1d71b8', '#2b3f97'], open: 0.6, breathe: 0.12, sun: 2, horizon: 1, posts: 3, laps: 1, stars: 0, windows: 6 },
|
||||
night: { g: ['#1d71b8', '#22337e', '#312783'], open: 0.32, breathe: 0.06, sun: 0, horizon: 0, posts: 1, laps: 1, stars: 1, windows: 14 }
|
||||
};
|
||||
var part = hero.getAttribute('data-daypart') || 'day';
|
||||
var P = DAY[part] || DAY.day;
|
||||
|
||||
/* Знак — настоящие контуры логотипа (координаты исходника 5669×5669).
|
||||
Три группы по порядку наложения: правый лист (задний), средний с тенью на правом, левый (передний) с тенью на среднем. */
|
||||
var GLYPH = [
|
||||
{ side: 1, sheets: ["M3720.19,2839.18l-572.18,1154.71-60.86,122.81-329.71-882.38c-1.19-3.17-2.33-6.37-3.44-9.59l71.95-505.75c42.35-78.96,97.59-152.06,163.21-211.45l541.2-489.89,66.89,74.35,87.56,97.32c124.93,138.85,141.13,436.45,35.38,649.87Z", "M4723.87,3339.65l-1093.38,989.71c-87.45,79.16-182.61,115.97-254.55,98.46-48.02-11.69-83.39-47.1-105.12-105.25l-26.86-71.89c.21-.42.41-.83.62-1.25l654.81-1321.45c67.88-136.98,99.36-301.15,88.64-462.25-11.04-166.03-65.93-311.7-154.54-410.19l-87.97-97.77,404.13-365.81c87.45-79.16,182.61-115.97,254.55-98.46,48.02,11.69,83.39,47.1,105.11,105.25l419.71,1123.26c65.38,174.96-28.57,457.81-205.15,617.64Z"], shades: [] },
|
||||
{ side: 0, sheets: ["M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-356.23,718.89c-124.39,251.03-101.72,591.81,50.64,761.15l574.59,638.64,18.48-128.96-518.73-576.56ZM3684.81,2189.31l-87.56-97.32-66.89-74.35-66.89-74.34-580.67-645.4c-36.29-40.34-75.92-60.7-118.03-60.7-6.06,0-12.17.42-18.34,1.27-73.35,10.06-148.41,79.17-200.79,184.86l-212.3,428.44,153.87,88.2c114.94,65.89,212.58,187.13,274.93,341.4,33.16,82.06,54.57,168.96,63.58,255.66,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77-105.14,733.41,109,121.15c36.29,40.34,75.92,60.7,118.03,60.7,6.06,0,12.17-.42,18.34-1.27,55.4-7.6,111.78-48.89,158.62-114.18,15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81,572.18-1154.71c105.75-213.42,89.55-511.02-35.38-649.87Z"], shades: ["M3056.27,2581.67l540.98-489.68-66.89-74.35-66.89-74.34-541.42,490.09c-34.48,31.22-66.75,66.01-96.33,103.64,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77,298.85,799.81c15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81-296.9-794.57c-65.37-174.97,28.58-457.81,205.16-617.65Z"] },
|
||||
{ side: -1, sheets: ["M2624.35,2719.79l-179.41,1251.42-18.48,128.96-11.4,79.49c-2.35,16.38-5.34,32.21-8.94,47.42-22.07,93.22-66.84,162.99-124.06,190.91-18.29,8.93-37.5,13.39-57.54,13.38-28.6,0-58.89-9.09-90.56-27.24l-1040.33-596.3c-162.04-92.88-270.39-370.53-236.59-606.3l209.28-1459.87c16.74-116.76,66.46-205.86,133-238.33,18.3-8.92,37.51-13.38,57.55-13.38,28.6,0,58.88,9.09,90.56,27.24l723.11,414.48,86.92,49.82,86.91,49.82,143.38,82.18c162.05,92.88,270.39,370.53,236.6,606.3Z"], shades: ["M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-86.92-49.82-358.91,724.31c-67.88,136.98-99.36,301.15-88.64,462.25,11.04,166.02,65.93,311.7,154.54,410.19l628.59,698.66c3.6-15.21,6.59-31.04,8.94-47.42l11.4-79.49,18.48-128.96-518.73-576.56Z", "M2754,3224.73l68.32-476.56c1.39-9.67,2.6-19.4,3.63-29.19l-71.95,505.75Z"] }
|
||||
];
|
||||
var GLYPH_PIVOT = { x: 2900, y: 4450 }, GLYPH_TOP = 1237, GLYPH_H = 4431 - 1237;
|
||||
var GPATH = (typeof Path2D === 'function') ? GLYPH.map(function (g) {
|
||||
return { side: g.side, sheets: g.sheets.map(function (p) { return new Path2D(p); }), shades: g.shades.map(function (p) { return new Path2D(p); }) };
|
||||
}) : null;
|
||||
|
||||
/* Детерминированный генератор — звёзды и окна одинаковы между кадрами и заморозками */
|
||||
function rng(seed) { return function () { seed = (seed * 16807) % 2147483647; return (seed - 1) / 2147483646; }; }
|
||||
|
||||
var W = 0, H = 0, dpr = 1, stars = [], wins = [], cols = [], cardX = 0, cardW = 0;
|
||||
|
||||
function layout() {
|
||||
var r = hero.getBoundingClientRect();
|
||||
dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
W = Math.max(1, Math.round(r.width)); H = Math.max(1, Math.round(r.height));
|
||||
canvas.width = Math.round(W * dpr); canvas.height = Math.round(H * dpr);
|
||||
off.width = canvas.width; off.height = canvas.height;
|
||||
canvas.style.width = W + 'px'; canvas.style.height = H + 'px';
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
/* Колонки сетки — ровно по контейнеру страницы (1200, поля 32/16) */
|
||||
var container = hero.querySelector('.lp-container');
|
||||
var cr = container.getBoundingClientRect();
|
||||
var pad = parseFloat(getComputedStyle(container).paddingLeft) || 0;
|
||||
var left = cr.left - r.left + pad, width = cr.width - pad * 2;
|
||||
cols = [];
|
||||
for (var i = 0; i <= 12; i++) cols.push(left + width * i / 12);
|
||||
/* Центр карточки примера — ось веера: карточка «вырастает» из знака */
|
||||
var card = hero.querySelector('.lp-demo .ps-post') || hero.querySelector('.lp-demo');
|
||||
if (card) { var k = card.getBoundingClientRect(); cardX = k.left - r.left + k.width / 2; cardW = k.width; }
|
||||
else { cardX = W * 0.72; cardW = W * 0.3; }
|
||||
var R = rng(part.length * 97 + 13);
|
||||
stars = [];
|
||||
for (var s = 0; s < 46; s++) stars.push({ x: R() * W, y: R() * H * 0.8, r: 0.6 + R() * 1.4, k: 1 + Math.floor(R() * 3), o: R() });
|
||||
wins = [];
|
||||
var row = H / 6;
|
||||
for (var w = 0; w < P.windows; w++) wins.push({ c: 6 + Math.floor(R() * 6), y: Math.round(1 + R() * 4) * row, o: R(), k: 1 + Math.floor(R() * 2) });
|
||||
}
|
||||
|
||||
function roundRect(x, y, w, h, rad) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + rad, y); ctx.lineTo(x + w - rad, y); ctx.quadraticCurveTo(x + w, y, x + w, y + rad);
|
||||
ctx.lineTo(x + w, y + h - rad); ctx.quadraticCurveTo(x + w, y + h, x + w - rad, y + h);
|
||||
ctx.lineTo(x + rad, y + h); ctx.quadraticCurveTo(x, y + h, x, y + h - rad);
|
||||
ctx.lineTo(x, y + rad); ctx.quadraticCurveTo(x, y, x + rad, y); ctx.closePath();
|
||||
}
|
||||
|
||||
function draw(t) {
|
||||
var ph = (t % PERIOD) / PERIOD * TAU; // фаза цикла 0..2π
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
|
||||
/* 1. Свет: градиент 200° — светлая сторона справа сверху, глубокая слева снизу (под текстом) */
|
||||
var a = 245 * Math.PI / 180, cx = W / 2, cy = H / 2, len = Math.abs(W * Math.sin(a)) + Math.abs(H * Math.cos(a));
|
||||
var gx = Math.sin(a) * len / 2, gy = -Math.cos(a) * len / 2;
|
||||
var g = ctx.createLinearGradient(cx - gx, cy - gy, cx + gx, cy + gy);
|
||||
g.addColorStop(0, P.g[0]); g.addColorStop(0.62, P.g[1]); g.addColorStop(1, P.g[2]);
|
||||
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
|
||||
|
||||
/* 2. Фактура: колонки сетки по контейнеру, едва заметно */
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.05)'; ctx.lineWidth = 1;
|
||||
for (var i = 0; i < cols.length; i++) { var x = Math.round(cols[i]) + 0.5; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke(); }
|
||||
|
||||
/* Ночь: редкие звёзды в правой половине, мерцание на кратных частотах фазы */
|
||||
if (P.stars) {
|
||||
for (var s = 0; s < stars.length; s++) {
|
||||
var st = stars[s];
|
||||
if (st.x < W * 0.5) continue;
|
||||
var tw = 0.4 + 0.6 * (0.5 + 0.5 * Math.sin(ph * st.k + st.o * TAU));
|
||||
ctx.fillStyle = 'rgba(255,255,255,' + (0.5 * tw).toFixed(3) + ')';
|
||||
ctx.beginPath(); ctx.arc(st.x, st.y, st.r * 0.8, 0, TAU); ctx.fill();
|
||||
}
|
||||
}
|
||||
|
||||
/* 3. Знак — одноцветная версия логотипа целиком: белые листы, тени вырезаны (зазоры между листами).
|
||||
Знак не разбирается на части — в исходнике листы хранятся видимыми кусками, и при раздельном повороте
|
||||
вылезают рваные края. Движение — у знака целиком: покачивание вокруг оси ±2,5°, дыхание масштаба ±2,5%,
|
||||
раз в цикл по знаку проходит мягкий блик. Слой собирается отдельно и кладётся с одной прозрачностью. */
|
||||
if (!GPATH) return;
|
||||
var narrow = W < 960;
|
||||
var base = (narrow ? Math.min(H * 0.5, W * 0.8) : H * 1.15) / GLYPH_H;
|
||||
var breathe = 1 + 0.025 * Math.sin(ph);
|
||||
var gScale = base * breathe;
|
||||
var gw = 4100 * base; // ширина знака в исходнике ≈ 4100
|
||||
var px = narrow ? W - gw * 0.34 : Math.min(W - gw * 0.24, cardX + cardW * 0.34);
|
||||
var py = H + GLYPH_H * base * 0.04;
|
||||
var sway = Math.sin(ph + Math.PI / 3) * 2.5 * Math.PI / 180;
|
||||
var oc = off.getContext('2d');
|
||||
oc.setTransform(1, 0, 0, 1, 0, 0); oc.clearRect(0, 0, off.width, off.height);
|
||||
oc.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
oc.save();
|
||||
oc.translate(px, py); oc.rotate(sway); oc.scale(gScale, gScale);
|
||||
oc.translate(-GLYPH_PIVOT.x, -GLYPH_PIVOT.y);
|
||||
oc.fillStyle = '#ffffff';
|
||||
for (var gi = 0; gi < GPATH.length; gi++) for (var si = 0; si < GPATH[gi].sheets.length; si++) oc.fill(GPATH[gi].sheets[si]);
|
||||
/* Тени не вырезают лист, а приглушают его на 45% — как в цветном логотипе: листы целые, глубина видна */
|
||||
oc.globalCompositeOperation = 'destination-out';
|
||||
oc.globalAlpha = 0.45;
|
||||
for (var gj = 0; gj < GPATH.length; gj++) for (var sk = 0; sk < GPATH[gj].shades.length; sk++) oc.fill(GPATH[gj].shades[sk]);
|
||||
oc.globalAlpha = 1;
|
||||
oc.restore();
|
||||
/* Блик: полоса идёт слева направо один раз за цикл, начинается и заканчивается за пределами знака */
|
||||
var u = (ph / TAU);
|
||||
var left = px - gw * 0.9, right = px + gw * 0.9;
|
||||
var bx = left + (right - left) * u;
|
||||
var band = gw * 0.35;
|
||||
var sg = oc.createLinearGradient(bx - band, py - band * 0.6, bx + band, py + band * 0.6); // наклон от ширины полосы, не от высоты экрана
|
||||
sg.addColorStop(0, 'rgba(255,255,255,0)'); sg.addColorStop(0.5, 'rgba(255,255,255,1)'); sg.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
oc.save();
|
||||
oc.globalCompositeOperation = 'source-atop';
|
||||
oc.globalAlpha = 0.9;
|
||||
oc.fillStyle = sg; oc.fillRect(0, 0, W, H);
|
||||
oc.restore();
|
||||
ctx.save();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
/* основной тон знака; блик внутри слоя добавляет до +60% к яркости на своей полосе */
|
||||
ctx.globalAlpha = P.stars ? 0.1 : 0.12;
|
||||
ctx.drawImage(off, 0, 0);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
var running = !reduce && freeze === null, visible = true, start = performance.now();
|
||||
function loop(now) {
|
||||
if (running && visible && !document.hidden) draw((now - start) / 1000);
|
||||
requestAnimationFrame(loop);
|
||||
}
|
||||
function init() {
|
||||
layout();
|
||||
if (freeze !== null) { draw(parseFloat(freeze) || 0); window.__ready = true; return; }
|
||||
if (reduce) { draw(PERIOD * 0.25); return; } // статичный кадр
|
||||
requestAnimationFrame(loop);
|
||||
}
|
||||
function relayout() { layout(); if (!running) draw(freeze !== null ? parseFloat(freeze) || 0 : PERIOD * 0.25); }
|
||||
window.addEventListener('resize', relayout);
|
||||
/* Высота первого экрана меняется вместе с примером поста — холст следует за ней */
|
||||
if ('ResizeObserver' in window) {
|
||||
var lastH = 0;
|
||||
new ResizeObserver(function (en) { var h = Math.round(en[0].contentRect.height); if (h !== lastH) { lastH = h; relayout(); } }).observe(hero);
|
||||
}
|
||||
if ('IntersectionObserver' in window) new IntersectionObserver(function (e) { visible = e[0].isIntersecting; }).observe(hero);
|
||||
if (document.fonts && document.fonts.ready) document.fonts.ready.then(init); else init();
|
||||
})();
|
||||
@@ -0,0 +1,215 @@
|
||||
/* ИИ Пресс-секретарь — токены дизайн-системы. Сгенерировано из tokens.json. */
|
||||
|
||||
@font-face {
|
||||
font-family: "Donbass";
|
||||
src: url("fonts/donbass-regular.woff2") format("woff2");
|
||||
font-weight: 400;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Donbass";
|
||||
src: url("fonts/donbass-medium.woff2") format("woff2");
|
||||
font-weight: 500;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Donbass";
|
||||
src: url("fonts/donbass-semibold.woff2") format("woff2");
|
||||
font-weight: 600;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Donbass";
|
||||
src: url("fonts/donbass-bold.woff2") format("woff2");
|
||||
font-weight: 700;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
:root {
|
||||
--surface: #f4f7fb;
|
||||
--surface-raised: #ffffff;
|
||||
--surface-sunken: #e9eff6;
|
||||
--surface-glass: rgba(255, 255, 255, 0.72);
|
||||
--hairline: #d6e0ec;
|
||||
--border-strong: #7d8fa8;
|
||||
--ink: #0e1b2e;
|
||||
--ink-secondary: #46566c;
|
||||
--ink-tertiary: #5d6d84;
|
||||
--brand: #1d71b8;
|
||||
--brand-pressed: #175e9a;
|
||||
--brand-bright: #009fe3;
|
||||
--logo-deep: #1d71b8;
|
||||
--logo-shade: #312783;
|
||||
--brand-tint: #e9f4fc;
|
||||
--on-brand: #ffffff;
|
||||
--indigo: #312783;
|
||||
--indigo-tint: #ecebfa;
|
||||
--pillar-1: var(--brand);
|
||||
--pillar-1-tint: var(--brand-tint);
|
||||
--pillar-2: #0b6b78;
|
||||
--pillar-2-tint: #e0f2f4;
|
||||
--pillar-3: #a12a6c;
|
||||
--pillar-3-tint: #fbe8f2;
|
||||
--success: #0b7552;
|
||||
--success-tint: #e1f3eb;
|
||||
--warning: #8f5300;
|
||||
--warning-tint: #fcf0dc;
|
||||
--danger: #b83710;
|
||||
--danger-tint: #fce8e1;
|
||||
--focus: var(--brand);
|
||||
--scrim: rgba(14, 27, 46, 0.36);
|
||||
--glass-edge: rgba(255, 255, 255, 0.75);
|
||||
--glass-sheen: rgba(255, 255, 255, 0.55);
|
||||
--ambient-1: rgba(0, 159, 227, 0.22);
|
||||
--ambient-2: rgba(49, 39, 131, 0.12);
|
||||
--ambient-3: rgba(29, 113, 184, 0.16);
|
||||
--space-1: 4px;
|
||||
--space-2: 8px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 20px;
|
||||
--space-6: 24px;
|
||||
--space-8: 32px;
|
||||
--space-12: 48px;
|
||||
--space-16: 64px;
|
||||
--inset-badge: 8px;
|
||||
--inset-control: 12px;
|
||||
--inset-card: 20px;
|
||||
--inset-panel: 24px;
|
||||
--gap-icon: 8px;
|
||||
--gap-row: 12px;
|
||||
--stack-text: 4px;
|
||||
--stack-group: 16px;
|
||||
--stack-section: 32px;
|
||||
--page-gutter: 32px;
|
||||
--radius-xs: 8px;
|
||||
--radius-sm: 12px;
|
||||
--radius-md: 16px;
|
||||
--radius-lg: 22px;
|
||||
--radius-xl: 28px;
|
||||
--radius-pill: 999px;
|
||||
--target-min: 44px;
|
||||
--control-sm: 36px;
|
||||
--control-md: 44px;
|
||||
--control-lg: 52px;
|
||||
--icon-sm: 16px;
|
||||
--icon-md: 20px;
|
||||
--icon-lg: 24px;
|
||||
--tile-sm: 32px;
|
||||
--tile-md: 40px;
|
||||
--tile-lg: 44px;
|
||||
--dur-tap: 120ms;
|
||||
--dur-move: 240ms;
|
||||
--dur-sheet: 380ms;
|
||||
--dur-think: 1400ms;
|
||||
--dur-snappy: 320ms;
|
||||
--dur-smooth: 440ms;
|
||||
--dur-bouncy: 520ms;
|
||||
--ease-soft: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
--ease-spring: cubic-bezier(0.34, 1.4, 0.64, 1);
|
||||
--ease-standard: cubic-bezier(0.2, 0, 0, 1);
|
||||
--spring-snappy: linear(0, 0.0383, 0.1297, 0.2472, 0.3722, 0.493, 0.6027, 0.6978, 0.7773, 0.8416, 0.8921, 0.9306, 0.959, 0.9793, 0.9931, 1.0021, 1.0074, 1.0101, 1.0111, 1.0109, 1.01, 1.0087, 1.0073, 1.006, 1.0047, 1.0036, 1.0027, 1.0019, 1);
|
||||
--spring-smooth: linear(0, 0.0435, 0.1411, 0.259, 0.3782, 0.4888, 0.5862, 0.6691, 0.7381, 0.7944, 0.8397, 0.8757, 0.9041, 0.9264, 0.9437, 0.9571, 0.9674, 0.9753, 0.9813, 0.9859, 0.9894, 0.992, 0.994, 0.9955, 0.9967, 0.9975, 0.9981, 0.9986, 1);
|
||||
--spring-bouncy: linear(0, 0.0666, 0.2222, 0.413, 0.6018, 0.7662, 0.8954, 0.9872, 1.0448, 1.0745, 1.0835, 1.0787, 1.0661, 1.0502, 1.0344, 1.0205, 1.0094, 1.0015, 0.9965, 0.9939, 0.993, 0.9934, 0.9944, 0.9957, 0.997, 0.9982, 0.9992, 0.9998, 1);
|
||||
--blur-glass: 24px;
|
||||
--shadow-1: 0 0.5px 1px rgba(14, 27, 46, 0.06), 0 2px 8px rgba(14, 27, 46, 0.04);
|
||||
--shadow-2: 0 1px 2px rgba(14, 27, 46, 0.06), 0 10px 28px -6px rgba(29, 113, 184, 0.18);
|
||||
--shadow-float: 0 2px 6px rgba(14, 27, 46, 0.06), 0 24px 56px -12px rgba(14, 27, 46, 0.22);
|
||||
--font-display: Donbass, "SF Pro Rounded", -apple-system, "Segoe UI", system-ui, sans-serif;
|
||||
--font-text: Donbass, -apple-system, "SF Pro Text", "Segoe UI", system-ui, sans-serif;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--surface: #0a1322;
|
||||
--surface-raised: #121e33;
|
||||
--surface-sunken: #060c17;
|
||||
--surface-glass: rgba(18, 30, 51, 0.72);
|
||||
--hairline: #24344d;
|
||||
--border-strong: #647a99;
|
||||
--ink: #eaf1fa;
|
||||
--ink-secondary: #a9b8cc;
|
||||
--ink-tertiary: #8a9bb3;
|
||||
--brand: #4cb3f0;
|
||||
--brand-pressed: #7cc7f4;
|
||||
--brand-bright: #009fe3;
|
||||
--logo-deep: #1d71b8;
|
||||
--logo-shade: #312783;
|
||||
--brand-tint: #13304f;
|
||||
--on-brand: #04182b;
|
||||
--indigo: #a49df2;
|
||||
--indigo-tint: #211c4a;
|
||||
--pillar-1: var(--brand);
|
||||
--pillar-1-tint: var(--brand-tint);
|
||||
--pillar-2: #5fcfdc;
|
||||
--pillar-2-tint: #0e2c31;
|
||||
--pillar-3: #f390c6;
|
||||
--pillar-3-tint: #371429;
|
||||
--success: #4fd1a1;
|
||||
--success-tint: #0f2e25;
|
||||
--warning: #f2b765;
|
||||
--warning-tint: #33240d;
|
||||
--danger: #ff9370;
|
||||
--danger-tint: #3a1a12;
|
||||
--focus: var(--brand);
|
||||
--scrim: rgba(0, 0, 0, 0.56);
|
||||
--glass-edge: rgba(255, 255, 255, 0.12);
|
||||
--glass-sheen: rgba(164, 210, 255, 0.16);
|
||||
--ambient-1: rgba(0, 159, 227, 0.18);
|
||||
--ambient-2: rgba(164, 157, 242, 0.12);
|
||||
--ambient-3: rgba(29, 113, 184, 0.2);
|
||||
--shadow-1: 0 0.5px 1px rgba(0, 0, 0, 0.5), 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
--shadow-2: 0 1px 2px rgba(0, 0, 0, 0.5), 0 12px 32px -6px rgba(0, 0, 0, 0.55);
|
||||
--shadow-float: 0 2px 6px rgba(0, 0, 0, 0.5), 0 24px 56px -12px rgba(0, 0, 0, 0.7);
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
--surface: #0a1322;
|
||||
--surface-raised: #121e33;
|
||||
--surface-sunken: #060c17;
|
||||
--surface-glass: rgba(18, 30, 51, 0.72);
|
||||
--hairline: #24344d;
|
||||
--border-strong: #647a99;
|
||||
--ink: #eaf1fa;
|
||||
--ink-secondary: #a9b8cc;
|
||||
--ink-tertiary: #8a9bb3;
|
||||
--brand: #4cb3f0;
|
||||
--brand-pressed: #7cc7f4;
|
||||
--brand-bright: #009fe3;
|
||||
--logo-deep: #1d71b8;
|
||||
--logo-shade: #312783;
|
||||
--brand-tint: #13304f;
|
||||
--on-brand: #04182b;
|
||||
--indigo: #a49df2;
|
||||
--indigo-tint: #211c4a;
|
||||
--pillar-1: var(--brand);
|
||||
--pillar-1-tint: var(--brand-tint);
|
||||
--pillar-2: #5fcfdc;
|
||||
--pillar-2-tint: #0e2c31;
|
||||
--pillar-3: #f390c6;
|
||||
--pillar-3-tint: #371429;
|
||||
--success: #4fd1a1;
|
||||
--success-tint: #0f2e25;
|
||||
--warning: #f2b765;
|
||||
--warning-tint: #33240d;
|
||||
--danger: #ff9370;
|
||||
--danger-tint: #3a1a12;
|
||||
--focus: var(--brand);
|
||||
--scrim: rgba(0, 0, 0, 0.56);
|
||||
--glass-edge: rgba(255, 255, 255, 0.12);
|
||||
--glass-sheen: rgba(164, 210, 255, 0.16);
|
||||
--ambient-1: rgba(0, 159, 227, 0.18);
|
||||
--ambient-2: rgba(164, 157, 242, 0.12);
|
||||
--ambient-3: rgba(29, 113, 184, 0.2);
|
||||
--shadow-1: 0 0.5px 1px rgba(0, 0, 0, 0.5), 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
--shadow-2: 0 1px 2px rgba(0, 0, 0, 0.5), 0 12px 32px -6px rgba(0, 0, 0, 0.55);
|
||||
--shadow-float: 0 2px 6px rgba(0, 0, 0, 0.5), 0 24px 56px -12px rgba(0, 0, 0, 0.7);
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
+635
-1118
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
{# Карточка поста (PostCard). Ожидает переменные post и platform_label. #}
|
||||
{#- Заголовок — первая строка, где есть хотя бы 4 знака (строка из одного эмодзи не годится) -#}
|
||||
{%- set lines = (post.content or '').strip().split('\n') | map('trim') | reject('equalto', '') | list -%}
|
||||
{%- set ns = namespace(idx=0) -%}
|
||||
{%- for l in lines %}{% if ns.idx == 0 and l|length > 3 %}{% set ns.idx = loop.index %}{% endif %}{% endfor -%}
|
||||
{%- set head_i = (ns.idx or 1) - 1 -%}
|
||||
{%- set title = (lines[head_i] if lines else 'Пост') | truncate(90, True, '…') -%}
|
||||
{%- set rest = lines[head_i + 1:] | join(' ') -%}
|
||||
<article class="ps-card">
|
||||
<div class="ps-card-top">
|
||||
{% if post.published %}
|
||||
<span class="ps-badge ps-badge--success">{{ ui.icon('megaphone', 14) }}<span>Опубликован</span></span>
|
||||
{% else %}
|
||||
<span class="ps-badge ps-badge--ai">{{ ui.icon('sparkle', 14) }}<span>Сгенерирован ИИ</span></span>
|
||||
{% endif %}
|
||||
<span class="ps-card-channels">{{ platform_label(post.platform) }}{% if post.style %} · {{ post.style | truncate(24, True, '…') }}{% endif %}</span>
|
||||
</div>
|
||||
<h3 class="ps-card-title"><a class="ps-card-title-link" href="/posts/{{ post.id }}">{{ title }}</a></h3>
|
||||
{% if rest %}<p class="ps-card-excerpt">{{ rest }}</p>{% endif %}
|
||||
<div class="ps-card-foot">
|
||||
<span>{{ post.created_at|local_dt }}</span>
|
||||
<span class="ps-card-len">{{ (post.content or '')|length|num }} зн.</span>
|
||||
{% if post.images %}<span class="ps-card-img">{{ ui.icon('image', 16) }}{{ post.images|length }}</span>{% endif %}
|
||||
{{ ui.icon('chevron-right', 18, 'ps-card-chev') }}
|
||||
</div>
|
||||
</article>
|
||||
@@ -0,0 +1,21 @@
|
||||
{# Компоненты дизайн-системы «ИИ Пресс-секретарь» для Jinja. Сгенерировано из дизайн-системы. #}
|
||||
{% set ICONS = {"send": "M12 19V5M5.5 11.5L12 5l6.5 6.5", "mic": "M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3zM19 11a7 7 0 0 1-14 0M12 18v3", "attach": "M20 11.5l-8.2 8.2a5 5 0 0 1-7.1-7.1l8.6-8.6a3.5 3.5 0 0 1 5 5l-8.5 8.5a2 2 0 0 1-2.8-2.8l7.8-7.8", "sparkle": "M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9zM18.5 16.5l.8 1.7 1.7.8-1.7.8-.8 1.7-.8-1.7-1.7-.8 1.7-.8z", "stop": "M9 7h6a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2z", "copy": "M10 8h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-8a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2zM16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2", "edit": "M4 20h4L19 9a2.83 2.83 0 0 0-4-4L4 16zM13.5 6.5l4 4", "refresh": "M20 12a8 8 0 1 1-2.34-5.66M20 4v5h-5", "check": "M5 12.5l4.5 4.5L19 7.5", "close": "M6.5 6.5l11 11M17.5 6.5l-11 11", "plus": "M12 5v14M5 12h14", "chevron-right": "M9.5 6l6 6-6 6", "news": "M7 3h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM14 3v5h5M8.5 13h7M8.5 17h5", "megaphone": "M4 10v4a1 1 0 0 0 1 1h2l8 4V5L7 9H5a1 1 0 0 0-1 1zM18.5 9a4 4 0 0 1 0 6M8 15.5l1 4.5", "chat": "M20 12a8 8 0 0 1-11.6 7.1L4 20l1-4.2A8 8 0 1 1 20 12z", "calendar": "M6 5h12a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM4 10h16M8.5 3v4M15.5 3v4", "clock": "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7.5V12l3 2", "home": "M4 11l8-7 8 7v8a2 2 0 0 1-2 2h-3v-6H9v6H6a2 2 0 0 1-2-2z", "user": "M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4.5 20a7.5 7.5 0 0 1 15 0", "settings": "M4 7h9M19 7h1M4 17h1M11 17h9M16 4.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5zM8 14.5a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5z", "alert": "M12 4.5l8.5 14.5h-17zM12 10v4M12 16.8v.2", "info": "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v5.5M12 7.8v.2", "search": "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4", "image": "M5 4h14a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1zM4 16l5-5 4 4 3-3 4 4M15.5 8.5v.01", "chart": "M4 20h16M7 16v-5M12 16V7M17 16V9", "cpu": "M7 5h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM10 10h4v4h-4zM9.5 2.5V5M14.5 2.5V5M9.5 19v2.5M14.5 19v2.5M2.5 9.5H5M2.5 14.5H5M19 9.5h2.5M19 14.5h2.5", "persona": "M5 5h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM9 12a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM6 16a3 3 0 0 1 6 0M14.5 10h3.5M14.5 13.5h3.5", "history": "M3.5 12a8.5 8.5 0 1 0 2.5-6M3.5 4v4h4M12 8v4.5l3 1.5", "download": "M12 4v11M7.5 10.5L12 15l4.5-4.5M5 20h14", "upload": "M12 15V4M7.5 8.5L12 4l4.5 4.5M5 20h14", "trash": "M5 7h14M10 7V5h4v2M7 7l1 12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1l1-12M10.5 11v5M13.5 11v5", "link": "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1", "key": "M8 7a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 11h9M18 11v3.5M15.5 11v2.5", "users": "M9 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7zM3 20a6 6 0 0 1 12 0M16 4.5a3.5 3.5 0 0 1 0 6.5M17.5 14.5A6 6 0 0 1 21 20", "building": "M5 21V5a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v16M15 9h3a1 1 0 0 1 1 1v11M3 21h18M8.5 8h3M8.5 12h3M8.5 16h3", "landmark": "M4 21h16M6 21V11M10 21V11M14 21V11M18 21V11M12 3l8 6H4z", "grid": "M6 4h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zM15 4h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-3a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zM6 13h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2zM15 13h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-3a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2z", "eye": "M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z", "eye-off": "M4 4l16 16M9.9 5.8A9.6 9.6 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a16 16 0 0 1-2.6 3.4M6.3 7.6C3.9 9.3 2.5 12 2.5 12S6 18.5 12 18.5c1.7 0 3.2-.5 4.5-1.2M9.9 9.9a3 3 0 0 0 4.2 4.2", "chevron-down": "M6 9.5l6 6 6-6", "chevron-left": "M14.5 6l-6 6 6 6", "logout": "M10 5H6a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h4M15 8l4 4-4 4M19 12H9", "theme": "M20 14.5A8.5 8.5 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z"} %}
|
||||
{% set PRESET_ART = {"cover": "<rect class=\"b\" width=\"64\" height=\"48\"/><rect class=\"s\" x=\"8\" y=\"26\" width=\"34\" height=\"6\" rx=\"3\"/><rect class=\"a\" x=\"8\" y=\"35\" width=\"22\" height=\"4\" rx=\"2\"/>", "quote": "<rect class=\"t\" width=\"64\" height=\"48\"/><circle class=\"b\" cx=\"22\" cy=\"18\" r=\"6\"/><circle class=\"b\" cx=\"38\" cy=\"18\" r=\"6\"/><rect class=\"c\" x=\"12\" y=\"31\" width=\"40\" height=\"4\" rx=\"2\"/><rect class=\"c\" x=\"20\" y=\"38\" width=\"24\" height=\"3\" rx=\"1.5\"/>", "announce": "<rect class=\"t\" width=\"64\" height=\"48\"/><rect class=\"a\" x=\"8\" y=\"8\" width=\"22\" height=\"8\" rx=\"4\"/><rect class=\"b\" x=\"8\" y=\"22\" width=\"48\" height=\"7\" rx=\"3.5\"/><rect class=\"c\" x=\"8\" y=\"34\" width=\"30\" height=\"4\" rx=\"2\"/>", "mockup": "<rect class=\"t\" width=\"64\" height=\"48\"/><rect class=\"b\" x=\"22\" y=\"5\" width=\"20\" height=\"38\" rx=\"5\"/><rect class=\"s\" x=\"25\" y=\"10\" width=\"14\" height=\"26\" rx=\"2\"/>", "collage": "<rect class=\"t\" width=\"64\" height=\"48\"/><rect class=\"b\" x=\"6\" y=\"6\" width=\"24\" height=\"36\" rx=\"4\"/><rect class=\"a\" x=\"34\" y=\"6\" width=\"24\" height=\"16\" rx=\"4\"/><rect class=\"c\" x=\"34\" y=\"26\" width=\"24\" height=\"16\" rx=\"4\"/>", "background": "<rect class=\"b\" width=\"64\" height=\"48\"/><circle class=\"a\" cx=\"52\" cy=\"8\" r=\"20\"/><circle class=\"t\" cx=\"8\" cy=\"46\" r=\"14\"/>", "portrait": "<rect class=\"t\" width=\"64\" height=\"48\"/><circle class=\"b\" cx=\"32\" cy=\"19\" r=\"9\"/><path class=\"b\" d=\"M13 48a19 17 0 0 1 38 0z\"/>", "product": "<rect class=\"t\" width=\"64\" height=\"48\"/><ellipse class=\"c\" cx=\"32\" cy=\"41\" rx=\"15\" ry=\"3\"/><rect class=\"b\" x=\"22\" y=\"9\" width=\"20\" height=\"29\" rx=\"6\"/>", "landscape": "<rect class=\"t\" width=\"64\" height=\"48\"/><circle class=\"a\" cx=\"47\" cy=\"13\" r=\"6\"/><path class=\"b\" d=\"M0 48L20 22l14 16 10-10 20 20z\"/>", "abstract": "<rect class=\"t\" width=\"64\" height=\"48\"/><circle class=\"b\" cx=\"21\" cy=\"20\" r=\"13\"/><rect class=\"a\" x=\"27\" y=\"17\" width=\"30\" height=\"22\" rx=\"6\" transform=\"rotate(12 42 28)\"/>", "meme": "<rect class=\"t\" width=\"64\" height=\"48\"/><rect class=\"b\" x=\"8\" y=\"12\" width=\"48\" height=\"24\" rx=\"4\"/><rect class=\"c\" x=\"14\" y=\"4\" width=\"36\" height=\"5\" rx=\"2.5\"/><rect class=\"c\" x=\"14\" y=\"39\" width=\"36\" height=\"5\" rx=\"2.5\"/>", "minimal": "<rect class=\"s\" width=\"64\" height=\"48\"/><circle class=\"b\" cx=\"32\" cy=\"24\" r=\"5\"/>"} %}
|
||||
|
||||
{% macro icon(name, size=20, cls='', label='') -%}
|
||||
<svg class="ps-icon {{ cls }}" width="{{ size }}" height="{{ size }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"{% if label %} role="img" aria-label="{{ label }}"{% else %} aria-hidden="true"{% endif %}><path d="{{ ICONS.get(name, '') }}"/></svg>
|
||||
{%- endmacro %}
|
||||
{% macro mark(uid='pl', tone='color', size=40) -%}
|
||||
<span class="ps-logo-mark" style="width:{{ size }}px;height:{{ size }}px" aria-hidden="true">
|
||||
{%- if tone == 'color' -%}
|
||||
<svg viewBox="0 0 5669.29 5669.29" xmlns="http://www.w3.org/2000/svg" focusable="false"><defs><linearGradient id="{{ uid }}g137" x1="1189.35" y1="5684.39" x2="4479.95" y2="-15.1" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#1d71b8"/><stop offset="1" stop-color="#009fe3"/></linearGradient><linearGradient id="{{ uid }}g14a" x1="2583.32" y1="3977.34" x2="3684.12" y2="2070.69" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#009fe3"/><stop offset="1" stop-color="#312783"/></linearGradient><linearGradient id="{{ uid }}g14b" x1="1783.3" y1="3867.5" x2="2693.66" y2="2290.71" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#009fe3"/><stop offset="1" stop-color="#312783"/></linearGradient><linearGradient id="{{ uid }}g14c" x1="2671.48" y1="3177.09" x2="2908.46" y2="2766.62" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#009fe3"/><stop offset="1" stop-color="#312783"/></linearGradient></defs><rect width="5669.29" height="5669.29" rx="1589.68" ry="1589.68" fill="url(#{{ uid }}g137)"/><path fill="#fff" d="M3720.19,2839.18l-572.18,1154.71-60.86,122.81-329.71-882.38c-1.19-3.17-2.33-6.37-3.44-9.59l71.95-505.75c42.35-78.96,97.59-152.06,163.21-211.45l541.2-489.89,66.89,74.35,87.56,97.32c124.93,138.85,141.13,436.45,35.38,649.87Z"/><path fill="#fff" d="M4723.87,3339.65l-1093.38,989.71c-87.45,79.16-182.61,115.97-254.55,98.46-48.02-11.69-83.39-47.1-105.12-105.25l-26.86-71.89c.21-.42.41-.83.62-1.25l654.81-1321.45c67.88-136.98,99.36-301.15,88.64-462.25-11.04-166.03-65.93-311.7-154.54-410.19l-87.97-97.77,404.13-365.81c87.45-79.16,182.61-115.97,254.55-98.46,48.02,11.69,83.39,47.1,105.11,105.25l419.71,1123.26c65.38,174.96-28.57,457.81-205.15,617.64Z"/><path fill="url(#{{ uid }}g14a)" d="M3056.27,2581.67l540.98-489.68-66.89-74.35-66.89-74.34-541.42,490.09c-34.48,31.22-66.75,66.01-96.33,103.64,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77,298.85,799.81c15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81-296.9-794.57c-65.37-174.97,28.58-457.81,205.16-617.65Z"/><path fill="#fff" d="M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-356.23,718.89c-124.39,251.03-101.72,591.81,50.64,761.15l574.59,638.64,18.48-128.96-518.73-576.56ZM3684.81,2189.31l-87.56-97.32-66.89-74.35-66.89-74.34-580.67-645.4c-36.29-40.34-75.92-60.7-118.03-60.7-6.06,0-12.17.42-18.34,1.27-73.35,10.06-148.41,79.17-200.79,184.86l-212.3,428.44,153.87,88.2c114.94,65.89,212.58,187.13,274.93,341.4,33.16,82.06,54.57,168.96,63.58,255.66,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77-105.14,733.41,109,121.15c36.29,40.34,75.92,60.7,118.03,60.7,6.06,0,12.17-.42,18.34-1.27,55.4-7.6,111.78-48.89,158.62-114.18,15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81,572.18-1154.71c105.75-213.42,89.55-511.02-35.38-649.87Z"/><path fill="url(#{{ uid }}g14b)" d="M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-86.92-49.82-358.91,724.31c-67.88,136.98-99.36,301.15-88.64,462.25,11.04,166.02,65.93,311.7,154.54,410.19l628.59,698.66c3.6-15.21,6.59-31.04,8.94-47.42l11.4-79.49,18.48-128.96-518.73-576.56Z"/><path fill="#fff" d="M2624.35,2719.79l-179.41,1251.42-18.48,128.96-11.4,79.49c-2.35,16.38-5.34,32.21-8.94,47.42-22.07,93.22-66.84,162.99-124.06,190.91-18.29,8.93-37.5,13.39-57.54,13.38-28.6,0-58.89-9.09-90.56-27.24l-1040.33-596.3c-162.04-92.88-270.39-370.53-236.59-606.3l209.28-1459.87c16.74-116.76,66.46-205.86,133-238.33,18.3-8.92,37.51-13.38,57.55-13.38,28.6,0,58.88,9.09,90.56,27.24l723.11,414.48,86.92,49.82,86.91,49.82,143.38,82.18c162.05,92.88,270.39,370.53,236.6,606.3Z"/><path fill="url(#{{ uid }}g14c)" d="M2754,3224.73l68.32-476.56c1.39-9.67,2.6-19.4,3.63-29.19l-71.95,505.75Z"/></svg>
|
||||
{%- else -%}
|
||||
<svg viewBox="795 735 4200 4200" xmlns="http://www.w3.org/2000/svg" focusable="false"><defs><mask id="{{ uid }}m" maskUnits="userSpaceOnUse" x="0" y="0" width="5669.29" height="5669.29"><path fill="#fff" d="M3720.19,2839.18l-572.18,1154.71-60.86,122.81-329.71-882.38c-1.19-3.17-2.33-6.37-3.44-9.59l71.95-505.75c42.35-78.96,97.59-152.06,163.21-211.45l541.2-489.89,66.89,74.35,87.56,97.32c124.93,138.85,141.13,436.45,35.38,649.87Z"/><path fill="#fff" d="M4723.87,3339.65l-1093.38,989.71c-87.45,79.16-182.61,115.97-254.55,98.46-48.02-11.69-83.39-47.1-105.12-105.25l-26.86-71.89c.21-.42.41-.83.62-1.25l654.81-1321.45c67.88-136.98,99.36-301.15,88.64-462.25-11.04-166.03-65.93-311.7-154.54-410.19l-87.97-97.77,404.13-365.81c87.45-79.16,182.61-115.97,254.55-98.46,48.02,11.69,83.39,47.1,105.11,105.25l419.71,1123.26c65.38,174.96-28.57,457.81-205.15,617.64Z"/><path fill="#000" d="M3056.27,2581.67l540.98-489.68-66.89-74.35-66.89-74.34-541.42,490.09c-34.48,31.22-66.75,66.01-96.33,103.64,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77,298.85,799.81c15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81-296.9-794.57c-65.37-174.97,28.58-457.81,205.16-617.65Z"/><path fill="#fff" d="M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-356.23,718.89c-124.39,251.03-101.72,591.81,50.64,761.15l574.59,638.64,18.48-128.96-518.73-576.56ZM3684.81,2189.31l-87.56-97.32-66.89-74.35-66.89-74.34-580.67-645.4c-36.29-40.34-75.92-60.7-118.03-60.7-6.06,0-12.17.42-18.34,1.27-73.35,10.06-148.41,79.17-200.79,184.86l-212.3,428.44,153.87,88.2c114.94,65.89,212.58,187.13,274.93,341.4,33.16,82.06,54.57,168.96,63.58,255.66,6.36,61.34,6.52,122.59.23,181.95l-71.95,505.75-29.64,206.77-105.14,733.41,109,121.15c36.29,40.34,75.92,60.7,118.03,60.7,6.06,0,12.17-.42,18.34-1.27,55.4-7.6,111.78-48.89,158.62-114.18,15.18-21.15,29.35-44.82,42.17-70.68l21.77-43.93,60.86-122.81,572.18-1154.71c105.75-213.42,89.55-511.02-35.38-649.87Z"/><path fill="#000" d="M1926.21,3394.65c-124.93-138.85-141.13-436.46-35.38-649.87l353.54-713.47-86.91-49.82-86.92-49.82-358.91,724.31c-67.88,136.98-99.36,301.15-88.64,462.25,11.04,166.02,65.93,311.7,154.54,410.19l628.59,698.66c3.6-15.21,6.59-31.04,8.94-47.42l11.4-79.49,18.48-128.96-518.73-576.56Z"/><path fill="#fff" d="M2624.35,2719.79l-179.41,1251.42-18.48,128.96-11.4,79.49c-2.35,16.38-5.34,32.21-8.94,47.42-22.07,93.22-66.84,162.99-124.06,190.91-18.29,8.93-37.5,13.39-57.54,13.38-28.6,0-58.89-9.09-90.56-27.24l-1040.33-596.3c-162.04-92.88-270.39-370.53-236.59-606.3l209.28-1459.87c16.74-116.76,66.46-205.86,133-238.33,18.3-8.92,37.51-13.38,57.55-13.38,28.6,0,58.88,9.09,90.56,27.24l723.11,414.48,86.92,49.82,86.91,49.82,143.38,82.18c162.05,92.88,270.39,370.53,236.6,606.3Z"/><path fill="#000" d="M2754,3224.73l68.32-476.56c1.39-9.67,2.6-19.4,3.63-29.19l-71.95,505.75Z"/></mask></defs><rect width="5669.29" height="5669.29" fill="currentColor" mask="url(#{{ uid }}m)"/></svg>
|
||||
{%- endif -%}</span>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro logo(uid='pl', tone='color', size=40, variant='lockup') -%}
|
||||
<span class="ps-logo ps-logo--{{ tone }}" role="img" aria-label="ИИ Пресс-секретарь" style="--ps-logo-size: {{ size }}px">
|
||||
{{ mark(uid, tone, size) }}
|
||||
{%- if variant == 'lockup' %}<span class="ps-logo-word" aria-hidden="true"><span class="ps-logo-ai">ИИ</span><span class="ps-logo-name">Пресс-секретарь</span></span>{% endif %}</span>
|
||||
{%- endmacro %}
|
||||
+422
-227
@@ -1,261 +1,456 @@
|
||||
{%- set path = request.url.path -%}
|
||||
{%- set nav = [
|
||||
('/dashboard', 'Главная', 'home', ['/dashboard']),
|
||||
('/generate', 'Создать пост', 'sparkle', ['/generate']),
|
||||
('/plan', 'Контент-план', 'calendar', ['/plan']),
|
||||
('/history', 'Мои посты', 'news', ['/history', '/posts']),
|
||||
('/images', 'Картинки', 'image', ['/images']),
|
||||
('/channels', 'Каналы', 'megaphone', ['/channels']),
|
||||
('/surveys', 'Медиа-образы', 'persona', ['/surveys', '/survey']),
|
||||
('/stats', 'Статистика', 'chart', ['/stats']),
|
||||
('/provider', 'ИИ-провайдеры', 'cpu', ['/provider', '/tenchat']),
|
||||
('/profile/edit', 'Профиль', 'user', ['/profile', '/delete-account']),
|
||||
] -%}
|
||||
{%- set nav_groups = [
|
||||
('', [nav[0]]),
|
||||
('Контент', [nav[1], nav[2], nav[3], nav[4]]),
|
||||
('Бренд и каналы', [nav[6], nav[5], nav[7]]),
|
||||
('Настройки', [nav[8], nav[9]]),
|
||||
] -%}
|
||||
{%- macro is_active(prefixes) -%}{% for p in prefixes %}{% if path == p or path.startswith(p ~ '/') %}1{% endif %}{% endfor %}{%- endmacro -%}
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}Личный кабинет{% endblock %}</title>
|
||||
<link rel="stylesheet" href="/static/style.css?v=3">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>{% block title %}Личный кабинет{% endblock %} · ИИ Пресс-секретарь</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/static/press/app-icon.svg">
|
||||
<link rel="stylesheet" href="/static/press/tokens.css?v=2">
|
||||
<link rel="stylesheet" href="/static/press/components.css?v=4">
|
||||
<link rel="stylesheet" href="/static/style.css?v=20">
|
||||
<script>
|
||||
(function () {
|
||||
function isDark() {
|
||||
return document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
}
|
||||
function setIcon(btn) {
|
||||
if (btn) btn.textContent = isDark() ? '\u2600\uFE0F' : '\uD83C\uDF19';
|
||||
}
|
||||
try {
|
||||
var saved = localStorage.getItem('theme');
|
||||
if (saved !== 'light') {
|
||||
document.documentElement.setAttribute('data-theme', 'dark');
|
||||
}
|
||||
if (saved === 'light' || saved === 'dark') document.documentElement.setAttribute('data-theme', saved);
|
||||
} catch (e) {}
|
||||
document.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('[data-theme-toggle]');
|
||||
if (!btn) return;
|
||||
if (isDark()) {
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
try { localStorage.setItem('theme', 'light'); } catch (e) {}
|
||||
} else {
|
||||
document.documentElement.setAttribute('data-theme', 'dark');
|
||||
try { localStorage.setItem('theme', 'dark'); } catch (e) {}
|
||||
}
|
||||
setIcon(btn);
|
||||
});
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
setIcon(document.querySelector('[data-theme-toggle]'));
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/press/glass.js?v=4" defer></script>
|
||||
<script type="speculationrules">
|
||||
{"prefetch": [{"where": {"and": [{"href_matches": "/*"}, {"not": {"href_matches": "/media/*"}}, {"not": {"href_matches": "/surveys/*/export"}}, {"not": {"href_matches": "/delete-account"}}]}, "eagerness": "moderate"}]}
|
||||
</script>
|
||||
{% block head %}{% endblock %}
|
||||
</head>
|
||||
<body>
|
||||
<aside class="sidebar" id="sidebar">
|
||||
<a class="sidebar-brand" href="{{ '/dashboard' if user else '/login' }}">
|
||||
<svg class="sidebar-brand-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||
<span>ИИ Пресс-секретарь</span>
|
||||
</a>
|
||||
|
||||
{% if user %}
|
||||
<nav class="sidebar-nav">
|
||||
<a href="/dashboard" class="sidebar-link {% if request.path == '/dashboard' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
|
||||
<span>Главная</span>
|
||||
</a>
|
||||
<a href="/generate" class="sidebar-link {% if request.path == '/generate' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
|
||||
<span>Создать пост</span>
|
||||
</a>
|
||||
<a href="/plan" class="sidebar-link {% if request.path == '/plan' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
|
||||
<span>План</span>
|
||||
</a>
|
||||
<a href="/history" class="sidebar-link {% if request.path == '/history' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
|
||||
<span>Мои посты</span>
|
||||
</a>
|
||||
<a href="/images" class="sidebar-link {% if request.path == '/images' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
|
||||
<span>Картинки</span>
|
||||
</a>
|
||||
<a href="/channels" class="sidebar-link {% if request.path == '/channels' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z"/></svg>
|
||||
<span>Каналы</span>
|
||||
</a>
|
||||
<a href="/surveys" class="sidebar-link {% if '/surveys' in request.path %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><path d="M9 14l2 2 4-4"/></svg>
|
||||
<span>Медиа-образы</span>
|
||||
</a>
|
||||
<a href="/stats" class="sidebar-link {% if request.path == '/stats' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
|
||||
<span>Статистика</span>
|
||||
</a>
|
||||
|
||||
<div class="sidebar-divider"></div>
|
||||
|
||||
<a href="/provider" class="sidebar-link {% if request.path == '/provider' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2" ry="2"/><rect x="9" y="9" width="6" height="6"/><line x1="9" y1="1" x2="9" y2="4"/><line x1="15" y1="1" x2="15" y2="4"/><line x1="9" y1="20" x2="9" y2="23"/><line x1="15" y1="20" x2="15" y2="23"/><line x1="20" y1="9" x2="23" y2="9"/><line x1="20" y1="14" x2="23" y2="14"/><line x1="1" y1="9" x2="4" y2="9"/><line x1="1" y1="14" x2="4" y2="14"/></svg>
|
||||
<span>ИИ</span>
|
||||
</a>
|
||||
<a href="/profile/edit" class="sidebar-link {% if request.path == '/profile/edit' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
|
||||
<span>Профиль</span>
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-footer">
|
||||
<button type="button" class="sidebar-link" data-theme-toggle aria-label="Переключить тему">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
|
||||
<span>Тема</span>
|
||||
</button>
|
||||
<form action="/logout" method="post" class="sidebar-form">
|
||||
<button type="submit" class="sidebar-link">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
|
||||
<span>Выйти</span>
|
||||
</button>
|
||||
</form>
|
||||
<body class="{% if user %}is-cabinet{% else %}is-auth{% endif %}">
|
||||
{% if user %}
|
||||
<div class="ps-shell app-shell">
|
||||
<nav class="ps-sidenav app-sidenav app-glass" aria-label="Разделы кабинета">
|
||||
<a class="ps-sidenav-logo app-logo-link" href="/dashboard">{{ ui.logo('navlogo', 'color', 32) }}</a>
|
||||
<div class="app-nav" data-nav>
|
||||
<span class="app-nav-indicator" aria-hidden="true"></span>
|
||||
{% for caption, items in nav_groups %}
|
||||
<div class="app-nav-section">
|
||||
{% if caption %}<div class="app-nav-caption" id="navg{{ loop.index }}">{{ caption }}</div>{% endif %}
|
||||
<ul class="app-nav-group"{% if caption %} aria-labelledby="navg{{ loop.index }}"{% endif %}>
|
||||
{% for href, label, icon, prefixes in items %}
|
||||
{% set active = is_active(prefixes) %}
|
||||
<li><a href="{{ href }}" data-prefixes="{{ prefixes | join(' ') }}" class="ps-sidenav-item{% if active %} is-active{% endif %}"{% if active %} aria-current="page"{% endif %}>{{ ui.icon(icon, 20) }}<span>{{ label }}</span></a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<nav class="sidebar-nav">
|
||||
<a href="/login" class="sidebar-link {% if request.path == '/login' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>
|
||||
<span>Вход</span>
|
||||
<div class="app-sidenav-foot">
|
||||
<ul class="ps-sidenav-list">
|
||||
<li><button type="button" class="ps-sidenav-item" data-theme-toggle>{{ ui.icon('theme', 20) }}<span data-theme-label>Тема</span></button></li>
|
||||
<li><form action="/logout" method="post" class="inline-form">
|
||||
<button type="submit" class="ps-sidenav-item">{{ ui.icon('logout', 20) }}<span>Выйти</span></button>
|
||||
</form></li>
|
||||
</ul>
|
||||
{% if active_persona %}
|
||||
<a class="ps-sidenav-persona" href="/surveys/{{ active_persona.id }}">
|
||||
<span class="ps-sidenav-persona-icon" aria-hidden="true">{{ ui.icon('persona', 18) }}</span>
|
||||
<span class="ps-sidenav-persona-text">
|
||||
<span class="ps-sidenav-persona-cap">Активный медиа-образ</span>
|
||||
<span class="ps-sidenav-persona-name">{{ active_persona.title }}</span>
|
||||
</span>
|
||||
{{ ui.icon('chevron-right', 16) }}
|
||||
</a>
|
||||
<a href="/register" class="sidebar-link {% if request.path == '/register' %}active{% endif %}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="8.5" cy="7" r="4"/><line x1="20" y1="8" x2="20" y2="14"/><line x1="23" y1="11" x2="17" y2="11"/></svg>
|
||||
<span>Регистрация</span>
|
||||
{% else %}
|
||||
<a class="ps-sidenav-persona" href="/survey">
|
||||
<span class="ps-sidenav-persona-icon" aria-hidden="true">{{ ui.icon('plus', 18) }}</span>
|
||||
<span class="ps-sidenav-persona-text">
|
||||
<span class="ps-sidenav-persona-cap">Медиа-образа пока нет</span>
|
||||
<span class="ps-sidenav-persona-name">Создать медиа-образ</span>
|
||||
</span>
|
||||
{{ ui.icon('chevron-right', 16) }}
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-footer">
|
||||
<button type="button" class="sidebar-link" data-theme-toggle aria-label="Переключить тему">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
|
||||
<span>Тема</span>
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</aside>
|
||||
</nav>
|
||||
|
||||
<button class="sidebar-toggle" id="sidebarToggle" aria-label="Меню">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
|
||||
</button>
|
||||
<div class="app-body">
|
||||
<header class="app-topbar app-glass">
|
||||
<a href="/dashboard" class="app-logo-link">{{ ui.logo('toplogo', 'color', 28) }}</a>
|
||||
<button type="button" class="ps-iconbtn" data-theme-toggle aria-label="Сменить тему">{{ ui.icon('theme', 22) }}</button>
|
||||
</header>
|
||||
|
||||
<main class="main-content">
|
||||
{% if flash_message %}
|
||||
<div class="flash">{{ flash_message }}</div>
|
||||
{% endif %}
|
||||
{% if errors %}
|
||||
<div class="errors">
|
||||
<ul>
|
||||
{% for error in errors %}
|
||||
<li>{{ error }}</li>
|
||||
<div class="app-compactbar" data-compactbar aria-hidden="true"><span class="app-compactbar-title">{{ self.title() }}</span></div>
|
||||
<main class="ps-main app-main" id="main">
|
||||
{% if errors %}
|
||||
<div class="app-alert" role="alert">
|
||||
<span class="app-alert-icon">{{ ui.icon('alert', 18) }}</span>
|
||||
<ul>{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{%- set tab_more_active = not (is_active(['/dashboard']) or is_active(['/generate']) or is_active(['/plan']) or is_active(['/history', '/posts'])) %}
|
||||
<nav class="ps-tabbar app-tabbar app-glass" aria-label="Разделы" data-tabs>
|
||||
<span class="app-tab-indicator" aria-hidden="true"></span>
|
||||
<a href="/dashboard" data-prefixes="/dashboard" class="ps-tab{% if is_active(['/dashboard']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('home', 24) }}</span><span class="ps-tab-label">Главная</span></a>
|
||||
<a href="/generate" data-prefixes="/generate" class="ps-tab{% if is_active(['/generate']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('sparkle', 24) }}</span><span class="ps-tab-label">Создать</span></a>
|
||||
<a href="/plan" data-prefixes="/plan" class="ps-tab{% if is_active(['/plan']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('calendar', 24) }}</span><span class="ps-tab-label">План</span></a>
|
||||
<a href="/history" data-prefixes="/history /posts" class="ps-tab{% if is_active(['/history', '/posts']) %} is-active" aria-current="page{% endif %}"><span class="ps-tab-icon">{{ ui.icon('news', 24) }}</span><span class="ps-tab-label">Посты</span></a>
|
||||
<button type="button" class="ps-tab{% if tab_more_active %} is-active{% endif %}" data-sheet-open="moreSheet" aria-haspopup="dialog" aria-expanded="false" aria-controls="moreSheet"><span class="ps-tab-icon">{{ ui.icon('grid', 24) }}</span><span class="ps-tab-label">Ещё</span></button>
|
||||
</nav>
|
||||
|
||||
<div class="app-sheet" id="moreSheet" role="dialog" aria-modal="true" aria-label="Все разделы" hidden>
|
||||
<div class="app-sheet-scrim" data-sheet-close></div>
|
||||
<div class="app-sheet-panel app-glass">
|
||||
<div class="app-sheet-head">
|
||||
<h2 class="ps-h2">Разделы</h2>
|
||||
<button type="button" class="ps-iconbtn" data-sheet-close aria-label="Закрыть">{{ ui.icon('close', 22) }}</button>
|
||||
</div>
|
||||
<ul class="ps-sidenav-list">
|
||||
{% for href, label, icon, prefixes in nav[4:] %}
|
||||
<li><a href="{{ href }}" class="ps-sidenav-item{% if is_active(prefixes) %} is-active" aria-current="page{% endif %}">{{ ui.icon(icon, 20) }}<span>{{ label }}</span></a></li>
|
||||
{% endfor %}
|
||||
<li><form action="/logout" method="post" class="inline-form">
|
||||
<button type="submit" class="ps-sidenav-item">{{ ui.icon('logout', 20) }}<span>Выйти</span></button>
|
||||
</form></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="app-auth">
|
||||
<a href="/" class="app-auth-logo">{{ ui.logo('authlogo', 'white', 44) }}</a>
|
||||
<main class="app-auth-card" id="main">
|
||||
{% if errors %}
|
||||
<div class="app-alert" role="alert">
|
||||
<span class="app-alert-icon">{{ ui.icon('alert', 18) }}</span>
|
||||
<ul>{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% block content %}{% endblock %}
|
||||
{{ self.content() }}
|
||||
</main>
|
||||
<button type="button" class="ps-btn ps-btn--glass ps-btn--sm app-auth-theme" data-theme-toggle>{{ ui.icon('theme', 16) }}<span data-theme-label>Тема</span></button>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var toggle = document.getElementById('sidebarToggle');
|
||||
var sidebar = document.getElementById('sidebar');
|
||||
if (toggle && sidebar) {
|
||||
toggle.addEventListener('click', function () {
|
||||
sidebar.classList.toggle('open');
|
||||
{%- set flash_text = (flash_message or '') | replace('❌', '') | replace('✅', '') | replace('⚠️', '') | trim -%}
|
||||
{%- set flash_low = flash_text | lower -%}
|
||||
{%- set flash_bad = flash_text and ('ошибк' in flash_low or 'не удалось' in flash_low or 'недопустим' in flash_low or 'не подключ' in flash_low or 'не найден' in flash_low) -%}
|
||||
<div class="app-toasts" id="toasts" aria-live="polite">
|
||||
{% if flash_text %}
|
||||
<div class="ps-toast app-glass ps-toast--{{ 'danger' if flash_bad else 'success' }}" role="{{ 'alert' if flash_bad else 'status' }}" data-autoclose{% if flash_bad %} data-humanize{% endif %}>
|
||||
<span class="ps-toast-icon" aria-hidden="true">{{ ui.icon('alert' if flash_bad else 'check', 18) }}</span>
|
||||
<div class="ps-toast-text"><p class="ps-toast-title">{{ flash_text }}</p></div>
|
||||
<button type="button" class="ps-iconbtn" data-toast-close aria-label="Закрыть уведомление">{{ ui.icon('close', 18) }}</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{# Подтверждение удаления — лист, а не системное окно. Текст берётся из data-confirm формы. #}
|
||||
<div class="app-sheet" id="confirmSheet" role="alertdialog" aria-modal="true" aria-labelledby="confirmTitle" aria-describedby="confirmBody" hidden>
|
||||
<div class="app-sheet-scrim" data-sheet-close></div>
|
||||
<div class="app-sheet-panel app-glass app-confirm">
|
||||
<span class="ps-empty-icon app-confirm-icon" aria-hidden="true">{{ ui.icon('trash', 28) }}</span>
|
||||
<h2 class="ps-h2" id="confirmTitle"></h2>
|
||||
<p class="app-muted" id="confirmBody"></p>
|
||||
<div class="app-actions app-confirm-actions">
|
||||
<button type="button" class="ps-btn ps-btn--danger" data-confirm-ok>{{ ui.icon('trash', 20) }}<span class="ps-btn-label">Удалить</span></button>
|
||||
<button type="button" class="ps-btn ps-btn--quiet" data-sheet-close><span class="ps-btn-label">Оставить</span></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template id="tpl-thinking"><div class="ps-thinking" role="status" aria-live="polite"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span data-label></span></div></template>
|
||||
<template id="tpl-icon-check">{{ ui.icon('check', 18) }}</template>
|
||||
<template id="tpl-icon-alert">{{ ui.icon('alert', 18) }}</template>
|
||||
<template id="tpl-icon-close">{{ ui.icon('close', 18) }}</template>
|
||||
<template id="tpl-icon-sparkle">{{ ui.icon('sparkle', 18) }}</template>
|
||||
|
||||
<script>
|
||||
window.Press = window.Press || {};
|
||||
|
||||
/* === Склонение по числу: Press.plural(3, ['идея', 'идеи', 'идей']) === */
|
||||
Press.plural = function (n, forms) {
|
||||
var a = Math.abs(n) % 100, b = a % 10;
|
||||
if (a > 10 && a < 20) return forms[2];
|
||||
if (b > 1 && b < 5) return forms[1];
|
||||
if (b === 1) return forms[0];
|
||||
return forms[2];
|
||||
};
|
||||
|
||||
/* === Тосты: цвет по смыслу, пауза на наведении и фокусе === */
|
||||
function armToast(el) {
|
||||
var left = 5000, started = Date.now(), timer = null;
|
||||
function run() { started = Date.now(); timer = setTimeout(function () { el.remove(); }, left); }
|
||||
function pause() { if (timer) { clearTimeout(timer); timer = null; left -= Date.now() - started; } }
|
||||
el.addEventListener('mouseenter', pause); el.addEventListener('focusin', pause);
|
||||
el.addEventListener('mouseleave', function () { if (!el.contains(document.activeElement)) run(); });
|
||||
el.addEventListener('focusout', function (e) { if (!el.contains(e.relatedTarget)) run(); });
|
||||
run();
|
||||
}
|
||||
Press.toast = function (title, tone, body) {
|
||||
tone = tone || 'success';
|
||||
var wrap = document.getElementById('toasts');
|
||||
var el = document.createElement('div');
|
||||
el.className = 'ps-toast app-glass ps-toast--' + tone;
|
||||
el.setAttribute('role', tone === 'danger' ? 'alert' : 'status');
|
||||
var iconId = tone === 'danger' || tone === 'warning' ? 'tpl-icon-alert' : tone === 'ai' ? 'tpl-icon-sparkle' : 'tpl-icon-check';
|
||||
el.innerHTML = '<span class="ps-toast-icon" aria-hidden="true">' + document.getElementById(iconId).innerHTML + '</span>' +
|
||||
'<div class="ps-toast-text"><p class="ps-toast-title"></p>' + (body ? '<p class="ps-toast-body"></p>' : '') + '</div>' +
|
||||
'<button type="button" class="ps-iconbtn" data-toast-close aria-label="Закрыть уведомление">' + document.getElementById('tpl-icon-close').innerHTML + '</button>';
|
||||
el.querySelector('.ps-toast-title').textContent = title;
|
||||
if (body) el.querySelector('.ps-toast-body').textContent = body;
|
||||
wrap.appendChild(el);
|
||||
armToast(el);
|
||||
};
|
||||
|
||||
/* === Технические ошибки → «что случилось и что сделать» === */
|
||||
Press.humanError = function (msg) {
|
||||
msg = String(msg || '');
|
||||
if (/\b(401|403)\b|Unauthorized|Forbidden|invalid.*key|api key/i.test(msg))
|
||||
return 'Провайдер ИИ не принял ключ. Проверьте ключ в разделе «ИИ-провайдеры».';
|
||||
if (/\b429\b|rate limit|too many/i.test(msg))
|
||||
return 'Слишком много запросов к провайдеру ИИ. Подождите минуту и повторите.';
|
||||
if (/timed? ?out|timeout/i.test(msg))
|
||||
return 'Провайдер ИИ не ответил вовремя. Попробуйте ещё раз через минуту.';
|
||||
if (/\b(500|502|503|504)\b|Bad Gateway|Service Unavailable/i.test(msg))
|
||||
return 'Сервис сейчас недоступен. Повторите через минуту.';
|
||||
if (/ProxyError|Max retries|ConnectionError|Failed to establish|Failed to fetch|NetworkError|Load failed/i.test(msg))
|
||||
return 'Нет связи с сервером. Проверьте интернет и повторите.';
|
||||
return msg || 'Не получилось выполнить действие. Повторите через минуту — если не поможет, проверьте раздел «ИИ-провайдеры».';
|
||||
};
|
||||
document.querySelectorAll('[data-humanize] .ps-toast-title').forEach(function (t) { t.textContent = Press.humanError(t.textContent); });
|
||||
document.querySelectorAll('[data-autoclose]').forEach(armToast);
|
||||
|
||||
/* === Запросы к API: истёкшая сессия и не-JSON — понятной ошибкой === */
|
||||
Press.SESSION = 'session-expired';
|
||||
Press.sessionExpired = function () {
|
||||
if (Press._sessionShown) return; Press._sessionShown = true;
|
||||
Press.toast('Сессия истекла', 'warning', 'Войдите заново — открываю страницу входа.');
|
||||
setTimeout(function () { location.href = '/login'; }, 2500);
|
||||
};
|
||||
Press.fetchJSON = function (url, opts) {
|
||||
return fetch(url, Object.assign({ credentials: 'same-origin', headers: { 'Accept': 'application/json' } }, opts || {}))
|
||||
.then(function (r) {
|
||||
if (r.redirected && /\/login(\?|$)/.test(r.url)) { Press.sessionExpired(); throw new Error(Press.SESSION); }
|
||||
var ct = r.headers.get('content-type') || '';
|
||||
if (ct.indexOf('json') < 0) throw new Error('Сервер ответил не так, как ожидалось (' + r.status + '). Обновите страницу и повторите.');
|
||||
return r.json().then(function (d) {
|
||||
if (!r.ok && d && !d.error) d.error = d.detail || ('Ошибка ' + r.status);
|
||||
return d;
|
||||
});
|
||||
document.addEventListener('click', function (e) {
|
||||
if (sidebar.classList.contains('open') && !sidebar.contains(e.target) && e.target !== toggle) {
|
||||
sidebar.classList.remove('open');
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
function copyText(text, btn) {
|
||||
function done(ok) {
|
||||
if (!btn) return;
|
||||
var old = btn.textContent;
|
||||
btn.textContent = ok ? '\u2705 \u0421\u043a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u043e' : '\u274c \u041e\u0448\u0438\u0431\u043a\u0430';
|
||||
setTimeout(function () { btn.textContent = old; }, 1500);
|
||||
}
|
||||
function fallback() {
|
||||
var ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
var ok = false;
|
||||
try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
|
||||
document.body.removeChild(ta);
|
||||
done(ok);
|
||||
}
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.writeText(text).then(function () { done(true); }, fallback);
|
||||
} else {
|
||||
fallback();
|
||||
})
|
||||
.catch(function (err) {
|
||||
if (err.message === Press.SESSION) throw err;
|
||||
if (err instanceof TypeError) throw new Error('Нет связи с сервером. Проверьте интернет и повторите.');
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
/* Опрос фоновой задачи: не дольше 5 минут; всё, кроме «в работе» и «готово с результатом», — ошибка */
|
||||
Press.pollTask = function (taskId, cb, startedAt) {
|
||||
startedAt = startedAt || Date.now();
|
||||
if (Date.now() - startedAt > 5 * 60 * 1000) {
|
||||
cb.fail('Ответ не пришёл за 5 минут. Повторите — возможно, провайдер ИИ перегружен.');
|
||||
return;
|
||||
}
|
||||
Press.fetchJSON('/api/tasks/' + taskId)
|
||||
.then(function (data) {
|
||||
if (data.status === 'running' || data.status === 'pending') {
|
||||
setTimeout(function () { Press.pollTask(taskId, cb, startedAt); }, 1500);
|
||||
} else if (data.status === 'done' && data.result) {
|
||||
cb.done(data.result);
|
||||
} else if (data.status === 'error') {
|
||||
cb.fail(data.error || 'Не получилось. Проверьте настройки в разделе «ИИ-провайдеры».');
|
||||
} else {
|
||||
cb.fail(data.error || 'Задача не найдена или завершилась без результата. Повторите.');
|
||||
}
|
||||
})
|
||||
.catch(function (err) { if (err.message !== Press.SESSION) cb.fail(err.message); });
|
||||
};
|
||||
|
||||
/* === Листы: фокус внутрь, Tab не выходит наружу, после закрытия — обратно на кнопку === */
|
||||
var sheetOpener = null;
|
||||
function focusables(root) {
|
||||
return Array.prototype.slice.call(root.querySelectorAll('a[href], button:not(:disabled), input:not(:disabled), select, textarea, [tabindex]:not([tabindex="-1"])'))
|
||||
.filter(function (el) { return el.offsetParent !== null; });
|
||||
}
|
||||
Press.openSheet = function (sheet, opener) {
|
||||
sheetOpener = opener || document.activeElement;
|
||||
sheet.hidden = false;
|
||||
if (opener) opener.setAttribute('aria-expanded', 'true');
|
||||
var f = focusables(sheet.querySelector('.app-sheet-panel'));
|
||||
if (f.length) f[0].focus();
|
||||
};
|
||||
Press.closeSheet = function (sheet) {
|
||||
sheet.hidden = true;
|
||||
if (sheetOpener) { sheetOpener.setAttribute('aria-expanded', 'false'); if (document.contains(sheetOpener)) sheetOpener.focus(); }
|
||||
sheetOpener = null;
|
||||
};
|
||||
|
||||
/* === Подтверждение удаления: форма с data-confirm открывает лист === */
|
||||
var pendingForm = null;
|
||||
document.addEventListener('submit', function (e) {
|
||||
var form = e.target;
|
||||
if (!form.hasAttribute('data-confirm') || form.dataset.confirmed === '1') return;
|
||||
e.preventDefault();
|
||||
pendingForm = form;
|
||||
var sheet = document.getElementById('confirmSheet');
|
||||
document.getElementById('confirmTitle').textContent = form.getAttribute('data-confirm');
|
||||
document.getElementById('confirmBody').textContent = form.getAttribute('data-confirm-body') || 'Вернуть будет нельзя.';
|
||||
sheet.querySelector('[data-confirm-ok] .ps-btn-label').textContent = form.getAttribute('data-confirm-ok') || 'Удалить';
|
||||
Press.openSheet(sheet, form.querySelector('button[type="submit"]') || e.submitter);
|
||||
/* Фокус — на безопасное «Оставить»: случайный Enter ничего не удаляет */
|
||||
sheet.querySelector('.app-confirm-actions [data-sheet-close]').focus();
|
||||
sheet.querySelector('[data-confirm-ok]').disabled = false;
|
||||
}, true);
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var c = e.target.closest('[data-toast-close]');
|
||||
if (c) { c.closest('.ps-toast').remove(); return; }
|
||||
var ok = e.target.closest('[data-confirm-ok]');
|
||||
if (ok && pendingForm) {
|
||||
var form = pendingForm; pendingForm = null;
|
||||
form.dataset.confirmed = '1';
|
||||
ok.disabled = true;
|
||||
HTMLFormElement.prototype.submit.call(form);
|
||||
return;
|
||||
}
|
||||
var o = e.target.closest('[data-sheet-open]');
|
||||
if (o) { var s = document.getElementById(o.getAttribute('data-sheet-open')); if (s) Press.openSheet(s, o); return; }
|
||||
var x = e.target.closest('[data-sheet-close]');
|
||||
if (x) { pendingForm = null; Press.closeSheet(x.closest('.app-sheet')); return; }
|
||||
/* Карточки выбора (ChoiceGroup) поверх обычного radio */
|
||||
var ch = e.target.closest('.ps-choice[data-value]');
|
||||
if (ch && !ch.disabled) {
|
||||
var grid = ch.closest('[role="radiogroup"]');
|
||||
grid.querySelectorAll('.ps-choice').forEach(function (b) {
|
||||
var on = b === ch;
|
||||
b.classList.toggle('is-selected', on);
|
||||
b.setAttribute('aria-checked', on ? 'true' : 'false');
|
||||
b.tabIndex = on ? 0 : -1;
|
||||
});
|
||||
var input = document.getElementById(grid.getAttribute('data-input'));
|
||||
if (input) { input.value = ch.getAttribute('data-value'); input.dispatchEvent(new Event('change', { bubbles: true })); }
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', function (e) {
|
||||
var open = document.querySelector('.app-sheet:not([hidden])');
|
||||
if (open) {
|
||||
if (e.key === 'Escape') { pendingForm = null; Press.closeSheet(open); return; }
|
||||
if (e.key === 'Tab') {
|
||||
var f = focusables(open.querySelector('.app-sheet-panel'));
|
||||
if (!f.length) return;
|
||||
var first = f[0], last = f[f.length - 1];
|
||||
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
|
||||
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
|
||||
else if (!open.contains(document.activeElement)) { e.preventDefault(); first.focus(); }
|
||||
return;
|
||||
}
|
||||
}
|
||||
document.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('[data-copy-target]');
|
||||
if (!btn) return;
|
||||
var el = document.getElementById(btn.getAttribute('data-copy-target'));
|
||||
if (el) copyText(el.textContent, btn);
|
||||
});
|
||||
/* Стрелки в группах выбора: карточки выбора и шаблоны картинок */
|
||||
var grid = e.target.closest && e.target.closest('[role="radiogroup"].ps-choices-grid, [role="radiogroup"].ps-presets');
|
||||
if (!grid) return;
|
||||
var d = (e.key === 'ArrowRight' || e.key === 'ArrowDown') ? 1 : (e.key === 'ArrowLeft' || e.key === 'ArrowUp') ? -1 : 0;
|
||||
if (!d) return;
|
||||
e.preventDefault();
|
||||
var items = Array.prototype.slice.call(grid.querySelectorAll('.ps-choice:not(:disabled), .ps-preset:not(:disabled)'));
|
||||
var i = items.indexOf(e.target.closest('.ps-choice, .ps-preset'));
|
||||
var next = items[(i + d + items.length) % items.length];
|
||||
next.click(); next.focus();
|
||||
});
|
||||
|
||||
/* === Background Task Engine === */
|
||||
window.TaskEngine = {
|
||||
start: function(formEl, opts) {
|
||||
var fd = new FormData(formEl);
|
||||
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
|
||||
var resultEl = document.getElementById(opts.resultId || 'taskResult');
|
||||
var formContainer = document.getElementById(opts.formId || 'taskForm');
|
||||
var btn = formEl.querySelector('button[type="submit"]');
|
||||
var errEl = document.getElementById(opts.errorId || 'taskError');
|
||||
function copyText(text, btn) {
|
||||
function done(ok) {
|
||||
Press.toast(ok ? 'Скопировано' : 'Не удалось скопировать', ok ? 'success' : 'danger', ok ? '' : 'Выделите текст и скопируйте вручную (Ctrl+C).');
|
||||
}
|
||||
function fallback() {
|
||||
var ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.style.position = 'fixed';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
var ok = false;
|
||||
try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
|
||||
document.body.removeChild(ta);
|
||||
done(ok);
|
||||
}
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.writeText(text).then(function () { done(true); }, fallback);
|
||||
} else {
|
||||
fallback();
|
||||
}
|
||||
}
|
||||
document.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('[data-copy-target]');
|
||||
if (!btn) return;
|
||||
var el = document.getElementById(btn.getAttribute('data-copy-target'));
|
||||
if (el) copyText(el.textContent, btn);
|
||||
});
|
||||
|
||||
// Hide form, show loader
|
||||
if (formContainer) formContainer.style.display = 'none';
|
||||
if (resultEl) resultEl.style.display = 'none';
|
||||
if (errEl) { errEl.style.display = 'none'; errEl.textContent = ''; }
|
||||
if (loaderEl) loaderEl.style.display = 'flex';
|
||||
/* === Фоновые задачи страниц: создать пост, план, картинка === */
|
||||
window.TaskEngine = {
|
||||
start: function(formEl, opts) {
|
||||
if (opts._busy) return;
|
||||
opts._busy = true;
|
||||
var fd = new FormData(formEl);
|
||||
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
|
||||
var resultEl = document.getElementById(opts.resultId || 'taskResult');
|
||||
var formContainer = document.getElementById(opts.formId || 'taskForm');
|
||||
var errEl = document.getElementById(opts.errorId || 'taskError');
|
||||
|
||||
fetch('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.status === 'error' || data.error) {
|
||||
if (formContainer && !opts.keepForm) formContainer.style.display = 'none';
|
||||
if (resultEl) resultEl.style.display = 'none';
|
||||
if (errEl) { errEl.style.display = 'none'; errEl.textContent = ''; }
|
||||
if (loaderEl) loaderEl.style.display = 'flex';
|
||||
if (opts.onStart) opts.onStart();
|
||||
|
||||
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function(data) {
|
||||
if (!data.task_id) { TaskEngine.fail(opts, data.error || 'Не удалось запустить задачу. Повторите.'); return; }
|
||||
Press.pollTask(data.task_id, {
|
||||
done: function (result) {
|
||||
opts._busy = false;
|
||||
if (loaderEl) loaderEl.style.display = 'none';
|
||||
if (formContainer) formContainer.style.display = '';
|
||||
if (errEl) { errEl.style.display = 'block'; errEl.textContent = data.error || 'Ошибка запуска задачи'; }
|
||||
return;
|
||||
}
|
||||
TaskEngine.poll(data.task_id, opts);
|
||||
})
|
||||
.catch(function(err) {
|
||||
if (loaderEl) loaderEl.style.display = 'none';
|
||||
if (formContainer) formContainer.style.display = '';
|
||||
if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Ошибка сети: ' + err.message; }
|
||||
if (opts.onEnd) opts.onEnd(true);
|
||||
if (opts.onDone) opts.onDone(result);
|
||||
},
|
||||
fail: function (msg) { TaskEngine.fail(opts, msg); }
|
||||
});
|
||||
},
|
||||
poll: function(taskId, opts) {
|
||||
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
|
||||
var resultEl = document.getElementById(opts.resultId || 'taskResult');
|
||||
var formContainer = document.getElementById(opts.formId || 'taskForm');
|
||||
var errEl = document.getElementById(opts.errorId || 'taskError');
|
||||
|
||||
fetch('/api/tasks/' + taskId)
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.status === 'running' || data.status === 'pending') {
|
||||
setTimeout(function() { TaskEngine.poll(taskId, opts); }, 1500);
|
||||
return;
|
||||
}
|
||||
if (loaderEl) loaderEl.style.display = 'none';
|
||||
|
||||
if (data.status === 'error') {
|
||||
if (formContainer) formContainer.style.display = '';
|
||||
if (errEl) { errEl.style.display = 'block'; errEl.textContent = data.error || 'Ошибка генерации'; }
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.status === 'done' && opts.onDone) {
|
||||
opts.onDone(data.result || {});
|
||||
}
|
||||
})
|
||||
.catch(function(err) {
|
||||
if (loaderEl) loaderEl.style.display = 'none';
|
||||
if (formContainer) formContainer.style.display = '';
|
||||
if (errEl) { errEl.style.display = 'block'; errEl.textContent = 'Ошибка сети: ' + err.message; }
|
||||
});
|
||||
}
|
||||
};
|
||||
</script>
|
||||
})
|
||||
.catch(function(err) { if (err.message !== Press.SESSION) TaskEngine.fail(opts, err.message); else opts._busy = false; });
|
||||
},
|
||||
fail: function(opts, message) {
|
||||
opts._busy = false;
|
||||
var loaderEl = document.getElementById(opts.loaderId || 'taskLoader');
|
||||
var formContainer = document.getElementById(opts.formId || 'taskForm');
|
||||
var errEl = document.getElementById(opts.errorId || 'taskError');
|
||||
if (loaderEl) loaderEl.style.display = 'none';
|
||||
if (formContainer) formContainer.style.display = '';
|
||||
if (errEl) { errEl.style.display = 'flex'; errEl.textContent = Press.humanError(message); errEl.title = message; }
|
||||
if (opts.onEnd) opts.onEnd(false);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,19 +1,48 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Добавить канал — Личный кабинет{% endblock %}
|
||||
{% block title %}Добавить канал{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Добавить канал</h1>
|
||||
<div class="card">
|
||||
<p class="form-hint">
|
||||
Введите <strong>@username</strong> канала/чата или числовой ID.<br>
|
||||
Бот должен быть добавлен в админы канала, иначе публикация не сработает.
|
||||
</p>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/channels" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">Каналы</span></a>
|
||||
<h1 class="ps-h1">Добавить канал</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ps-split" style="--ps-aside: 340px">
|
||||
{% if verify %}
|
||||
<form method="post" action="/channels/verify" class="ps-panel app-form">
|
||||
<h2 class="ps-h2">Подтвердите, что канал ваш</h2>
|
||||
<p>Бот — администратор в «{{ verify.title }}». Осталось подтвердить, что канал принадлежит вам: добавьте код в описание канала в Telegram и сохраните.</p>
|
||||
<div class="ps-field">
|
||||
<label for="verify_code" class="ps-field-label">Код для описания</label>
|
||||
<input id="verify_code" class="ps-field-control" type="text" value="{{ verify.code }}" readonly onfocus="this.select()">
|
||||
<p class="ps-field-hint"><span>После проверки код можно удалить из описания.</span></p>
|
||||
</div>
|
||||
<div class="app-actions">
|
||||
<button type="submit" class="ps-btn ps-btn--primary">{{ ui.icon('check', 20) }}<span class="ps-btn-label">Проверить код</span></button>
|
||||
<a href="/channels/add" class="ps-btn ps-btn--quiet"><span class="ps-btn-label">Другой канал</span></a>
|
||||
</div>
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="post" action="/channels/add" class="ps-panel app-form">
|
||||
<div class="ps-field{% if errors %} is-error{% endif %}">
|
||||
<label for="chat_input" class="ps-field-label">@username или ID</label>
|
||||
<input id="chat_input" class="ps-field-control" type="text" name="chat_input" value="{{ form.chat_input if form else '' }}"
|
||||
placeholder="@my_channel или -1001234567890" aria-describedby="chat-hint" required>
|
||||
<p id="chat-hint" class="ps-field-hint">{% if errors %}{{ ui.icon('alert', 16) }}{% endif %}<span>Например: @teplyhleb_dn или -1001234567890</span></p>
|
||||
</div>
|
||||
<button type="submit" class="ps-btn ps-btn--primary">{{ ui.icon('check', 20) }}<span class="ps-btn-label">Проверить и добавить</span></button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
<aside class="ps-panel">
|
||||
<h2 class="ps-h2">Перед добавлением</h2>
|
||||
<ol class="app-stack" style="margin:0; padding-left: 20px; color: var(--ink-secondary)">
|
||||
<li>Откройте канал или чат в Telegram.</li>
|
||||
<li>Добавьте бота в администраторы с правом публиковать сообщения.</li>
|
||||
<li>Вставьте @username канала или его числовой ID и нажмите «Проверить и добавить».</li>
|
||||
<li>Добавьте выданный код в описание канала — так мы убедимся, что канал ваш.</li>
|
||||
</ol>
|
||||
</aside>
|
||||
</div>
|
||||
<form method="post" action="/channels/add" class="form">
|
||||
<label>@username или ID
|
||||
<input type="text" name="chat_input" value="{{ form.chat_input if form else '' }}"
|
||||
placeholder="@my_channel или -1001234567890" required>
|
||||
</label>
|
||||
<button type="submit">Проверить и добавить</button>
|
||||
</form>
|
||||
<p><a href="/channels">← Назад к каналам</a></p>
|
||||
{% endblock %}
|
||||
@@ -1,37 +1,42 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Каналы публикации — Личный кабинет{% endblock %}
|
||||
{% block title %}Каналы{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Каналы публикации</h1>
|
||||
<p class="form-hint">Добавьте Telegram-каналы и чаты, куда бот будет публиковать посты. Бот должен быть админом в канале.</p>
|
||||
|
||||
<div class="grid">
|
||||
<a class="tile" href="/channels/add">➕ Добавить канал</a>
|
||||
{%- set chat_types = {'channel': 'Канал', 'group': 'Группа', 'supergroup': 'Супергруппа', 'private': 'Личный чат'} -%}
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Каналы</h1>
|
||||
<p class="ps-lead">Telegram-каналы и чаты, куда публикуются посты. Бот должен быть в них администратором.</p>
|
||||
</div>
|
||||
<a href="/channels/add" class="ps-btn ps-btn--primary">{{ ui.icon('plus', 20) }}<span class="ps-btn-label">Добавить канал</span></a>
|
||||
</div>
|
||||
|
||||
{% if channels %}
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>Название</th><th>Тип</th><th>Username</th><th>Добавлен</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<div class="app-list">
|
||||
{% for ch in channels %}
|
||||
<tr>
|
||||
<td>{{ ch.title }}</td>
|
||||
<td>{{ ch.chat_type }}</td>
|
||||
<td>{% if ch.username %}@{{ ch.username }}{% else %}—{% endif %}</td>
|
||||
<td>{{ ch.created_at }}</td>
|
||||
<td>
|
||||
<form action="/channels/{{ ch.id }}/delete" method="post" class="inline-form" onsubmit="return confirm('Удалить канал?')">
|
||||
<button type="submit" class="button-link button-link-danger">🗑</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{%- set name = (ch.title or ch.username or '?') | replace('@', '') -%}
|
||||
<div class="ps-channel">
|
||||
<span class="ps-channel-avatar" aria-hidden="true">{{ name[:1] | upper }}</span>
|
||||
<span class="ps-channel-text">
|
||||
<span class="ps-channel-title">{{ ch.title or ('@' ~ ch.username) }}</span>
|
||||
<span class="ps-channel-meta">{% if ch.username %}@{{ ch.username }}{% else %}ID {{ ch.chat_id }}{% endif %} · {{ chat_types.get(ch.chat_type, ch.chat_type) }}</span>
|
||||
</span>
|
||||
<span class="ps-badge ps-badge--neutral" title="При подключении бот был администратором канала">{{ ui.icon('check', 14) }}<span>Подключён {{ ch.created_at|local_dt('%d.%m.%Y') }}</span></span>
|
||||
<span class="ps-channel-actions">
|
||||
<form action="/channels/{{ ch.id }}/delete" method="post" class="inline-form" data-confirm="Удалить канал?" data-confirm-body="{{ ch.title }} — публиковать в него больше не получится.">
|
||||
<button type="submit" class="ps-iconbtn" aria-label="Удалить канал {{ ch.title }}">{{ ui.icon('trash', 20) }}</button>
|
||||
</form>
|
||||
</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p>Нет добавленных каналов. <a href="/channels/add">Добавьте первый →</a></p>
|
||||
</div>
|
||||
{% else %}
|
||||
<section class="ps-panel">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('megaphone', 28) }}</span>
|
||||
<h2 class="ps-empty-title">Каналов пока нет</h2>
|
||||
<p class="ps-empty-text">Добавьте Telegram-канал или чат — и публикуйте посты в один клик.</p>
|
||||
<a href="/channels/add" class="ps-btn ps-btn--primary">{{ ui.icon('plus', 20) }}<span class="ps-btn-label">Добавить канал</span></a>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -1,41 +1,122 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Главная — Личный кабинет{% endblock %}
|
||||
{% block title %}Главная{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Привет, {{ user.name }}!</h1>
|
||||
<div class="card">
|
||||
<p><strong>Телефон:</strong> {{ user.phone }}</p>
|
||||
<p><strong>Email:</strong> {{ user.email }}</p>
|
||||
<p><strong>В кабинете с:</strong> {{ user.created_at }}</p>
|
||||
{%- set first_name = user.name | first_name -%}
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1"><span data-greeting>{{ greeting_for_hour() }}</span>{% if first_name %}, {{ first_name }}{% endif %}</h1>
|
||||
<p class="ps-lead">
|
||||
{% if counters.posts %}Всего {{ counters.posts }} {{ plural(counters.posts, ['пост', 'поста', 'постов']) }} и {{ counters.published }} {{ plural(counters.published, ['публикация', 'публикации', 'публикаций']) }}.
|
||||
{% else %}Здесь появятся ваши посты, картинки и публикации.{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
<a href="/generate" class="ps-btn ps-btn--primary ps-btn--lg">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Создать пост</span></a>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Медиа-образ</h2>
|
||||
{% if latest_survey %}
|
||||
<p><strong>Активный:</strong> <a href="/surveys/{{ latest_survey.id }}">{{ latest_survey.title }}</a></p>
|
||||
<p class="form-hint">Посты генерируются на основе этого медиа-образа.</p>
|
||||
<div class="post-actions">
|
||||
<a href="/surveys/{{ latest_survey.id }}" class="copy-btn">Открыть</a>
|
||||
<a href="/survey" class="copy-btn">➕ Создать новый</a>
|
||||
<a href="/survey/import" class="copy-btn">📤 Загрузить из файла</a>
|
||||
{% if not latest_survey %}
|
||||
<section class="ps-panel">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('persona', 28) }}</span>
|
||||
<h2 class="ps-empty-title">Начните с медиа-образа</h2>
|
||||
<p class="ps-empty-text">Опишите бренд, личность или сообщество один раз — и посты будут звучать вашим голосом. Это 5 минут.</p>
|
||||
<div class="app-actions" style="justify-content:center">
|
||||
<a href="/survey" class="ps-btn ps-btn--primary">{{ ui.icon('plus', 20) }}<span class="ps-btn-label">Создать медиа-образ</span></a>
|
||||
<a href="/survey/import" class="ps-btn ps-btn--quiet">{{ ui.icon('upload', 20) }}<span class="ps-btn-label">Загрузить из файла</span></a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% else %}
|
||||
<div class="ps-grid-4">
|
||||
<div class="ps-stat">
|
||||
<span class="ps-stat-icon" aria-hidden="true">{{ ui.icon('news', 20) }}</span>
|
||||
<span class="ps-stat-label">Постов создано</span>
|
||||
<span class="ps-stat-value">{{ counters.posts|num }}</span>
|
||||
</div>
|
||||
<div class="ps-stat">
|
||||
<span class="ps-stat-icon" aria-hidden="true">{{ ui.icon('image', 20) }}</span>
|
||||
<span class="ps-stat-label">Картинок</span>
|
||||
<span class="ps-stat-value">{{ counters.images|num }}</span>
|
||||
</div>
|
||||
<div class="ps-stat">
|
||||
<span class="ps-stat-icon" aria-hidden="true">{{ ui.icon('megaphone', 20) }}</span>
|
||||
<span class="ps-stat-label">Опубликовано</span>
|
||||
<span class="ps-stat-value">{{ counters.published|num }}</span>
|
||||
</div>
|
||||
<div class="ps-stat">
|
||||
<span class="ps-stat-icon" aria-hidden="true">{{ ui.icon('persona', 20) }}</span>
|
||||
<span class="ps-stat-label">Медиа-образов</span>
|
||||
<span class="ps-stat-value">{{ counters.surveys|num }}</span>
|
||||
<span class="ps-stat-note">Активный — {{ latest_survey.title | truncate(28, True, '…') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ps-grid-2">
|
||||
<article class="ps-persona is-active">
|
||||
<div class="ps-persona-top">
|
||||
<span class="ps-persona-icon" aria-hidden="true">{{ ui.icon('persona', 22) }}</span>
|
||||
<span class="ps-persona-type">Медиа-образ</span>
|
||||
<span class="ps-badge ps-badge--brand">{{ ui.icon('check', 14) }}<span>Активный</span></span>
|
||||
</div>
|
||||
<h3 class="ps-persona-name">{{ latest_survey.title }}</h3>
|
||||
<p class="ps-persona-sum">Посты, картинки и контент-план строятся по этой анкете: личность, УТП, тон голоса, аудитория.</p>
|
||||
<div class="ps-persona-actions">
|
||||
<a href="/surveys/{{ latest_survey.id }}" class="ps-btn ps-btn--quiet ps-btn--sm">{{ ui.icon('edit', 16) }}<span class="ps-btn-label">Анкета</span></a>
|
||||
<a href="/surveys/{{ latest_survey.id }}/export" class="ps-btn ps-btn--quiet ps-btn--sm">{{ ui.icon('download', 16) }}<span class="ps-btn-label">Экспорт .docx</span></a>
|
||||
</div>
|
||||
</article>
|
||||
<section class="ps-panel">
|
||||
<h2 class="ps-h2">Быстрый старт</h2>
|
||||
<div class="ps-grid-tiles">
|
||||
<a href="/generate" class="ps-action">
|
||||
<span class="ps-action-icon" aria-hidden="true">{{ ui.icon('sparkle', 20) }}</span>
|
||||
<span class="ps-action-title">Создать пост</span>
|
||||
<span class="ps-action-desc">Платформа, стиль — и готово</span>
|
||||
</a>
|
||||
<a href="/plan" class="ps-action">
|
||||
<span class="ps-action-icon" aria-hidden="true">{{ ui.icon('calendar', 20) }}</span>
|
||||
<span class="ps-action-title">Контент-план</span>
|
||||
<span class="ps-action-desc">Идеи постов на неделю и дальше</span>
|
||||
</a>
|
||||
<a href="/surveys" class="ps-action">
|
||||
<span class="ps-action-icon" aria-hidden="true">{{ ui.icon('persona', 20) }}</span>
|
||||
<span class="ps-action-title">Медиа-образы</span>
|
||||
<span class="ps-action-desc">Анкеты бренда и тон голоса</span>
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<section class="app-section">
|
||||
<div class="app-section-head">
|
||||
<h2 class="ps-h2">Последние посты</h2>
|
||||
{% if recent_posts %}<a href="/history" class="ps-btn ps-btn--quiet ps-btn--sm"><span class="ps-btn-label">Все посты</span>{{ ui.icon('chevron-right', 16) }}</a>{% endif %}
|
||||
</div>
|
||||
{% if recent_posts %}
|
||||
<div class="ps-grid-3">
|
||||
{% for post in recent_posts %}{% include "_post_card.html" %}{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p>Медиа-образ ещё не создан. Создайте его — посты будут генерироваться на его основе.</p>
|
||||
<div class="post-actions">
|
||||
<a href="/survey" class="copy-btn">➕ Создать медиа-образ</a>
|
||||
<a href="/survey/import" class="copy-btn">📤 Загрузить из файла</a>
|
||||
<div class="ps-panel">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('news', 28) }}</span>
|
||||
<h3 class="ps-empty-title">Постов пока нет</h3>
|
||||
<p class="ps-empty-text">Выберите платформу и стиль — первый пост появится здесь.</p>
|
||||
{% if latest_survey %}<a href="/generate" class="ps-btn ps-btn--primary">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Создать пост</span></a>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<a class="tile" href="/generate">💡 Сгенерировать пост</a>
|
||||
<a class="tile" href="/plan">📅 Контент-план</a>
|
||||
<a class="tile" href="/history">📜 Мои посты</a>
|
||||
<a class="tile" href="/images">🖼 Медиа-библиотека</a>
|
||||
<a class="tile" href="/channels">📢 Каналы публикации</a>
|
||||
<a class="tile" href="/surveys">📋 Мои медиа-образы</a>
|
||||
<a class="tile" href="/stats">📈 Статистика</a>
|
||||
<a class="tile" href="/profile/edit">✏️ Редактировать профиль</a>
|
||||
<a class="tile tile-danger" href="/delete-account">🗑 Удалить аккаунт</a>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
/* Приветствие по часам пользователя: утро 5–11, день 11–17, вечер 17–23, ночь 23–5 */
|
||||
(function () {
|
||||
var el = document.querySelector('[data-greeting]');
|
||||
if (!el) return;
|
||||
var h = new Date().getHours();
|
||||
el.textContent = h >= 5 && h < 11 ? 'Доброе утро' : h >= 11 && h < 17 ? 'Добрый день' : h >= 17 && h < 23 ? 'Добрый вечер' : 'Доброй ночи';
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,11 +1,29 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Удаление аккаунта — Личный кабинет{% endblock %}
|
||||
{% block title %}Удаление аккаунта{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Удалить аккаунт?</h1>
|
||||
<p>Это безвозвратно удалит твой профиль и всю историю постов.</p>
|
||||
<form method="post" action="/delete-account" class="form">
|
||||
<input type="hidden" name="confirm" value="yes">
|
||||
<button type="submit" class="button-danger">Да, удалить аккаунт</button>
|
||||
</form>
|
||||
<p><a href="/dashboard">Отмена, вернуться в кабинет</a></p>
|
||||
<section class="ps-panel" style="max-width: 560px; width: 100%; justify-self: center; margin-top: var(--space-8)">
|
||||
<div class="ps-empty" style="padding-bottom: var(--space-4)">
|
||||
<span class="ps-empty-icon" aria-hidden="true" style="background: var(--danger-tint); color: var(--danger)">{{ ui.icon('alert', 28) }}</span>
|
||||
<h1 class="ps-empty-title">Удалить аккаунт?</h1>
|
||||
<p class="ps-empty-text">Удалятся профиль, все посты, картинки, медиа-образы и контент-план. Вернуть их будет нельзя.</p>
|
||||
</div>
|
||||
<form method="post" action="/delete-account" class="app-form" id="deleteForm">
|
||||
<input type="hidden" name="confirm" value="yes">
|
||||
<div class="ps-field">
|
||||
<label for="word" class="ps-field-label">Чтобы подтвердить, введите слово «удалить»</label>
|
||||
<input id="word" class="ps-field-control" type="text" autocomplete="off" required>
|
||||
</div>
|
||||
<div class="app-actions">
|
||||
<button type="submit" class="ps-btn ps-btn--danger" id="deleteBtn" disabled>{{ ui.icon('trash', 20) }}<span class="ps-btn-label">Удалить аккаунт</span></button>
|
||||
<a href="/profile/edit" class="ps-btn ps-btn--quiet"><span class="ps-btn-label">Оставить</span></a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block scripts %}
|
||||
<script>
|
||||
document.getElementById('word').addEventListener('input', function () {
|
||||
document.getElementById('deleteBtn').disabled = this.value.trim().toLowerCase() !== 'удалить';
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,100 +1,200 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Сгенерировать пост — Личный кабинет{% endblock %}
|
||||
{% block title %}Создать пост{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Пост в своём стиле</h1>
|
||||
{%- set platform_meta = {
|
||||
'telegram': ('send', 'До 4 096 знаков', 4096),
|
||||
'instagram': ('image', 'Подпись до 2 200 знаков', 2200),
|
||||
'linkedin': ('building', 'До 3 000 знаков', 3000),
|
||||
'twitter': ('chat', 'До 280 знаков', 280),
|
||||
'tenchat': ('users', 'Деловая соцсеть', 4096),
|
||||
'ad': ('megaphone', 'Короткий продающий текст', 4096),
|
||||
} -%}
|
||||
{%- set styles = [('экспертный', 'Экспертный'), ('вовлекающий', 'Вовлекающий'), ('личный', 'Личный'), ('продающий', 'Продающий')] -%}
|
||||
{%- set cur_platform = (prefill.platform if prefill and prefill.platform else (form.platform if form else 'telegram')) -%}
|
||||
{%- if cur_platform not in (platforms | map('first') | list) %}{% set cur_platform = 'telegram' %}{% endif -%}
|
||||
{%- set cur_style = form.style if form and form.style else 'экспертный' -%}
|
||||
{%- set style_known = cur_style in styles | map('first') | list -%}
|
||||
|
||||
{% if latest_survey %}
|
||||
<div class="card">
|
||||
<p><strong>Медиа-образ:</strong> <a href="/surveys/{{ latest_survey.id }}">{{ latest_survey.title }}</a></p>
|
||||
<p class="form-hint">Пост сгенерируется на основе этого медиа-образа (личность, УТП, Tone of Voice, структура мысли).</p>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Создать пост</h1>
|
||||
<p class="ps-lead">{% if latest_survey %}Медиа-образ: {{ latest_survey.title }}.{% else %}Посты пишутся по медиа-образу — сначала создайте его.{% endif %}</p>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p>⚠️ Медиа-образ не найден. Посты генерируются на основе медиа-образа.</p>
|
||||
<a href="/survey" class="copy-btn">➕ Создать медиа-образ</a>
|
||||
|
||||
{% if prefill and prefill.idea %}
|
||||
<div class="app-alert app-alert--info" role="status">
|
||||
<span class="app-alert-icon">{{ ui.icon('calendar', 18) }}</span>
|
||||
<ul><li>Идея и платформа из контент-плана уже подставлены.</li></ul>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div id="taskError" class="task-error"></div>
|
||||
<div class="ps-split ps-split--start" style="--ps-aside: 380px">
|
||||
<section class="ps-panel" id="taskForm" aria-labelledby="params-title">
|
||||
<h2 class="ps-h2" id="params-title">Параметры</h2>
|
||||
<form method="post" action="/generate" class="app-form" id="generateForm" onsubmit="return startPostGen(event)">
|
||||
{% if surveys and surveys|length > 1 %}
|
||||
<div class="ps-field">
|
||||
<label for="survey_id" class="ps-field-label">Медиа-образ</label>
|
||||
<div class="ps-select">
|
||||
<select id="survey_id" name="survey_id" class="ps-field-control ps-select-control">
|
||||
<option value="">Последний — {{ latest_survey.title if latest_survey else '' }}</option>
|
||||
{% for s in surveys %}<option value="{{ s.id }}">{{ s.title }}</option>{% endfor %}
|
||||
</select>
|
||||
{{ ui.icon('chevron-down', 18, 'ps-select-chev') }}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div id="taskLoader" class="task-loader">
|
||||
<div class="spinner"></div>
|
||||
<div class="task-loader-text">Генерирую пост...</div>
|
||||
<div class="task-loader-sub">Это может занять 15–60 секунд</div>
|
||||
</div>
|
||||
<div class="ps-choices">
|
||||
<span class="ps-field-label" id="platform-label">Платформа</span>
|
||||
<input type="hidden" name="platform" id="platformInput" value="{{ cur_platform }}">
|
||||
<div class="ps-choices-grid is-compact" role="radiogroup" aria-labelledby="platform-label" data-input="platformInput">
|
||||
{% for key, label in platforms %}
|
||||
{%- set m = platform_meta.get(key, ('news', '', 4096)) -%}
|
||||
{%- set sel = key == cur_platform -%}
|
||||
<button type="button" role="radio" class="ps-choice{% if sel %} is-selected{% endif %}" aria-checked="{{ 'true' if sel else 'false' }}" tabindex="{{ 0 if sel else -1 }}" data-value="{{ key }}" data-limit="{{ m[2] }}" data-icon="{{ m[0] }}">
|
||||
<span class="ps-choice-body">
|
||||
<span class="ps-choice-icon" aria-hidden="true">{{ ui.icon(m[0], 16) }}</span>
|
||||
<span class="ps-choice-text"><span class="ps-choice-title">{{ label }}</span></span>
|
||||
<span class="ps-choice-check" aria-hidden="true">{{ ui.icon('check', 14) }}</span>
|
||||
</span>
|
||||
</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="taskResult" class="task-result"></div>
|
||||
<div class="ps-choices">
|
||||
<span class="ps-field-label" id="style-label">Стиль</span>
|
||||
<input type="hidden" name="style" id="styleInput" value="{{ cur_style }}">
|
||||
<div class="ps-choices-grid is-compact" role="radiogroup" aria-labelledby="style-label" data-input="styleInput">
|
||||
{% for value, label in styles %}
|
||||
{%- set sel = value == cur_style or (not style_known and loop.first) -%}
|
||||
<button type="button" role="radio" class="ps-choice{% if sel %} is-selected{% endif %}" aria-checked="{{ 'true' if sel else 'false' }}" tabindex="{{ 0 if sel else -1 }}" data-value="{{ value }}">
|
||||
<span class="ps-choice-body no-icon">
|
||||
<span class="ps-choice-text"><span class="ps-choice-title">{{ label }}</span></span>
|
||||
<span class="ps-choice-check" aria-hidden="true">{{ ui.icon('check', 14) }}</span>
|
||||
</span>
|
||||
</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="taskForm">
|
||||
<form method="post" action="/generate" class="form" id="generateForm" onsubmit="return startPostGen(event)">
|
||||
{% if surveys and surveys|length > 1 %}
|
||||
<label>Медиа-образ
|
||||
<select name="survey_id">
|
||||
<option value="">Последний (по умолчанию)</option>
|
||||
{% for s in surveys %}
|
||||
<option value="{{ s.id }}">{{ s.title }} ({{ s.created_at }})</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<div class="ps-field">
|
||||
<div class="ps-field-top">
|
||||
<label for="wishes" class="ps-field-label">Пожелания</label>
|
||||
<span class="ps-field-count">необязательно</span>
|
||||
</div>
|
||||
<textarea id="wishes" name="wishes" rows="4" class="ps-field-control" placeholder="О чём пост, какие факты упомянуть, призыв к действию">{{ prefill.idea if prefill else (form.wishes if form else '') }}</textarea>
|
||||
</div>
|
||||
|
||||
<input type="hidden" name="task_type" value="generate_post">
|
||||
{% if prefill %}<input type="hidden" name="plan_id" value="{{ prefill.plan_id }}">{% endif %}
|
||||
<button type="submit" class="ps-btn ps-btn--primary ps-btn--lg ps-btn--block" id="genBtn" {% if not latest_survey %}disabled{% endif %}>
|
||||
{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">{{ 'Сгенерировать заново' if result else 'Сгенерировать пост' }}</span>
|
||||
</button>
|
||||
{% if not latest_survey %}
|
||||
<a href="/survey" class="ps-btn ps-btn--secondary ps-btn--block">{{ ui.icon('plus', 20) }}<span class="ps-btn-label">Создать медиа-образ</span></a>
|
||||
{% endif %}
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="app-stack-lg" aria-live="polite">
|
||||
<div id="taskError" class="task-error" role="alert"></div>
|
||||
<div id="taskLoader" class="task-loader">
|
||||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Пишу пост по медиа-образу…</span></div>
|
||||
<span class="task-loader-sub">Обычно 15–60 секунд</span>
|
||||
</div>
|
||||
|
||||
<div id="taskResult" class="task-result"></div>
|
||||
|
||||
<div id="resultStatic">
|
||||
{% if result %}
|
||||
{%- set m = platform_meta.get(form.platform, ('news', '', 4096)) -%}
|
||||
<article class="ps-post">
|
||||
<header class="ps-post-head">
|
||||
<span class="ps-post-platform">{{ ui.icon(m[0], 16) }}{% for k, l in platforms if k == form.platform %}{{ l }}{% endfor %}</span>
|
||||
{% if form.style %}<span class="ps-post-tag">{{ form.style }}</span>{% endif %}
|
||||
</header>
|
||||
<div class="ps-post-text"><p>{{ result }}</p></div>
|
||||
<footer class="ps-post-foot">
|
||||
<span class="ps-post-count{% if result|length > m[2] %} is-over{% endif %}">{{ result|length|num }} / {{ m[2]|num }} зн.</span>
|
||||
<div class="ps-post-actions">
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-copy-target="post-text">{{ ui.icon('copy', 16) }}<span class="ps-btn-label">Копировать</span></button>
|
||||
<a href="/history" class="ps-btn ps-btn--primary ps-btn--sm">{{ ui.icon('news', 16) }}<span class="ps-btn-label">К постам</span></a>
|
||||
</div>
|
||||
</footer>
|
||||
</article>
|
||||
<div id="post-text" hidden>{{ result }}</div>
|
||||
{% else %}
|
||||
<div class="ps-panel" id="emptyState">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('sparkle', 28) }}</span>
|
||||
<h3 class="ps-empty-title">Здесь появится пост</h3>
|
||||
<p class="ps-empty-text">Выберите платформу и стиль, при желании добавьте пожелания и нажмите «Сгенерировать пост».</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
<label>Платформа
|
||||
<select name="platform" required>
|
||||
{% for key, label in platforms %}
|
||||
<option value="{{ key }}" {% if (prefill and prefill.platform == key) or (form and form.platform == key) %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>Стиль (например: дружелюбный, с юмором, экспертный)
|
||||
<input type="text" name="style" value="{{ form.style if form else '' }}" required>
|
||||
</label>
|
||||
<label>Пожелания к посту
|
||||
<textarea name="wishes" rows="3">{{ prefill.idea if prefill else (form.wishes if form else '') }}</textarea>
|
||||
</label>
|
||||
<input type="hidden" name="task_type" value="generate_post">
|
||||
{% if prefill %}<input type="hidden" name="plan_id" value="{{ prefill.plan_id }}">{% endif %}
|
||||
<button type="submit" {% if not latest_survey %}disabled{% endif %}>Сгенерировать</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{% if result %}
|
||||
<h2>Готовый пост</h2>
|
||||
<div class="card result">{{ result }}</div>
|
||||
<div class="post-actions">
|
||||
<button type="button" class="copy-btn" data-copy-target="post-text">📋 Копировать</button>
|
||||
</div>
|
||||
<div id="post-text" hidden>{{ result }}</div>
|
||||
{% endif %}
|
||||
<p><a href="/dashboard">← Назад в кабинет</a></p>
|
||||
<template id="tpl-post">
|
||||
<article class="ps-post">
|
||||
<header class="ps-post-head">
|
||||
<span class="ps-post-platform" data-platform></span>
|
||||
<span class="ps-post-tag" data-style></span>
|
||||
</header>
|
||||
<div class="ps-post-text" data-text></div>
|
||||
<footer class="ps-post-foot">
|
||||
<span class="ps-post-count" data-count></span>
|
||||
<span class="ps-post-note is-danger" data-over hidden>{{ ui.icon('alert', 14) }}Длиннее лимита платформы — сократите текст</span>
|
||||
<div class="ps-post-actions">
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-copy>{{ ui.icon('copy', 16) }}<span class="ps-btn-label">Копировать</span></button>
|
||||
<a class="ps-btn ps-btn--primary ps-btn--sm" data-open>{{ ui.icon('edit', 16) }}<span class="ps-btn-label">Доработать и опубликовать</span></a>
|
||||
</div>
|
||||
</footer>
|
||||
</article>
|
||||
</template>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
function fmtNum(n) { return Number(n).toLocaleString('ru-RU'); }
|
||||
function startPostGen(e) {
|
||||
e.preventDefault();
|
||||
var form = document.getElementById('generateForm');
|
||||
var btn = document.getElementById('genBtn');
|
||||
var label = btn.querySelector('.ps-btn-label');
|
||||
var platformBtn = document.querySelector('#taskForm [data-input="platformInput"] .ps-choice.is-selected');
|
||||
TaskEngine.start(form, {
|
||||
loaderId: 'taskLoader',
|
||||
formId: 'taskForm',
|
||||
errorId: 'taskError',
|
||||
resultId: 'taskResult',
|
||||
onDone: function(result) {
|
||||
var html = '<h2>Готовый пост</h2>' +
|
||||
'<div class="card result">' + escHtml(result.content) + '</div>' +
|
||||
'<div class="post-actions">' +
|
||||
'<button type="button" class="copy-btn" onclick="copyText(\'' + escAttr(result.content).replace(/'/g, "\\'") + '\', this)">📋 Копировать</button>' +
|
||||
' <a href="/posts/' + result.post_id + '" class="copy-btn">Открыть пост →</a>' +
|
||||
'</div>';
|
||||
document.getElementById('taskResult').innerHTML = html;
|
||||
document.getElementById('taskResult').style.display = 'block';
|
||||
loaderId: 'taskLoader', formId: 'resultStatic', errorId: 'taskError', resultId: 'taskResult',
|
||||
onStart: function () {
|
||||
btn.disabled = true; btn.classList.add('is-loading'); label.textContent = 'Пишу пост…';
|
||||
},
|
||||
onEnd: function () {
|
||||
btn.disabled = false; btn.classList.remove('is-loading'); label.textContent = 'Сгенерировать заново';
|
||||
},
|
||||
onDone: function (result) {
|
||||
var tpl = document.getElementById('tpl-post').content.firstElementChild.cloneNode(true);
|
||||
var text = result.content || '';
|
||||
var limit = platformBtn ? +platformBtn.getAttribute('data-limit') : 4096;
|
||||
tpl.querySelector('[data-platform]').innerHTML = platformBtn ? platformBtn.querySelector('.ps-choice-icon').innerHTML + platformBtn.querySelector('.ps-choice-title').textContent : '';
|
||||
tpl.querySelector('[data-style]').textContent = document.getElementById('styleInput').value;
|
||||
text.split(/\n{2,}/).forEach(function (para) {
|
||||
var p = document.createElement('p'); p.textContent = para; tpl.querySelector('[data-text]').appendChild(p);
|
||||
});
|
||||
var count = tpl.querySelector('[data-count]');
|
||||
count.textContent = fmtNum(text.length) + ' / ' + fmtNum(limit) + ' зн.';
|
||||
if (text.length > limit) { count.classList.add('is-over'); tpl.querySelector('[data-over]').hidden = false; }
|
||||
tpl.querySelector('[data-copy]').addEventListener('click', function () { copyText(text); });
|
||||
tpl.querySelector('[data-open]').href = '/posts/' + result.post_id;
|
||||
var box = document.getElementById('taskResult');
|
||||
box.innerHTML = ''; box.appendChild(tpl); box.style.display = 'block';
|
||||
Press.toast('Пост готов: ' + fmtNum(text.length) + ' зн.', 'success', 'Он сохранён в «Мои посты».');
|
||||
}
|
||||
});
|
||||
return false;
|
||||
}
|
||||
function escHtml(s) {
|
||||
var d = document.createElement('div');
|
||||
d.textContent = s || '';
|
||||
return d.innerHTML;
|
||||
}
|
||||
function escAttr(s) {
|
||||
return (s || '').replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/"/g,'"').replace(/\n/g,'\\n');
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,39 +1,26 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Мои посты — Личный кабинет{% endblock %}
|
||||
{% block title %}Мои посты{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Мои посты</h1>
|
||||
{% if posts %}
|
||||
<ul class="post-list">
|
||||
{% for post in posts %}
|
||||
<li class="card">
|
||||
<div class="post-meta">{{ platform_label(post.platform) }} · {{ post.created_at }}
|
||||
{% if post.published %} · ✅ Опубликован{% endif %}
|
||||
</div>
|
||||
<div class="post-content" id="post-content-{{ post.id }}">{{ post.content }}</div>
|
||||
{% if post.images %}
|
||||
<div class="post-images">
|
||||
{% for img in post.images %}
|
||||
<img src="/media/{{ img.filename }}" class="post-thumb" alt="">
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="post-actions">
|
||||
<button type="button" class="copy-btn" data-copy-target="post-content-{{ post.id }}">📋 Копировать</button>
|
||||
<a class="button-link" href="/posts/{{ post.id }}">👁 Открыть</a>
|
||||
<a class="button-link" href="/posts/{{ post.id }}/edit">✏️ Изменить</a>
|
||||
<form method="post" action="/posts/{{ post.id }}/delete" class="inline-form"
|
||||
onsubmit="return confirm('Удалить этот пост? Действие необратимо.');">
|
||||
<button type="submit" class="button-link button-link-danger">🗑 Удалить</button>
|
||||
</form>
|
||||
</div>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p>Постов пока нет.</p>
|
||||
<p><a href="/generate">💡 Сгенерировать первый пост</a></p>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Мои посты</h1>
|
||||
{% if posts %}<p class="ps-lead">{{ posts|length }} {{ plural(posts|length, ['пост', 'поста', 'постов']) }}. Откройте пост, чтобы доработать его в чате с ИИ, добавить картинки и опубликовать.</p>{% endif %}
|
||||
</div>
|
||||
<a href="/generate" class="ps-btn ps-btn--primary">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Создать пост</span></a>
|
||||
</div>
|
||||
|
||||
{% if posts %}
|
||||
<div class="ps-grid-3" style="grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr))">
|
||||
{% for post in posts %}{% include "_post_card.html" %}{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<section class="ps-panel">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('news', 28) }}</span>
|
||||
<h2 class="ps-empty-title">Постов пока нет</h2>
|
||||
<p class="ps-empty-text">Выберите платформу и стиль — первый пост появится здесь.</p>
|
||||
<a href="/generate" class="ps-btn ps-btn--primary">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Создать пост</span></a>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
<p><a href="/dashboard">← Назад в кабинет</a></p>
|
||||
{% endblock %}
|
||||
@@ -1,74 +1,95 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Сгенерировать картинку — Личный кабинет{% endblock %}
|
||||
{% block title %}Сгенерировать картинку{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Генерация картинки</h1>
|
||||
|
||||
<div id="taskError" class="task-error"></div>
|
||||
|
||||
<div id="taskLoader" class="task-loader">
|
||||
<div class="spinner"></div>
|
||||
<div class="task-loader-text">Генерирую картинку...</div>
|
||||
<div class="task-loader-sub">Это может занять 15–60 секунд</div>
|
||||
{#- Шаблоны бэкенда → миниатюры PresetPicker из дизайн-системы -#}
|
||||
{%- set art_for = {'product': 'product', 'lifestyle': 'portrait', 'food': 'product', 'business': 'mockup', 'abstract': 'abstract',
|
||||
'portrait': 'portrait', 'infographic': 'announce', 'banner': 'cover', 'nature': 'landscape', 'minimal': 'minimal',
|
||||
'story': 'collage', 'before_after': 'collage'} -%}
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/images" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">Картинки</span></a>
|
||||
<h1 class="ps-h1">Новая картинка</h1>
|
||||
<p class="ps-lead">Выберите шаблон или опишите идею своими словами.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="taskError" class="task-error" role="alert"></div>
|
||||
<div id="taskLoader" class="task-loader">
|
||||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Рисую картинку…</span></div>
|
||||
<span class="task-loader-sub">Обычно 15–60 секунд</span>
|
||||
</div>
|
||||
<div id="taskResult" class="task-result"></div>
|
||||
|
||||
<div id="taskForm">
|
||||
<!-- Выбор шаблона -->
|
||||
<h2>Выбери шаблон</h2>
|
||||
<div class="template-grid" id="templateGrid">
|
||||
{% for t in templates %}
|
||||
<button type="button" class="template-card" data-key="{{ t.key }}"
|
||||
data-prompt="{{ t.prompt }}" data-style="{{ t.style }}"
|
||||
data-size="{{ t.size }}" data-hint="{{ t.hint }}">
|
||||
<span class="template-icon">{{ t.icon }}</span>
|
||||
<span class="template-name">{{ t.name }}</span>
|
||||
<span class="template-hint">{{ t.hint }}</span>
|
||||
</button>
|
||||
{% endfor %}
|
||||
<button type="button" class="template-card template-card-custom" data-key="custom">
|
||||
<span class="template-icon">✏️</span>
|
||||
<span class="template-name">Свой вариант</span>
|
||||
<span class="template-hint">Напиши промпт сам</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="selectedTemplateHint" class="selected-hint" style="display:none;"></div>
|
||||
|
||||
<!-- Форма генерации -->
|
||||
<form method="post" action="/images/generate" class="form" id="imageForm" onsubmit="return startImageGen(event)" enctype="multipart/form-data">
|
||||
<label>Что нарисовать?
|
||||
<textarea name="prompt" id="promptInput" rows="4" required
|
||||
placeholder="Например: современный кофейный стакан на белом фоне, логотип для кофейни">{{ form.prompt if form else '' }}</textarea>
|
||||
</label>
|
||||
<label>Исходное изображение <span class="form-hint">(необязательно) — ИИ использует его как основу</span>
|
||||
<input type="file" name="reference_image" id="referenceImage" accept="image/*">
|
||||
</label>
|
||||
<div id="refImagePreview" style="display:none; margin: 5px 0 10px;">
|
||||
<img id="refImageThumb" style="max-height:120px; border-radius:8px; border:1px solid var(--border);">
|
||||
<button type="button" class="button-link button-link-danger" onclick="clearRefImage()" style="margin-left:8px">✕ Убрать</button>
|
||||
<div id="taskForm" class="app-stack-lg">
|
||||
<section class="ps-panel">
|
||||
<h2 class="ps-h2">Шаблон</h2>
|
||||
<div class="ps-presets" id="templateGrid" role="radiogroup" aria-label="Шаблон изображения">
|
||||
{% for t in templates %}
|
||||
<button type="button" role="radio" aria-checked="false" class="ps-preset" data-key="{{ t.key }}"
|
||||
data-prompt="{{ t.prompt }}" data-style="{{ t.style }}" data-size="{{ t.size }}" data-hint="{{ t.hint }}" title="{{ t.hint }}">
|
||||
<span class="ps-preset-art" aria-hidden="true"><svg viewBox="0 0 64 48" preserveAspectRatio="xMidYMid slice">{{ ui.PRESET_ART[art_for.get(t.key, 'minimal')] | safe }}</svg></span>
|
||||
<span class="ps-preset-label">{{ t.name }}</span>
|
||||
</button>
|
||||
{% endfor %}
|
||||
<button type="button" role="radio" aria-checked="false" class="ps-preset" data-key="custom">
|
||||
<span class="ps-preset-art app-preset-custom" aria-hidden="true">{{ ui.icon('edit', 24) }}</span>
|
||||
<span class="ps-preset-label">Свой вариант</span>
|
||||
</button>
|
||||
</div>
|
||||
<label>Размер
|
||||
<select name="size" id="sizeInput" required>
|
||||
{% for key, (value, label) in sizes.items() %}
|
||||
<option value="{{ key }}" {% if form and form.size == key %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label>Стиль
|
||||
<select name="style" id="styleInput">
|
||||
{% for key, (label, suffix) in styles.items() %}
|
||||
<option value="{{ key }}" {% if form and form.style == key %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<div id="selectedTemplateHint" class="selected-hint" style="display:none;"></div>
|
||||
</section>
|
||||
|
||||
<form method="post" action="/images/generate" class="ps-panel app-form" id="imageForm" onsubmit="return startImageGen(event)" enctype="multipart/form-data">
|
||||
<h2 class="ps-h2">Что нарисовать</h2>
|
||||
<div class="ps-field">
|
||||
<label for="promptInput" class="ps-field-label">Описание</label>
|
||||
<textarea name="prompt" id="promptInput" rows="4" class="ps-field-control" required
|
||||
placeholder="Например: стакан кофе на деревянном столе, утренний свет">{{ form.prompt if form else '' }}</textarea>
|
||||
</div>
|
||||
<div class="ps-grid-2 app-grid-fields">
|
||||
<div class="ps-field">
|
||||
<label for="sizeInput" class="ps-field-label">Размер</label>
|
||||
<div class="ps-select">
|
||||
<select name="size" id="sizeInput" class="ps-field-control ps-select-control" required>
|
||||
{% for key, (value, label) in sizes.items() %}
|
||||
<option value="{{ key }}" {% if form and form.size == key %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
{{ ui.icon('chevron-down', 18, 'ps-select-chev') }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="styleInput" class="ps-field-label">Стиль</label>
|
||||
<div class="ps-select">
|
||||
<select name="style" id="styleInput" class="ps-field-control ps-select-control">
|
||||
{% for key, (label, suffix) in styles.items() %}
|
||||
<option value="{{ key }}" {% if form and form.style == key %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
{{ ui.icon('chevron-down', 18, 'ps-select-chev') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<label class="ps-drop" id="refDrop">
|
||||
<input type="file" name="reference_image" id="referenceImage" accept="image/*" class="ps-drop-input">
|
||||
<span class="ps-drop-icon" aria-hidden="true">{{ ui.icon('image', 24) }}</span>
|
||||
<span class="ps-drop-title">Референс для стиля</span>
|
||||
<span class="ps-drop-hint">Необязательно. ИИ повторит стиль картинки.</span>
|
||||
</label>
|
||||
<div id="refImagePreview" class="app-actions" style="display:none">
|
||||
<img id="refImageThumb" alt="Референс" style="max-height:96px; border-radius: var(--radius-sm)">
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" onclick="clearRefImage()">{{ ui.icon('close', 16) }}<span class="ps-btn-label">Убрать</span></button>
|
||||
</div>
|
||||
<input type="hidden" name="task_type" value="generate_image">
|
||||
<button type="submit" id="submitBtn" disabled>🎨 Сгенерировать</button>
|
||||
<p class="form-hint">Генерация занимает 10–60 секунд. Картинка сохранится в медиа-библиотеку.</p>
|
||||
<div class="app-actions">
|
||||
<button type="submit" id="submitBtn" class="ps-btn ps-btn--primary ps-btn--lg" disabled>{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Сгенерировать изображение</span></button>
|
||||
<span class="form-hint">Картинка сохранится в библиотеку.</span>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<p><a href="/images">← Назад в библиотеку</a></p>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
function clearRefImage() {
|
||||
document.getElementById('referenceImage').value = '';
|
||||
@@ -84,8 +105,15 @@ document.getElementById('referenceImage').addEventListener('change', function(e)
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
</script>
|
||||
<script>
|
||||
(function() {
|
||||
var drop = document.getElementById('refDrop'), input = document.getElementById('referenceImage');
|
||||
drop.addEventListener('dragover', function (e) { e.preventDefault(); drop.classList.add('is-over'); });
|
||||
drop.addEventListener('dragleave', function () { drop.classList.remove('is-over'); });
|
||||
drop.addEventListener('drop', function (e) {
|
||||
e.preventDefault(); drop.classList.remove('is-over');
|
||||
input.files = e.dataTransfer.files; input.dispatchEvent(new Event('change'));
|
||||
});
|
||||
})();
|
||||
(function() {
|
||||
var grid = document.getElementById('templateGrid');
|
||||
var promptInput = document.getElementById('promptInput');
|
||||
@@ -95,77 +123,67 @@ document.getElementById('referenceImage').addEventListener('change', function(e)
|
||||
var submitBtn = document.getElementById('submitBtn');
|
||||
var selectedKey = null;
|
||||
|
||||
grid.addEventListener('click', function(e) {
|
||||
var card = e.target.closest('.template-card');
|
||||
if (!card) return;
|
||||
function select(card) {
|
||||
grid.querySelectorAll('.ps-preset').forEach(function(c) {
|
||||
var on = c === card;
|
||||
c.classList.toggle('is-selected', on);
|
||||
c.setAttribute('aria-checked', on ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
|
||||
// Снять выделение со всех
|
||||
grid.querySelectorAll('.template-card').forEach(function(c) { c.classList.remove('selected'); });
|
||||
card.classList.add('selected');
|
||||
grid.addEventListener('click', function(e) {
|
||||
var card = e.target.closest('.ps-preset');
|
||||
if (!card) return;
|
||||
select(card);
|
||||
selectedKey = card.dataset.key;
|
||||
|
||||
if (selectedKey === 'custom') {
|
||||
hintEl.style.display = 'none';
|
||||
promptInput.value = '';
|
||||
/* стираем только текст шаблона; свой текст человека оставляем */
|
||||
var fromTemplate = Array.prototype.some.call(grid.querySelectorAll('.ps-preset[data-prompt]'), function (c) { return c.dataset.prompt === promptInput.value; });
|
||||
if (fromTemplate) promptInput.value = '';
|
||||
promptInput.focus();
|
||||
promptInput.removeAttribute('readonly');
|
||||
submitBtn.disabled = !promptInput.value.trim();
|
||||
return;
|
||||
}
|
||||
|
||||
var prompt = card.dataset.prompt;
|
||||
var style = card.dataset.style;
|
||||
var size = card.dataset.size;
|
||||
var hint = card.dataset.hint;
|
||||
|
||||
promptInput.value = prompt;
|
||||
if (styleInput.querySelector('option[value="' + style + '"]')) {
|
||||
styleInput.value = style;
|
||||
}
|
||||
if (sizeInput.querySelector('option[value="' + size + '"]')) {
|
||||
sizeInput.value = size;
|
||||
}
|
||||
|
||||
hintEl.textContent = '💡 ' + hint;
|
||||
promptInput.value = card.dataset.prompt;
|
||||
if (styleInput.querySelector('option[value="' + card.dataset.style + '"]')) styleInput.value = card.dataset.style;
|
||||
if (sizeInput.querySelector('option[value="' + card.dataset.size + '"]')) sizeInput.value = card.dataset.size;
|
||||
hintEl.textContent = card.dataset.hint;
|
||||
hintEl.style.display = 'block';
|
||||
submitBtn.disabled = false;
|
||||
});
|
||||
|
||||
// Разрешить ввод вручную при изменении текста
|
||||
// Текст изменён вручную — переключаем на «Свой вариант»
|
||||
promptInput.addEventListener('input', function() {
|
||||
if (selectedKey && selectedKey !== 'custom') {
|
||||
// Пользователь изменил текст — переключаем на "свой вариант"
|
||||
grid.querySelectorAll('.template-card').forEach(function(c) { c.classList.remove('selected'); });
|
||||
var customCard = grid.querySelector('[data-key="custom"]');
|
||||
if (customCard) customCard.classList.add('selected');
|
||||
select(grid.querySelector('[data-key="custom"]'));
|
||||
selectedKey = 'custom';
|
||||
hintEl.style.display = 'none';
|
||||
}
|
||||
submitBtn.disabled = !promptInput.value.trim();
|
||||
});
|
||||
submitBtn.disabled = !promptInput.value.trim();
|
||||
})();
|
||||
</script>
|
||||
|
||||
<script>
|
||||
function startImageGen(e) {
|
||||
e.preventDefault();
|
||||
var form = document.getElementById('imageForm');
|
||||
TaskEngine.start(form, {
|
||||
loaderId: 'taskLoader',
|
||||
formId: 'taskForm',
|
||||
errorId: 'taskError',
|
||||
resultId: 'taskResult',
|
||||
TaskEngine.start(document.getElementById('imageForm'), {
|
||||
loaderId: 'taskLoader', formId: 'taskForm', errorId: 'taskError', resultId: 'taskResult',
|
||||
onDone: function(result) {
|
||||
var html = '<div class="card">' +
|
||||
'<p>✅ Картинка сгенерирована!</p>' +
|
||||
'<div class="media-grid"><div class="media-card">' +
|
||||
'<a href="/media/' + result.filename + '" class="media-link" target="_blank">' +
|
||||
'<img class="media-thumb" src="/media/' + result.filename + '" alt="Картинка">' +
|
||||
'</a></div></div>' +
|
||||
'<p><a href="/images" class="copy-btn">Перейти в библиотеку →</a> ' +
|
||||
'<a href="/images/generate" class="copy-btn">Ещё одна →</a></p></div>';
|
||||
document.getElementById('taskResult').innerHTML = html;
|
||||
document.getElementById('taskResult').style.display = 'block';
|
||||
var box = document.getElementById('taskResult');
|
||||
box.innerHTML =
|
||||
'<section class="ps-panel">' +
|
||||
'<h2 class="ps-h2">Готово</h2>' +
|
||||
'<a href="/media/' + encodeURIComponent(result.filename) + '" target="_blank" rel="noopener" class="ps-post-image" style="display:block; max-width:640px">' +
|
||||
'<img src="/media/' + encodeURIComponent(result.filename) + '" alt="Сгенерированная картинка" style="object-fit:cover"></a>' +
|
||||
'<div class="app-actions">' +
|
||||
'<a href="/images" class="ps-btn ps-btn--primary"><span class="ps-btn-label">В библиотеку</span></a>' +
|
||||
'<a href="/images/generate" class="ps-btn ps-btn--secondary"><span class="ps-btn-label">Ещё одна</span></a>' +
|
||||
'</div></section>';
|
||||
box.style.display = 'block';
|
||||
Press.toast('Картинка готова', 'success', 'Она сохранена в библиотеку.');
|
||||
}
|
||||
});
|
||||
return false;
|
||||
|
||||
@@ -1,34 +1,42 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Картинки — Личный кабинет{% endblock %}
|
||||
{% block title %}Картинки{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Медиа-библиотека</h1>
|
||||
<p><a class="copy-btn" href="/images/generate">🎨 Сгенерировать картинку</a></p>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Картинки</h1>
|
||||
<p class="ps-lead">{% if images %}{{ images|length }} {{ plural(images|length, ['картинка', 'картинки', 'картинок']) }} в библиотеке.{% else %}Библиотека иллюстраций к постам.{% endif %}</p>
|
||||
</div>
|
||||
<a href="/images/generate" class="ps-btn ps-btn--primary">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Сгенерировать картинку</span></a>
|
||||
</div>
|
||||
|
||||
{% if images %}
|
||||
<div class="media-grid">
|
||||
<div class="app-gallery">
|
||||
{% for img in images %}
|
||||
<div class="media-card">
|
||||
<a href="/media/{{ img.filename }}" target="_blank" title="Открыть в полном размере">
|
||||
<img class="media-thumb" src="/media/{{ img.filename }}" alt="{{ img.prompt }}" loading="lazy">
|
||||
<figure class="app-gallery-item" style="margin:0">
|
||||
<a href="/media/{{ img.filename }}" target="_blank" rel="noopener" aria-label="Открыть в полном размере">
|
||||
<img src="/media/{{ img.filename }}" alt="{{ img.prompt }}" loading="lazy">
|
||||
</a>
|
||||
<div class="media-body">
|
||||
<div class="media-prompt" title="{{ img.prompt }}">{{ img.prompt }}</div>
|
||||
<div class="post-meta">{{ img.created_at }}</div>
|
||||
<div class="post-actions">
|
||||
<a class="copy-btn" href="/media/{{ img.filename }}" download>⬇ Скачать</a>
|
||||
<form method="post" action="/images/{{ img.id }}/delete" class="inline-form"
|
||||
onsubmit="return confirm('Удалить эту картинку?');">
|
||||
<button type="submit" class="button-link button-link-danger">🗑 Удалить</button>
|
||||
<figcaption class="app-gallery-body">
|
||||
<p class="app-gallery-prompt" title="{{ img.prompt }}">{{ img.prompt }}</p>
|
||||
<span class="app-caption">{{ img.created_at|local_dt }}</span>
|
||||
<div class="app-actions" style="margin-left:-6px">
|
||||
<a class="ps-btn ps-btn--quiet ps-btn--sm" href="/media/{{ img.filename }}" download>{{ ui.icon('download', 16) }}<span class="ps-btn-label">Скачать</span></a>
|
||||
<form method="post" action="/images/{{ img.id }}/delete" class="inline-form" data-confirm="Удалить картинку?" data-confirm-body="Её нельзя будет вернуть.">
|
||||
<button type="submit" class="ps-iconbtn" aria-label="Удалить картинку">{{ ui.icon('trash', 20) }}</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</figcaption>
|
||||
</figure>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p>Картинок пока нет.</p>
|
||||
<p><a href="/images/generate">🎨 Сгенерировать первую картинку</a></p>
|
||||
</div>
|
||||
<section class="ps-panel">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('image', 28) }}</span>
|
||||
<h2 class="ps-empty-title">Картинок пока нет</h2>
|
||||
<p class="ps-empty-text">Выберите шаблон или опишите идею — ИИ нарисует иллюстрацию в стиле вашего медиа-образа.</p>
|
||||
<a href="/images/generate" class="ps-btn ps-btn--primary">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Сгенерировать картинку</span></a>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
<p><a href="/dashboard">← Назад в кабинет</a></p>
|
||||
{% endblock %}
|
||||
@@ -2,15 +2,16 @@
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>ИИ Пресс-секретарь — умный контент для вашего бизнеса</title>
|
||||
<meta name="description" content="ИИ Пресс-секретарь — сервис, который создаёт контент-план, генерирует посты и картинки для вашего бизнеса и публикует их в Telegram.">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>ИИ Пресс-секретарь — говорит вашим голосом</title>
|
||||
<meta name="description" content="ИИ Пресс-секретарь пишет посты, рисует картинки и строит контент-план в стиле вашего медиа-образа и публикует в Telegram в один клик.">
|
||||
<link rel="icon" type="image/svg+xml" href="/static/press/app-icon.svg">
|
||||
|
||||
<!-- OpenGraph -->
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:site_name" content="ИИ Пресс-секретарь">
|
||||
<meta property="og:title" content="ИИ Пресс-секретарь — умный контент для вашего бизнеса">
|
||||
<meta property="og:description" content="Создавайте контент-план, генерируйте посты и картинки для своего бизнеса и публикуйте их в Telegram — всё в одном сервисе.">
|
||||
<meta property="og:title" content="ИИ Пресс-секретарь — говорит вашим голосом">
|
||||
<meta property="og:description" content="Посты, картинки и контент-план в стиле вашего бренда — и публикация в Telegram в один клик.">
|
||||
<meta property="og:url" content="https://press.my-dpr.ru/">
|
||||
<meta property="og:image" content="https://press.my-dpr.ru/static/og-image.png">
|
||||
<meta property="og:image:width" content="1536">
|
||||
@@ -18,427 +19,439 @@
|
||||
<meta property="og:image:alt" content="ИИ Пресс-секретарь — сервис для генерации контента и публикации в Telegram">
|
||||
<meta property="og:locale" content="ru_RU">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:title" content="ИИ Пресс-секретарь — умный контент для вашего бизнеса">
|
||||
<meta name="twitter:description" content="Создавайте контент-план, генерируйте посты и картинки для своего бизнеса и публикуйте их в Telegram.">
|
||||
<meta name="twitter:title" content="ИИ Пресс-секретарь — говорит вашим голосом">
|
||||
<meta name="twitter:description" content="Посты, картинки и контент-план в стиле вашего бренда — и публикация в Telegram в один клик.">
|
||||
<meta name="twitter:image" content="https://press.my-dpr.ru/static/og-image.png">
|
||||
|
||||
<link rel="stylesheet" href="/static/press/tokens.css?v=2">
|
||||
<link rel="stylesheet" href="/static/press/components.css?v=4">
|
||||
<link rel="stylesheet" href="/static/style.css?v=20">
|
||||
<script>
|
||||
// Тёмная тема по умолчанию; светлая — по выбору пользователя (сохраняется в localStorage)
|
||||
(function () {
|
||||
try {
|
||||
var saved = localStorage.getItem('theme');
|
||||
if (saved === 'light') {
|
||||
document.documentElement.setAttribute('data-theme', 'light');
|
||||
}
|
||||
if (saved === 'light' || saved === 'dark') document.documentElement.setAttribute('data-theme', saved);
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
<style>
|
||||
/* Тёмная тема по умолчанию */
|
||||
:root {
|
||||
--bg: #0f172a;
|
||||
--surface: #1e293b;
|
||||
--surface-2: #273449;
|
||||
--text: #e2e8f0;
|
||||
--text-muted: #94a3b8;
|
||||
--accent: #60a5fa;
|
||||
--accent-hover: #93c5fd;
|
||||
--accent-soft: #1e3a5f;
|
||||
--border: #334155;
|
||||
--border-strong: #475569;
|
||||
}
|
||||
/* Светлая тема (по выбору пользователя) */
|
||||
:root[data-theme="light"] {
|
||||
--bg: #f4f5f7;
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f1f3f6;
|
||||
--text: #1f2328;
|
||||
--text-muted: #4b5563;
|
||||
--accent: #2563eb;
|
||||
--accent-hover: #1d4ed8;
|
||||
--accent-soft: #eef2ff;
|
||||
--border: #e2e5ea;
|
||||
--border-strong: #d1d5db;
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.6;
|
||||
}
|
||||
.container { max-width: 1080px; margin: 0 auto; padding: 0 24px; }
|
||||
/* Лендинг: сетка 12 колонок, контейнер 1200px, разделы через space-12 */
|
||||
.lp-container { width: 100%; max-width: 1200px; margin: 0 auto; padding: 0 var(--space-8); }
|
||||
.lp-section { padding: var(--space-16) 0; }
|
||||
.lp-section + .lp-section { padding-top: 0; }
|
||||
.lp-head { display: grid; gap: var(--space-3); max-width: 640px; margin-bottom: var(--space-8); }
|
||||
.lp-kicker { font: 600 12px/16px var(--font-text); letter-spacing: 0.04em; text-transform: uppercase; color: var(--brand); }
|
||||
.lp-h2 { margin: 0; font: 600 28px/34px var(--font-display); letter-spacing: -0.01em; color: var(--ink); text-wrap: balance; }
|
||||
.lp-lead { margin: 0; font: 400 17px/26px var(--font-text); color: var(--ink-secondary); }
|
||||
|
||||
/* Header */
|
||||
.header {
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 16px 0;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
/* Шапка — стекло поверх контента */
|
||||
.lp-header {
|
||||
position: sticky; top: 0; z-index: 50;
|
||||
background: var(--surface-glass);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass)) saturate(180%); backdrop-filter: blur(var(--blur-glass)) saturate(180%);
|
||||
box-shadow: inset 0 -1px 0 var(--hairline);
|
||||
}
|
||||
.header-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 18px;
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.brand-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
}
|
||||
.header-actions { display: flex; align-items: center; gap: 12px; }
|
||||
.lp-header-inner { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); min-height: 68px; }
|
||||
.lp-header-actions { display: flex; align-items: center; gap: var(--space-2); }
|
||||
.lp-short { display: none; }
|
||||
.lp-logo { display: inline-flex; text-decoration: none !important; }
|
||||
|
||||
/* Бургер-меню (скрыто на десктопе) */
|
||||
.burger {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
/* Первый экран — градиент бренда, текст на глубокой стороне */
|
||||
.lp-hero {
|
||||
position: relative; overflow: hidden; color: #ffffff;
|
||||
background: linear-gradient(245deg, var(--brand-bright), var(--logo-deep) 62%, #1a63aa);
|
||||
}
|
||||
.burger-line {
|
||||
display: block;
|
||||
width: 20px;
|
||||
height: 2px;
|
||||
background: var(--text);
|
||||
border-radius: 2px;
|
||||
transition: transform .2s ease, opacity .2s ease;
|
||||
}
|
||||
.burger.open .burger-line:nth-child(1) { transform: translateY(7px) rotate(45deg); }
|
||||
.burger.open .burger-line:nth-child(2) { opacity: 0; }
|
||||
.burger.open .burger-line:nth-child(3) { transform: translateY(-7px) rotate(-45deg); }
|
||||
.lp-hero-inner { display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); align-items: center; gap: var(--space-12); padding-block: var(--space-16); }
|
||||
.lp-hero-text { display: grid; gap: var(--space-6); justify-items: start; }
|
||||
.lp-display { margin: 0; color: #ffffff; font: 700 48px/52px var(--font-display); letter-spacing: -0.025em; text-wrap: balance; }
|
||||
.lp-hero-lead { margin: 0; max-width: 34em; font: 400 19px/28px var(--font-text); color: #ffffff; }
|
||||
.lp-hero-actions { display: flex; flex-wrap: wrap; gap: var(--space-3); }
|
||||
.lp-btn-white { background: #ffffff; color: var(--logo-deep); box-shadow: var(--shadow-2); }
|
||||
.lp-btn-white:hover:not(:disabled) { background: var(--brand-tint); }
|
||||
.lp-btn-outline { background: rgba(9, 40, 80, 0.32); color: #ffffff; box-shadow: inset 0 0 0 1.5px rgba(255, 255, 255, 0.72); }
|
||||
.lp-btn-outline:hover:not(:disabled) { background: rgba(255, 255, 255, 0.24); }
|
||||
.lp-hero .ps-btn:focus-visible { outline-color: #ffffff; }
|
||||
.lp-hero-note { display: flex; flex-wrap: wrap; gap: var(--space-2) var(--space-5); margin: 0; padding: 0; list-style: none; font: 500 15px/20px var(--font-text); color: #ffffff; }
|
||||
.lp-hero-note li { display: inline-flex; align-items: center; gap: var(--space-2); }
|
||||
|
||||
.mobile-menu {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 12px 24px 16px;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.mobile-menu.open { display: flex; }
|
||||
.mobile-menu-link { text-align: center; }
|
||||
.btn {
|
||||
display: inline-block;
|
||||
padding: 10px 20px;
|
||||
border-radius: 8px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-ghost { background: transparent; color: var(--text); border: 1px solid var(--border); }
|
||||
.btn-ghost:hover { background: var(--accent-soft); }
|
||||
|
||||
/* Hero */
|
||||
.hero {
|
||||
padding: 80px 0 64px;
|
||||
text-align: center;
|
||||
}
|
||||
.hero h1 {
|
||||
font-size: 44px;
|
||||
line-height: 1.15;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.hero h1 span { color: var(--accent); }
|
||||
.hero p {
|
||||
font-size: 19px;
|
||||
color: var(--text-muted);
|
||||
max-width: 640px;
|
||||
margin: 0 auto 32px;
|
||||
}
|
||||
.hero-actions { display: flex; gap: 14px; justify-content: center; flex-wrap: wrap; }
|
||||
/* ---------- Первый экран: фон рисует hero-bg.js (холст) ----------
|
||||
Главный объект — знак веером, второй план — каналы с постами, фактура — сетка по контейнеру.
|
||||
Без JS остаётся градиент бренда. */
|
||||
.lp-bg { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 0; pointer-events: none; }
|
||||
.lp-hero-inner { position: relative; z-index: 1; }
|
||||
|
||||
/* Features */
|
||||
.features {
|
||||
padding: 40px 0 72px;
|
||||
/* Пример работы сервиса справа */
|
||||
.lp-demo { position: relative; display: grid; gap: var(--space-3); color: var(--ink); }
|
||||
.lp-demo .ps-post { box-shadow: var(--shadow-float); }
|
||||
/* Пример поста мягко парит; плашки вокруг — стекло */
|
||||
/* Карточка примера — контент: стоит на месте, движется только фон */
|
||||
.lp-demo .lp-persona-pill, .lp-demo .ps-chip { background: var(--surface-glass); -webkit-backdrop-filter: blur(var(--blur-glass)) saturate(180%); backdrop-filter: blur(var(--blur-glass)) saturate(180%); box-shadow: var(--shadow-2), inset 0 1px 0 var(--glass-edge); }
|
||||
@media (prefers-reduced-motion: reduce) { .lp-demo { animation: none; } }
|
||||
.lp-demo-row { display: flex; flex-wrap: wrap; gap: var(--space-2); }
|
||||
.lp-demo .ps-thinking { justify-self: start; box-shadow: var(--shadow-2); }
|
||||
.lp-demo-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-2); }
|
||||
.lp-demo .ps-post { transition: opacity var(--dur-tap) var(--ease-standard), transform var(--dur-smooth) var(--spring-smooth); }
|
||||
.lp-demo .ps-post.is-switching { opacity: 0; transform: translateY(6px) scale(0.99); }
|
||||
/* Подпись лежит над светлым краем градиента — на тёмном стекле, иначе контраст 3:1 */
|
||||
.lp-demo-cap { justify-self: start; margin: 0; padding: var(--space-1) var(--space-3); border-radius: var(--radius-pill); font: 500 13px/18px var(--font-text); color: #ffffff;
|
||||
background: rgba(9, 40, 80, 0.42); -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px); }
|
||||
.lp-demo .ps-chip:disabled { opacity: 0.45; cursor: progress; }
|
||||
.lp-demo .ps-chip.is-selected { background: var(--brand-tint); color: var(--brand); box-shadow: inset 0 0 0 1.5px var(--brand), var(--shadow-2); }
|
||||
.lp-demo .ps-post-text p { transition: opacity var(--dur-tap) var(--ease-standard); }
|
||||
.lp-demo .ps-post.is-busy .ps-post-text p { opacity: 0.4; }
|
||||
.lp-demo [data-demo-published] { color: var(--success); }
|
||||
.lp-persona-pill {
|
||||
display: inline-flex; align-items: center; gap: var(--space-2); justify-self: start; padding: 6px 12px 6px 6px;
|
||||
border-radius: var(--radius-pill); background: var(--surface-raised); box-shadow: var(--shadow-2);
|
||||
font: 500 13px/18px var(--font-text); color: var(--ink-secondary);
|
||||
}
|
||||
.features-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
.feature {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
padding: 28px 24px;
|
||||
}
|
||||
.feature-icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 12px;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 24px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.feature h3 { font-size: 18px; margin-bottom: 8px; }
|
||||
.feature p { color: var(--text-muted); font-size: 15px; }
|
||||
.lp-persona-pill b { color: var(--ink); font-weight: 600; }
|
||||
.lp-persona-pill .ps-sidenav-persona-icon { width: 28px; height: 28px; border-radius: 50%; }
|
||||
|
||||
/* How it works */
|
||||
.how {
|
||||
padding: 56px 0;
|
||||
background: var(--surface);
|
||||
border-top: 1px solid var(--border);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.how h2 { text-align: center; font-size: 30px; margin-bottom: 40px; }
|
||||
.steps {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 24px;
|
||||
}
|
||||
.step { text-align: center; padding: 0 12px; }
|
||||
.step-num {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: 0 auto 14px;
|
||||
}
|
||||
.step h4 { margin-bottom: 6px; }
|
||||
.step p { color: var(--text-muted); font-size: 15px; }
|
||||
/* Возможности */
|
||||
.lp-features { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 250px), 1fr)); gap: var(--space-4); }
|
||||
.lp-feature { display: grid; align-content: start; gap: var(--space-2); padding: var(--inset-card); border-radius: var(--radius-lg); background: var(--surface-raised); box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); }
|
||||
.lp-feature .ps-action-icon { margin-bottom: var(--space-2); }
|
||||
.lp-feature h3 { margin: 0; font: 600 20px/26px var(--font-display); color: var(--ink); }
|
||||
.lp-feature p { margin: 0; font: 400 15px/22px var(--font-text); color: var(--ink-secondary); }
|
||||
.lp-feature .lp-feature-ai { background: var(--indigo-tint); color: var(--indigo); }
|
||||
|
||||
/* CTA */
|
||||
.cta {
|
||||
padding: 72px 0;
|
||||
text-align: center;
|
||||
/* Как это работает */
|
||||
.lp-steps { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr)); gap: var(--space-4); counter-reset: step; list-style: none; margin: 0; padding: 0; }
|
||||
.lp-step { display: grid; align-content: start; gap: var(--space-2); padding: var(--inset-card); border-radius: var(--radius-lg); background: var(--surface-sunken); }
|
||||
.lp-step-num { display: grid; place-items: center; width: var(--tile-md); height: var(--tile-md); margin-bottom: var(--space-2); border-radius: var(--radius-sm); background: var(--brand); color: var(--on-brand); font: 700 17px/1 var(--font-display); font-variant-numeric: tabular-nums; }
|
||||
.lp-step h3 { margin: 0; font: 600 17px/24px var(--font-text); color: var(--ink); }
|
||||
.lp-step p { margin: 0; font: 400 15px/22px var(--font-text); color: var(--ink-secondary); }
|
||||
|
||||
/* Столпы контент-плана */
|
||||
.lp-split { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.15fr); gap: var(--space-12); align-items: center; }
|
||||
.lp-pillars { display: grid; gap: var(--space-4); }
|
||||
.lp-pillar-row { display: grid; gap: var(--space-2); }
|
||||
.lp-pillar-row p { margin: 0; color: var(--ink-secondary); }
|
||||
.lp-plan { display: grid; gap: var(--space-3); }
|
||||
.lp-plan .ps-planday { animation: none; box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline); }
|
||||
|
||||
/* Призыв */
|
||||
.lp-cta {
|
||||
display: grid; justify-items: center; gap: var(--space-4); padding: var(--space-12) var(--space-6); text-align: center;
|
||||
border-radius: var(--radius-xl); background: var(--surface-raised); box-shadow: var(--shadow-1), inset 0 0 0 1px var(--hairline);
|
||||
}
|
||||
.cta h2 { font-size: 30px; margin-bottom: 14px; }
|
||||
.cta p { color: var(--text-muted); font-size: 17px; margin-bottom: 28px; }
|
||||
.lp-cta .lp-lead { max-width: 36em; }
|
||||
|
||||
/* Footer */
|
||||
.footer {
|
||||
padding: 24px 0;
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
font-size: 14px;
|
||||
.lp-footer { padding: var(--space-8) 0 calc(var(--space-8) + env(safe-area-inset-bottom)); box-shadow: inset 0 1px 0 var(--hairline); }
|
||||
.lp-footer-inner { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-4); }
|
||||
.lp-footer nav { display: flex; flex-wrap: wrap; gap: var(--space-1); }
|
||||
.lp-footer small { font: 400 13px/18px var(--font-text); color: var(--ink-tertiary); }
|
||||
|
||||
@media (max-width: 959px) {
|
||||
.lp-hero-inner, .lp-split { grid-template-columns: minmax(0, 1fr); gap: var(--space-8); }
|
||||
.lp-display { font-size: 44px; line-height: 48px; }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.hero { padding: 48px 0 40px; }
|
||||
.hero h1 { font-size: 32px; }
|
||||
.hero p { font-size: 17px; }
|
||||
|
||||
/* Адаптивный хедер для мобильных: бургер-меню */
|
||||
.header { padding: 12px 0; }
|
||||
.header-inner { gap: 8px; }
|
||||
.brand { gap: 8px; font-size: 16px; }
|
||||
.brand-icon { width: 28px; height: 28px; font-size: 16px; }
|
||||
.header-actions { gap: 8px; }
|
||||
.theme-toggle { padding: 8px 10px; }
|
||||
|
||||
/* Скрываем кнопки "Войти" и "Регистрация" из хедера, показываем бургер */
|
||||
.header-login, .header-register { display: none; }
|
||||
.burger { display: flex; }
|
||||
}
|
||||
|
||||
@media (max-width: 400px) {
|
||||
/* На очень узких экранах скрываем текст бренда */
|
||||
.brand span:not(.brand-icon) { display: none; }
|
||||
.brand { gap: 0; }
|
||||
@media (max-width: 599px) {
|
||||
.lp-container { padding: 0 var(--space-4); }
|
||||
.lp-section { padding: var(--space-12) 0; }
|
||||
.lp-hero-inner { padding-block: var(--space-8) var(--space-12); }
|
||||
.lp-display { font-size: 36px; line-height: 40px; }
|
||||
.lp-hero-lead { font-size: 17px; line-height: 26px; }
|
||||
.lp-hero-actions .ps-btn { flex: 1 1 100%; }
|
||||
.lp-h2 { font-size: 24px; line-height: 30px; }
|
||||
.lp-header .lp-login { display: none; }
|
||||
.lp-long { display: none; }
|
||||
.lp-short { display: inline; }
|
||||
.lp-header .ps-logo-word { font-size: 14px; }
|
||||
}
|
||||
@media (max-width: 359px) { .lp-header .ps-logo-word { display: none; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header">
|
||||
<div class="container header-inner">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-icon">🤖</span>
|
||||
<span>ИИ Пресс-секретарь</span>
|
||||
</a>
|
||||
<div class="header-actions">
|
||||
<button type="button" class="btn btn-ghost theme-toggle" data-theme-toggle aria-label="Переключить тему">🌙</button>
|
||||
<a class="btn btn-ghost header-login" href="/login"><span>Войти</span></a>
|
||||
<a class="btn btn-primary header-register" href="/register">Регистрация</a>
|
||||
<button type="button" class="burger" id="burgerBtn" aria-label="Открыть меню" aria-expanded="false">
|
||||
<span class="burger-line"></span>
|
||||
<span class="burger-line"></span>
|
||||
<span class="burger-line"></span>
|
||||
</button>
|
||||
<body class="lp-body">
|
||||
<header class="lp-header app-glass">
|
||||
<div class="lp-container lp-header-inner">
|
||||
<a class="lp-logo" href="/" aria-label="ИИ Пресс-секретарь — на главную">{{ ui.logo('lphead', 'color', 32) }}</a>
|
||||
<div class="lp-header-actions">
|
||||
<button type="button" class="ps-iconbtn" data-theme-toggle aria-label="Сменить тему">{{ ui.icon('theme', 22) }}</button>
|
||||
<a class="ps-btn ps-btn--quiet lp-login" href="/login"><span class="ps-btn-label">Войти</span></a>
|
||||
<a class="ps-btn ps-btn--primary" href="/register" aria-label="Зарегистрироваться"><span class="ps-btn-label lp-long">Зарегистрироваться</span><span class="ps-btn-label lp-short">Начать</span></a>
|
||||
</div>
|
||||
</div>
|
||||
<nav class="mobile-menu" id="mobileMenu">
|
||||
<a class="btn btn-ghost mobile-menu-link" href="/login"><span>Войти</span></a>
|
||||
<a class="btn btn-primary mobile-menu-link" href="/register">Регистрация</a>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<section class="hero">
|
||||
<div class="container">
|
||||
<h1>Ваш личный <span>ИИ Пресс-секретарь</span></h1>
|
||||
<p>Создавайте контент-план, генерируйте посты и картинки для своего бизнеса и публикуйте их в Telegram — всё в одном сервисе.</p>
|
||||
<div class="hero-actions">
|
||||
<a class="btn btn-primary" href="/register">Начать бесплатно</a>
|
||||
<a class="btn btn-ghost" href="/login">Войти в кабинет</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<main id="main">
|
||||
<section class="lp-hero" data-daypart="day">
|
||||
<canvas class="lp-bg" aria-hidden="true"></canvas>
|
||||
<div class="lp-container lp-hero-inner">
|
||||
<div class="lp-hero-text">
|
||||
{{ ui.logo('lphero', 'white', 48, 'mark') }}
|
||||
<h1 class="lp-display">Пресс-секретарь, который говорит вашим голосом</h1>
|
||||
<p class="lp-hero-lead">Опишите бренд один раз — и нейросеть будет писать посты, рисовать картинки и строить контент-план в вашем стиле. Публикация в Telegram — в один клик.</p>
|
||||
<div class="lp-hero-actions">
|
||||
<a class="ps-btn ps-btn--lg lp-btn-white" href="/register">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Начать бесплатно</span></a>
|
||||
<a class="ps-btn ps-btn--lg lp-btn-outline" href="/login"><span class="ps-btn-label">Войти в кабинет</span></a>
|
||||
</div>
|
||||
<ul class="lp-hero-note">
|
||||
<li>{{ ui.icon('check', 18) }}Медиа-образ за 5 минут</li>
|
||||
<li>{{ ui.icon('check', 18) }}Без дизайнера и копирайтера</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<section class="features">
|
||||
<div class="container">
|
||||
<div class="features-grid">
|
||||
<div class="feature">
|
||||
<div class="feature-icon">✍️</div>
|
||||
<h3>Генерация постов</h3>
|
||||
<p>ИИ пишет готовые тексты для вашего бизнеса с учётом вашего медиа-образа и стиля.</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="feature-icon">🎨</div>
|
||||
<h3>Генерация картинок</h3>
|
||||
<p>Создавайте иллюстрации к постам автоматически — без дизайнера и фотостока.</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="feature-icon">📅</div>
|
||||
<h3>Контент-план</h3>
|
||||
<p>Планируйте публикации на неделю вперёд и следите за выполнением плана.</p>
|
||||
</div>
|
||||
<div class="feature">
|
||||
<div class="feature-icon">📣</div>
|
||||
<h3>Публикация в Telegram</h3>
|
||||
<p>Публикуйте посты в свои каналы прямо из личного кабинета.</p>
|
||||
<div class="lp-demo" id="demo" aria-label="Пример работы сервиса">
|
||||
<p class="lp-demo-cap">Пример — нажмите на команду и посмотрите, как работает кабинет</p>
|
||||
<div class="lp-demo-head">
|
||||
<span class="lp-persona-pill">
|
||||
<span class="ps-sidenav-persona-icon" aria-hidden="true">{{ ui.icon('persona', 16) }}</span>
|
||||
<span>Медиа-образ: <b data-demo-name>Пекарня «Тёплый хлеб»</b></span>
|
||||
</span>
|
||||
</div>
|
||||
<article class="ps-post" aria-live="polite">
|
||||
<header class="ps-post-head">
|
||||
<span class="ps-post-platform" data-demo-platform>{{ ui.icon('send', 16) }}Telegram</span>
|
||||
<span class="ps-post-tag" data-demo-style>Вовлекающий</span>
|
||||
<span class="ps-post-tag" data-demo-version hidden>Версия 2</span>
|
||||
</header>
|
||||
<div class="ps-post-text" data-demo-text></div>
|
||||
<footer class="ps-post-foot">
|
||||
<span class="ps-post-count" data-demo-count></span>
|
||||
<span class="ps-post-note" data-demo-published hidden>{{ ui.icon('check', 14) }}<span>Опубликовано</span></span>
|
||||
<div class="ps-post-actions">
|
||||
<button type="button" class="ps-btn ps-btn--primary ps-btn--sm" data-demo-publish>{{ ui.icon('send', 16) }}<span class="ps-btn-label">Опубликовать</span></button>
|
||||
</div>
|
||||
</footer>
|
||||
</article>
|
||||
<div class="ps-thinking" data-demo-thinking hidden role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Переписываю…</span></div>
|
||||
<div class="lp-demo-row" role="group" aria-label="Команды правки">
|
||||
<button type="button" class="ps-chip ps-chip--sm" data-demo-cmd="short">{{ ui.icon('sparkle', 16) }}<span>Сократи вдвое</span></button>
|
||||
<button type="button" class="ps-chip ps-chip--sm" data-demo-cmd="official">{{ ui.icon('sparkle', 16) }}<span>Сделай официальнее</span></button>
|
||||
<button type="button" class="ps-chip ps-chip--sm" data-demo-cmd="cta">{{ ui.icon('sparkle', 16) }}<span>Добавь призыв</span></button>
|
||||
<button type="button" class="ps-chip ps-chip--sm" data-demo-cmd="orig" hidden>{{ ui.icon('history', 16) }}<span>Вернуть исходный</span></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section class="how">
|
||||
<div class="container">
|
||||
<h2>Как это работает</h2>
|
||||
<div class="steps">
|
||||
<div class="step">
|
||||
<div class="step-num">1</div>
|
||||
<h4>Зарегистрируйтесь</h4>
|
||||
<p>Создайте аккаунт в личном кабинете за пару минут.</p>
|
||||
<section class="lp-section" aria-labelledby="features-title">
|
||||
<div class="lp-container">
|
||||
<div class="lp-head">
|
||||
<span class="lp-kicker">Что умеет</span>
|
||||
<h2 class="lp-h2" id="features-title">Весь контент — в одном кабинете</h2>
|
||||
<p class="lp-lead">Рядом с каждым результатом видно, по какому медиа-образу он сделан.</p>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-num">2</div>
|
||||
<h4>Опишите медиа-образ</h4>
|
||||
<p>Расскажите о своём бизнесе — ИИ подстроится под ваш стиль.</p>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-num">3</div>
|
||||
<h4>Генерируйте контент</h4>
|
||||
<p>Создавайте посты, картинки и контент-план автоматически.</p>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-num">4</div>
|
||||
<h4>Публикуйте</h4>
|
||||
<p>Отправляйте готовые посты в свои Telegram-каналы.</p>
|
||||
<div class="lp-features">
|
||||
<article class="lp-feature">
|
||||
<span class="ps-action-icon lp-feature-ai" aria-hidden="true">{{ ui.icon('persona', 20) }}</span>
|
||||
<h3>Медиа-образ</h3>
|
||||
<p>Анкета бренда, личности или сообщества. Можно заполнить автоматически по ссылке на канал.</p>
|
||||
</article>
|
||||
<article class="lp-feature">
|
||||
<span class="ps-action-icon" aria-hidden="true">{{ ui.icon('sparkle', 20) }}</span>
|
||||
<h3>Посты</h3>
|
||||
<p>Выберите платформу и стиль — пост готов. Правки готовыми командами: «Сократи вдвое», «Добавь призыв».</p>
|
||||
</article>
|
||||
<article class="lp-feature">
|
||||
<span class="ps-action-icon" aria-hidden="true">{{ ui.icon('image', 20) }}</span>
|
||||
<h3>Картинки</h3>
|
||||
<p>Иллюстрации к постам по шаблону или по концепциям, которые ИИ подберёт к тексту.</p>
|
||||
</article>
|
||||
<article class="lp-feature">
|
||||
<span class="ps-action-icon" aria-hidden="true">{{ ui.icon('megaphone', 20) }}</span>
|
||||
<h3>Публикация</h3>
|
||||
<p>Пост и фото уходят в ваш Telegram-канал одним сообщением — прямо из кабинета.</p>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section class="cta">
|
||||
<div class="container">
|
||||
<h2>Готовы начать?</h2>
|
||||
<p>Зарегистрируйтесь и получите доступ к личному кабинету.</p>
|
||||
<a class="btn btn-primary" href="/register">Зарегистрироваться</a>
|
||||
</div>
|
||||
</section>
|
||||
<section class="lp-section" aria-labelledby="plan-title">
|
||||
<div class="lp-container lp-split">
|
||||
<div class="lp-pillars">
|
||||
<div class="lp-head" style="margin-bottom: 0">
|
||||
<span class="lp-kicker">Контент-план</span>
|
||||
<h2 class="lp-h2" id="plan-title">Идеи на каждый день по трём столпам</h2>
|
||||
<p class="lp-lead">План строится по вашему медиа-образу. Нажмите «Создать пост» — идея и платформа подставятся сами.</p>
|
||||
</div>
|
||||
<div class="lp-pillar-row">
|
||||
<div class="app-legend">
|
||||
<span class="ps-pillar ps-pillar--1"><span class="ps-pillar-mark" aria-hidden="true"></span>О продукте</span>
|
||||
<span class="ps-pillar ps-pillar--2"><span class="ps-pillar-mark" aria-hidden="true"></span>Экспертиза</span>
|
||||
<span class="ps-pillar ps-pillar--3"><span class="ps-pillar-mark" aria-hidden="true"></span>Вовлечение</span>
|
||||
</div>
|
||||
<p class="form-hint">Пример для компании. У личного бренда и сообщества — свои столпы.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="lp-plan" aria-label="Пример контент-плана">
|
||||
<div class="ps-planday is-done">
|
||||
<div class="ps-planday-date"><span class="ps-planday-num">12</span><span class="ps-planday-wd">пн</span></div>
|
||||
<div class="ps-planday-body">
|
||||
<div class="ps-planday-meta"><span class="ps-pillar ps-pillar--1"><span class="ps-pillar-mark"></span>О продукте</span><span class="ps-planday-platform">{{ ui.icon('send', 14) }}Telegram</span></div>
|
||||
<p class="ps-planday-idea">Почему наш хлеб пахнет так, будто его испекли пять минут назад</p>
|
||||
</div>
|
||||
<div class="ps-planday-action"><span class="ps-badge ps-badge--success">{{ ui.icon('sparkle', 14) }}<span>Пост готов</span></span></div>
|
||||
</div>
|
||||
<div class="ps-planday">
|
||||
<div class="ps-planday-date"><span class="ps-planday-num">13</span><span class="ps-planday-wd">вт</span></div>
|
||||
<div class="ps-planday-body">
|
||||
<div class="ps-planday-meta"><span class="ps-pillar ps-pillar--2"><span class="ps-pillar-mark"></span>Экспертиза</span><span class="ps-planday-platform">{{ ui.icon('image', 14) }}Instagram</span></div>
|
||||
<p class="ps-planday-idea">Закваска или дрожжи: в чём разница — разбираем с технологом</p>
|
||||
</div>
|
||||
<div class="ps-planday-action"><button type="button" class="ps-btn ps-btn--secondary ps-btn--sm" data-demo-plan>{{ ui.icon('sparkle', 16) }}<span class="ps-btn-label">Создать пост</span></button></div>
|
||||
</div>
|
||||
<div class="ps-planday">
|
||||
<div class="ps-planday-date"><span class="ps-planday-num">14</span><span class="ps-planday-wd">ср</span></div>
|
||||
<div class="ps-planday-body">
|
||||
<div class="ps-planday-meta"><span class="ps-pillar ps-pillar--3"><span class="ps-pillar-mark"></span>Вовлечение</span><span class="ps-planday-platform">{{ ui.icon('send', 14) }}Telegram</span></div>
|
||||
<p class="ps-planday-idea">Опрос: какой хлеб испечь в субботу — ржаной или с семечками?</p>
|
||||
</div>
|
||||
<div class="ps-planday-action"><button type="button" class="ps-btn ps-btn--secondary ps-btn--sm" data-demo-plan>{{ ui.icon('sparkle', 16) }}<span class="ps-btn-label">Создать пост</span></button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer class="footer">
|
||||
<div class="container">
|
||||
© 2026 ИИ Пресс-секретарь · <a href="/login">Вход</a> · <a href="/register">Регистрация</a> · <a href="/dashboard">Кабинет</a>
|
||||
<section class="lp-section" aria-labelledby="how-title">
|
||||
<div class="lp-container">
|
||||
<div class="lp-head">
|
||||
<span class="lp-kicker">Как это работает</span>
|
||||
<h2 class="lp-h2" id="how-title">Четыре шага до первого поста</h2>
|
||||
</div>
|
||||
<ol class="lp-steps">
|
||||
<li class="lp-step"><span class="lp-step-num" aria-hidden="true">1</span><h3>Зарегистрируйтесь</h3><p>Имя, телефон, email и пароль — аккаунт готов за минуту.</p></li>
|
||||
<li class="lp-step"><span class="lp-step-num" aria-hidden="true">2</span><h3>Опишите медиа-образ</h3><p>Кто вы, чем полезны, как говорите. Или дайте ссылку на канал — ИИ заполнит сам.</p></li>
|
||||
<li class="lp-step"><span class="lp-step-num" aria-hidden="true">3</span><h3>Создавайте контент</h3><p>Посты, картинки и план на неделю вперёд — в вашем стиле.</p></li>
|
||||
<li class="lp-step"><span class="lp-step-num" aria-hidden="true">4</span><h3>Публикуйте</h3><p>Добавьте Telegram-канал и отправляйте готовые посты в один клик.</p></li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="lp-section">
|
||||
<div class="lp-container">
|
||||
<div class="lp-cta">
|
||||
{{ ui.logo('lpcta', 'color', 56, 'mark') }}
|
||||
<h2 class="lp-h2">Начните с медиа-образа — это 5 минут</h2>
|
||||
<p class="lp-lead">После регистрации кабинет сразу предложит заполнить анкету. Первый пост — через пару минут после неё.</p>
|
||||
<div class="app-actions" style="justify-content: center">
|
||||
<a class="ps-btn ps-btn--primary ps-btn--lg" href="/register">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Начать бесплатно</span></a>
|
||||
<a class="ps-btn ps-btn--quiet ps-btn--lg" href="/login"><span class="ps-btn-label">У меня есть аккаунт</span></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer class="lp-footer">
|
||||
<div class="lp-container lp-footer-inner">
|
||||
{{ ui.logo('lpfoot', 'mono', 28) }}
|
||||
<nav aria-label="Ссылки">
|
||||
<a class="ps-btn ps-btn--quiet ps-btn--sm" href="/login"><span class="ps-btn-label">Вход</span></a>
|
||||
<a class="ps-btn ps-btn--quiet ps-btn--sm" href="/register"><span class="ps-btn-label">Регистрация</span></a>
|
||||
<a class="ps-btn ps-btn--quiet ps-btn--sm" href="/dashboard"><span class="ps-btn-label">Кабинет</span></a>
|
||||
</nav>
|
||||
<small>© 2026 ИИ Пресс-секретарь</small>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="/static/press/glass.js?v=4" defer></script>
|
||||
<script src="/static/press/hero-bg.js?v=13" defer></script>
|
||||
<script>
|
||||
(function () {
|
||||
function isDark() {
|
||||
return document.documentElement.getAttribute('data-theme') !== 'light';
|
||||
}
|
||||
function setIcon(btn) {
|
||||
if (btn) btn.textContent = isDark() ? '\u2600\uFE0F' : '\uD83C\uDF19';
|
||||
}
|
||||
document.addEventListener('click', function (e) {
|
||||
var btn = e.target.closest('[data-theme-toggle]');
|
||||
if (!btn) return;
|
||||
if (isDark()) {
|
||||
document.documentElement.setAttribute('data-theme', 'light');
|
||||
try { localStorage.setItem('theme', 'light'); } catch (err) {}
|
||||
} else {
|
||||
document.documentElement.removeAttribute('data-theme');
|
||||
try { localStorage.setItem('theme', 'dark'); } catch (err) {}
|
||||
}
|
||||
setIcon(btn);
|
||||
/* Вариант узора по времени суток у посетителя: утро 5–11, день 11–17, вечер 17–22, ночь 22–5 */
|
||||
(function () {
|
||||
var hero = document.querySelector('.lp-hero');
|
||||
if (!hero) return;
|
||||
var h = new Date().getHours();
|
||||
var part = h >= 5 && h < 11 ? 'morning' : h < 17 && h >= 11 ? 'day' : h >= 17 && h < 22 ? 'evening' : 'night';
|
||||
var q = new URLSearchParams(location.search).get('daypart');
|
||||
if (q && /^(morning|day|evening|night)$/.test(q)) part = q;
|
||||
hero.setAttribute('data-daypart', part);
|
||||
})();
|
||||
</script>
|
||||
<template id="tpl-pl-telegram">{{ ui.icon('send', 16) }}</template>
|
||||
<template id="tpl-pl-instagram">{{ ui.icon('image', 16) }}</template>
|
||||
<template id="tpl-pl-linkedin">{{ ui.icon('building', 16) }}</template>
|
||||
<template id="tpl-ready"><span class="ps-badge ps-badge--success">{{ ui.icon('sparkle', 14) }}<span>Пост готов</span></span></template>
|
||||
<script>
|
||||
/* Живой пример на первом экране: 10 медиа-образов, у каждого три правки. Ничего не отправляется. */
|
||||
(function () {
|
||||
var demo = document.getElementById('demo');
|
||||
if (!demo) return;
|
||||
var EX = [{"name": "Пекарня «Тёплый хлеб»", "platform": "telegram", "style": "Вовлекающий", "orig": ["Наш хлеб пахнет так, будто его испекли пять минут назад. Потому что так и есть: печём с 6:30 до 17:00 и ничего не замораживаем.", "Артёма, 84. До 9 утра к багету — кофе в подарок."], "short": ["Печём с 6:30 до 17:00 и ничего не замораживаем.", "Артёма, 84. До 9 утра к багету — кофе в подарок."], "official": ["Пекарня «Тёплый хлеб» печёт хлеб каждый день с 6:30 до 17:00 и не использует замороженное тесто.", "Адрес: ул. Артёма, 84. До 9:00 к каждому багету — кофе в подарок."], "cta": "Заходите утром: первая партия ещё тёплая."}, {"name": "Стоматология «Улыбка рядом»", "platform": "instagram", "style": "Экспертный", "orig": ["Зубы реагируют на холодное — это не повод терпеть. Чаще всего дело в истончённой эмали или открытых шейках зубов.", "На осмотре за 20 минут найдём причину и подберём пасту или защитное покрытие. Ул. Университетская, 12."], "short": ["Зубы реагируют на холодное? Чаще всего виновата истончённая эмаль.", "Найдём причину за 20 минут осмотра. Ул. Университетская, 12."], "official": ["Повышенная чувствительность зубов к холодному обычно связана с истончением эмали или обнажением шеек зубов.", "Клиника «Улыбка рядом» проводит диагностику за 20 минут и подбирает лечение. Адрес: ул. Университетская, 12."], "cta": "Запишитесь на осмотр по телефону в профиле — подберём удобное время."}, {"name": "Автосервис «Гараж на Шахтёрской»", "platform": "telegram", "style": "Экспертный", "orig": ["Скрип при торможении — первый звонок: колодки стёрлись до сигнальной пластины. Если тянуть, пострадают и диски.", "Колодки меняем за час и заодно проверяем тормозную жидкость."], "short": ["Тормоза скрипят — пора менять колодки, пока целы диски.", "Меняем за час."], "official": ["Скрип при торможении указывает на износ тормозных колодок. Своевременная замена предотвращает повреждение тормозных дисков.", "Автосервис выполняет замену колодок за один час, включая проверку тормозной жидкости."], "cta": "Запишитесь заранее: на субботу окна заканчиваются уже в четверг."}, {"name": "Волонтёрский центр «Рядом»", "platform": "telegram", "style": "Вовлекающий", "orig": ["В субботу собираем подарки для пожилых жителей нашего района. Нужны тёплые носки, чай и открытки, подписанные от руки.", "Пункт сбора — библиотека на Артёма, 45, с 10:00 до 16:00."], "short": ["В субботу собираем тёплые носки, чай и открытки для пожилых соседей.", "Библиотека на Артёма, 45, с 10:00 до 16:00."], "official": ["В субботу волонтёрский центр «Рядом» проводит сбор подарков для пожилых жителей района: тёплых носков, чая и подписанных открыток.", "Пункт приёма — библиотека по адресу ул. Артёма, 45, с 10:00 до 16:00."], "cta": "Не получается прийти? Напишите нам — заберём подарок сами."}, {"name": "Фитнес-студия «Пульс»", "platform": "instagram", "style": "Продающий", "orig": ["Первая тренировка — бесплатно. Тренер покажет технику, подберёт нагрузку и составит план на месяц.", "Группы утром, днём и вечером — время Line truncated
|
||||
var PLATFORM = { telegram: ['send', 'Telegram', '@канал'], instagram: ['image', 'Instagram', 'профиль'], linkedin: ['building', 'LinkedIn', 'профиль'] };
|
||||
var STYLE_AFTER = { official: 'Официальный' };
|
||||
var post = demo.querySelector('.ps-post'), textEl = demo.querySelector('[data-demo-text]');
|
||||
var count = demo.querySelector('[data-demo-count]'), ver = demo.querySelector('[data-demo-version]');
|
||||
var thinking = demo.querySelector('[data-demo-thinking]'), chips = demo.querySelectorAll('[data-demo-cmd]');
|
||||
var pub = demo.querySelector('[data-demo-publish]'), pubNote = demo.querySelector('[data-demo-published]');
|
||||
var idx = 0, version = 1, current = 'orig', busy = false;
|
||||
function paras(ex, key) { return key === 'cta' ? ex.orig.concat([ex.cta]) : ex[key]; }
|
||||
function render(key) {
|
||||
var ex = EX[idx];
|
||||
textEl.innerHTML = '';
|
||||
paras(ex, key).forEach(function (t) { var p = document.createElement('p'); p.textContent = t; textEl.appendChild(p); });
|
||||
var limit = ex.platform === 'instagram' ? 2200 : ex.platform === 'linkedin' ? 3000 : 4096;
|
||||
count.textContent = paras(ex, key).join('\n\n').length.toLocaleString('ru-RU') + ' / ' + limit.toLocaleString('ru-RU') + ' зн.';
|
||||
demo.querySelector('[data-demo-style]').textContent = STYLE_AFTER[key] || ex.style;
|
||||
}
|
||||
function resetPublish() {
|
||||
pub.disabled = false; pub.querySelector('.ps-btn-label').textContent = 'Опубликовать';
|
||||
pub.classList.add('ps-btn--primary'); pub.classList.remove('ps-btn--secondary'); pubNote.hidden = true;
|
||||
}
|
||||
function resetChips() {
|
||||
chips.forEach(function (x) { x.disabled = false; x.classList.remove('is-selected'); });
|
||||
demo.querySelector('[data-demo-cmd="orig"]').hidden = true;
|
||||
}
|
||||
function show(i) {
|
||||
var ex = EX[i];
|
||||
idx = i; version = 1; current = 'orig';
|
||||
demo.querySelector('[data-demo-name]').textContent = ex.name;
|
||||
var pl = PLATFORM[ex.platform];
|
||||
demo.querySelector('[data-demo-platform]').innerHTML = document.getElementById('tpl-pl-' + ex.platform).innerHTML + pl[1];
|
||||
ver.hidden = true; render('orig'); resetChips(); resetPublish();
|
||||
}
|
||||
/* Случайный пример при каждом открытии; не повторяем показанный в прошлый раз */
|
||||
var start = Math.floor(Math.random() * EX.length);
|
||||
try {
|
||||
var last = +localStorage.getItem('lp-demo-last');
|
||||
if (start === last) start = (start + 1 + Math.floor(Math.random() * (EX.length - 1))) % EX.length;
|
||||
localStorage.setItem('lp-demo-last', start);
|
||||
} catch (e) {}
|
||||
show(start);
|
||||
chips.forEach(function (c) {
|
||||
c.addEventListener('click', function () {
|
||||
var key = c.getAttribute('data-demo-cmd');
|
||||
if (key === current || busy) return;
|
||||
busy = true;
|
||||
chips.forEach(function (x) { x.disabled = true; });
|
||||
pub.disabled = true;
|
||||
post.classList.add('is-busy'); thinking.hidden = false;
|
||||
thinking.querySelector('span:last-child').textContent = key === 'orig' ? 'Возвращаю версию…' : 'Переписываю…';
|
||||
setTimeout(function () {
|
||||
render(key); current = key; version += 1; busy = false;
|
||||
ver.hidden = false; ver.textContent = 'Версия ' + version;
|
||||
post.classList.remove('is-busy'); thinking.hidden = true;
|
||||
chips.forEach(function (x) { x.disabled = false; x.classList.toggle('is-selected', x === c && key !== 'orig'); });
|
||||
demo.querySelector('[data-demo-cmd="orig"]').hidden = key === 'orig';
|
||||
resetPublish();
|
||||
}, 900);
|
||||
});
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
setIcon(document.querySelector('[data-theme-toggle]'));
|
||||
});
|
||||
pub.addEventListener('click', function () {
|
||||
if (busy) return;
|
||||
pub.disabled = true; pub.querySelector('.ps-btn-label').textContent = 'Публикую…';
|
||||
setTimeout(function () {
|
||||
pub.querySelector('.ps-btn-label').textContent = 'Опубликовано';
|
||||
pub.classList.remove('ps-btn--primary'); pub.classList.add('ps-btn--secondary');
|
||||
pubNote.querySelector('span').textContent = 'Опубликовано в ' + PLATFORM[EX[idx].platform][1];
|
||||
pubNote.hidden = false;
|
||||
}, 700);
|
||||
});
|
||||
/* Контент-план: «Создать пост» готовит пост и отмечает день */
|
||||
document.querySelectorAll('[data-demo-plan]').forEach(function (b) {
|
||||
b.addEventListener('click', function () {
|
||||
b.disabled = true; b.querySelector('.ps-btn-label').textContent = 'Пишу пост…';
|
||||
setTimeout(function () {
|
||||
b.closest('.ps-planday').classList.add('is-done');
|
||||
b.parentNode.innerHTML = document.getElementById('tpl-ready').innerHTML;
|
||||
}, 900);
|
||||
});
|
||||
|
||||
// Бургер-меню
|
||||
var burgerBtn = document.getElementById('burgerBtn');
|
||||
var mobileMenu = document.getElementById('mobileMenu');
|
||||
if (burgerBtn && mobileMenu) {
|
||||
function toggleMenu(force) {
|
||||
var isOpen = typeof force === 'boolean' ? force : !mobileMenu.classList.contains('open');
|
||||
mobileMenu.classList.toggle('open', isOpen);
|
||||
burgerBtn.classList.toggle('open', isOpen);
|
||||
burgerBtn.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
|
||||
burgerBtn.setAttribute('aria-label', isOpen ? 'Закрыть меню' : 'Открыть меню');
|
||||
}
|
||||
burgerBtn.addEventListener('click', function (e) {
|
||||
e.stopPropagation();
|
||||
toggleMenu();
|
||||
});
|
||||
// Закрытие при клике по ссылке в меню
|
||||
mobileMenu.addEventListener('click', function (e) {
|
||||
if (e.target.closest('a')) toggleMenu(false);
|
||||
});
|
||||
// Закрытие при клике вне меню
|
||||
document.addEventListener('click', function (e) {
|
||||
if (mobileMenu.classList.contains('open') &&
|
||||
!e.target.closest('.header-inner') &&
|
||||
!e.target.closest('.mobile-menu')) {
|
||||
toggleMenu(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,15 +1,20 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Вход — Личный кабинет{% endblock %}
|
||||
{% block title %}Вход{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Вход</h1>
|
||||
<form method="post" action="/login" class="form">
|
||||
<label>Email
|
||||
<input type="email" name="email" value="{{ form.email if form else '' }}" required>
|
||||
</label>
|
||||
<label>Пароль
|
||||
<input type="password" name="password" required>
|
||||
</label>
|
||||
<button type="submit">Войти</button>
|
||||
<div class="app-stack">
|
||||
<h1 class="ps-h2">Вход в кабинет</h1>
|
||||
<p class="ps-lead">Посты, картинки и контент-план — вашим голосом.</p>
|
||||
</div>
|
||||
<form method="post" action="/login" class="app-form">
|
||||
<div class="ps-field">
|
||||
<label for="email" class="ps-field-label">Email</label>
|
||||
<input id="email" class="ps-field-control" type="email" name="email" autocomplete="email" value="{{ form.email if form else '' }}" required>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="password" class="ps-field-label">Пароль</label>
|
||||
<input id="password" class="ps-field-control" type="password" name="password" autocomplete="current-password" required>
|
||||
</div>
|
||||
<button type="submit" class="ps-btn ps-btn--primary ps-btn--lg ps-btn--block">Войти</button>
|
||||
</form>
|
||||
<p>Ещё нет аккаунта? <a href="/register">Зарегистрироваться</a></p>
|
||||
<p class="app-auth-switch">Ещё нет аккаунта? <a href="/register">Зарегистрироваться</a></p>
|
||||
{% endblock %}
|
||||
@@ -1,89 +1,122 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Контент-план — Личный кабинет{% endblock %}
|
||||
{% block title %}Контент-план{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Контент-план</h1>
|
||||
|
||||
{% if plan %}
|
||||
<div class="chips">
|
||||
<span class="chip chip-planned">📝 В плане: {{ status_counts.get('planned', 0) }}</span>
|
||||
<span class="chip chip-published">✅ Опубликовано: {{ status_counts.get('published', 0) }}</span>
|
||||
<span class="chip chip-postponed">🕓 Отложено: {{ status_counts.get('postponed', 0) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="plan-list">
|
||||
{% for item in plan %}
|
||||
<div class="card plan-item status-{{ item.status }}">
|
||||
<div class="plan-item-head">
|
||||
<span class="plan-day">День {{ item.day }}</span>
|
||||
<span class="plan-platform">{{ platform_label(item.platform) }}</span>
|
||||
<span class="status-badge status-{{ item.status }}">
|
||||
{% if item.status == 'published' %}✅ Опубликовано
|
||||
{% elif item.status == 'postponed' %}🕓 Отложено
|
||||
{% else %}📝 В плане{% endif %}
|
||||
</span>
|
||||
</div>
|
||||
<div class="plan-idea">{{ item.idea }}</div>
|
||||
<div class="post-actions">
|
||||
<a href="/generate?plan_id={{ item.id }}&platform={{ item.platform }}&idea={{ item.idea | urlencode }}" class="copy-btn">✍️ Создать пост</a>
|
||||
<form method="post" action="/plan/{{ item.id }}/status" class="inline-form">
|
||||
<select name="status" class="status-select">
|
||||
<option value="planned" {% if item.status == 'planned' %}selected{% endif %}>📝 В плане</option>
|
||||
<option value="published" {% if item.status == 'published' %}selected{% endif %}>✅ Опубликовано</option>
|
||||
<option value="postponed" {% if item.status == 'postponed' %}selected{% endif %}>🕓 Отложено</option>
|
||||
</select>
|
||||
<button type="submit" class="copy-btn">Сохранить</button>
|
||||
</form>
|
||||
<form method="post" action="/plan/{{ item.id }}/delete" class="inline-form"
|
||||
onsubmit="return confirm('Удалить этот пункт плана?');">
|
||||
<button type="submit" class="button-link button-link-danger">🗑 Удалить</button>
|
||||
</form>
|
||||
</div>
|
||||
{%- set status_meta = {
|
||||
'planned': ('neutral', 'edit', 'В плане'),
|
||||
'published': ('success', 'megaphone', 'Опубликовано'),
|
||||
'postponed': ('warning', 'clock', 'Отложено'),
|
||||
} -%}
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Контент-план</h1>
|
||||
{% if plan %}<p class="ps-lead">{{ plan|length }} {{ plural(plan|length, ['идея', 'идеи', 'идей']) }} для постов. Нажмите «Создать пост» — идея и платформа подставятся сами.</p>
|
||||
{% else %}<p class="ps-lead">Идеи постов на каждый день — по вашему медиа-образу.</p>{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p>Контент-плана пока нет. Составь его на 1–14 дней — он будет сохранён, и ты сможешь отмечать опубликованные и отложенные посты.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<h2>{% if plan %}Пересоставить план{% else %}Составить план{% endif %}</h2>
|
||||
|
||||
<div id="taskError" class="task-error"></div>
|
||||
|
||||
<div id="taskLoader" class="task-loader">
|
||||
<div class="spinner"></div>
|
||||
<div class="task-loader-text">Составляю контент-план...</div>
|
||||
<div class="task-loader-sub">Генерация занимает 20–60 секунд</div>
|
||||
</div>
|
||||
|
||||
<div id="taskResult" class="task-result"></div>
|
||||
<div class="ps-split" style="--ps-aside: 340px">
|
||||
<section class="app-stack-lg">
|
||||
{% if plan %}
|
||||
<div class="app-legend" aria-label="Статусы">
|
||||
<span class="ps-badge ps-badge--neutral">{{ ui.icon('edit', 14) }}<span>В плане: {{ status_counts.get('planned', 0) }}</span></span>
|
||||
<span class="ps-badge ps-badge--success">{{ ui.icon('megaphone', 14) }}<span>Опубликовано: {{ status_counts.get('published', 0) }}</span></span>
|
||||
<span class="ps-badge ps-badge--warning">{{ ui.icon('clock', 14) }}<span>Отложено: {{ status_counts.get('postponed', 0) }}</span></span>
|
||||
</div>
|
||||
<div class="app-stack">
|
||||
{% for item in plan %}
|
||||
{%- set st = status_meta.get(item.status, status_meta.planned) -%}
|
||||
<div class="ps-planday{% if item.status == 'published' %} is-done{% endif %}">
|
||||
<div class="ps-planday-date">
|
||||
<span class="ps-planday-num">{{ item.day }}</span>
|
||||
<span class="ps-planday-wd">день</span>
|
||||
</div>
|
||||
<div class="ps-planday-body">
|
||||
<div class="ps-planday-meta">
|
||||
<span class="ps-badge ps-badge--{{ st[0] }}">{{ ui.icon(st[1], 14) }}<span>{{ st[2] }}</span></span>
|
||||
<span class="ps-planday-platform">{{ ui.icon('send' if item.platform == 'telegram' else 'news', 14) }}{{ platform_label(item.platform) }}</span>
|
||||
</div>
|
||||
<p class="ps-planday-idea">{{ item.idea }}</p>
|
||||
<div class="app-actions">
|
||||
<form method="post" action="/plan/{{ item.id }}/status" class="inline-form plan-status-form">
|
||||
<label class="visually-hidden" for="st-{{ item.id }}">Статус пункта</label>
|
||||
<select id="st-{{ item.id }}" name="status" class="status-select app-status-select" onchange="this.form.submit()">
|
||||
<option value="planned" {% if item.status == 'planned' %}selected{% endif %}>В плане</option>
|
||||
<option value="published" {% if item.status == 'published' %}selected{% endif %}>Опубликовано</option>
|
||||
<option value="postponed" {% if item.status == 'postponed' %}selected{% endif %}>Отложено</option>
|
||||
</select>
|
||||
<noscript><button type="submit" class="ps-btn ps-btn--quiet ps-btn--sm">Сохранить</button></noscript>
|
||||
</form>
|
||||
<form method="post" action="/plan/{{ item.id }}/delete" class="inline-form"
|
||||
data-confirm="Удалить этот пункт плана?">
|
||||
<button type="submit" class="ps-iconbtn" aria-label="Удалить пункт плана, день {{ item.day }}">{{ ui.icon('trash', 20) }}</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ps-planday-action">
|
||||
<a href="/generate?plan_id={{ item.id }}&platform={{ item.platform }}&idea={{ item.idea | urlencode }}" class="ps-btn ps-btn--secondary ps-btn--sm">{{ ui.icon('sparkle', 16) }}<span class="ps-btn-label">Создать пост</span></a>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="ps-panel">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('calendar', 28) }}</span>
|
||||
<h2 class="ps-empty-title">Плана пока нет</h2>
|
||||
<p class="ps-empty-text">Выберите период в параметрах и нажмите «Сгенерировать план». Отмечайте опубликованные и отложенные посты — статистика соберётся сама.</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<div id="taskForm">
|
||||
<form method="post" action="/plan" class="form" id="planForm" onsubmit="return startPlanGen(event)">
|
||||
<label>На сколько дней (1-14)
|
||||
<input type="number" name="days" min="1" max="14" value="7" required>
|
||||
</label>
|
||||
<input type="hidden" name="task_type" value="generate_plan">
|
||||
<button type="submit">📅 Составить план</button>
|
||||
</form>
|
||||
<aside class="ps-panel app-plan-params" aria-labelledby="plan-params">
|
||||
<h2 class="ps-h2" id="plan-params">Параметры</h2>
|
||||
<div id="taskError" class="task-error" role="alert"></div>
|
||||
<div id="taskLoader" class="task-loader">
|
||||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Составляю план…</span></div>
|
||||
<span class="task-loader-sub">Обычно 20–60 секунд</span>
|
||||
</div>
|
||||
<div id="taskResult" class="task-result"></div>
|
||||
<div id="taskForm">
|
||||
<form method="post" action="/plan" class="app-form" id="planForm" onsubmit="return startPlanGen(event)">
|
||||
<div class="ps-field">
|
||||
<div class="ps-field-top">
|
||||
<label for="days" class="ps-field-label">Период</label>
|
||||
<output for="days" class="ps-slider-value" id="daysOut">7 дней</output>
|
||||
</div>
|
||||
<input id="days" type="range" name="days" class="ps-slider" min="1" max="14" step="1" value="7" style="--ps-pct: 46.15%">
|
||||
<div class="ps-slider-scale" aria-hidden="true"><span>1 день</span><span>14 дней</span></div>
|
||||
</div>
|
||||
{% if active_persona %}
|
||||
<p class="form-hint">Медиа-образ: {{ active_persona.title }}.</p>
|
||||
{% endif %}
|
||||
<input type="hidden" name="task_type" value="generate_plan">
|
||||
<button type="submit" class="ps-btn ps-btn--primary ps-btn--block">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">{{ 'Пересоставить план' if plan else 'Сгенерировать план' }}</span></button>
|
||||
{% if plan %}<p class="form-hint">Новый план заменит текущий.</p>{% endif %}
|
||||
</form>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<p><a href="/dashboard">← Назад в кабинет</a></p>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
(function () {
|
||||
var r = document.getElementById('days'), out = document.getElementById('daysOut');
|
||||
function sync() {
|
||||
var v = +r.value;
|
||||
out.textContent = v + ' ' + (function (n) { var a = n % 100, b = n % 10; if (a > 10 && a < 20) return 'дней'; if (b > 1 && b < 5) return 'дня'; if (b === 1) return 'день'; return 'дней'; })(v);
|
||||
r.style.setProperty('--ps-pct', ((v - r.min) / (r.max - r.min) * 100) + '%');
|
||||
}
|
||||
r.addEventListener('input', sync); sync();
|
||||
})();
|
||||
function startPlanGen(e) {
|
||||
e.preventDefault();
|
||||
var form = document.getElementById('planForm');
|
||||
TaskEngine.start(form, {
|
||||
loaderId: 'taskLoader',
|
||||
formId: 'taskForm',
|
||||
errorId: 'taskError',
|
||||
resultId: 'taskResult',
|
||||
onDone: function(result) {
|
||||
var html = '<div class="card"><p>✅ План на ' + result.days + ' дн. составлен! (' + result.items + ' пунктов)</p>' +
|
||||
'<p><a href="/plan" class="copy-btn">Обновить страницу →</a></p></div>';
|
||||
document.getElementById('taskResult').innerHTML = html;
|
||||
document.getElementById('taskResult').style.display = 'block';
|
||||
TaskEngine.start(document.getElementById('planForm'), {
|
||||
loaderId: 'taskLoader', formId: 'taskForm', errorId: 'taskError', resultId: 'taskResult',
|
||||
onDone: function (result) {
|
||||
Press.toast('План готов: ' + result.items + ' ' + Press.plural(result.items, ['идея', 'идеи', 'идей']), 'success', 'Обновляю страницу…');
|
||||
setTimeout(function () { location.reload(); }, 900);
|
||||
}
|
||||
});
|
||||
return false;
|
||||
|
||||
@@ -1,449 +1,529 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Пост — Личный кабинет{% endblock %}
|
||||
{% block title %}Пост{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Пост</h1>
|
||||
<div class="card">
|
||||
<div class="post-meta">
|
||||
{{ platform_label(post.platform) }} · {{ post.created_at }}
|
||||
{% if post.style %} · Стиль: {{ post.style }}{% endif %}
|
||||
{%- set art_for = {'product': 'product', 'lifestyle': 'portrait', 'food': 'product', 'business': 'mockup', 'abstract': 'abstract',
|
||||
'portrait': 'portrait', 'infographic': 'announce', 'banner': 'cover', 'nature': 'landscape', 'minimal': 'minimal',
|
||||
'story': 'collage', 'before_after': 'collage'} -%}
|
||||
{%- set limits = {'telegram': 4096, 'instagram': 2200, 'linkedin': 3000, 'twitter': 280} -%}
|
||||
{%- set limit = limits.get(post.platform, 4096) -%}
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/history" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">Мои посты</span></a>
|
||||
<h1 class="ps-h1">Пост</h1>
|
||||
<p class="ps-lead">{{ platform_label(post.platform) }}{% if post.style %} · {{ post.style }}{% endif %} · {{ post.created_at|local_dt }}</p>
|
||||
</div>
|
||||
{% if post.published %}
|
||||
<div class="post-meta" style="color: var(--success-text);">
|
||||
✅ Опубликован в «{{ post.published_to }}» · {{ post.published_at }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if post.wishes %}
|
||||
<div class="post-notes"><strong>Пожелания:</strong> {{ post.wishes }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- === ТЕКУЩИЙ ТЕКСТ ПОСТА === -->
|
||||
<div class="card" id="postCard">
|
||||
<h2>📄 Текст поста</h2>
|
||||
<div class="post-content" id="postContent">{{ post.content }}</div>
|
||||
<div class="post-editor-actions" style="margin-top: 12px;">
|
||||
<button type="button" class="copy-btn" onclick="copyPostText()">📋 Копировать</button>
|
||||
<a class="copy-btn" href="/posts/{{ post.id }}/publish">📤 Опубликовать</a>
|
||||
<a class="button-link" href="/posts/{{ post.id }}/edit">✏️ Редактировать вручную</a>
|
||||
<div class="app-head-actions">
|
||||
<form method="post" action="/posts/{{ post.id }}/delete" class="inline-form" data-confirm="Удалить пост?" data-confirm-body="Его версии и картинки тоже удалятся.">
|
||||
<button type="submit" class="ps-iconbtn" aria-label="Удалить пост">{{ ui.icon('trash', 22) }}</button>
|
||||
</form>
|
||||
<a class="ps-btn ps-btn--primary" href="/posts/{{ post.id }}/publish">{{ ui.icon('send', 20) }}<span class="ps-btn-label">Опубликовать</span></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- === ЧАТ С НЕЙРОСЕТЬЮ === -->
|
||||
<div class="card">
|
||||
<h2>🤖 Редактировать с помощью ИИ</h2>
|
||||
<p class="form-hint">Напишите, что нужно изменить — нейросеть перепишет пост. Например: «сократи вдвое», «сделай официальнее», «добавь призыв к действию».</p>
|
||||
<div class="ps-split" style="--ps-aside: 360px">
|
||||
<div class="app-stack-lg">
|
||||
<!-- Текущий текст поста -->
|
||||
<article class="ps-post" id="postCard">
|
||||
<header class="ps-post-head">
|
||||
<span class="ps-post-platform">{{ ui.icon('send' if post.platform == 'telegram' else 'news', 16) }}{{ platform_label(post.platform) }}</span>
|
||||
{% if post.style %}<span class="ps-post-tag">{{ post.style }}</span>{% endif %}
|
||||
<span class="ps-post-tag" id="postVersion"{% if not revisions %} hidden{% endif %}>Версия {{ revisions|length }}</span>
|
||||
{% if post.published %}
|
||||
<span class="ps-badge ps-badge--success">{{ ui.icon('megaphone', 14) }}<span>Опубликован{% if post.published_to %} в «{{ post.published_to }}»{% endif %}</span></span>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if images %}
|
||||
<div class="ps-post-image"><img src="/media/{{ images[0].filename }}" alt="" style="object-fit:cover"></div>
|
||||
{% endif %}
|
||||
<div class="ps-post-text"><p id="postContent">{{ post.content }}</p></div>
|
||||
<footer class="ps-post-foot">
|
||||
<span class="ps-post-count{% if post.content|length > limit %} is-over{% endif %}" id="postCount" data-limit="{{ limit }}">{{ post.content|length|num }} / {{ limit|num }} зн.</span>
|
||||
<span class="ps-post-note is-danger" id="postOver"{% if post.content|length <= limit %} hidden{% endif %}>{{ ui.icon('alert', 14) }}Длиннее лимита платформы — сократите текст</span>
|
||||
{% if post.platform == 'telegram' and images and post.content|length > 1024 %}
|
||||
<span class="ps-post-note">{{ ui.icon('info', 14) }}Длиннее 1 024 знаков: фото уйдёт без подписи, текст — следующим сообщением</span>
|
||||
{% endif %}
|
||||
<div class="ps-post-actions">
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" onclick="copyPostText()">{{ ui.icon('copy', 16) }}<span class="ps-btn-label">Копировать</span></button>
|
||||
<a class="ps-btn ps-btn--quiet ps-btn--sm" href="/posts/{{ post.id }}/edit">{{ ui.icon('edit', 16) }}<span class="ps-btn-label">Изменить вручную</span></a>
|
||||
</div>
|
||||
</footer>
|
||||
</article>
|
||||
{% if post.wishes %}
|
||||
<p class="form-hint" style="margin-top: calc(var(--space-4) * -1)">Пожелания: {{ post.wishes }}</p>
|
||||
{% endif %}
|
||||
|
||||
<!-- История чата -->
|
||||
<div class="ai-chat" id="aiChat">
|
||||
<div class="ai-chat-msg ai-chat-msg--system">
|
||||
<div class="ai-chat-bubble ai-chat-bubble--system">Пост сгенерирован. Напишите инструкцию, чтобы изменить его.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Лоадер -->
|
||||
<div id="aiChatLoader" class="task-loader" style="display:none; padding: 15px;">
|
||||
<div class="spinner"></div>
|
||||
<div class="task-loader-text">Нейросеть переписывает пост...</div>
|
||||
</div>
|
||||
<div id="aiChatError" class="task-error"></div>
|
||||
|
||||
<!-- Поле ввода -->
|
||||
<div class="ai-chat-input">
|
||||
<textarea id="aiChatInput" class="ai-chat-textarea" rows="2"
|
||||
placeholder="Например: сократи вдвое, сделай веселее, добавь эмодзи..."
|
||||
onkeydown="if(event.key==='Enter' && !event.shiftKey){event.preventDefault(); sendAiInstruction();}"></textarea>
|
||||
<button type="button" class="copy-btn" onclick="sendAiInstruction()" id="aiChatSendBtn">→ Отправить</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- === СКРИПТ ЧАТА === -->
|
||||
<script>
|
||||
var _currentPostContent = {{ post.content | tojson }};
|
||||
|
||||
function copyPostText() {
|
||||
navigator.clipboard.writeText(document.getElementById('postContent').textContent);
|
||||
}
|
||||
|
||||
function sendAiInstruction() {
|
||||
var input = document.getElementById('aiChatInput');
|
||||
var instruction = input.value.trim();
|
||||
if (!instruction) return;
|
||||
|
||||
var errEl = document.getElementById('aiChatError');
|
||||
var loader = document.getElementById('aiChatLoader');
|
||||
var sendBtn = document.getElementById('aiChatSendBtn');
|
||||
|
||||
errEl.style.display = 'none';
|
||||
loader.style.display = 'flex';
|
||||
sendBtn.disabled = true;
|
||||
input.disabled = true;
|
||||
|
||||
// Добавляем сообщение пользователя в чат
|
||||
addChatMsg('user', instruction);
|
||||
input.value = '';
|
||||
|
||||
var fd = new FormData();
|
||||
fd.append('task_type', 'modify_post');
|
||||
fd.append('post_id', '{{ post.id }}');
|
||||
fd.append('instruction', instruction);
|
||||
|
||||
fetch('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.error) { showAiError(errEl, data.error, loader, sendBtn, input); return; }
|
||||
pollModifyTask(data.task_id, errEl, loader, sendBtn, input, instruction);
|
||||
})
|
||||
.catch(function(e) { showAiError(errEl, 'Ошибка сети: ' + e, loader, sendBtn, input); });
|
||||
}
|
||||
|
||||
function pollModifyTask(taskId, errEl, loader, sendBtn, input, instruction) {
|
||||
fetch('/api/tasks/' + taskId)
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.status === 'running' || data.status === 'pending') {
|
||||
setTimeout(function() { pollModifyTask(taskId, errEl, loader, sendBtn, input, instruction); }, 1500);
|
||||
return;
|
||||
}
|
||||
loader.style.display = 'none';
|
||||
sendBtn.disabled = false;
|
||||
input.disabled = false;
|
||||
input.focus();
|
||||
|
||||
if (data.status === 'error') {
|
||||
showAiError(errEl, data.error || 'Ошибка модификации', null, null, null);
|
||||
return;
|
||||
}
|
||||
if (data.status === 'done' && data.result) {
|
||||
var newContent = data.result.content;
|
||||
_currentPostContent = newContent;
|
||||
|
||||
// Обновляем текст поста на странице
|
||||
document.getElementById('postContent').textContent = newContent;
|
||||
|
||||
// Добавляем ответ ИИ в чат
|
||||
addChatMsg('ai', newContent, instruction);
|
||||
|
||||
// Убираем ошибку
|
||||
errEl.style.display = 'none';
|
||||
}
|
||||
})
|
||||
.catch(function(e) { showAiError(errEl, 'Ошибка сети: ' + e, null, null, null); });
|
||||
}
|
||||
|
||||
function addChatMsg(role, text, instruction) {
|
||||
var chat = document.getElementById('aiChat');
|
||||
var now = new Date();
|
||||
var dateStr = now.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit'});
|
||||
|
||||
var html = '';
|
||||
if (role === 'user') {
|
||||
html = '<div class="ai-chat-msg ai-chat-msg--user">' +
|
||||
'<div class="ai-chat-bubble ai-chat-bubble--user">' + escH(text) + '</div>' +
|
||||
'<div class="ai-chat-time">' + dateStr + '</div></div>';
|
||||
} else {
|
||||
var preview = text.substring(0, 200) + (text.length > 200 ? '…' : '');
|
||||
var fullId = 'aifull-' + Date.now();
|
||||
html = '<div class="ai-chat-msg ai-chat-msg--ai">' +
|
||||
'<div class="ai-chat-meta">🤖 ИИ изменил пост по запросу: «' + escH(instruction || '') + '»</div>' +
|
||||
'<div class="ai-chat-bubble ai-chat-bubble--ai">' +
|
||||
'<div class="ai-chat-preview" id="aiprev-' + fullId + '">' + escH(preview) + '</div>' +
|
||||
'<div class="ai-chat-full" id="' + fullId + '" style="display:none"><pre>' + escH(text) + '</pre></div>' +
|
||||
'<button type="button" class="button-link" onclick="toggleAiFull(\'' + fullId + '\')" style="margin-top:6px;">Показать весь текст</button>' +
|
||||
'</div>' +
|
||||
'<div class="ai-chat-time">' + dateStr + '</div></div>';
|
||||
}
|
||||
|
||||
chat.insertAdjacentHTML('beforeend', html);
|
||||
chat.scrollTop = chat.scrollHeight;
|
||||
}
|
||||
|
||||
function toggleAiFull(id) {
|
||||
var prev = document.getElementById('aiprev-' + id);
|
||||
var full = document.getElementById(id);
|
||||
if (!prev || !full) return;
|
||||
if (full.style.display === 'none') {
|
||||
prev.style.display = 'none';
|
||||
full.style.display = '';
|
||||
} else {
|
||||
full.style.display = 'none';
|
||||
prev.style.display = '';
|
||||
}
|
||||
}
|
||||
|
||||
function showAiError(el, msg, loader, sendBtn, input) {
|
||||
if (loader) loader.style.display = 'none';
|
||||
if (sendBtn) { sendBtn.disabled = false; }
|
||||
if (input) { input.disabled = false; input.focus(); }
|
||||
el.textContent = msg;
|
||||
el.style.display = 'block';
|
||||
}
|
||||
|
||||
function escH(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
|
||||
</script>
|
||||
|
||||
<!-- === ГАЛЕРЕЯ ИЗОБРАЖЕНИЙ === -->
|
||||
<div class="card">
|
||||
<h2>🖼 Изображения</h2>
|
||||
{% if images %}
|
||||
<div class="media-grid">
|
||||
{% for img in images %}
|
||||
<div class="media-card">
|
||||
<a href="/media/{{ img.filename }}" class="media-link" target="_blank">
|
||||
<img src="/media/{{ img.filename }}" class="media-thumb" alt="">
|
||||
</a>
|
||||
<div class="media-body">
|
||||
<span class="form-hint">{{ img.source }} · {{ img.created_at }}</span>
|
||||
<form action="/posts/{{ post.id }}/images/{{ img.id }}/delete" method="post" class="inline-form"
|
||||
onsubmit="return confirm('Удалить изображение?')">
|
||||
<button type="submit" class="button-link button-link-danger">🗑 Удалить</button>
|
||||
</form>
|
||||
<!-- Чат правок с ИИ -->
|
||||
<section class="app-stack" aria-labelledby="chat-title">
|
||||
<h2 class="ps-h2" id="chat-title">Правки с ИИ</h2>
|
||||
<div class="app-stack" id="aiChat" style="gap: var(--space-6)">
|
||||
<div class="ps-msg ps-msg--ai">
|
||||
<span class="ps-msg-avatar" aria-hidden="true">{{ ui.mark('chatav0', 'color', 32) }}</span>
|
||||
<div class="ps-msg-body">
|
||||
<div class="ps-msg-meta"><span class="ps-msg-author">Пресс-секретарь</span><span class="ps-ai-tag">ИИ</span></div>
|
||||
<div class="ps-msg-bubble"><p>Пост готов. Напишите, что изменить, или выберите готовую команду ниже.</p></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="form-hint">Изображений пока нет.</p>
|
||||
{% endif %}
|
||||
<div id="aiChatLoader" style="display:none"><div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Переписываю…</span></div></div>
|
||||
<div id="aiChatError" class="task-error" role="alert"></div>
|
||||
|
||||
<!-- Загрузка файлов -->
|
||||
<h3>📎 Загрузить изображения</h3>
|
||||
<form method="post" action="/posts/{{ post.id }}/images/upload" enctype="multipart/form-data" class="form">
|
||||
<label>Файлы (можно несколько)
|
||||
<input type="file" name="files" accept="image/*" multiple required>
|
||||
</label>
|
||||
<button type="submit">📎 Загрузить</button>
|
||||
</form>
|
||||
|
||||
<!-- Генерация изображения -->
|
||||
<h3>🎨 Сгенерировать изображение для поста</h3>
|
||||
<div id="postImgError" class="task-error"></div>
|
||||
|
||||
<!-- Лоадер анализа -->
|
||||
<div id="postImgAnalyzeLoader" class="task-loader" style="padding: 20px;">
|
||||
<div class="spinner"></div>
|
||||
<div class="task-loader-text">Анализирую пост...</div>
|
||||
<div class="task-loader-sub">ИИ подбирает лучшие варианты</div>
|
||||
<div class="ps-composer">
|
||||
<div class="ps-composer-suggest" id="aiSuggest">
|
||||
{% for s in ['Сократи вдвое', 'Сделай официальнее', 'Добавь призыв к действию', 'Перепиши в стиле эксперта'] %}
|
||||
<button type="button" class="ps-chip ps-chip--sm" data-suggest="{{ s }}">{{ ui.icon('sparkle', 16) }}<span>{{ s }}</span></button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="ps-composer-row">
|
||||
<textarea id="aiChatInput" class="ps-composer-input" rows="1" aria-label="Что изменить в посте"
|
||||
placeholder="Что изменить? Например: «сократи вдвое»"
|
||||
onkeydown="if(event.key==='Enter' && !event.shiftKey){event.preventDefault(); sendAiInstruction();}"></textarea>
|
||||
<button type="button" class="ps-iconbtn ps-iconbtn--filled" id="aiChatSendBtn" aria-label="Отправить" onclick="sendAiInstruction()" disabled>{{ ui.icon('send', 22) }}</button>
|
||||
</div>
|
||||
<p class="ps-composer-note">Пресс-секретарь пишет черновик. В канал пост уходит только по вашей команде.</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- Лоадер генерации -->
|
||||
<div id="postImgGenLoader" class="task-loader" style="padding: 20px;">
|
||||
<div class="spinner"></div>
|
||||
<div class="task-loader-text">Генерирую изображение...</div>
|
||||
<div class="task-loader-sub">Это может занять 15–60 секунд</div>
|
||||
</div>
|
||||
<aside class="app-stack-lg">
|
||||
<!-- История версий -->
|
||||
<section class="ps-panel" aria-labelledby="ver-title">
|
||||
<h2 class="ps-h2" id="ver-title">История изменений</h2>
|
||||
{% if revisions %}
|
||||
<ol class="ps-history" aria-label="История изменений" id="versionList">
|
||||
{% for r in revisions %}
|
||||
<li class="ps-history-item{% if loop.first %} is-active{% endif %}" data-rev="{{ r.id }}">
|
||||
<span class="ps-history-dot" aria-hidden="true"></span>
|
||||
<span class="ps-history-text">
|
||||
<span class="ps-history-title">Версия {{ loop.revindex }}</span>
|
||||
<span class="ps-history-meta">{{ r.created_at|local_dt('%H:%M · %d.%m.%Y') }} · {{ r.content|length|num }} зн.</span>
|
||||
</span>
|
||||
{% if loop.first %}
|
||||
<span class="ps-history-current">Текущая</span>
|
||||
{% else %}
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-restore="{{ r.id }}">{{ ui.icon('history', 16) }}<span class="ps-btn-label">Вернуть</span></button>
|
||||
{% endif %}
|
||||
<template data-content>{{ r.content }}</template>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ol>
|
||||
{% else %}
|
||||
<p class="form-hint" id="versionEmpty">Каждая правка в чате и вручную станет версией — любую можно будет вернуть.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
<div id="postImgResult" class="task-result"></div>
|
||||
|
||||
<!-- Шаг 1: Выбор концепции -->
|
||||
<div id="postImgConceptsSection">
|
||||
<p class="form-hint" style="margin-bottom: 10px;">ИИ проанализирует пост и предложит варианты:</p>
|
||||
<button type="button" class="copy-btn" id="postImgAnalyzeBtn" onclick="startAnalyzeConcepts()">🤖 ИИ подберёт вариант</button>
|
||||
|
||||
<div style="margin-top: 12px;">
|
||||
<p class="form-hint" style="margin-bottom: 8px;">Или выбери шаблон вручную:</p>
|
||||
<div class="template-grid" id="postImgGrid">
|
||||
{% for t in templates %}
|
||||
<button type="button" class="template-card" data-key="{{ t.key }}"
|
||||
data-prompt="{{ t.prompt }}" data-style="{{ t.style }}" data-size="{{ t.size }}">
|
||||
<span class="template-icon">{{ t.icon }}</span>
|
||||
<span class="template-name">{{ t.name }}</span>
|
||||
<span class="template-hint">{{ t.hint }}</span>
|
||||
</button>
|
||||
<!-- Картинки поста -->
|
||||
<section class="ps-panel" aria-labelledby="img-title">
|
||||
<h2 class="ps-h2" id="img-title">Картинки</h2>
|
||||
{% if images %}
|
||||
<div class="app-gallery" style="grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--space-3)">
|
||||
{% for img in images %}
|
||||
<figure class="app-gallery-item" style="margin:0">
|
||||
<a href="/media/{{ img.filename }}" target="_blank" rel="noopener" aria-label="Открыть картинку"><img src="/media/{{ img.filename }}" alt=""></a>
|
||||
<figcaption class="app-actions" style="padding: 4px; justify-content: space-between">
|
||||
<span class="app-caption" style="padding-left: 8px">{{ 'ИИ' if img.source == 'generated' else 'Загружена' }}</span>
|
||||
<form action="/posts/{{ post.id }}/images/{{ img.id }}/delete" method="post" class="inline-form" data-confirm="Удалить картинку?">
|
||||
<button type="submit" class="ps-iconbtn" aria-label="Удалить картинку">{{ ui.icon('trash', 18) }}</button>
|
||||
</form>
|
||||
</figcaption>
|
||||
</figure>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="/posts/{{ post.id }}/images/upload" enctype="multipart/form-data" id="uploadForm">
|
||||
<label class="ps-drop" id="uploadDrop">
|
||||
<input type="file" name="files" accept="image/*" multiple required class="ps-drop-input" id="uploadInput">
|
||||
<span class="ps-drop-icon" aria-hidden="true">{{ ui.icon('upload', 24) }}</span>
|
||||
<span class="ps-drop-title">Перетащите фото или выберите</span>
|
||||
<span class="ps-drop-hint">Можно несколько файлов</span>
|
||||
</label>
|
||||
</form>
|
||||
|
||||
<div id="postImgError" class="task-error" role="alert"></div>
|
||||
<div id="postImgAnalyzeLoader" class="task-loader">
|
||||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Подбираю 4 концепции…</span></div>
|
||||
</div>
|
||||
<div id="postImgGenLoader" class="task-loader">
|
||||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Рисую картинку…</span></div>
|
||||
<span class="task-loader-sub">Обычно 15–60 секунд</span>
|
||||
</div>
|
||||
<div id="postImgResult" class="task-result"></div>
|
||||
|
||||
<div id="postImgConceptsSection" class="app-stack">
|
||||
<button type="button" class="ps-btn ps-btn--secondary ps-btn--block" id="postImgAnalyzeBtn" onclick="startAnalyzeConcepts()">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Подобрать концепцию</span></button>
|
||||
<details>
|
||||
<summary>Сгенерировать по шаблону</summary>
|
||||
<div class="ps-presets" id="postImgGrid" style="margin-top: var(--space-3); grid-template-columns: repeat(auto-fill, minmax(96px, 1fr))">
|
||||
{% for t in templates %}
|
||||
<button type="button" class="ps-preset" data-key="{{ t.key }}" title="{{ t.hint }}">
|
||||
<span class="ps-preset-art" aria-hidden="true"><svg viewBox="0 0 64 48" preserveAspectRatio="xMidYMid slice">{{ ui.PRESET_ART[art_for.get(t.key, 'minimal')] | safe }}</svg></span>
|
||||
<span class="ps-preset-label">{{ t.name }}</span>
|
||||
</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div id="postImgConceptsList" class="app-stack" style="display:none;">
|
||||
<div class="ps-choices-grid" id="postImgConcepts" style="grid-template-columns: 1fr"></div>
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" onclick="resetConcepts()">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">К шаблонам</span></button>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/posts/{{ post.id }}/images/generate" id="postImgForm" style="display:none;">
|
||||
<input type="hidden" name="task_type" id="postImgTaskType" value="generate_post_image">
|
||||
<input type="hidden" name="post_id" value="{{ post.id }}">
|
||||
<input type="hidden" name="template_key" id="postImgTemplateKey" value="">
|
||||
<input type="hidden" name="concept_prompt" id="postImgConceptPrompt" value="">
|
||||
<input type="hidden" name="concept_style" id="postImgConceptStyle" value="">
|
||||
<input type="hidden" name="concept_size" id="postImgConceptSize" value="">
|
||||
</form>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<template id="tpl-icon-history">{{ ui.icon('history', 16) }}</template>
|
||||
<template id="tpl-msg-ai">
|
||||
<div class="ps-msg ps-msg--ai">
|
||||
<span class="ps-msg-avatar" aria-hidden="true">{{ ui.mark('chatav1', 'color', 32) }}</span>
|
||||
<div class="ps-msg-body">
|
||||
<div class="ps-msg-meta"><span class="ps-msg-author">Пресс-секретарь</span><span class="ps-ai-tag">ИИ</span><time></time></div>
|
||||
<div class="ps-msg-bubble"><p data-text></p></div>
|
||||
<div class="ps-msg-actions">
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-act="copy">{{ ui.icon('copy', 16) }}<span class="ps-btn-label">Копировать</span></button>
|
||||
<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-act="again">{{ ui.icon('refresh', 16) }}<span class="ps-btn-label">Другой вариант</span></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Шаг 2: Концепции от ИИ (скрыт до анализа) -->
|
||||
<div id="postImgConceptsList" style="display:none;">
|
||||
<h4 style="margin-bottom: 10px;">Выбери вариант:</h4>
|
||||
<div id="postImgConcepts" class="concept-grid"></div>
|
||||
<button type="button" class="button-link" style="margin-top: 10px;" onclick="resetConcepts()">← Назад к шаблонам</button>
|
||||
</template>
|
||||
<template id="tpl-msg-user">
|
||||
<div class="ps-msg ps-msg--user">
|
||||
<div class="ps-msg-body">
|
||||
<div class="ps-msg-meta"><time></time></div>
|
||||
<div class="ps-msg-bubble"><p data-text></p></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Скрытая форма для отправки -->
|
||||
<form method="post" action="/posts/{{ post.id }}/images/generate" class="form" id="postImgForm" style="display:none;">
|
||||
<input type="hidden" name="task_type" id="postImgTaskType" value="generate_post_image">
|
||||
<input type="hidden" name="post_id" value="{{ post.id }}">
|
||||
<input type="hidden" name="template_key" id="postImgTemplateKey" value="">
|
||||
<input type="hidden" name="concept_prompt" id="postImgConceptPrompt" value="">
|
||||
<input type="hidden" name="concept_style" id="postImgConceptStyle" value="">
|
||||
<input type="hidden" name="concept_size" id="postImgConceptSize" value="">
|
||||
<button type="submit" id="postImgSubmitBtn">🎨 Сгенерировать</button>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
var form = document.getElementById('postImgForm');
|
||||
var grid = document.getElementById('postImgGrid');
|
||||
if (!form || !grid) return;
|
||||
|
||||
// Клик по шаблону — сразу генерация
|
||||
grid.addEventListener('click', function(e) {
|
||||
var card = e.target.closest('.template-card');
|
||||
if (!card) return;
|
||||
grid.querySelectorAll('.template-card').forEach(function(c) { c.classList.remove('selected'); });
|
||||
card.classList.add('selected');
|
||||
|
||||
document.getElementById('postImgTaskType').value = 'generate_post_image';
|
||||
document.getElementById('postImgTemplateKey').value = card.dataset.key || '';
|
||||
document.getElementById('postImgConceptPrompt').value = '';
|
||||
document.getElementById('postImgConceptStyle').value = '';
|
||||
document.getElementById('postImgConceptSize').value = '';
|
||||
|
||||
runPostImgGeneration('postImgConceptsSection');
|
||||
});
|
||||
})();
|
||||
|
||||
function startAnalyzeConcepts() {
|
||||
var errEl = document.getElementById('postImgError');
|
||||
var loader = document.getElementById('postImgAnalyzeLoader');
|
||||
var section = document.getElementById('postImgConceptsSection');
|
||||
var conceptsList = document.getElementById('postImgConceptsList');
|
||||
|
||||
errEl.style.display = 'none';
|
||||
section.style.display = 'none';
|
||||
conceptsList.style.display = 'none';
|
||||
loader.style.display = 'flex';
|
||||
|
||||
var fd = new FormData();
|
||||
fd.append('task_type', 'analyze_post_image');
|
||||
fd.append('post_id', '{{ post.id }}');
|
||||
|
||||
fetch('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.error) { showError(errEl, data.error, section, loader); return; }
|
||||
pollAnalyze(data.task_id, errEl, loader, section, conceptsList);
|
||||
})
|
||||
.catch(function(err) { showError(errEl, 'Ошибка сети: ' + err.message, section, loader); });
|
||||
}
|
||||
|
||||
function pollAnalyze(taskId, errEl, loader, section, conceptsList) {
|
||||
fetch('/api/tasks/' + taskId)
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.status === 'running' || data.status === 'pending') {
|
||||
setTimeout(function() { pollAnalyze(taskId, errEl, loader, section, conceptsList); }, 1500);
|
||||
return;
|
||||
}
|
||||
loader.style.display = 'none';
|
||||
if (data.status === 'error') { showError(errEl, data.error, section, null); return; }
|
||||
if (data.status === 'done' && data.result && data.result.concepts) {
|
||||
showConcepts(data.result.concepts, conceptsList, section);
|
||||
}
|
||||
})
|
||||
.catch(function(err) { showError(errEl, 'Ошибка сети: ' + err.message, section, null); });
|
||||
}
|
||||
|
||||
function showConcepts(concepts, container, hiddenSection) {
|
||||
var html = '';
|
||||
concepts.forEach(function(c, i) {
|
||||
var styleLabels = {photo:'Фото',illustration:'Иллюстрация',minimal:'Минимализм','3d':'3D',flat:'Плоская графика'};
|
||||
var sizeLabels = {square:'Квадрат',wide:'Широкий',tall:'Вертикальный'};
|
||||
html += '<button type="button" class="concept-card" onclick="selectConcept(' + i + ')">' +
|
||||
'<div class="concept-title">' + escH(c.title) + '</div>' +
|
||||
'<div class="concept-desc">' + escH(c.description) + '</div>' +
|
||||
'<div class="concept-meta">' +
|
||||
'<span class="concept-tag">' + (styleLabels[c.style] || c.style) + '</span> ' +
|
||||
'<span class="concept-tag">' + (sizeLabels[c.size] || c.size) + '</span>' +
|
||||
'</div></button>';
|
||||
});
|
||||
document.getElementById('postImgConcepts').innerHTML = html;
|
||||
document.getElementById('postImgConceptsList').style.display = 'block';
|
||||
|
||||
// Сохраняем концепции для выбора
|
||||
window._postImgConcepts = concepts;
|
||||
}
|
||||
|
||||
function selectConcept(idx) {
|
||||
var c = window._postImgConcepts[idx];
|
||||
if (!c) return;
|
||||
|
||||
document.getElementById('postImgTaskType').value = 'generate_post_image_with_concept';
|
||||
document.getElementById('postImgTemplateKey').value = '';
|
||||
document.getElementById('postImgConceptPrompt').value = c.description;
|
||||
document.getElementById('postImgConceptStyle').value = c.style || 'none';
|
||||
document.getElementById('postImgConceptSize').value = c.size || 'wide';
|
||||
|
||||
runPostImgGeneration('postImgConceptsList');
|
||||
}
|
||||
|
||||
function runPostImgGeneration(hideSectionId) {
|
||||
var form = document.getElementById('postImgForm');
|
||||
var hideSection = document.getElementById(hideSectionId);
|
||||
var genLoader = document.getElementById('postImgGenLoader');
|
||||
|
||||
if (hideSection) hideSection.style.display = 'none';
|
||||
genLoader.style.display = 'flex';
|
||||
|
||||
var fd = new FormData(form);
|
||||
fetch('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.error) { showError(document.getElementById('postImgError'), data.error, hideSection, genLoader); return; }
|
||||
pollGenerate(data.task_id);
|
||||
})
|
||||
.catch(function(err) { showError(document.getElementById('postImgError'), 'Ошибка сети: ' + err.message, hideSection, genLoader); });
|
||||
}
|
||||
|
||||
function pollGenerate(taskId) {
|
||||
var genLoader = document.getElementById('postImgGenLoader');
|
||||
var errEl = document.getElementById('postImgError');
|
||||
|
||||
fetch('/api/tasks/' + taskId)
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.status === 'running' || data.status === 'pending') {
|
||||
setTimeout(function() { pollGenerate(taskId); }, 1500);
|
||||
return;
|
||||
}
|
||||
genLoader.style.display = 'none';
|
||||
if (data.status === 'error') {
|
||||
showError(errEl, data.error, document.getElementById('postImgConceptsSection'), null);
|
||||
return;
|
||||
}
|
||||
if (data.status === 'done' && data.result) {
|
||||
var html = '<div class="media-grid"><div class="media-card">' +
|
||||
'<a href="/media/' + data.result.filename + '" class="media-link" target="_blank">' +
|
||||
'<img src="/media/' + data.result.filename + '" class="media-thumb" alt=""></a>' +
|
||||
'<div class="media-body"><span class="form-hint">generated · только что</span></div></div></div>' +
|
||||
'<p style="margin-top:10px;"><button type="button" class="copy-btn" onclick="resetConcepts()">← Ещё вариант</button> ' +
|
||||
'<a href="/images" class="copy-btn">В библиотеку →</a></p>';
|
||||
document.getElementById('postImgResult').innerHTML = html;
|
||||
document.getElementById('postImgResult').style.display = 'block';
|
||||
}
|
||||
})
|
||||
.catch(function(err) { showError(errEl, 'Ошибка сети: ' + err.message, document.getElementById('postImgConceptsSection'), null); });
|
||||
}
|
||||
|
||||
function resetConcepts() {
|
||||
document.getElementById('postImgResult').style.display = 'none';
|
||||
document.getElementById('postImgConceptsList').style.display = 'none';
|
||||
document.getElementById('postImgConceptsSection').style.display = '';
|
||||
document.getElementById('postImgError').style.display = 'none';
|
||||
document.getElementById('postImgGenLoader').style.display = 'none';
|
||||
document.getElementById('postImgAnalyzeLoader').style.display = 'none';
|
||||
}
|
||||
|
||||
function showError(el, msg, showSection, hideLoader) {
|
||||
if (hideLoader) hideLoader.style.display = 'none';
|
||||
if (showSection) showSection.style.display = '';
|
||||
el.textContent = msg;
|
||||
el.style.display = 'block';
|
||||
}
|
||||
|
||||
function escH(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
|
||||
</script>
|
||||
</div>
|
||||
|
||||
<div class="post-actions">
|
||||
<a class="copy-btn" href="/posts/{{ post.id }}/publish">📤 Опубликовать</a>
|
||||
<a class="button-link" href="/posts/{{ post.id }}/edit">✏️ Полное редактирование</a>
|
||||
<form method="post" action="/posts/{{ post.id }}/delete" class="inline-form"
|
||||
onsubmit="return confirm('Удалить этот пост? Действие необратимо.');">
|
||||
<button type="submit" class="button-link button-link-danger">🗑 Удалить</button>
|
||||
</form>
|
||||
</div>
|
||||
<p><a href="/history">← Назад к постам</a></p>
|
||||
</template>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
var _currentPostContent = {{ post.content | tojson }};
|
||||
var _lastInstruction = '';
|
||||
var POST_ID = {{ post.id }};
|
||||
|
||||
function copyPostText() { copyText(document.getElementById('postContent').textContent); }
|
||||
|
||||
function setPostContent(text) {
|
||||
_currentPostContent = text;
|
||||
document.getElementById('postContent').textContent = text;
|
||||
var c = document.getElementById('postCount'), limit = +c.getAttribute('data-limit');
|
||||
c.textContent = text.length.toLocaleString('ru-RU') + ' / ' + limit.toLocaleString('ru-RU') + ' зн.';
|
||||
c.classList.toggle('is-over', text.length > limit);
|
||||
document.getElementById('postOver').hidden = text.length <= limit;
|
||||
}
|
||||
|
||||
/* --- Композер --- */
|
||||
(function () {
|
||||
var input = document.getElementById('aiChatInput'), send = document.getElementById('aiChatSendBtn');
|
||||
function grow() { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 200) + 'px'; send.disabled = !input.value.trim() || input.disabled; }
|
||||
input.addEventListener('input', grow);
|
||||
document.getElementById('aiSuggest').addEventListener('click', function (e) {
|
||||
var b = e.target.closest('[data-suggest]'); if (!b) return;
|
||||
input.value = b.getAttribute('data-suggest'); grow(); input.focus();
|
||||
});
|
||||
window._growComposer = grow;
|
||||
grow();
|
||||
})();
|
||||
|
||||
var _aiBusy = false;
|
||||
|
||||
/* Пока ИИ отвечает — композер и кнопки «Другой вариант» выключены: параллельных правок не бывает */
|
||||
function setAiBusy(on) {
|
||||
_aiBusy = on;
|
||||
var input = document.getElementById('aiChatInput');
|
||||
input.disabled = on;
|
||||
document.getElementById('aiChatLoader').style.display = on ? 'block' : 'none';
|
||||
document.getElementById('aiSuggest').hidden = on;
|
||||
document.querySelectorAll('[data-act="again"]').forEach(function (b) { b.disabled = on; });
|
||||
window._growComposer();
|
||||
if (!on) input.focus();
|
||||
}
|
||||
|
||||
/* base — текст, к которому применяется правка: для «Другого варианта» это текст до первой попытки */
|
||||
function sendAiInstruction(forced, base) {
|
||||
if (_aiBusy) return;
|
||||
var input = document.getElementById('aiChatInput');
|
||||
var instruction = (forced || input.value).trim();
|
||||
if (!instruction) return;
|
||||
var errEl = document.getElementById('aiChatError');
|
||||
errEl.style.display = 'none';
|
||||
addChatMsg('user', base !== undefined ? 'Другой вариант: ' + instruction : instruction);
|
||||
input.value = '';
|
||||
setAiBusy(true);
|
||||
var prev = _currentPostContent;
|
||||
|
||||
function run() {
|
||||
var fd = new FormData();
|
||||
fd.append('task_type', 'modify_post');
|
||||
fd.append('post_id', POST_ID);
|
||||
fd.append('instruction', instruction);
|
||||
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function (data) {
|
||||
if (!data.task_id) { aiFail(data.error || 'Не удалось запустить правку. Повторите.'); return; }
|
||||
Press.pollTask(data.task_id, {
|
||||
done: function (result) {
|
||||
setAiBusy(false);
|
||||
var basis = base !== undefined ? base : prev;
|
||||
setPostContent(result.content);
|
||||
addChatMsg('ai', 'Готово: ' + result.content.length.toLocaleString('ru-RU') + ' зн. вместо ' + basis.length.toLocaleString('ru-RU') + '. Прошлая версия — в истории.', { instruction: instruction, base: basis });
|
||||
addVersion(result.content, prev);
|
||||
},
|
||||
fail: aiFail
|
||||
});
|
||||
})
|
||||
.catch(function (err) { if (err.message !== Press.SESSION) aiFail(err.message); });
|
||||
}
|
||||
/* Другой вариант: сначала возвращаем текст до правки, затем повторяем команду — получается альтернатива, а не правка правки */
|
||||
if (base !== undefined && base !== _currentPostContent) {
|
||||
var fd = new FormData(); fd.append('content', base);
|
||||
Press.fetchJSON('/api/posts/' + POST_ID + '/edit-text', { method: 'POST', body: fd })
|
||||
.then(function (d) {
|
||||
if (!d.ok) { aiFail(d.error || 'Не удалось подготовить другой вариант. Повторите.'); return; }
|
||||
addVersion(d.content, prev); setPostContent(d.content); prev = d.content; run();
|
||||
})
|
||||
.catch(function (err) { if (err.message !== Press.SESSION) aiFail(err.message); });
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
}
|
||||
|
||||
function aiFail(msg) {
|
||||
setAiBusy(false);
|
||||
var el = document.getElementById('aiChatError');
|
||||
el.textContent = Press.humanError(msg); el.title = msg || '';
|
||||
el.style.display = 'flex';
|
||||
}
|
||||
|
||||
function addChatMsg(role, text, ctx) {
|
||||
var tpl = document.getElementById(role === 'user' ? 'tpl-msg-user' : 'tpl-msg-ai').content.firstElementChild.cloneNode(true);
|
||||
tpl.querySelector('[data-text]').textContent = text;
|
||||
tpl.querySelector('time').textContent = new Date().toLocaleTimeString('ru-RU', {hour: '2-digit', minute: '2-digit'});
|
||||
var copy = tpl.querySelector('[data-act="copy"]');
|
||||
if (copy) copy.addEventListener('click', function () { copyText(_currentPostContent); });
|
||||
var again = tpl.querySelector('[data-act="again"]');
|
||||
if (again) {
|
||||
if (ctx) again.addEventListener('click', function () { sendAiInstruction(ctx.instruction, ctx.base); });
|
||||
else again.remove();
|
||||
}
|
||||
var chat = document.getElementById('aiChat');
|
||||
chat.appendChild(tpl);
|
||||
tpl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
|
||||
/* --- История версий --- */
|
||||
function versionItem(title, meta, content, current) {
|
||||
var li = document.createElement('li');
|
||||
li.className = 'ps-history-item' + (current ? ' is-active' : '');
|
||||
li.innerHTML = '<span class="ps-history-dot" aria-hidden="true"></span><span class="ps-history-text"><span class="ps-history-title"></span><span class="ps-history-meta"></span></span>' +
|
||||
(current ? '<span class="ps-history-current">Текущая</span>' : restoreBtnHtml()) + '<template data-content></template>';
|
||||
li.querySelector('.ps-history-title').textContent = title;
|
||||
li.querySelector('.ps-history-meta').textContent = meta;
|
||||
li.querySelector('template').innerHTML = escHtml(content);
|
||||
return li;
|
||||
}
|
||||
function restoreBtnHtml() {
|
||||
return '<button type="button" class="ps-btn ps-btn--quiet ps-btn--sm" data-restore>' + document.getElementById('tpl-icon-history').innerHTML + '<span class="ps-btn-label">Вернуть</span></button>';
|
||||
}
|
||||
function escHtml(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
|
||||
function addVersion(content, prevContent) {
|
||||
var list = document.getElementById('versionList');
|
||||
var now = new Date().toLocaleTimeString('ru-RU', {hour: '2-digit', minute: '2-digit'});
|
||||
if (!list) {
|
||||
// Первая правка: показываем исходный текст как версию 1
|
||||
list = document.createElement('ol');
|
||||
list.className = 'ps-history'; list.id = 'versionList'; list.setAttribute('aria-label', 'История изменений');
|
||||
var empty = document.getElementById('versionEmpty');
|
||||
empty.parentNode.replaceChild(list, empty);
|
||||
list.appendChild(versionItem('Исходная версия', prevContent.length.toLocaleString('ru-RU') + ' зн.', prevContent, false));
|
||||
}
|
||||
var cur = list.querySelector('.is-active');
|
||||
if (cur) {
|
||||
cur.classList.remove('is-active');
|
||||
var badge = cur.querySelector('.ps-history-current');
|
||||
if (badge) badge.outerHTML = restoreBtnHtml();
|
||||
}
|
||||
var n = (+list.getAttribute('data-total') || list.children.length) + 1;
|
||||
list.setAttribute('data-total', n);
|
||||
list.insertBefore(versionItem('Версия ' + n, now + ' · ' + content.length.toLocaleString('ru-RU') + ' зн.', content, true), list.firstChild);
|
||||
var tag = document.getElementById('postVersion');
|
||||
tag.hidden = false; tag.textContent = 'Версия ' + n;
|
||||
}
|
||||
document.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('[data-restore]'); if (!b || _aiBusy) return;
|
||||
var li = b.closest('.ps-history-item');
|
||||
var content = li.querySelector('template[data-content]').content.textContent;
|
||||
var prev = _currentPostContent;
|
||||
b.disabled = true;
|
||||
var fd = new FormData(); fd.append('content', content);
|
||||
Press.fetchJSON('/api/posts/' + POST_ID + '/edit-text', { method: 'POST', body: fd })
|
||||
.then(function (d) {
|
||||
b.disabled = false;
|
||||
if (d.ok) {
|
||||
setPostContent(d.content);
|
||||
addVersion(d.content, prev);
|
||||
Press.toast('Версия возвращена', 'success', 'Она стала новой текущей версией.');
|
||||
} else { Press.toast('Не удалось вернуть версию', 'danger', Press.humanError(d.error)); }
|
||||
})
|
||||
.catch(function (err) { b.disabled = false; if (err.message !== Press.SESSION) Press.toast('Не удалось вернуть версию', 'danger', err.message); });
|
||||
});
|
||||
|
||||
/* --- Загрузка фото: только картинки, отправляем сразу после выбора --- */
|
||||
(function () {
|
||||
var drop = document.getElementById('uploadDrop'), input = document.getElementById('uploadInput'), form = document.getElementById('uploadForm');
|
||||
function sendIfImages(files) {
|
||||
var imgs = Array.prototype.filter.call(files, function (f) { return /^image\//.test(f.type); });
|
||||
if (!imgs.length) { Press.toast('Это не картинка', 'warning', 'Загрузите JPG, PNG или WebP.'); input.value = ''; return; }
|
||||
if (imgs.length < files.length) Press.toast('Часть файлов пропущена', 'warning', 'Загружаю только картинки: ' + imgs.length + ' из ' + files.length + '.');
|
||||
var dt = new DataTransfer(); imgs.forEach(function (f) { dt.items.add(f); });
|
||||
input.files = dt.files;
|
||||
form.submit();
|
||||
}
|
||||
input.addEventListener('change', function () { if (input.files.length) sendIfImages(input.files); });
|
||||
drop.addEventListener('dragover', function (e) { e.preventDefault(); drop.classList.add('is-over'); });
|
||||
drop.addEventListener('dragleave', function () { drop.classList.remove('is-over'); });
|
||||
drop.addEventListener('drop', function (e) { e.preventDefault(); drop.classList.remove('is-over'); if (e.dataTransfer.files.length) sendIfImages(e.dataTransfer.files); });
|
||||
})();
|
||||
|
||||
/* --- Генерация картинки к посту --- */
|
||||
(function() {
|
||||
var grid = document.getElementById('postImgGrid');
|
||||
if (!grid) return;
|
||||
grid.addEventListener('click', function(e) {
|
||||
var card = e.target.closest('.ps-preset');
|
||||
if (!card) return;
|
||||
grid.querySelectorAll('.ps-preset').forEach(function(c) { c.classList.toggle('is-selected', c === card); });
|
||||
document.getElementById('postImgTaskType').value = 'generate_post_image';
|
||||
document.getElementById('postImgTemplateKey').value = card.dataset.key || '';
|
||||
document.getElementById('postImgConceptPrompt').value = '';
|
||||
document.getElementById('postImgConceptStyle').value = '';
|
||||
document.getElementById('postImgConceptSize').value = '';
|
||||
runPostImgGeneration('postImgConceptsSection');
|
||||
});
|
||||
})();
|
||||
|
||||
function startAnalyzeConcepts() {
|
||||
var errEl = document.getElementById('postImgError');
|
||||
var loader = document.getElementById('postImgAnalyzeLoader');
|
||||
var section = document.getElementById('postImgConceptsSection');
|
||||
var conceptsList = document.getElementById('postImgConceptsList');
|
||||
if (loader.style.display === 'flex') return;
|
||||
|
||||
errEl.style.display = 'none';
|
||||
section.style.display = 'none';
|
||||
conceptsList.style.display = 'none';
|
||||
loader.style.display = 'flex';
|
||||
|
||||
var fd = new FormData();
|
||||
fd.append('task_type', 'analyze_post_image');
|
||||
fd.append('post_id', POST_ID);
|
||||
|
||||
function fail(msg) { showError(errEl, msg, section, loader); }
|
||||
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function(data) {
|
||||
if (!data.task_id) { fail(data.error || 'Не удалось начать подбор. Повторите.'); return; }
|
||||
Press.pollTask(data.task_id, {
|
||||
done: function (result) {
|
||||
loader.style.display = 'none';
|
||||
/* Без концепций — возвращаем кнопки, а не оставляем пустую панель */
|
||||
if (Array.isArray(result.concepts) && result.concepts.length) showConcepts(result.concepts);
|
||||
else fail('ИИ не предложил концепций. Попробуйте ещё раз или выберите шаблон.');
|
||||
},
|
||||
fail: fail
|
||||
});
|
||||
})
|
||||
.catch(function(err) { if (err.message !== Press.SESSION) fail(err.message); });
|
||||
}
|
||||
|
||||
function showConcepts(concepts) {
|
||||
var styleLabels = {photo: 'Фото', illustration: 'Иллюстрация', minimal: 'Минимализм', '3d': '3D', flat: 'Плоская графика'};
|
||||
var sizeLabels = {square: 'Квадрат', wide: 'Широкий', tall: 'Вертикальный'};
|
||||
var box = document.getElementById('postImgConcepts');
|
||||
box.innerHTML = '';
|
||||
box.setAttribute('role', 'list');
|
||||
concepts.forEach(function(c, i) {
|
||||
var b = document.createElement('button');
|
||||
b.type = 'button'; b.className = 'ps-choice'; b.setAttribute('role', 'listitem');
|
||||
b.innerHTML = '<span class="ps-choice-body no-icon"><span class="ps-choice-text">' +
|
||||
'<span class="ps-choice-kicker"></span><span class="ps-choice-title"></span><span class="ps-choice-desc"></span>' +
|
||||
'<span class="app-legend" style="margin-top:var(--space-2)"></span></span></span>';
|
||||
b.querySelector('.ps-choice-kicker').textContent = 'Концепция ' + (i + 1);
|
||||
b.querySelector('.ps-choice-title').textContent = c.title || '';
|
||||
b.querySelector('.ps-choice-desc').textContent = c.description || '';
|
||||
var tags = b.querySelector('.app-legend');
|
||||
[styleLabels[c.style] || c.style, sizeLabels[c.size] || c.size].forEach(function (t) {
|
||||
if (!t) return; var s = document.createElement('span'); s.className = 'ps-post-tag'; s.textContent = t; tags.appendChild(s);
|
||||
});
|
||||
b.addEventListener('click', function () { selectConcept(i); });
|
||||
box.appendChild(b);
|
||||
});
|
||||
document.getElementById('postImgConceptsList').style.display = '';
|
||||
window._postImgConcepts = concepts;
|
||||
}
|
||||
|
||||
function selectConcept(idx) {
|
||||
var c = window._postImgConcepts[idx];
|
||||
if (!c) return;
|
||||
document.getElementById('postImgTaskType').value = 'generate_post_image_with_concept';
|
||||
document.getElementById('postImgTemplateKey').value = '';
|
||||
document.getElementById('postImgConceptPrompt').value = c.description;
|
||||
document.getElementById('postImgConceptStyle').value = c.style || 'none';
|
||||
document.getElementById('postImgConceptSize').value = c.size || 'wide';
|
||||
runPostImgGeneration('postImgConceptsList');
|
||||
}
|
||||
|
||||
function runPostImgGeneration(hideSectionId) {
|
||||
var form = document.getElementById('postImgForm');
|
||||
var hideSection = document.getElementById(hideSectionId);
|
||||
var genLoader = document.getElementById('postImgGenLoader');
|
||||
var errEl = document.getElementById('postImgError');
|
||||
if (genLoader.style.display === 'flex') return;
|
||||
|
||||
errEl.style.display = 'none';
|
||||
if (hideSection) hideSection.style.display = 'none';
|
||||
genLoader.style.display = 'flex';
|
||||
|
||||
/* При ошибке возвращаем панель с кнопками — шаблоны и «Подобрать концепцию» */
|
||||
function fail(msg) { showError(errEl, msg, document.getElementById('postImgConceptsSection'), genLoader); }
|
||||
var fd = new FormData(form);
|
||||
Press.fetchJSON('/api/tasks', { method: 'POST', body: fd })
|
||||
.then(function(data) {
|
||||
if (!data.task_id) { fail(data.error || 'Не удалось начать генерацию. Повторите.'); return; }
|
||||
Press.pollTask(data.task_id, {
|
||||
done: function () {
|
||||
genLoader.style.display = 'none';
|
||||
Press.toast('Картинка готова', 'success', 'Обновляю пост…');
|
||||
setTimeout(function () { location.reload(); }, 900);
|
||||
},
|
||||
fail: fail
|
||||
});
|
||||
})
|
||||
.catch(function(err) { if (err.message !== Press.SESSION) fail(err.message); });
|
||||
}
|
||||
|
||||
function resetConcepts() {
|
||||
document.getElementById('postImgResult').style.display = 'none';
|
||||
document.getElementById('postImgConceptsList').style.display = 'none';
|
||||
document.getElementById('postImgConceptsSection').style.display = '';
|
||||
document.getElementById('postImgError').style.display = 'none';
|
||||
document.getElementById('postImgGenLoader').style.display = 'none';
|
||||
document.getElementById('postImgAnalyzeLoader').style.display = 'none';
|
||||
}
|
||||
|
||||
function showError(el, msg, showSection, hideLoader) {
|
||||
if (hideLoader) hideLoader.style.display = 'none';
|
||||
if (showSection) showSection.style.display = '';
|
||||
el.textContent = Press.humanError(msg); el.title = msg || '';
|
||||
el.style.display = 'flex';
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,18 +1,31 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Изменить пост — Личный кабинет{% endblock %}
|
||||
{% block title %}Изменить пост{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Изменить пост</h1>
|
||||
<div class="card">
|
||||
<p class="post-meta">{{ platform_label(post.platform) }} · {{ post.created_at }}</p>
|
||||
<form method="post" action="/posts/{{ post.id }}/edit" class="form">
|
||||
<label>Текст поста
|
||||
<textarea name="content" rows="12" required>{{ post.content }}</textarea>
|
||||
</label>
|
||||
<div class="form-actions">
|
||||
<button type="submit">💾 Сохранить</button>
|
||||
<a class="button-link" href="/posts/{{ post.id }}">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/posts/{{ post.id }}" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">К посту</span></a>
|
||||
<h1 class="ps-h1">Изменить пост</h1>
|
||||
<p class="ps-lead">{{ platform_label(post.platform) }} · {{ post.created_at|local_dt }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p><a href="/history">← Назад к истории</a></p>
|
||||
<form method="post" action="/posts/{{ post.id }}/edit" class="ps-panel app-form">
|
||||
<div class="ps-field">
|
||||
<div class="ps-field-top">
|
||||
<label for="content" class="ps-field-label">Текст поста</label>
|
||||
<span class="ps-field-count" id="len">{{ post.content|length }} зн.</span>
|
||||
</div>
|
||||
<textarea id="content" name="content" rows="14" class="ps-field-control" style="font-size:16px; line-height:25px" required>{{ post.content }}</textarea>
|
||||
</div>
|
||||
<div class="app-actions">
|
||||
<button type="submit" class="ps-btn ps-btn--primary">{{ ui.icon('check', 20) }}<span class="ps-btn-label">Сохранить</span></button>
|
||||
<a class="ps-btn ps-btn--quiet" href="/posts/{{ post.id }}"><span class="ps-btn-label">Отмена</span></a>
|
||||
</div>
|
||||
</form>
|
||||
{% endblock %}
|
||||
{% block scripts %}
|
||||
<script>
|
||||
document.getElementById('content').addEventListener('input', function () {
|
||||
document.getElementById('len').textContent = this.value.length.toLocaleString('ru-RU') + ' зн.';
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -2,218 +2,134 @@
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>ТЗ — Презентация сервиса «ИИ Пресс-секретарь»</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>ТЗ на презентацию · ИИ Пресс-секретарь</title>
|
||||
<meta name="description" content="Техническое задание на создание 10-слайдовой презентации сервиса ИИ Пресс-секретарь.">
|
||||
<link rel="icon" type="image/svg+xml" href="/static/press/app-icon.svg">
|
||||
<link rel="stylesheet" href="/static/press/tokens.css?v=2">
|
||||
<link rel="stylesheet" href="/static/press/components.css?v=4">
|
||||
<script>
|
||||
(function () {
|
||||
try {
|
||||
var saved = localStorage.getItem('theme');
|
||||
if (saved === 'light' || saved === 'dark') document.documentElement.setAttribute('data-theme', saved);
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/press/glass.js?v=4" defer></script>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f172a;
|
||||
--surface: #1e293b;
|
||||
--surface-2: #273449;
|
||||
--text: #e2e8f0;
|
||||
--text-muted: #94a3b8;
|
||||
--accent: #60a5fa;
|
||||
--accent-hover: #93c5fd;
|
||||
--accent-soft: #1e3a5f;
|
||||
--border: #334155;
|
||||
--border-strong: #475569;
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
/* Страница-документ на токенах дизайн-системы: ширина текста 720–900, ритм 4/16/32 */
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
font-family: var(--font-text);
|
||||
background: var(--surface-sunken);
|
||||
color: var(--ink);
|
||||
line-height: 1.5;
|
||||
hyphens: manual;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
.container { max-width: 900px; margin: 0 auto; padding: 0 24px; }
|
||||
.container { max-width: 900px; margin: 0 auto; padding: 0 var(--page-gutter); }
|
||||
|
||||
/* Header */
|
||||
.header {
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 16px 0;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
position: sticky; top: 0; z-index: 10;
|
||||
background: var(--surface-glass);
|
||||
-webkit-backdrop-filter: blur(var(--blur-glass)) saturate(1.8);
|
||||
backdrop-filter: blur(var(--blur-glass)) saturate(1.8);
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
}
|
||||
.header-inner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 18px;
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
}
|
||||
.brand-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-block;
|
||||
padding: 10px 20px;
|
||||
border-radius: 8px;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.btn-primary { background: var(--accent); color: #fff; }
|
||||
.btn-primary:hover { background: var(--accent-hover); }
|
||||
.btn-ghost { background: transparent; color: var(--text); border: 1px solid var(--border); }
|
||||
.btn-ghost:hover { background: var(--accent-soft); }
|
||||
.header-inner { display: flex; align-items: center; gap: var(--space-3); min-height: 64px; }
|
||||
.header-inner .brand { margin-right: auto; display: inline-flex; align-items: center; min-height: var(--target-min); color: inherit; text-decoration: none; }
|
||||
|
||||
/* Content */
|
||||
.content { padding: 48px 0 72px; }
|
||||
.doc-title {
|
||||
font-size: 32px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.02em;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.doc-subtitle {
|
||||
color: var(--text-muted);
|
||||
font-size: 17px;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
.content { padding: var(--space-12) 0 var(--space-16); }
|
||||
.doc-title { margin: 0 0 var(--stack-text); }
|
||||
.doc-subtitle { margin: 0 0 var(--stack-section); }
|
||||
|
||||
.section {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
padding: 28px 28px;
|
||||
margin-bottom: 24px;
|
||||
background: var(--surface-raised);
|
||||
border: 1px solid var(--hairline);
|
||||
border-radius: var(--radius-xl);
|
||||
box-shadow: var(--shadow-1);
|
||||
padding: var(--space-8);
|
||||
margin-bottom: var(--stack-group);
|
||||
}
|
||||
.section--accent { border-color: var(--brand); box-shadow: 0 0 0 1px var(--brand) inset, var(--shadow-1); }
|
||||
.section h2 {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 16px;
|
||||
color: var(--accent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
display: flex; align-items: center; gap: var(--space-3);
|
||||
margin: 0 0 var(--stack-group);
|
||||
font-family: var(--font-display); font-size: 22px; line-height: 28px; font-weight: 600;
|
||||
}
|
||||
.section h3 {
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
margin: 18px 0 8px;
|
||||
}
|
||||
.section p { color: var(--text-muted); margin-bottom: 10px; }
|
||||
.section ul { padding-left: 20px; margin-bottom: 10px; }
|
||||
.section li { color: var(--text-muted); margin-bottom: 6px; }
|
||||
.section li strong { color: var(--text); }
|
||||
.section h2 .ps-icon { color: var(--brand); flex: none; }
|
||||
.section h3 { margin: var(--space-5) 0 var(--space-2); font-size: 17px; line-height: 24px; font-weight: 600; }
|
||||
.section p, .section li { color: var(--ink-secondary); text-wrap: pretty; }
|
||||
.section p { margin: 0 0 var(--space-3); }
|
||||
.section ul { margin: 0; padding-left: var(--space-5); }
|
||||
.section li { margin-bottom: var(--space-2); }
|
||||
.section li strong { color: var(--ink); }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: var(--space-3); }
|
||||
|
||||
.meta-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 16px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.meta-item {
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
.meta-item .label {
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.meta-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: var(--space-4); }
|
||||
.meta-grid + p { margin-top: var(--stack-group); }
|
||||
.meta-item { background: var(--surface-sunken); border-radius: var(--radius-lg); padding: var(--space-4); }
|
||||
.meta-item .label { font-size: 13px; line-height: 16px; color: var(--ink-secondary); margin-bottom: var(--space-1); }
|
||||
.meta-item .value { font-weight: 600; }
|
||||
|
||||
/* Slides table */
|
||||
.slides-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.slides-table th, .slides-table td {
|
||||
border: 1px solid var(--border);
|
||||
padding: 10px 14px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.slides-table th {
|
||||
background: var(--surface-2);
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
.slides-table td { color: var(--text-muted); }
|
||||
.slides-table td:first-child { color: var(--accent); font-weight: 600; white-space: nowrap; }
|
||||
.table-wrap { overflow-x: auto; margin: 0 calc(-1 * var(--space-2)); }
|
||||
.slides-table { width: 100%; border-collapse: collapse; }
|
||||
.slides-table th, .slides-table td { padding: var(--space-3) var(--space-2); text-align: left; vertical-align: top; border-bottom: 1px solid var(--hairline); }
|
||||
.slides-table th { font-size: 13px; line-height: 16px; font-weight: 600; color: var(--ink-secondary); }
|
||||
.slides-table td { color: var(--ink-secondary); }
|
||||
.slides-table td:nth-child(2) { color: var(--ink); font-weight: 600; }
|
||||
.slides-table td:first-child { color: var(--brand); font-weight: 600; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.slides-table tr:last-child td { border-bottom: 0; }
|
||||
|
||||
.tag {
|
||||
display: inline-block;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
border-radius: 6px;
|
||||
padding: 2px 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
margin: 2px 4px 2px 0;
|
||||
display: inline-flex; align-items: center;
|
||||
background: var(--brand-tint); color: var(--brand-pressed);
|
||||
border-radius: var(--radius-pill);
|
||||
padding: var(--space-1) var(--space-3);
|
||||
font-size: 13px; line-height: 16px; font-weight: 600;
|
||||
margin: 0 var(--space-1) var(--space-2) 0;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding: 24px 0;
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
font-size: 14px;
|
||||
}
|
||||
.footer { padding: var(--space-6) 0; border-top: 1px solid var(--hairline); color: var(--ink-secondary); font-size: 15px; text-align: center; }
|
||||
.footer a { color: var(--brand); display: inline-block; padding: var(--space-3) var(--space-1); }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.doc-title { font-size: 26px; }
|
||||
.content { padding: 32px 0 48px; }
|
||||
.section { padding: 20px; }
|
||||
.container { padding: 0 var(--space-4); }
|
||||
.content { padding: var(--space-8) 0 var(--space-12); }
|
||||
.section { padding: var(--space-5); border-radius: var(--radius-lg); }
|
||||
/* На телефоне в шапке только логотип и тема: скачивание — в первом блоке страницы */
|
||||
.header-inner .ps-btn { display: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="header">
|
||||
<div class="container header-inner">
|
||||
<a class="brand" href="/">
|
||||
<span class="brand-icon">🤖</span>
|
||||
<span>ИИ Пресс-секретарь</span>
|
||||
</a>
|
||||
<a class="btn btn-ghost" href="/">На сайт</a>
|
||||
<a class="btn btn-primary" href="/static/pressa-presentation.pptx" download>Скачать презентацию</a>
|
||||
<a class="brand" href="/" aria-label="ИИ Пресс-секретарь — на главную">{{ ui.logo('tzlogo', 'color', 28) }}</a>
|
||||
<button type="button" class="ps-iconbtn" data-theme-toggle aria-label="Сменить тему">{{ ui.icon('theme', 22) }}</button>
|
||||
<a class="ps-btn ps-btn--quiet" href="/"><span class="ps-btn-label">На сайт</span></a>
|
||||
<a class="ps-btn ps-btn--primary" href="/presentation.pptx" download>{{ ui.icon('download', 20) }}<span class="ps-btn-label">Презентация</span></a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<div class="container">
|
||||
<h1 class="doc-title">Техническое задание</h1>
|
||||
<p class="doc-subtitle">На создание 10-слайдовой презентации сервиса «ИИ Пресс-секретарь»</p>
|
||||
<h1 class="ps-h1 doc-title">Техническое задание</h1>
|
||||
<p class="ps-lead doc-subtitle">На создание 10-слайдовой презентации сервиса «ИИ Пресс-секретарь»</p>
|
||||
|
||||
<div class="section" style="border-color: var(--accent);">
|
||||
<h2>📥 Готовая презентация</h2>
|
||||
<div class="section section--accent">
|
||||
<h2>{{ ui.icon('download', 24) }}Готовая презентация</h2>
|
||||
<p>Презентация создана по этому ТЗ (10 слайдов, 16:9). Изображения сгенерированы через ИИ.</p>
|
||||
<p style="margin-top: 12px;">
|
||||
<a class="btn btn-primary" href="/static/pressa-presentation.pptx" download>⬇️ Скачать презентацию (PPTX)</a>
|
||||
<a class="btn btn-ghost" href="/static/pressa-presentation.pdf" download>📄 Скачать PDF</a>
|
||||
</p>
|
||||
<div class="actions">
|
||||
<a class="ps-btn ps-btn--primary" href="/presentation.pptx" download>{{ ui.icon('download', 20) }}<span class="ps-btn-label">Скачать PPTX</span></a>
|
||||
<a class="ps-btn ps-btn--secondary" href="/presentation.pdf" download>{{ ui.icon('news', 20) }}<span class="ps-btn-label">Скачать PDF</span></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>📋 Общая информация</h2>
|
||||
<h2>{{ ui.icon('info', 24) }}Общая информация</h2>
|
||||
<div class="meta-grid">
|
||||
<div class="meta-item">
|
||||
<div class="label">Название сервиса</div>
|
||||
@@ -236,7 +152,7 @@
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>🎯 Цель презентации</h2>
|
||||
<h2>{{ ui.icon('sparkle', 24) }}Цель презентации</h2>
|
||||
<p>Показать ценность сервиса «ИИ Пресс-секретарь» как комплексного решения для генерации и публикации контента в Telegram. Презентация должна:</p>
|
||||
<ul>
|
||||
<li>Заинтересовать потенциального клиента и побудить зарегистрироваться</li>
|
||||
@@ -247,21 +163,23 @@
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>🎨 Требования к стилю и дизайну</h2>
|
||||
<h2>{{ ui.icon('image', 24) }}Требования к стилю и дизайну</h2>
|
||||
<ul>
|
||||
<li><strong>Цветовая гамма:</strong> тёмная тема (тёмно-синий фон <code>#0f172a</code>, поверхности <code>#1e293b</code>), акцент — синий <code>#60a5fa</code> / <code>#2563eb</code>. Светлый текст <code>#e2e8f0</code>.</li>
|
||||
<li><strong>Стиль:</strong> современный, технологичный, чистый, минималистичный. Без перегруженности.</li>
|
||||
<li><strong>Шрифты:</strong> современные гротески (Inter, Manrope, Montserrat, Roboto).</li>
|
||||
<li><strong>Иконки:</strong> плоские, линейные, в едином стиле (можно эмодзи: ✍️ 🎨 📅 📣 🤖).</li>
|
||||
<li><strong>Изображения:</strong> сгенерированные иллюстрации в стиле сайта (робот-ассистент, элементы контент-маркетинга).</li>
|
||||
<li><strong>Брендбук:</strong> дизайн-система «ИИ Пресс-секретарь», версия 2 «Жидкое стекло» — те же токены, что у сайта и кабинета.</li>
|
||||
<li><strong>Цвет:</strong> фон <code>surface</code> #f4f7fb, карточки <code>surface-raised</code> #ffffff с рамкой <code>hairline</code> #d6e0ec, текст <code>ink</code> #0e1b2e и <code>ink-secondary</code> #46566c, акцент <code>brand</code> #1d71b8. Обложка и финальный слайд — градиент бренда #009fe3 → #1d71b8 с белым знаком.</li>
|
||||
<li><strong>Шрифт:</strong> Donbass (Regular, Medium, SemiBold, Bold), встроен в файл.</li>
|
||||
<li><strong>Логотип:</strong> только файлы из группы «Logos»: цветной логотип с надписью на светлых слайдах, белый — на градиенте. Знак не обрезается и не перекрашивается.</li>
|
||||
<li><strong>Иконки:</strong> линейные иконки дизайн-системы в плитках <code>brand-tint</code>. Без эмодзи.</li>
|
||||
<li><strong>Изображения:</strong> реальные экраны кабинета (главная, создание поста, пост с чатом правок, контент-план).</li>
|
||||
<li><strong>Тексты:</strong> по правилам голоса брендбука — на «вы», коротко, регистр как в предложении, «ёлочки» и длинное тире.</li>
|
||||
<li><strong>Язык:</strong> русский.</li>
|
||||
<li><strong>Формат слайдов:</strong> 16:9 (1920×1080).</li>
|
||||
<li><strong>Формат слайдов:</strong> 16:9 (13,33 × 7,5 дюйма).</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>📑 Структура презентации (10 слайдов)</h2>
|
||||
<table class="slides-table">
|
||||
<h2>{{ ui.icon('grid', 24) }}Структура презентации (10 слайдов)</h2>
|
||||
<div class="table-wrap"><table class="slides-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
@@ -293,7 +211,7 @@
|
||||
<tr>
|
||||
<td>5</td>
|
||||
<td><strong>Медиа-образ</strong></td>
|
||||
<td>Уникальный медиа-образ бренда: опрос о бизнесе, ИИ формирует бренд-бук, все посты в едином стиле, импорт из Telegram/VK/Tenchat/Instagram.</td>
|
||||
<td>Уникальный медиа-образ бренда: опрос о бизнесе, ИИ формирует бренд-бук, все посты в едином стиле, импорт из Telegram/VK/TenChat/Instagram.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>6</td>
|
||||
@@ -321,11 +239,11 @@
|
||||
<td>«Готовы начать?» — кнопки «Зарегистрироваться» и «Войти в кабинет», ссылка на сайт.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</table></div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>🛠️ Технические требования</h2>
|
||||
<h2>{{ ui.icon('settings', 24) }}Технические требования</h2>
|
||||
<ul>
|
||||
<li>Формат: <strong>PPTX</strong> (PowerPoint) или <strong>PDF</strong></li>
|
||||
<li>Соотношение сторон: <strong>16:9</strong></li>
|
||||
@@ -338,7 +256,7 @@
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>🔗 Ключевые факты о сервисе</h2>
|
||||
<h2>{{ ui.icon('link', 24) }}Ключевые факты о сервисе</h2>
|
||||
<p>Ссылки для использования в презентации:</p>
|
||||
<p>
|
||||
<span class="tag">Сайт: press.my-dpr.ru</span>
|
||||
@@ -353,7 +271,7 @@
|
||||
<li>Статистика, чат с ИИ, подключение каналов</li>
|
||||
</ul>
|
||||
<h3>Поддерживаемые платформы для анализа</h3>
|
||||
<p>Telegram, VK, Tenchat, Instagram</p>
|
||||
<p>Telegram, VK, TenChat, Instagram</p>
|
||||
<h3>Технологии</h3>
|
||||
<p>Python, FastAPI, SQLite, ИИ (OpenAI GPT, PiAPI)</p>
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,74 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Профиль — Личный кабинет{% endblock %}
|
||||
{% block title %}Профиль{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Редактировать профиль</h1>
|
||||
<form method="post" action="/profile/edit" class="form">
|
||||
<label>Имя
|
||||
<input type="text" name="name" value="{{ user.name }}" required>
|
||||
</label>
|
||||
<label>Телефон
|
||||
<input type="text" name="phone" value="{{ user.phone }}" required>
|
||||
</label>
|
||||
<button type="submit">Сохранить</button>
|
||||
</form>
|
||||
|
||||
<div class="card">
|
||||
<h2>Провайдер ИИ</h2>
|
||||
{% if provider %}
|
||||
<p><strong>Текущий:</strong> {{ provider_presets[provider.provider_type].name if provider.provider_type in provider_presets else provider.provider_type }}</p>
|
||||
{% else %}
|
||||
<p>Используются глобальные настройки (PiAPI).</p>
|
||||
{% endif %}
|
||||
<a href="/provider" class="copy-btn">⚙ Настроить провайдера</a>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Профиль</h1>
|
||||
<p class="ps-lead">{{ user.email }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>TenChat</h2>
|
||||
<p>Подключите аккаунт TenChat, чтобы публиковать посты автоматически.</p>
|
||||
<a href="/tenchat" class="copy-btn">🔑 Настроить TenChat</a>
|
||||
<div class="ps-grid-2">
|
||||
<form method="post" action="/profile/edit" class="ps-panel app-form">
|
||||
<h2 class="ps-h2">Личные данные</h2>
|
||||
<div class="ps-field">
|
||||
<label for="name" class="ps-field-label">Имя</label>
|
||||
<input id="name" class="ps-field-control" type="text" name="name" autocomplete="name" value="{{ user.name }}" required>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="phone" class="ps-field-label">Телефон</label>
|
||||
<input id="phone" class="ps-field-control" type="tel" name="phone" autocomplete="tel" value="{{ user.phone }}" required>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="email" class="ps-field-label">Email</label>
|
||||
<input id="email" class="ps-field-control" type="email" value="{{ user.email }}" disabled aria-describedby="email-hint">
|
||||
<p id="email-hint" class="ps-field-hint"><span>Email — это логин, его нельзя изменить.</span></p>
|
||||
</div>
|
||||
<div class="app-actions">
|
||||
<button type="submit" class="ps-btn ps-btn--primary">{{ ui.icon('check', 20) }}<span class="ps-btn-label">Сохранить</span></button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="app-stack-lg">
|
||||
<section class="ps-panel">
|
||||
<div class="ps-provider-head">
|
||||
<span class="ps-provider-icon" aria-hidden="true">{{ ui.icon('cpu', 22) }}</span>
|
||||
<span class="ps-provider-text">
|
||||
<h2 class="ps-provider-title">ИИ-провайдер</h2>
|
||||
<span class="ps-provider-desc">
|
||||
{%- if provider -%}
|
||||
{%- set tp = provider.text_provider_type -%}{%- set ip = provider.image_provider_type -%}
|
||||
Текст — {{ provider_presets[tp].name if tp in provider_presets else (tp or 'глобальные настройки') }}{% if not provider.text_api_key %} (глобальный ключ){% endif %},
|
||||
картинки — {{ provider_presets[ip].name if ip in provider_presets else (ip or 'глобальные настройки') }}{% if not provider.image_api_key %} (глобальный ключ){% endif %}
|
||||
{%- else -%}Глобальные настройки сервиса (PiAPI){%- endif -%}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="app-actions"><a href="/provider" class="ps-btn ps-btn--secondary ps-btn--sm">{{ ui.icon('settings', 16) }}<span class="ps-btn-label">Настроить</span></a></div>
|
||||
</section>
|
||||
<section class="ps-panel">
|
||||
<div class="ps-provider-head">
|
||||
<span class="ps-provider-icon" aria-hidden="true">{{ ui.icon('users', 22) }}</span>
|
||||
<span class="ps-provider-text">
|
||||
<h2 class="ps-provider-title">TenChat</h2>
|
||||
<span class="ps-provider-desc">Публикация постов в профиль TenChat</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="app-actions"><a href="/tenchat" class="ps-btn ps-btn--secondary ps-btn--sm">{{ ui.icon('key', 16) }}<span class="ps-btn-label">Подключить</span></a></div>
|
||||
</section>
|
||||
<section class="ps-panel">
|
||||
<div class="app-actions">
|
||||
<form action="/logout" method="post" class="inline-form">
|
||||
<button type="submit" class="ps-btn ps-btn--quiet">{{ ui.icon('logout', 20) }}<span class="ps-btn-label">Выйти</span></button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p><a href="/dashboard">← Назад в кабинет</a></p>
|
||||
<section class="ps-panel">
|
||||
<h2 class="ps-h2">Удаление аккаунта</h2>
|
||||
<p class="app-muted" style="margin:0">Удалятся профиль, посты, картинки, медиа-образы и контент-план. Вернуть их будет нельзя.</p>
|
||||
<div class="app-actions"><a href="/delete-account" class="ps-btn ps-btn--danger">{{ ui.icon('trash', 20) }}<span class="ps-btn-label">Удалить аккаунт</span></a></div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -1,162 +1,137 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Провайдеры ИИ — Личный кабинет{% endblock %}
|
||||
{% block title %}ИИ-провайдеры{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Провайдеры ИИ</h1>
|
||||
<p class="form-hint">Настройте провайдеров для генерации текста и изображений независимо. API ключи хранятся только у вас.</p>
|
||||
|
||||
{% if provider %}
|
||||
<div class="card">
|
||||
<p class="form-hint" style="margin:0">
|
||||
<strong>Текст:</strong> {{ provider_presets[provider.text_provider_type].name if provider.text_provider_type in provider_presets else provider.text_provider_type }} → {{ provider.text_model }}
|
||||
|
|
||||
<strong>Изображения:</strong>
|
||||
{% if provider.image_api_key %}
|
||||
{{ provider_presets[provider.image_provider_type].name if provider.image_provider_type in provider_presets else provider.image_provider_type }} → {{ provider.image_model or '(не указана)' }}
|
||||
{% else %}
|
||||
<em>глобальный PiAPI</em>
|
||||
{% endif %}
|
||||
<span class="form-hint">· {{ provider.updated_at }}</span>
|
||||
</p>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p style="margin:0">Используются глобальные настройки (PiAPI из .env). Настройте свои провайдеры для независимости.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- Табы -->
|
||||
<div class="provider-tabs">
|
||||
<button type="button" class="provider-tab active" onclick="switchTab('text')">✍️ Генерация текста</button>
|
||||
<button type="button" class="provider-tab" onclick="switchTab('image')">🎨 Генерация изображений</button>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/provider" class="form" id="providerForm">
|
||||
|
||||
<!-- === ТАБ: ТЕКСТ === -->
|
||||
<div class="provider-tab-content active" id="tabText">
|
||||
<h2>✍️ Генерация текста</h2>
|
||||
<label>Провайдер
|
||||
<select name="text_provider_type" id="textProviderType" required onchange="updatePresets('text')">
|
||||
<option value="" disabled {% if not provider and not form %}selected{% endif %}>Выберите провайдера</option>
|
||||
{% for key, preset in provider_presets.items() %}
|
||||
<option value="{{ key }}"
|
||||
{% if (provider and provider.text_provider_type == key) or (form and form.text_provider_type == key) %}selected{% endif %}>
|
||||
{{ preset.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>API ключ
|
||||
<input type="password" name="text_api_key" id="textApiKey"
|
||||
value="{{ form.text_api_key if form else '' }}"
|
||||
placeholder="Ваш API ключ">
|
||||
</label>
|
||||
<label style="flex-direction: row; align-items: center; gap: 8px;">
|
||||
<input type="checkbox" name="text_use_global" value="1" id="textUseGlobal"
|
||||
onchange="toggleGlobal('text')">
|
||||
<span>Использовать глобальные настройки (PiAPI из .env)</span>
|
||||
</label>
|
||||
|
||||
<label>Base URL
|
||||
<input type="text" name="text_base_url" id="textBaseUrl"
|
||||
value="{{ form.text_base_url if form else (provider.text_base_url if provider else '') }}"
|
||||
placeholder="https://...">
|
||||
</label>
|
||||
|
||||
<label>Модель
|
||||
<input type="text" name="text_model" id="textModel"
|
||||
value="{{ form.text_model if form else (provider.text_model if provider else '') }}"
|
||||
placeholder="напр. gpt-4o, glm-5.2, claude-sonnet-5">
|
||||
</label>
|
||||
|
||||
<div class="card" style="margin-top:15px; background: var(--bg-secondary);">
|
||||
<p style="margin:0; font-size: 13px;"><strong>Популярные модели для текста:</strong></p>
|
||||
<ul style="margin:5px 0 0 18px; font-size: 13px;">
|
||||
<li><code>gpt-4o</code> — OpenAI, OpenRouter, PiAPI</li>
|
||||
<li><code>claude-sonnet-5</code> — Anthropic через OpenRouter</li>
|
||||
<li><code>glm-5.2</code> — OpenCode Zen (платная)</li>
|
||||
<li><code>deepseek-v4-flash-free</code> — OpenCode Zen (бесплатная)</li>
|
||||
<li><code>hy3-free</code> — OpenCode Zen (бесплатная, reasoning)</li>
|
||||
</ul>
|
||||
{%- macro provider_fields(kind) -%}
|
||||
{%- set p_type = provider[kind ~ '_provider_type'] if provider else '' -%}
|
||||
{%- set use_global_checked = (kind == 'text') and ((form and form['text_use_global']) or (not form and (not provider or not provider['text_api_key']))) -%}
|
||||
<div class="ps-field">
|
||||
<label for="{{ kind }}ProviderType" class="ps-field-label">Провайдер</label>
|
||||
<div class="ps-select">
|
||||
<select name="{{ kind }}_provider_type" id="{{ kind }}ProviderType" class="ps-field-control ps-select-control" required onchange="updatePresets('{{ kind }}')">
|
||||
<option value="" disabled {% if not provider and not form %}selected{% endif %}>Выберите провайдера</option>
|
||||
{% for key, preset in provider_presets.items() %}
|
||||
{% if kind == 'text' or preset.supports_images %}
|
||||
<option value="{{ key }}" {% if (provider and p_type == key) or (form and form[kind ~ '_provider_type'] == key) %}selected{% endif %}>{{ preset.name }}</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</select>
|
||||
{{ ui.icon('chevron-down', 18, 'ps-select-chev') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- === ТАБ: ИЗОБРАЖЕНИЯ === -->
|
||||
<div class="provider-tab-content" id="tabImage">
|
||||
<h2>🎨 Генерация изображений</h2>
|
||||
<label>Провайдер
|
||||
<select name="image_provider_type" id="imageProviderType" required onchange="updatePresets('image')">
|
||||
<option value="" disabled {% if not provider and not form %}selected{% endif %}>Выберите провайдера</option>
|
||||
{% for key, preset in provider_presets.items() %}
|
||||
{% if preset.supports_images %}
|
||||
<option value="{{ key }}"
|
||||
{% if (provider and provider.image_provider_type == key) or (form and form.image_provider_type == key) %}selected{% endif %}>
|
||||
{{ preset.name }}
|
||||
</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>API ключ
|
||||
<input type="password" name="image_api_key" id="imageApiKey"
|
||||
value="{{ form.image_api_key if form else '' }}"
|
||||
placeholder="Ваш API ключ">
|
||||
</label>
|
||||
<label style="flex-direction: row; align-items: center; gap: 8px;">
|
||||
<input type="checkbox" name="image_use_global" value="1" id="imageUseGlobal"
|
||||
onchange="toggleGlobal('image')">
|
||||
<span>Использовать глобальные настройки (PiAPI из .env)</span>
|
||||
</label>
|
||||
|
||||
<label>Base URL
|
||||
<input type="text" name="image_base_url" id="imageBaseUrl"
|
||||
value="{{ form.image_base_url if form else (provider.image_base_url if provider else '') }}"
|
||||
placeholder="https://...">
|
||||
</label>
|
||||
|
||||
<label>Модель
|
||||
<input type="text" name="image_model" id="imageModel"
|
||||
value="{{ form.image_model if form else (provider.image_model if provider else '') }}"
|
||||
placeholder="напр. gpt-image-1, dall-e-3">
|
||||
</label>
|
||||
|
||||
<div class="card" style="margin-top:15px; background: var(--bg-secondary);">
|
||||
<p style="margin:0; font-size: 13px;"><strong>Популярные модели для изображений:</strong></p>
|
||||
<ul style="margin:5px 0 0 18px; font-size: 13px;">
|
||||
<li><code>gpt-image-1</code> — OpenAI, PiAPI (рекомендуется)</li>
|
||||
<li><code>gpt-image-1-mini</code> — OpenAI (быстрая, дешевле)</li>
|
||||
<li><code>dall-e-3</code> — OpenAI (старая, через прямой API)</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="{{ kind }}Model" class="ps-field-label">Модель</label>
|
||||
<input type="text" name="{{ kind }}_model" id="{{ kind }}Model" class="ps-field-control"
|
||||
value="{{ form[kind ~ '_model'] if form else (provider[kind ~ '_model'] if provider else '') }}"
|
||||
placeholder="{{ 'напр. gpt-4o, glm-5.2' if kind == 'text' else 'напр. gpt-image-1' }}">
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="{{ kind }}ApiKey" class="ps-field-label">API-ключ</label>
|
||||
<div class="ps-secret">
|
||||
<input type="password" name="{{ kind }}_api_key" id="{{ kind }}ApiKey" class="ps-field-control ps-secret-control" autocomplete="off" spellcheck="false"
|
||||
value="{{ form[kind ~ '_api_key'] if form else '' }}" placeholder="Ваш API-ключ">
|
||||
<button type="button" class="ps-iconbtn" data-secret-toggle aria-label="Показать ключ">{{ ui.icon('eye', 20) }}</button>
|
||||
</div>
|
||||
</div>
|
||||
{%- set saved_key = provider[kind ~ '_api_key'] if provider else '' -%}
|
||||
<p class="ps-field-hint">{{ ui.icon('key', 16) }}<span>{% if saved_key %}Сохранён ключ {{ saved_key[:3] }}…{{ saved_key[-3:] }}. При сохранении введите ключ ещё раз.{% else %}Ключ хранится только в вашем кабинете.{% endif %}</span></p>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="{{ kind }}BaseUrl" class="ps-field-label">Базовый URL</label>
|
||||
<input type="text" name="{{ kind }}_base_url" id="{{ kind }}BaseUrl" class="ps-field-control"
|
||||
value="{{ form[kind ~ '_base_url'] if form else (provider[kind ~ '_base_url'] if provider else '') }}" placeholder="https://…">
|
||||
</div>
|
||||
<label class="app-check" style="grid-column: 1 / -1">
|
||||
<input type="checkbox" name="{{ kind }}_use_global" value="1" id="{{ kind }}UseGlobal" onchange="toggleGlobal('{{ kind }}')" {% if use_global_checked %}checked{% endif %}>
|
||||
<span>{% if kind == 'text' %}Использовать стандартные настройки (Qwen){% else %}Использовать глобальные настройки (PiAPI){% endif %}</span>
|
||||
</label>
|
||||
{%- endmacro -%}
|
||||
|
||||
<button type="submit">Сохранить настройки</button>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">ИИ-провайдеры</h1>
|
||||
<p class="ps-lead">Текст и картинки можно генерировать через разных провайдеров. По умолчанию текст идёт через Qwen сервиса, картинки — через глобальные настройки (PiAPI).</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/provider" id="providerForm" class="app-stack-lg">
|
||||
<div class="ps-grid-2">
|
||||
<section class="ps-provider">
|
||||
<header class="ps-provider-head">
|
||||
<span class="ps-provider-icon" aria-hidden="true">{{ ui.icon('chat', 22) }}</span>
|
||||
<span class="ps-provider-text">
|
||||
<h2 class="ps-provider-title">Текст</h2>
|
||||
<span class="ps-provider-desc">Посты, правки в чате, контент-план, анализ соцсетей</span>
|
||||
</span>
|
||||
{% if provider and provider.text_api_key %}
|
||||
<span class="ps-badge ps-badge--success">{{ ui.icon('check', 14) }}<span>Подключено</span></span>
|
||||
{% else %}
|
||||
<span class="ps-badge ps-badge--neutral">{{ ui.icon('info', 14) }}<span>Стандартные (Qwen)</span></span>
|
||||
{% endif %}
|
||||
</header>
|
||||
<div class="ps-provider-body" style="grid-template-columns: 1fr">{{ provider_fields('text') }}</div>
|
||||
<details>
|
||||
<summary>Популярные модели</summary>
|
||||
<ul class="form-hint" style="margin: 8px 0 0; padding-left: 18px">
|
||||
<li><code>{{ default_text.model }}</code> — стандартный Qwen сервиса</li>
|
||||
<li><code>gpt-4o</code> — OpenAI, OpenRouter, PiAPI</li>
|
||||
<li><code>claude-sonnet-5</code> — Anthropic через OpenRouter</li>
|
||||
<li><code>glm-5.2</code> — OpenCode Zen (платная)</li>
|
||||
<li><code>deepseek-v4-flash-free</code> — OpenCode Zen (бесплатная)</li>
|
||||
<li><code>hy3-free</code> — OpenCode Zen (бесплатная, reasoning)</li>
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section class="ps-provider">
|
||||
<header class="ps-provider-head">
|
||||
<span class="ps-provider-icon" aria-hidden="true">{{ ui.icon('image', 22) }}</span>
|
||||
<span class="ps-provider-text">
|
||||
<h2 class="ps-provider-title">Изображения</h2>
|
||||
<span class="ps-provider-desc">Картинки к постам: шаблоны, концепции, референсы</span>
|
||||
</span>
|
||||
{% if provider and provider.image_api_key %}
|
||||
<span class="ps-badge ps-badge--success">{{ ui.icon('check', 14) }}<span>Подключено</span></span>
|
||||
{% else %}
|
||||
<span class="ps-badge ps-badge--neutral">{{ ui.icon('info', 14) }}<span>Глобальные настройки</span></span>
|
||||
{% endif %}
|
||||
</header>
|
||||
<div class="ps-provider-body" style="grid-template-columns: 1fr">{{ provider_fields('image') }}</div>
|
||||
<details>
|
||||
<summary>Популярные модели</summary>
|
||||
<ul class="form-hint" style="margin: 8px 0 0; padding-left: 18px">
|
||||
<li><code>gpt-image-1</code> — OpenAI, PiAPI (рекомендуется)</li>
|
||||
<li><code>gpt-image-1-mini</code> — OpenAI (быстрее и дешевле)</li>
|
||||
<li><code>dall-e-3</code> — OpenAI (прямой API)</li>
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="app-actions">
|
||||
<button type="submit" class="ps-btn ps-btn--primary">{{ ui.icon('check', 20) }}<span class="ps-btn-label">Сохранить</span></button>
|
||||
{% if provider %}<span class="app-caption">Обновлено {{ provider.updated_at|local_dt }}</span>{% endif %}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<p style="margin-top:20px"><a href="/profile/edit">← Назад в профиль</a> · <a href="/dashboard">← На главную</a></p>
|
||||
<section class="ps-panel">
|
||||
<div class="ps-provider-head">
|
||||
<span class="ps-provider-icon" aria-hidden="true">{{ ui.icon('users', 22) }}</span>
|
||||
<span class="ps-provider-text">
|
||||
<h2 class="ps-provider-title">TenChat</h2>
|
||||
<span class="ps-provider-desc">Публикация постов в профиль TenChat</span>
|
||||
</span>
|
||||
<a href="/tenchat" class="ps-btn ps-btn--secondary ps-btn--sm">{{ ui.icon('key', 16) }}<span class="ps-btn-label">Настроить</span></a>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
const PRESETS = {
|
||||
{% for key, preset in provider_presets.items() %}
|
||||
"{{ key }}": {"base_url": "{{ preset.base_url }}", "text_model": "{{ preset.text_model }}", "image_model": "{{ preset.image_model }}"},
|
||||
{% endfor %}
|
||||
};
|
||||
|
||||
function switchTab(tab) {
|
||||
// Переключаем кнопки
|
||||
document.querySelectorAll('.provider-tab').forEach(function(btn) { btn.classList.remove('active'); });
|
||||
document.querySelectorAll('.provider-tab-content').forEach(function(c) { c.classList.remove('active'); });
|
||||
// Активируем нужный таб
|
||||
if (tab === 'text') {
|
||||
document.querySelectorAll('.provider-tab')[0].classList.add('active');
|
||||
document.getElementById('tabText').classList.add('active');
|
||||
} else {
|
||||
document.querySelectorAll('.provider-tab')[1].classList.add('active');
|
||||
document.getElementById('tabImage').classList.add('active');
|
||||
}
|
||||
}
|
||||
const DEFAULT_TEXT = {"base_url": "{{ default_text.base_url }}", "model": "{{ default_text.model }}"};
|
||||
|
||||
function updatePresets(kind) {
|
||||
var typeEl = document.getElementById(kind + "ProviderType");
|
||||
@@ -177,16 +152,40 @@ function toggleGlobal(kind) {
|
||||
var key = document.getElementById(kind + "ApiKey");
|
||||
var baseUrl = document.getElementById(kind + "BaseUrl");
|
||||
var model = document.getElementById(kind + "Model");
|
||||
var typeEl = document.getElementById(kind + "ProviderType");
|
||||
if (cb.checked) {
|
||||
key.disabled = true;
|
||||
key.placeholder = "Используются глобальные настройки";
|
||||
key.placeholder = "Используются стандартные настройки";
|
||||
key.value = "";
|
||||
baseUrl.value = "https://api.piapi.ai/v1";
|
||||
model.value = (kind === "text") ? "gpt-4o" : "gpt-image-1";
|
||||
if (kind === "text") {
|
||||
if (typeEl) typeEl.value = "qwen";
|
||||
baseUrl.value = DEFAULT_TEXT.base_url;
|
||||
model.value = DEFAULT_TEXT.model;
|
||||
baseUrl.disabled = true;
|
||||
model.disabled = true;
|
||||
} else {
|
||||
baseUrl.value = "https://api.piapi.ai/v1";
|
||||
model.value = "gpt-image-1";
|
||||
}
|
||||
} else {
|
||||
key.disabled = false;
|
||||
key.placeholder = "Ваш API ключ";
|
||||
key.placeholder = "Ваш API-ключ";
|
||||
baseUrl.disabled = false;
|
||||
model.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var cb = document.getElementById('textUseGlobal');
|
||||
if (cb && cb.checked) toggleGlobal('text');
|
||||
});
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('[data-secret-toggle]'); if (!b) return;
|
||||
var input = b.parentNode.querySelector('input');
|
||||
var show = input.type === 'password';
|
||||
input.type = show ? 'text' : 'password';
|
||||
b.setAttribute('aria-label', show ? 'Скрыть ключ' : 'Показать ключ');
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,59 +1,70 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Опубликовать пост — Личный кабинет{% endblock %}
|
||||
{% block title %}Опубликовать пост{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Публикация поста</h1>
|
||||
|
||||
<div class="card">
|
||||
<p><strong>Платформа:</strong> {{ platform_label(post.platform) }}</p>
|
||||
<p><strong>Создан:</strong> {{ post.created_at }}</p>
|
||||
{% if post.published %}
|
||||
<p><strong>Статус:</strong> ✅ Опубликован в «{{ post.published_to }}» {{ post.published_at }}</p>
|
||||
{% else %}
|
||||
<p><strong>Статус:</strong> ⏳ Не опубликован</p>
|
||||
{% endif %}
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/posts/{{ post.id }}" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">К посту</span></a>
|
||||
<h1 class="ps-h1">Публикация</h1>
|
||||
<p class="ps-lead">{{ platform_label(post.platform) }} · создан {{ post.created_at|local_dt }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Текст поста</h2>
|
||||
<div class="result">{{ post.content }}</div>
|
||||
</div>
|
||||
<div class="ps-split" style="--ps-aside: 380px">
|
||||
<article class="ps-post">
|
||||
<header class="ps-post-head">
|
||||
<span class="ps-post-platform">{{ ui.icon('send', 16) }}{{ platform_label(post.platform) }}</span>
|
||||
{% if post.published %}
|
||||
<span class="ps-badge ps-badge--success">{{ ui.icon('megaphone', 14) }}<span>Опубликован{% if post.published_to %} в «{{ post.published_to }}»{% endif %}</span></span>
|
||||
{% else %}
|
||||
<span class="ps-badge ps-badge--neutral">{{ ui.icon('clock', 14) }}<span>Ещё не опубликован</span></span>
|
||||
{% endif %}
|
||||
</header>
|
||||
<div class="ps-post-text"><p>{{ post.content }}</p></div>
|
||||
<footer class="ps-post-foot">
|
||||
<span class="ps-post-count{% if post.content|length > 4096 %} is-over{% endif %}">{{ post.content|length|num }} / 4 096 зн.</span>
|
||||
{% if post.content|length > 1024 %}
|
||||
<span class="ps-post-note">{{ ui.icon('info', 14) }}Если есть картинка: длиннее 1 024 знаков — фото уйдёт без подписи, текст — следующим сообщением</span>
|
||||
{% endif %}
|
||||
</footer>
|
||||
</article>
|
||||
|
||||
{% if channels %}
|
||||
<form method="post" action="/posts/{{ post.id }}/publish" class="form">
|
||||
<label>Канал для публикации
|
||||
<select name="channel_id" required>
|
||||
<option value="" disabled selected>Выберите канал или чат</option>
|
||||
{% for ch in channels %}
|
||||
<option value="{{ ch.id }}">{{ ch.title }} ({{ ch.chat_type }}){% if ch.username %} @{{ ch.username }}{% endif %}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<button type="submit">📤 Опубликовать в Telegram</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p>⚠️ Нет добавленных каналов. <a href="/channels/add">Добавьте канал →</a></p>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="app-stack-lg">
|
||||
<section class="ps-panel">
|
||||
<h2 class="ps-h2">Telegram</h2>
|
||||
{% if channels %}
|
||||
<form method="post" action="/posts/{{ post.id }}/publish" class="app-form">
|
||||
<div class="ps-field">
|
||||
<label for="channel_id" class="ps-field-label">Канал или чат</label>
|
||||
<div class="ps-select">
|
||||
<select id="channel_id" name="channel_id" class="ps-field-control ps-select-control" required>
|
||||
<option value="" disabled selected>Выберите канал</option>
|
||||
{% for ch in channels %}
|
||||
<option value="{{ ch.id }}">{{ ch.title }}{% if ch.username %} · @{{ ch.username }}{% endif %}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
{{ ui.icon('chevron-down', 18, 'ps-select-chev') }}
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" class="ps-btn ps-btn--primary ps-btn--block">{{ ui.icon('send', 20) }}<span class="ps-btn-label">Опубликовать в Telegram</span></button>
|
||||
</form>
|
||||
{% else %}
|
||||
<p class="app-muted" style="margin:0">Каналов пока нет. Добавьте канал, где бот — администратор.</p>
|
||||
<a href="/channels/add" class="ps-btn ps-btn--secondary">{{ ui.icon('plus', 20) }}<span class="ps-btn-label">Добавить канал</span></a>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
{% if tenchat_connected %}
|
||||
<div class="card" style="margin-top:15px;">
|
||||
<h2>TenChat</h2>
|
||||
<p>Опубликовать этот пост в ваш профиль TenChat (@{{ tenchat_username }}).</p>
|
||||
<form method="post" action="/posts/{{ post.id }}/publish/tenchat" class="form" style="margin:0;">
|
||||
<button type="submit">📤 Опубликовать в TenChat</button>
|
||||
</form>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card" style="margin-top:15px;">
|
||||
<h2>TenChat</h2>
|
||||
<p>Подключите TenChat, чтобы публиковать посты в профиль.</p>
|
||||
<a href="/tenchat" class="copy-btn">🔑 Настроить TenChat</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="post-actions">
|
||||
<a href="/posts/{{ post.id }}" class="copy-btn">← Назад к посту</a>
|
||||
<a href="/channels" class="copy-btn">⚙ Управление каналами</a>
|
||||
<section class="ps-panel">
|
||||
<h2 class="ps-h2">TenChat</h2>
|
||||
{% if tenchat_connected %}
|
||||
<p class="app-muted" style="margin:0">Пост уйдёт в ваш профиль @{{ tenchat_username }}.</p>
|
||||
<form method="post" action="/posts/{{ post.id }}/publish/tenchat" class="inline-form">
|
||||
<button type="submit" class="ps-btn ps-btn--secondary ps-btn--block">{{ ui.icon('send', 20) }}<span class="ps-btn-label">Опубликовать в TenChat</span></button>
|
||||
</form>
|
||||
{% else %}
|
||||
<p class="app-muted" style="margin:0">Подключите TenChat, чтобы публиковать посты в профиль.</p>
|
||||
<a href="/tenchat" class="ps-btn ps-btn--secondary">{{ ui.icon('key', 20) }}<span class="ps-btn-label">Подключить TenChat</span></a>
|
||||
{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -1,24 +1,33 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Регистрация — Личный кабинет{% endblock %}
|
||||
{% block title %}Регистрация{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Регистрация</h1>
|
||||
<form method="post" action="/register" class="form">
|
||||
<label>Имя
|
||||
<input type="text" name="name" value="{{ form.name if form else '' }}" required>
|
||||
</label>
|
||||
<label>Телефон
|
||||
<input type="text" name="phone" value="{{ form.phone if form else '' }}" required>
|
||||
</label>
|
||||
<label>Email
|
||||
<input type="email" name="email" value="{{ form.email if form else '' }}" required>
|
||||
</label>
|
||||
<label>Пароль
|
||||
<input type="password" name="password" minlength="8" required>
|
||||
</label>
|
||||
<label>Повтори пароль
|
||||
<input type="password" name="password_confirm" minlength="8" required>
|
||||
</label>
|
||||
<button type="submit">Зарегистрироваться</button>
|
||||
<div class="app-stack">
|
||||
<h1 class="ps-h2">Регистрация</h1>
|
||||
<p class="ps-lead">После регистрации начнём с медиа-образа — это 5 минут.</p>
|
||||
</div>
|
||||
<form method="post" action="/register" class="app-form">
|
||||
<div class="ps-field">
|
||||
<label for="name" class="ps-field-label">Имя</label>
|
||||
<input id="name" class="ps-field-control" type="text" name="name" autocomplete="name" value="{{ form.name if form else '' }}" required>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="phone" class="ps-field-label">Телефон</label>
|
||||
<input id="phone" class="ps-field-control" type="tel" name="phone" autocomplete="tel" placeholder="+7 900 000-00-00" value="{{ form.phone if form else '' }}" required>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="email" class="ps-field-label">Email</label>
|
||||
<input id="email" class="ps-field-control" type="email" name="email" autocomplete="email" value="{{ form.email if form else '' }}" required>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="password" class="ps-field-label">Пароль</label>
|
||||
<input id="password" class="ps-field-control" type="password" name="password" autocomplete="new-password" minlength="8" aria-describedby="password-hint" required>
|
||||
<p id="password-hint" class="ps-field-hint"><span>Не короче 8 знаков</span></p>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="password_confirm" class="ps-field-label">Повторите пароль</label>
|
||||
<input id="password_confirm" class="ps-field-control" type="password" name="password_confirm" autocomplete="new-password" minlength="8" required>
|
||||
</div>
|
||||
<button type="submit" class="ps-btn ps-btn--primary ps-btn--lg ps-btn--block">Зарегистрироваться</button>
|
||||
</form>
|
||||
<p>Уже есть аккаунт? <a href="/login">Войти</a></p>
|
||||
<p class="app-auth-switch">Уже есть аккаунт? <a href="/login">Войти</a></p>
|
||||
{% endblock %}
|
||||
@@ -1,20 +1,47 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Статистика — Личный кабинет{% endblock %}
|
||||
{% block title %}Статистика{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Статистика использования</h1>
|
||||
<div class="card">
|
||||
<p><strong>В кабинете с:</strong> {{ stats.created_at }}</p>
|
||||
<p><strong>Всего постов:</strong> {{ stats.total_posts }}</p>
|
||||
{%- set labels = {'instagram': 'Instagram', 'linkedin': 'LinkedIn', 'telegram': 'Telegram', 'twitter': 'Twitter/X', 'tenchat': 'TenChat', 'ad': 'Рекламный пост'} -%}
|
||||
{%- set max_count = (stats.by_platform.values() | max) if stats.by_platform else 1 -%}
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Статистика</h1>
|
||||
<p class="ps-lead">В кабинете с {{ stats.created_at|local_dt('%d.%m.%Y') }}.</p>
|
||||
</div>
|
||||
</div>
|
||||
<h2>По платформам</h2>
|
||||
{% if stats.by_platform %}
|
||||
<ul>
|
||||
{% for platform, count in stats.by_platform.items() %}
|
||||
<li>{{ platform }}: {{ count }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<p>Пока нет постов.</p>
|
||||
{% endif %}
|
||||
<p><a href="/dashboard">← Назад в кабинет</a></p>
|
||||
|
||||
<div class="ps-grid-4">
|
||||
<div class="ps-stat">
|
||||
<span class="ps-stat-icon" aria-hidden="true">{{ ui.icon('news', 20) }}</span>
|
||||
<span class="ps-stat-label">Постов создано</span>
|
||||
<span class="ps-stat-value">{{ stats.total_posts }}</span>
|
||||
</div>
|
||||
<div class="ps-stat">
|
||||
<span class="ps-stat-icon" aria-hidden="true">{{ ui.icon('grid', 20) }}</span>
|
||||
<span class="ps-stat-label">Платформ</span>
|
||||
<span class="ps-stat-value">{{ stats.by_platform | length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="ps-panel">
|
||||
<h2 class="ps-h2">Посты по платформам</h2>
|
||||
{% if stats.by_platform %}
|
||||
<div class="app-bars">
|
||||
{% for platform, count in stats.by_platform | dictsort(by='value', reverse=True) %}
|
||||
<div class="app-bar">
|
||||
<span class="app-bar-label">{{ labels.get(platform, platform) }}</span>
|
||||
<span class="app-bar-track" role="img" aria-label="{{ labels.get(platform, platform) }}: {{ count }}"><span class="app-bar-fill" style="width: {{ (count / max_count * 100) | round(1) }}%"></span></span>
|
||||
<span class="app-bar-value">{{ count }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('chart', 28) }}</span>
|
||||
<h3 class="ps-empty-title">Данных пока нет</h3>
|
||||
<p class="ps-empty-text">Создайте первый пост — здесь появится разбивка по платформам.</p>
|
||||
<a href="/generate" class="ps-btn ps-btn--primary">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Создать пост</span></a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -1,24 +1,30 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Опрос медиа-образа — Личный кабинет{% endblock %}
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Медиа-образ{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Опрос для создания медиа-образа</h1>
|
||||
<p class="form-hint">Заполните поля по шагам. На последнем шаге можно сохранить и сгенерировать документ стратегии.</p>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/surveys" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">Медиа-образы</span></a>
|
||||
<h1 class="ps-h1">Новый медиа-образ</h1>
|
||||
<p class="ps-lead">12 коротких шагов. На последнем — сохранить образ и получить документ стратегии.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ps-split app-survey-layout" style="--ps-aside: 340px">
|
||||
|
||||
<!-- === АНАЛИЗ ПРОФИЛЯ СОЦСЕТИ === -->
|
||||
<div class="card" id="socialAnalyzer">
|
||||
<h2 style="margin-top:0">🔍 Автозаполнение из профиля соцсети</h2>
|
||||
<p class="form-hint">Вставьте ссылку на профиль или канал — ИИ проанализирует посты и заполнит поля медиа-образа. Поддерживается Telegram (автоматически), VK, Tenchat, Instagram (вручную).</p>
|
||||
<aside class="ps-panel app-survey-aside" id="socialAnalyzer">
|
||||
<h2 class="ps-h2">Автозаполнение</h2>
|
||||
<p class="form-hint">Вставьте ссылку на канал — ИИ прочитает последние посты и заполнит поля. Telegram — автоматически, для VK, TenChat и Instagram вставьте тексты постов.</p>
|
||||
|
||||
<div id="socialTaskError" class="task-error"></div>
|
||||
<div id="socialTaskLoader" class="task-loader" style="display:none; padding:15px">
|
||||
<div class="spinner"></div>
|
||||
<div class="task-loader-text">Анализирую посты...</div>
|
||||
<div class="ps-thinking" role="status"><span class="ps-fan" aria-hidden="true"><i></i><i></i><i></i></span><span>Анализирую посты…</span></div>
|
||||
<div class="task-loader-sub">Это может занять 20–60 секунд</div>
|
||||
</div>
|
||||
<div id="socialTaskResult" class="task-result" style="display:none"></div>
|
||||
|
||||
<div id="socialForm">
|
||||
<label>Ссылка на профиль/канал
|
||||
<label>Ссылка на канал или профиль
|
||||
<input type="url" id="socialUrl" placeholder="https://t.me/channel, https://vk.com/username, https://tenchat.ru/username">
|
||||
</label>
|
||||
|
||||
@@ -29,9 +35,9 @@
|
||||
<p class="form-hint" id="manualHint"></p>
|
||||
</div>
|
||||
|
||||
<button type="button" class="copy-btn" onclick="startSocialAnalysis()" id="socialAnalyzeBtn">🔍 Анализировать профиль</button>
|
||||
<button type="button" class="ps-btn ps-btn--secondary ps-btn--block" onclick="startSocialAnalysis()" id="socialAnalyzeBtn">Проанализировать</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<script>
|
||||
document.getElementById('socialUrl').addEventListener('input', function() {
|
||||
@@ -41,7 +47,7 @@ document.getElementById('socialUrl').addEventListener('input', function() {
|
||||
var hint = document.getElementById('manualHint');
|
||||
if (url && !isTG) {
|
||||
section.style.display = '';
|
||||
hint.textContent = 'Для VK, Tenchat и других платформ: откройте профиль, скопируйте 3-10 постов и вставьте сюда.';
|
||||
hint.textContent = 'Для VK, TenChat и других платформ: откройте профиль, скопируйте 3–10 постов и вставьте сюда.';
|
||||
} else {
|
||||
section.style.display = 'none';
|
||||
}
|
||||
@@ -49,7 +55,7 @@ document.getElementById('socialUrl').addEventListener('input', function() {
|
||||
|
||||
function startSocialAnalysis() {
|
||||
var url = document.getElementById('socialUrl').value.trim();
|
||||
if (!url) { alert('Вставьте ссылку на профиль'); return; }
|
||||
if (!url) { Press.toast('Вставьте ссылку на канал или профиль', 'warning', 'Например: https://t.me/имя_канала'); document.getElementById('socialUrl').focus(); return; }
|
||||
var manualPosts = document.getElementById('manualPosts') ? document.getElementById('manualPosts').value : '';
|
||||
|
||||
var fd = new FormData();
|
||||
@@ -62,44 +68,44 @@ function startSocialAnalysis() {
|
||||
document.getElementById('socialTaskError').style.display = 'none';
|
||||
document.getElementById('socialTaskResult').style.display = 'none';
|
||||
|
||||
fetch('/api/tasks', {method: 'POST', body: fd})
|
||||
.then(function(r) { return r.json(); })
|
||||
function fail(msg) {
|
||||
document.getElementById('socialTaskLoader').style.display = 'none';
|
||||
var err = document.getElementById('socialTaskError');
|
||||
err.textContent = Press.humanError(msg);
|
||||
err.style.display = 'flex';
|
||||
document.getElementById('socialForm').style.display = '';
|
||||
}
|
||||
Press.fetchJSON('/api/tasks', {method: 'POST', body: fd})
|
||||
.then(function(data) {
|
||||
var taskId = data.task_id;
|
||||
var poll = setInterval(function() {
|
||||
fetch('/api/tasks/' + taskId)
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(t) {
|
||||
if (t.status === 'done') {
|
||||
clearInterval(poll);
|
||||
document.getElementById('socialTaskLoader').style.display = 'none';
|
||||
onSocialAnalysisDone(t.result);
|
||||
} else if (t.status === 'error') {
|
||||
clearInterval(poll);
|
||||
document.getElementById('socialTaskLoader').style.display = 'none';
|
||||
document.getElementById('socialTaskError').textContent = t.error || 'Ошибка анализа';
|
||||
document.getElementById('socialTaskError').style.display = 'block';
|
||||
document.getElementById('socialForm').style.display = '';
|
||||
}
|
||||
});
|
||||
}, 1500);
|
||||
if (!data.task_id) { fail(data.error || 'Не удалось запустить анализ. Повторите через минуту.'); return; }
|
||||
Press.pollTask(data.task_id, {
|
||||
done: function (result) {
|
||||
document.getElementById('socialTaskLoader').style.display = 'none';
|
||||
onSocialAnalysisDone(result || {});
|
||||
},
|
||||
fail: fail
|
||||
});
|
||||
})
|
||||
.catch(function(e) {
|
||||
document.getElementById('socialTaskLoader').style.display = 'none';
|
||||
document.getElementById('socialTaskError').textContent = 'Ошибка сети: ' + e;
|
||||
document.getElementById('socialTaskError').style.display = 'block';
|
||||
document.getElementById('socialForm').style.display = '';
|
||||
});
|
||||
.catch(function(e) { fail(e.message); });
|
||||
}
|
||||
|
||||
function onSocialAnalysisDone(result) {
|
||||
var info = result.platform_info || {};
|
||||
var count = result.posts_count || 0;
|
||||
var html = '<div class="card"><p>✅ Проанализировано <strong>' + count + ' постов</strong> из ' + (info.platform || 'профиля') + ' (@' + (info.channel || '') + ')</p>';
|
||||
html += '<button type="button" class="copy-btn" onclick="applySocialData()">✅ Применить к медиа-образу</button>';
|
||||
html += ' <button type="button" class="button-link" onclick="resetSocialForm()">↩ Отмена</button></div>';
|
||||
document.getElementById('socialTaskResult').innerHTML = html;
|
||||
document.getElementById('socialTaskResult').style.display = '';
|
||||
/* Собираем через DOM: название канала и платформа приходят из введённой ссылки — в HTML их не вставляем */
|
||||
var box = document.getElementById('socialTaskResult');
|
||||
box.innerHTML = '';
|
||||
var wrap = document.createElement('div'); wrap.className = 'app-stack';
|
||||
var p = document.createElement('p'); p.className = 'app-muted'; p.style.margin = '0';
|
||||
var channel = info.channel && !/^https?:/i.test(info.channel) ? ' (@' + info.channel + ')' : '';
|
||||
p.textContent = 'Прочитал ' + count + ' ' + Press.plural(count, ['пост', 'поста', 'постов']) + ' из ' + (info.platform || 'профиля') + channel + '.';
|
||||
var apply = document.createElement('button'); apply.type = 'button'; apply.className = 'ps-btn ps-btn--primary ps-btn--block';
|
||||
apply.textContent = 'Заполнить анкету'; apply.addEventListener('click', applySocialData);
|
||||
var cancel = document.createElement('button'); cancel.type = 'button'; cancel.className = 'ps-btn ps-btn--quiet ps-btn--sm';
|
||||
cancel.textContent = 'Отмена'; cancel.addEventListener('click', resetSocialForm);
|
||||
wrap.appendChild(p); wrap.appendChild(apply); wrap.appendChild(cancel);
|
||||
box.appendChild(wrap);
|
||||
box.style.display = '';
|
||||
window._socialData = result;
|
||||
}
|
||||
|
||||
@@ -126,10 +132,11 @@ function applySocialData() {
|
||||
setVal('prompt_directions', d.prompt_directions);
|
||||
setVal('prompt_structure', d.prompt_structure);
|
||||
setVal('prompt_formats', d.prompt_formats);
|
||||
// Сворачиваем анализатор
|
||||
// Сворачиваем анализатор и переходим к шагу 1
|
||||
document.getElementById('socialAnalyzer').style.display = 'none';
|
||||
// Переходим к шагу 1
|
||||
showStep(1);
|
||||
var filled = document.querySelectorAll('.ai-filled-badge').length;
|
||||
if (filled) Press.toast('Заполнил ' + filled + ' ' + Press.plural(filled, ['поле', 'поля', 'полей']), 'ai', 'Проверьте их — они помечены «Сгенерирован ИИ».');
|
||||
}
|
||||
|
||||
function setVal(name, value) {
|
||||
@@ -138,14 +145,22 @@ function setVal(name, value) {
|
||||
if (Array.isArray(value)) {
|
||||
value = value.join('\n');
|
||||
}
|
||||
var el = document.querySelector('[name="' + name + '"]');
|
||||
if (el) {
|
||||
el.value = value;
|
||||
el.style.borderColor = 'var(--accent)';
|
||||
setTimeout(function() { el.style.borderColor = ''; }, 2000);
|
||||
/* Пишем в поле активного типа бренда (у неактивных блоков поля выключены) */
|
||||
var el = document.querySelector('[name="' + name + '"]:not(:disabled)');
|
||||
if (!el) return;
|
||||
el.value = value;
|
||||
var label = el.closest('label');
|
||||
if (label && !label.querySelector('.ai-filled-badge')) {
|
||||
var badge = document.createElement('span');
|
||||
badge.className = 'ps-badge ps-badge--ai ai-filled-badge';
|
||||
badge.innerHTML = document.getElementById('tpl-ai-badge').innerHTML;
|
||||
label.insertBefore(badge, el);
|
||||
/* Бейдж снимается, когда человек сам правит поле */
|
||||
el.addEventListener('input', function () { badge.remove(); }, { once: true });
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<template id="tpl-ai-badge">{{ ui.icon('sparkle', 14) }}<span>Сгенерирован ИИ</span></template>
|
||||
<!-- === КОНЕЦ АНАЛИЗАТОРА === -->
|
||||
|
||||
<div class="survey-wizard">
|
||||
@@ -159,7 +174,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 1: Основная информация -->
|
||||
<div class="survey-step" data-step="1">
|
||||
<h2>Шаг 1 — Основная информация</h2>
|
||||
<h2 class="ps-stepper-title">Основная информация</h2>
|
||||
<div class="form">
|
||||
<label>Тип медиа-образа
|
||||
<select name="brand_type" id="brandType" onchange="toggleBrandType()">
|
||||
@@ -203,7 +218,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 2: Цели -->
|
||||
<div class="survey-step" data-step="2" hidden>
|
||||
<h2>Шаг 2 — Цели на 12 месяцев</h2>
|
||||
<h2 class="ps-stepper-title">Цели на 12 месяцев</h2>
|
||||
<div class="form">
|
||||
<label>Целевое число подписчиков <input type="number" name="goal_audience_number" placeholder="10000"></label>
|
||||
<label>Основная платформа <input type="text" name="goal_audience_platform" placeholder="Напр. Telegram-канал"></label>
|
||||
@@ -218,7 +233,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 3: Позиционирование -->
|
||||
<div class="survey-step" data-step="3" hidden>
|
||||
<h2>Шаг 3 — Позиционирование и УТП</h2>
|
||||
<h2 class="ps-stepper-title">Позиционирование и УТП</h2>
|
||||
<div class="form">
|
||||
<label>Сущность бренда (одной строкой) <input type="text" name="brand_essence" placeholder="Напр. Цифровой архитектор, строящий IT-устойчивость бизнеса"></label>
|
||||
|
||||
@@ -252,7 +267,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 4: Аудитории и каналы -->
|
||||
<div class="survey-step" data-step="4" hidden>
|
||||
<h2>Шаг 4 — Аудитории и каналы</h2>
|
||||
<h2 class="ps-stepper-title">Аудитории и каналы</h2>
|
||||
<div class="form">
|
||||
<label>Идеальные подписчики / клиенты <span class="form-hint">По строкам</span>
|
||||
<textarea name="ideal_audiences" rows="5" placeholder="Владельцы МСП... IT-специалисты... Активная молодёжь..."></textarea>
|
||||
@@ -263,14 +278,14 @@ function setVal(name, value) {
|
||||
<thead><tr><th>Платформа</th><th>Тип</th><th>Частота</th><th>Описание</th><th></th></tr></thead>
|
||||
<tbody id="channelsBody"></tbody>
|
||||
</table>
|
||||
<button type="button" class="copy-btn" onclick="addChannel()">+ Добавить канал</button>
|
||||
<button type="button" class="copy-btn" onclick="addChannel()">Добавить канал</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Шаг 5: Визуальная идентичность -->
|
||||
<div class="survey-step" data-step="5" hidden>
|
||||
<h2>Шаг 5 — Визуальная идентичность</h2>
|
||||
<h2 class="ps-stepper-title">Визуальная идентичность</h2>
|
||||
<div class="form">
|
||||
<label>Концепция <input type="text" name="visual_concept" placeholder="Напр. Цифровой архитектор"></label>
|
||||
<h3>Цветовая палитра</h3>
|
||||
@@ -290,7 +305,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 6: Tone of Voice -->
|
||||
<div class="survey-step" data-step="6" hidden>
|
||||
<h2>Шаг 6 — Tone of Voice</h2>
|
||||
<h2 class="ps-stepper-title">Tone of Voice</h2>
|
||||
<div class="form">
|
||||
<label>Описание тона <input type="text" name="tov_description" placeholder="Напр. Стратег-прагматик с душой"></label>
|
||||
<label>Референсы / вдохновители <textarea name="tov_references" rows="3" placeholder="Напр. Уверенность Лаврова, глубина Гео, яркость Минаева..."></textarea></label>
|
||||
@@ -302,7 +317,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 7: Контент-стратегия -->
|
||||
<div class="survey-step" data-step="7" hidden>
|
||||
<h2>Шаг 7 — Контент-стратегия: Три столпа</h2>
|
||||
<h2 class="ps-stepper-title">Контент-стратегия: Три столпа</h2>
|
||||
<div class="form">
|
||||
<!-- Личный бренд -->
|
||||
<div class="brand-fields-personal">
|
||||
@@ -370,7 +385,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 8: Воронка и продукты -->
|
||||
<div class="survey-step" data-step="8" hidden>
|
||||
<h2>Шаг 8 — Воронка и продуктовый ряд</h2>
|
||||
<h2 class="ps-stepper-title">Воронка и продуктовый ряд</h2>
|
||||
<div class="form">
|
||||
<h3>Воронка вовлечения</h3>
|
||||
<div id="funnelContainer">
|
||||
@@ -387,7 +402,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 9: Метрики -->
|
||||
<div class="survey-step" data-step="9" hidden>
|
||||
<h2>Шаг 9 — Метрики</h2>
|
||||
<h2 class="ps-stepper-title">Метрики</h2>
|
||||
<div class="form">
|
||||
<label>Количественные метрики <span class="form-hint">По строкам, формат: Название | Целевое значение | Измерение</span>
|
||||
<textarea name="metrics_quantitative" rows="5" placeholder="Подписчики в Telegram | 10000 | Статистика канала Ежемесячный охват | 250000 | Аналитика соцсетей"></textarea>
|
||||
@@ -403,7 +418,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 10: Риски и рекомендации -->
|
||||
<div class="survey-step" data-step="10" hidden>
|
||||
<h2>Шаг 10 — Риски и рекомендации</h2>
|
||||
<h2 class="ps-stepper-title">Риски и рекомендации</h2>
|
||||
<div class="form">
|
||||
<label>Потенциальные риски <span class="form-hint">По строкам, формат: Риск | Решение</span>
|
||||
<textarea name="risks" rows="5" placeholder="Выгорание от ежедневного контента | Заранее создать банк контента... Конфликт образов | Связать через общую миссию..."></textarea>
|
||||
@@ -416,7 +431,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 11: Архетипы -->
|
||||
<div class="survey-step" data-step="11" hidden>
|
||||
<h2>Шаг 11 — Архетипический образ</h2>
|
||||
<h2 class="ps-stepper-title">Архетипический образ</h2>
|
||||
<div class="form">
|
||||
<h3>Ключевой архетип</h3>
|
||||
<label>Название <input type="text" name="archetype_key_name" placeholder="Напр. Ведущий-Герой"></label>
|
||||
@@ -437,7 +452,7 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Шаг 12: Промпт -->
|
||||
<div class="survey-step" data-step="12" hidden>
|
||||
<h2>Шаг 12 — Промпт для генерации контента</h2>
|
||||
<h2 class="ps-stepper-title">Как писать ваши посты</h2>
|
||||
<div class="form">
|
||||
<div class="brand-fields-personal">
|
||||
<label>Контекст и личность <textarea name="prompt_context" rows="5" placeholder="Кто я, мой бренд, мои роли..."></textarea></label>
|
||||
@@ -460,14 +475,15 @@ function setVal(name, value) {
|
||||
|
||||
<!-- Навигация -->
|
||||
<div class="survey-nav">
|
||||
<button type="button" id="btnPrev" onclick="prevStep()" hidden>← Назад</button>
|
||||
<button type="button" id="btnPrev" onclick="prevStep()" hidden>Назад</button>
|
||||
<span id="stepCounter"></span>
|
||||
<button type="button" id="btnNext" onclick="nextStep()">Далее →</button>
|
||||
<button type="submit" id="btnSubmit" hidden>💾 Сохранить и сгенерировать документ</button>
|
||||
<button type="button" id="btnNext" onclick="nextStep()">Далее</button>
|
||||
<button type="submit" id="btnSubmit" hidden>Сохранить образ</button>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const TOTAL_STEPS = 12;
|
||||
@@ -488,18 +504,18 @@ function toggleBrandType() {
|
||||
var isOrg = (type === "organization");
|
||||
var isCommunity = (type === "community");
|
||||
|
||||
document.querySelectorAll(".brand-fields-personal").forEach(function(el) {
|
||||
el.style.display = isPersonal ? "" : "none";
|
||||
});
|
||||
document.querySelectorAll(".brand-fields-organization").forEach(function(el) {
|
||||
el.style.display = isOrg ? "" : "none";
|
||||
});
|
||||
document.querySelectorAll(".brand-fields-community").forEach(function(el) {
|
||||
el.style.display = isCommunity ? "" : "none";
|
||||
});
|
||||
document.getElementById("fieldsPersonal").style.display = isPersonal ? "" : "none";
|
||||
document.getElementById("fieldsOrganization").style.display = isOrg ? "" : "none";
|
||||
document.getElementById("fieldsCommunity").style.display = isCommunity ? "" : "none";
|
||||
/* У каждого типа свои одноимённые поля. Неактивные блоки не только прячем, но и выключаем:
|
||||
выключенные поля не попадают в данные формы — сохраняется ровно то, что видит человек. */
|
||||
function setBlock(el, on) {
|
||||
el.style.display = on ? "" : "none";
|
||||
el.querySelectorAll("input, textarea, select").forEach(function (f) { f.disabled = !on; });
|
||||
}
|
||||
document.querySelectorAll(".brand-fields-personal").forEach(function(el) { setBlock(el, isPersonal); });
|
||||
document.querySelectorAll(".brand-fields-organization").forEach(function(el) { setBlock(el, isOrg); });
|
||||
document.querySelectorAll(".brand-fields-community").forEach(function(el) { setBlock(el, isCommunity); });
|
||||
setBlock(document.getElementById("fieldsPersonal"), isPersonal);
|
||||
setBlock(document.getElementById("fieldsOrganization"), isOrg);
|
||||
setBlock(document.getElementById("fieldsCommunity"), isCommunity);
|
||||
|
||||
updatePillarHints(type);
|
||||
}
|
||||
@@ -509,17 +525,17 @@ function updatePillarHints(type) {
|
||||
var p2 = document.querySelector(".pillar2-formats-hint");
|
||||
var p3 = document.querySelector(".pillar3-formats-hint");
|
||||
if (type === "community") {
|
||||
if (p1) p1.placeholder = "Миссия сообщества...\\nИстория создания...\\nЦенности и принципы...";
|
||||
if (p2) p2.placeholder = "Мероприятия и активности...\\nОбзоры встреч...\\nИтоги и анонсы...";
|
||||
if (p3) p3.placeholder = "Истории участников...\\nОтзывы и кейсы...\\nПриглашения к участию...";
|
||||
if (p1) p1.placeholder = "Миссия сообщества...\nИстория создания...\nЦенности и принципы...";
|
||||
if (p2) p2.placeholder = "Мероприятия и активности...\nОбзоры встреч...\nИтоги и анонсы...";
|
||||
if (p3) p3.placeholder = "Истории участников...\nОтзывы и кейсы...\nПриглашения к участию...";
|
||||
} else if (type === "organization") {
|
||||
if (p1) p1.placeholder = "Обзор продукта...\\nКейсы клиентов...\\nНовинки компании...";
|
||||
if (p2) p2.placeholder = "Экспертные статьи...\\nАналитика рынка...\\nРазборы технологий...";
|
||||
if (p3) p3.placeholder = "Опросы...\\nРозыгрыши...\\nОтзывы клиентов...";
|
||||
if (p1) p1.placeholder = "Обзор продукта...\nКейсы клиентов...\nНовинки компании...";
|
||||
if (p2) p2.placeholder = "Экспертные статьи...\nАналитика рынка...\nРазборы технологий...";
|
||||
if (p3) p3.placeholder = "Опросы...\nРозыгрыши...\nОтзывы клиентов...";
|
||||
} else {
|
||||
if (p1) p1.placeholder = "История пути...\\nЗакулисье...\\nОбщественная деятельность...";
|
||||
if (p2) p2.placeholder = "Экспертные разборы...\\nПрактические советы...\\nКейсы...";
|
||||
if (p3) p3.placeholder = "Опросы...\\nПрямые эфиры...\\nИнтерактивные челленджи...";
|
||||
if (p1) p1.placeholder = "История пути...\nЗакулисье...\nОбщественная деятельность...";
|
||||
if (p2) p2.placeholder = "Экспертные разборы...\nПрактические советы...\nКейсы...";
|
||||
if (p3) p3.placeholder = "Опросы...\nПрямые эфиры...\nИнтерактивные челленджи...";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -544,17 +560,21 @@ function addChannel(platform = "", type = "", frequency = "", description = "")
|
||||
const tbody = document.getElementById("channelsBody");
|
||||
const tr = document.createElement("tr");
|
||||
tr.innerHTML = `
|
||||
<td><input type="text" name="channels_${channelIdx}_platform" value="${platform}" placeholder="Напр. Telegram-канал"></td>
|
||||
<td><input type="text" name="channels_${channelIdx}_type" value="${type}" placeholder="Основной / доп."></td>
|
||||
<td><input type="text" name="channels_${channelIdx}_frequency" value="${frequency}" placeholder="Напр. 1 пост в день"></td>
|
||||
<td><input type="text" name="channels_${channelIdx}_description" value="${description}" placeholder="Описание"></td>
|
||||
<td><button type="button" class="button-link button-link-danger" onclick="this.closest('tr').remove()">✕</button></td>`;
|
||||
<td><input type="text" name="channels_${channelIdx}_platform" placeholder="Напр. Telegram-канал" aria-label="Платформа"></td>
|
||||
<td><input type="text" name="channels_${channelIdx}_type" placeholder="Основной / доп." aria-label="Тип"></td>
|
||||
<td><input type="text" name="channels_${channelIdx}_frequency" placeholder="Напр. 1 пост в день" aria-label="Частота"></td>
|
||||
<td><input type="text" name="channels_${channelIdx}_description" placeholder="Описание" aria-label="Описание"></td>
|
||||
<td><button type="button" class="ps-iconbtn" aria-label="Удалить строку">${document.getElementById('tpl-icon-close') ? document.getElementById('tpl-icon-close').innerHTML : '×'}</button></td>`;
|
||||
var vals = [platform, type, frequency, description];
|
||||
tr.querySelectorAll('input').forEach(function (inp, k) { inp.value = vals[k] || ''; });
|
||||
tr.querySelector('button').addEventListener('click', function () { tr.remove(); });
|
||||
tbody.appendChild(tr);
|
||||
channelIdx++;
|
||||
}
|
||||
|
||||
// --- Навигация ---
|
||||
function showStep(n) {
|
||||
currentStep = n;
|
||||
document.querySelectorAll(".survey-step").forEach(el => el.hidden = true);
|
||||
const el = document.querySelector(`.survey-step[data-step="${n}"]`);
|
||||
if (el) el.hidden = false;
|
||||
@@ -569,22 +589,32 @@ function showStep(n) {
|
||||
const ind = document.getElementById("stepsIndicator");
|
||||
ind.innerHTML = "";
|
||||
for (let i = 1; i <= TOTAL_STEPS; i++) {
|
||||
const dot = document.createElement("span");
|
||||
const dot = document.createElement("button");
|
||||
dot.type = "button";
|
||||
dot.className = "step-dot" + (i === n ? " active" : "") + (i < n ? " done" : "");
|
||||
dot.textContent = i;
|
||||
dot.onclick = () => showStep(i);
|
||||
dot.setAttribute("aria-label", "Шаг " + i + " из " + TOTAL_STEPS);
|
||||
if (i === n) dot.setAttribute("aria-current", "step");
|
||||
dot.addEventListener("click", () => showStep(i));
|
||||
ind.appendChild(dot);
|
||||
}
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
function nextStep() {
|
||||
if (currentStep < TOTAL_STEPS) { currentStep++; showStep(currentStep); }
|
||||
if (currentStep < TOTAL_STEPS) showStep(currentStep + 1);
|
||||
}
|
||||
function prevStep() {
|
||||
if (currentStep > 1) { currentStep--; showStep(currentStep); }
|
||||
if (currentStep > 1) showStep(currentStep - 1);
|
||||
}
|
||||
|
||||
/* Enter в однострочном поле — следующий шаг, а не сохранение. В многострочном — новая строка, как обычно. */
|
||||
document.getElementById("surveyForm").addEventListener("keydown", function (e) {
|
||||
if (e.key !== "Enter" || e.target.tagName !== "INPUT" || e.isComposing) return;
|
||||
e.preventDefault();
|
||||
if (currentStep < TOTAL_STEPS) nextStep();
|
||||
});
|
||||
|
||||
// --- Сборка данных ---
|
||||
function collectData() {
|
||||
const fd = new FormData(document.getElementById("surveyForm"));
|
||||
@@ -622,37 +652,40 @@ function collectData() {
|
||||
// --- Отправка ---
|
||||
document.getElementById("surveyForm").addEventListener("submit", async function(e) {
|
||||
e.preventDefault();
|
||||
/* Сохраняем только с последнего шага — неявная отправка формы раньше времени не создаёт пустой образ */
|
||||
if (currentStep !== TOTAL_STEPS) { nextStep(); return; }
|
||||
const data = collectData();
|
||||
var brandType = data.brand_type || "personal";
|
||||
var title = (brandType === "organization")
|
||||
? (data.org_name || "Без названия")
|
||||
: (data.client_name || "Без названия");
|
||||
var title = (brandType === "organization" || brandType === "community")
|
||||
? ((data.org_name || "").trim() || "Без названия")
|
||||
: ((data.client_name || "").trim() || "Без названия");
|
||||
const btn = document.getElementById("btnSubmit");
|
||||
btn.disabled = true;
|
||||
btn.textContent = "⏳ Генерация...";
|
||||
btn.textContent = "Сохраняю образ…";
|
||||
try {
|
||||
const resp = await fetch("/survey/submit", {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({title: title, data: data}),
|
||||
});
|
||||
if (resp.ok) {
|
||||
if (resp.ok && !resp.redirected) {
|
||||
const result = await resp.json();
|
||||
window.location.href = "/surveys/" + result.id;
|
||||
} else {
|
||||
alert("Ошибка при сохранении: " + resp.status);
|
||||
Press.toast("Не удалось сохранить медиа-образ", "danger", resp.redirected ? "Сессия истекла — войдите заново, ответы на этой странице сохранятся." : "Повторите через минуту. Ответы на этой странице сохранятся.");
|
||||
btn.disabled = false;
|
||||
btn.textContent = "💾 Сохранить и сгенерировать документ";
|
||||
btn.textContent = "Сохранить образ";
|
||||
}
|
||||
} catch (err) {
|
||||
alert("Ошибка сети: " + err);
|
||||
Press.toast("Нет связи с сервером", "danger", "Проверьте интернет и нажмите «Сохранить образ» ещё раз.");
|
||||
btn.disabled = false;
|
||||
btn.textContent = "💾 Сохранить и сгенерировать документ";
|
||||
btn.textContent = "Сохранить образ";
|
||||
}
|
||||
});
|
||||
|
||||
// --- Старт ---
|
||||
initFunnel();
|
||||
toggleBrandType();
|
||||
addChannel("Telegram-канал", "Основной", "1 пост в день", "Глубокий контент, экспертиза");
|
||||
addChannel("ВКвидео / Рутуб", "Доп.", "1 видео в неделю", "Длинные разборы, интервью");
|
||||
showStep(1);
|
||||
|
||||
@@ -1,26 +1,45 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Загрузить медиа-образ — Личный кабинет{% endblock %}
|
||||
{% block title %}Загрузить медиа-образ{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Загрузить медиа-образ</h1>
|
||||
|
||||
<div class="card">
|
||||
<p>Загрузите готовый медиа-образ файлом — он будет автоматически разобран и сохранён.</p>
|
||||
<p class="form-hint">Поддерживаются два формата:</p>
|
||||
<ul>
|
||||
<li><strong>.docx</strong> — документ стратегии (как образец). Разбирается через ИИ: извлекаются личность, УТП, Tone of Voice, столпы контента, архетипы и все поля опроса.</li>
|
||||
<li><strong>.json</strong> — структурированные данные опроса (прямой импорт полей).</li>
|
||||
</ul>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/surveys" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">Медиа-образы</span></a>
|
||||
<h1 class="ps-h1">Загрузить медиа-образ</h1>
|
||||
<p class="ps-lead">Готовый файл разберётся сам и сохранится как новый медиа-образ.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form method="post" action="/survey/import" enctype="multipart/form-data" class="form">
|
||||
<label>Файл медиа-образа
|
||||
<input type="file" name="file" accept=".docx,.json" required>
|
||||
</label>
|
||||
<button type="submit">📤 Загрузить</button>
|
||||
</form>
|
||||
|
||||
<div class="post-actions">
|
||||
<a href="/survey" class="copy-btn">➕ Заполнить форму вручную</a>
|
||||
<a href="/surveys" class="copy-btn">← К списку медиа-образов</a>
|
||||
<div class="ps-split" style="--ps-aside: 340px">
|
||||
<form method="post" action="/survey/import" enctype="multipart/form-data" class="ps-panel app-form" id="importForm">
|
||||
<label class="ps-drop" id="drop">
|
||||
<input type="file" name="file" accept=".docx,.json" class="ps-drop-input" id="fileInput" required>
|
||||
<span class="ps-drop-icon" aria-hidden="true">{{ ui.icon('upload', 24) }}</span>
|
||||
<span class="ps-drop-title" id="dropTitle">Перетащите файл или выберите на устройстве</span>
|
||||
<span class="ps-drop-hint">.docx или .json</span>
|
||||
</label>
|
||||
<div class="app-actions">
|
||||
<button type="submit" class="ps-btn ps-btn--primary">{{ ui.icon('upload', 20) }}<span class="ps-btn-label">Загрузить</span></button>
|
||||
<a href="/survey" class="ps-btn ps-btn--quiet"><span class="ps-btn-label">Заполнить анкету вручную</span></a>
|
||||
</div>
|
||||
</form>
|
||||
<aside class="ps-panel">
|
||||
<h2 class="ps-h2">Форматы</h2>
|
||||
<div class="app-stack">
|
||||
<div><strong>.docx</strong> <span class="app-muted">— документ стратегии. ИИ извлечёт личность, УТП, тон голоса, столпы контента и все поля анкеты.</span></div>
|
||||
<div><strong>.json</strong> <span class="app-muted">— структурированные данные анкеты, импорт полей напрямую.</span></div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}
|
||||
<script>
|
||||
(function () {
|
||||
var drop = document.getElementById('drop'), input = document.getElementById('fileInput'), title = document.getElementById('dropTitle');
|
||||
function show() { if (input.files.length) title.textContent = input.files[0].name; }
|
||||
input.addEventListener('change', show);
|
||||
drop.addEventListener('dragover', function (e) { e.preventDefault(); drop.classList.add('is-over'); });
|
||||
drop.addEventListener('dragleave', function () { drop.classList.remove('is-over'); });
|
||||
drop.addEventListener('drop', function (e) { e.preventDefault(); drop.classList.remove('is-over'); input.files = e.dataTransfer.files; show(); });
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,35 +1,47 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Медиа-образы — Личный кабинет{% endblock %}
|
||||
{% block title %}Медиа-образы{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Медиа-образы</h1>
|
||||
<div class="post-actions" style="margin-bottom:15px">
|
||||
<a class="tile" href="/survey">➕ Создать новый</a>
|
||||
<a class="tile" href="/survey/import">📤 Загрузить из файла</a>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<h1 class="ps-h1">Медиа-образы</h1>
|
||||
<p class="ps-lead">Анкета бренда, личности или сообщества. По ней ИИ пишет посты вашим голосом.</p>
|
||||
</div>
|
||||
<div class="app-head-actions">
|
||||
<a href="/survey/import" class="ps-btn ps-btn--secondary">{{ ui.icon('upload', 20) }}<span class="ps-btn-label">Загрузить из файла</span></a>
|
||||
<a href="/survey" class="ps-btn ps-btn--primary">{{ ui.icon('plus', 20) }}<span class="ps-btn-label">Создать медиа-образ</span></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if surveys %}
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>Название</th><th>Дата</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<div class="ps-grid-3">
|
||||
{% for s in surveys %}
|
||||
<tr>
|
||||
<td><a href="/surveys/{{ s.id }}">{{ s.title }}</a></td>
|
||||
<td>{{ s.created_at }}</td>
|
||||
<td>
|
||||
<a href="/surveys/{{ s.id }}/export" class="button-link">📄 .docx</a>
|
||||
<form action="/surveys/{{ s.id }}/delete" method="post" class="inline-form" onsubmit="return confirm('Удалить медиа-образ?')">
|
||||
<button type="submit" class="button-link button-link-danger">🗑</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{%- set active = loop.first -%}
|
||||
<article class="ps-persona{% if active %} is-active{% endif %}">
|
||||
<div class="ps-persona-top">
|
||||
<span class="ps-persona-icon" aria-hidden="true">{{ ui.icon('persona', 22) }}</span>
|
||||
<span class="ps-persona-type">Создан {{ s.created_at|local_dt('%d.%m.%Y') }}</span>
|
||||
{% if active %}<span class="ps-badge ps-badge--brand">{{ ui.icon('check', 14) }}<span>Активный</span></span>{% endif %}
|
||||
</div>
|
||||
<h3 class="ps-persona-name">{{ s.title }}</h3>
|
||||
{% if active %}<p class="ps-persona-sum">По нему сейчас генерируются посты и контент-план.</p>{% endif %}
|
||||
<div class="ps-persona-actions">
|
||||
<a href="/surveys/{{ s.id }}" class="ps-btn ps-btn--quiet ps-btn--sm">{{ ui.icon('edit', 16) }}<span class="ps-btn-label">Анкета</span></a>
|
||||
<a href="/surveys/{{ s.id }}/export" class="ps-btn ps-btn--quiet ps-btn--sm">{{ ui.icon('download', 16) }}<span class="ps-btn-label">Экспорт .docx</span></a>
|
||||
<form action="/surveys/{{ s.id }}/delete" method="post" class="inline-form" data-confirm="Удалить медиа-образ?" data-confirm-body="{{ s.title }} — анкета удалится, вернуть её будет нельзя.">
|
||||
<button type="submit" class="ps-iconbtn" aria-label="Удалить медиа-образ {{ s.title }}">{{ ui.icon('trash', 20) }}</button>
|
||||
</form>
|
||||
</div>
|
||||
</article>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p>Пока нет ни одного медиа-образа. <a href="/survey">Создайте первый →</a></p>
|
||||
</div>
|
||||
{% else %}
|
||||
<section class="ps-panel">
|
||||
<div class="ps-empty">
|
||||
<span class="ps-empty-icon" aria-hidden="true">{{ ui.icon('persona', 28) }}</span>
|
||||
<h2 class="ps-empty-title">Начните с медиа-образа</h2>
|
||||
<p class="ps-empty-text">12 коротких шагов: кто вы, чем полезны, как говорите. Можно заполнить автоматически по ссылке на канал.</p>
|
||||
<a href="/survey" class="ps-btn ps-btn--primary">{{ ui.icon('plus', 20) }}<span class="ps-btn-label">Создать медиа-образ</span></a>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -1,24 +1,26 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}{{ survey.title }} — Личный кабинет{% endblock %}
|
||||
{% block title %}{{ survey.title }}{% endblock %}
|
||||
{% block content %}
|
||||
<h1>{{ survey.title }}</h1>
|
||||
<div class="post-actions">
|
||||
<a href="/surveys/{{ survey.id }}/export" class="copy-btn">📄 Скачать .docx</a>
|
||||
<a href="/survey" class="copy-btn">➕ Новый опрос</a>
|
||||
<a href="/surveys" class="copy-btn">← К списку</a>
|
||||
<form action="/surveys/{{ survey.id }}/delete" method="post" class="inline-form" onsubmit="return confirm('Удалить медиа-образ?')">
|
||||
<button type="submit" class="button-link button-link-danger">🗑 Удалить</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<p><strong>Дата создания:</strong> {{ survey.created_at }}</p>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/surveys" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">Медиа-образы</span></a>
|
||||
<h1 class="ps-h1">{{ survey.title }}</h1>
|
||||
<p class="ps-lead">Создан {{ survey.created_at|local_dt('%d.%m.%Y') }}</p>
|
||||
</div>
|
||||
<div class="app-head-actions">
|
||||
<form action="/surveys/{{ survey.id }}/delete" method="post" class="inline-form" data-confirm="Удалить медиа-образ?" data-confirm-body="{{ survey.title }} — анкета удалится, вернуть её будет нельзя.">
|
||||
<button type="submit" class="ps-iconbtn" aria-label="Удалить медиа-образ">{{ ui.icon('trash', 22) }}</button>
|
||||
</form>
|
||||
<a href="/surveys/{{ survey.id }}/export" class="ps-btn ps-btn--secondary">{{ ui.icon('download', 20) }}<span class="ps-btn-label">Экспорт .docx</span></a>
|
||||
<a href="/generate" class="ps-btn ps-btn--primary">{{ ui.icon('sparkle', 20) }}<span class="ps-btn-label">Создать пост</span></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% set d = survey.data %}
|
||||
|
||||
<div class="app-survey-grid">
|
||||
<!-- 1. Резюме и цели -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>1. Резюме и цели</h2>
|
||||
<p><strong>Клиент:</strong> {{ d.client_name }} ({{ d.client_role }}), {{ d.client_location }}</p>
|
||||
<p><strong>Текущая ситуация:</strong> {{ d.current_situation }}</p>
|
||||
@@ -29,20 +31,20 @@
|
||||
<li><strong>Коммерциализация:</strong> {{ d.goal_commercial_leads }} заявок/мес ({{ d.goal_commercial_services }})</li>
|
||||
<li><strong>Контент:</strong> {{ d.goal_content_system }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 2. Позиционирование -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>2. Позиционирование и УТП</h2>
|
||||
<p><strong>Сущность бренда:</strong> {{ d.brand_essence }}</p>
|
||||
<p><strong>Кому помогаю:</strong> {{ d.positioning_who }}</p>
|
||||
<p><strong>Проблема:</strong> {{ d.positioning_problem }}</p>
|
||||
<p><strong>Результат:</strong> {{ d.positioning_result }}</p>
|
||||
<p><strong>УТП:</strong> {{ d.usp }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 3. Аудитории и каналы -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>3. Аудитории и каналы</h2>
|
||||
<h3>Идеальные подписчики:</h3>
|
||||
<ul>
|
||||
@@ -61,10 +63,10 @@
|
||||
</tbody>
|
||||
</table>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 4. Визуальная идентичность -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>4. Визуальная идентичность</h2>
|
||||
<p><strong>Концепция:</strong> {{ d.visual_concept }}</p>
|
||||
<h3>Цвета:</h3>
|
||||
@@ -80,10 +82,10 @@
|
||||
<li>Текст: {{ d.typography_body }}</li>
|
||||
<li>Акценты: {{ d.typography_accents }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 5. ToV -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>5. Tone of Voice</h2>
|
||||
<p><strong>Описание:</strong> {{ d.tov_description }}</p>
|
||||
<p><strong>Референсы:</strong> {{ d.tov_references }}</p>
|
||||
@@ -95,10 +97,10 @@
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 6. Контент-стратегия -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>6. Контент-стратегия: Три столпа</h2>
|
||||
<table class="table">
|
||||
<thead><tr><th>Столп</th><th>Цель</th><th>Форматы</th><th>Частота</th></tr></thead>
|
||||
@@ -111,10 +113,10 @@
|
||||
{% if d.special_formats %}
|
||||
<p><strong>Особые форматы:</strong> {{ d.special_formats }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 7. Воронка и продукты -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>7. Воронка и продуктовый ряд</h2>
|
||||
{% if d.funnel %}
|
||||
<table class="table">
|
||||
@@ -134,49 +136,49 @@
|
||||
<li><strong>Комплексные решения:</strong> {{ d.product_complex }}</li>
|
||||
<li><strong>Экспертные продукты:</strong> {{ d.product_expert }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 8. Метрики -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>8. Метрики</h2>
|
||||
{% if d.metrics_quantitative %}
|
||||
<h3>Количественные:</h3>
|
||||
<pre class="result">{{ d.metrics_quantitative }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.metrics_quantitative }}</p>
|
||||
{% endif %}
|
||||
{% if d.metrics_qualitative %}
|
||||
<h3>Качественные:</h3>
|
||||
<pre class="result">{{ d.metrics_qualitative }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.metrics_qualitative }}</p>
|
||||
{% endif %}
|
||||
{% if d.metrics_commercial %}
|
||||
<h3>Коммерческие:</h3>
|
||||
<pre class="result">{{ d.metrics_commercial }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.metrics_commercial }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 9. Риски -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>9. Риски и рекомендации</h2>
|
||||
{% if d.risks %}
|
||||
<h3>Риски:</h3>
|
||||
<pre class="result">{{ d.risks }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.risks }}</p>
|
||||
{% endif %}
|
||||
{% if d.recommendations %}
|
||||
<h3>Рекомендации:</h3>
|
||||
<pre class="result">{{ d.recommendations }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.recommendations }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 10. Архетипы -->
|
||||
<div class="card">
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>10. Архетипический образ</h2>
|
||||
<p><strong>Ключевой архетип:</strong> {{ d.archetype_key_name }}</p>
|
||||
<p><strong>Суть:</strong> {{ d.archetype_key_essence }}</p>
|
||||
{% if d.archetype_key_manifestations %}
|
||||
<pre class="result">{{ d.archetype_key_manifestations }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.archetype_key_manifestations }}</p>
|
||||
{% endif %}
|
||||
{% if d.archetype_supporting %}
|
||||
<h3>Вспомогательные:</h3>
|
||||
<pre class="result">{{ d.archetype_supporting }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.archetype_supporting }}</p>
|
||||
{% endif %}
|
||||
{% if d.archetype_synthesis %}
|
||||
<h3>Синтез:</h3>
|
||||
@@ -184,18 +186,19 @@
|
||||
{% endif %}
|
||||
{% if d.archetype_table %}
|
||||
<h3>Таблица проявлений:</h3>
|
||||
<pre class="result">{{ d.archetype_table }}</pre>
|
||||
<p class="result app-muted" style="margin:0">{{ d.archetype_table }}</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 11. Промпт -->
|
||||
<div class="card">
|
||||
<h2>11. Промпт для генерации контента</h2>
|
||||
<section class="ps-panel app-survey-section">
|
||||
<h2>11. Инструкция для ИИ</h2>
|
||||
{% if d.prompt_context %}<p><strong>Контекст:</strong> {{ d.prompt_context }}</p>{% endif %}
|
||||
{% if d.prompt_tov %}<p><strong>ToV:</strong> {{ d.prompt_tov }}</p>{% endif %}
|
||||
{% if d.prompt_structure %}<p><strong>Структура:</strong> {{ d.prompt_structure }}</p>{% endif %}
|
||||
{% if d.prompt_directions %}<p><strong>Направления:</strong></p><pre class="result">{{ d.prompt_directions }}</pre>{% endif %}
|
||||
{% if d.prompt_formats %}<p><strong>Форматы:</strong></p><pre class="result">{{ d.prompt_formats }}</pre>{% endif %}
|
||||
{% if d.prompt_technical %}<p><strong>Тех. требования:</strong></p><pre class="result">{{ d.prompt_technical }}</pre>{% endif %}
|
||||
{% if d.prompt_directions %}<p><strong>Направления:</strong></p><p class="result app-muted" style="margin:0">{{ d.prompt_directions }}</p>{% endif %}
|
||||
{% if d.prompt_formats %}<p><strong>Форматы:</strong></p><p class="result app-muted" style="margin:0">{{ d.prompt_formats }}</p>{% endif %}
|
||||
{% if d.prompt_technical %}<p><strong>Тех. требования:</strong></p><p class="result app-muted" style="margin:0">{{ d.prompt_technical }}</p>{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -1,65 +1,77 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}TenChat — Личный кабинет{% endblock %}
|
||||
{% block title %}TenChat{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Интеграция с TenChat</h1>
|
||||
<p class="form-hint">Подключите свой аккаунт TenChat, чтобы публиковать посты автоматически. Refresh token хранится только у вас и используется для публикации от вашего имени.</p>
|
||||
|
||||
{% if creds %}
|
||||
<div class="card">
|
||||
<p style="margin:0">
|
||||
<strong>Подключено:</strong> @{{ creds.tenchat_username }}
|
||||
| <span class="form-hint">подключено {{ creds.tenchat_connected_at }}</span>
|
||||
{% if creds.tenchat_last_refresh %}
|
||||
| <span class="form-hint">обновлено {{ creds.tenchat_last_refresh }}</span>
|
||||
{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<p style="margin:0">⚠️ TenChat не подключён. Введите refresh token ниже, чтобы публиковать посты.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="/tenchat" class="form">
|
||||
<h2>🔑 Refresh token TenChat</h2>
|
||||
|
||||
<label>Username в TenChat
|
||||
<input type="text" name="tenchat_username"
|
||||
value="{{ form.tenchat_username if form else (creds.tenchat_username if creds else '') }}"
|
||||
placeholder="например, kavalar" required>
|
||||
</label>
|
||||
|
||||
<label>Ключ TCRF (refresh token)
|
||||
<input type="password" name="tenchat_tcrf"
|
||||
value="{{ form.tenchat_tcrf if form else '' }}"
|
||||
placeholder="вставьте значение куки TCRF" required>
|
||||
</label>
|
||||
|
||||
<button type="submit">💾 Сохранить ключи</button>
|
||||
</form>
|
||||
|
||||
{% if creds %}
|
||||
<form method="post" action="/tenchat/disconnect" class="form" style="margin-top:15px"
|
||||
onsubmit="return confirm('Отключить TenChat? Ключи будут удалены.');">
|
||||
<button type="submit" style="background: var(--danger, #dc3545);">🔌 Отключить TenChat</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
<div class="card" style="margin-top:20px; background: var(--bg-secondary);">
|
||||
<h2>📖 Как получить refresh token</h2>
|
||||
<ol style="margin:5px 0 0 18px; font-size: 14px; line-height: 1.7;">
|
||||
<li>Откройте <a href="https://tenchat.ru" target="_blank" rel="noopener">tenchat.ru</a> и войдите в свой аккаунт.</li>
|
||||
<li>Нажмите <strong>F12</strong> (или <strong>Ctrl+Shift+I</strong>), чтобы открыть инструменты разработчика.</li>
|
||||
<li>Перейдите на вкладку <strong>Application</strong> (Приложение).</li>
|
||||
<li>В левом меню выберите <strong>Cookies</strong> → <strong>https://tenchat.ru</strong>.</li>
|
||||
<li>Найдите куку <strong>TCRF</strong> и скопируйте её значение.</li>
|
||||
<li>Вставьте значение в поле выше и нажмите «Сохранить ключи».</li>
|
||||
</ol>
|
||||
<p class="form-hint" style="margin-top:10px">
|
||||
⚠️ Refresh token живёт ~14 дней и автоматически обновляется при каждой публикации.
|
||||
Если публикация перестала работать — обновите ключ заново.
|
||||
</p>
|
||||
<div class="ps-main-head">
|
||||
<div>
|
||||
<a href="/provider" class="ps-btn ps-btn--quiet ps-btn--sm app-back">{{ ui.icon('chevron-left', 16) }}<span class="ps-btn-label">ИИ-провайдеры</span></a>
|
||||
<h1 class="ps-h1">TenChat</h1>
|
||||
<p class="ps-lead">Подключите аккаунт, чтобы публиковать посты в профиль. Ключ хранится только у вас и нужен для публикации от вашего имени.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p style="margin-top:20px"><a href="/profile/edit">← Назад в профиль</a> · <a href="/dashboard">← На главную</a></p>
|
||||
<div class="ps-split" style="--ps-aside: 380px">
|
||||
<div class="app-stack-lg">
|
||||
<section class="ps-provider">
|
||||
<header class="ps-provider-head">
|
||||
<span class="ps-provider-icon" aria-hidden="true">{{ ui.icon('users', 22) }}</span>
|
||||
<span class="ps-provider-text">
|
||||
<h2 class="ps-provider-title">Аккаунт TenChat</h2>
|
||||
<span class="ps-provider-desc">{% if creds %}@{{ creds.tenchat_username }} · подключено {{ creds.tenchat_connected_at|local_dt }}{% if creds.tenchat_last_refresh %} · ключ обновлён {{ creds.tenchat_last_refresh|local_dt }}{% endif %}{% else %}Введите username и ключ TCRF{% endif %}</span>
|
||||
</span>
|
||||
{% if creds %}
|
||||
<span class="ps-badge ps-badge--success">{{ ui.icon('check', 14) }}<span>Подключено</span></span>
|
||||
{% else %}
|
||||
<span class="ps-badge ps-badge--neutral">{{ ui.icon('info', 14) }}<span>Не настроено</span></span>
|
||||
{% endif %}
|
||||
</header>
|
||||
<form method="post" action="/tenchat" class="app-form">
|
||||
<div class="ps-field">
|
||||
<label for="tenchat_username" class="ps-field-label">Username в TenChat</label>
|
||||
<input id="tenchat_username" class="ps-field-control" type="text" name="tenchat_username"
|
||||
value="{{ form.tenchat_username if form else (creds.tenchat_username if creds else '') }}" placeholder="например, kavalar" required>
|
||||
</div>
|
||||
<div class="ps-field">
|
||||
<label for="tenchat_tcrf" class="ps-field-label">Ключ TCRF</label>
|
||||
<div class="ps-secret">
|
||||
<input id="tenchat_tcrf" class="ps-field-control ps-secret-control" type="password" name="tenchat_tcrf" autocomplete="off" spellcheck="false"
|
||||
value="{{ form.tenchat_tcrf if form else '' }}" placeholder="Значение куки TCRF" required>
|
||||
<button type="button" class="ps-iconbtn" data-secret-toggle aria-label="Показать ключ">{{ ui.icon('eye', 20) }}</button>
|
||||
</div>
|
||||
<p class="ps-field-hint">{{ ui.icon('key', 16) }}<span>Ключ живёт около 14 дней и обновляется при каждой публикации.</span></p>
|
||||
</div>
|
||||
<div class="app-actions">
|
||||
<button type="submit" class="ps-btn ps-btn--primary">{{ ui.icon('check', 20) }}<span class="ps-btn-label">Сохранить</span></button>
|
||||
</div>
|
||||
</form>
|
||||
{% if creds %}
|
||||
<form method="post" action="/tenchat/disconnect" class="inline-form" data-confirm="Отключить TenChat?" data-confirm-body="Ключ будет удалён." data-confirm-ok="Отключить">
|
||||
<button type="submit" class="ps-btn ps-btn--danger ps-btn--sm">{{ ui.icon('close', 16) }}<span class="ps-btn-label">Отключить TenChat</span></button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<aside class="ps-panel">
|
||||
<h2 class="ps-h2">Где взять ключ</h2>
|
||||
<ol class="app-stack" style="margin:0; padding-left: 20px; color: var(--ink-secondary)">
|
||||
<li>Откройте <a href="https://tenchat.ru" target="_blank" rel="noopener">tenchat.ru</a> и войдите в аккаунт.</li>
|
||||
<li>Нажмите F12, чтобы открыть инструменты разработчика.</li>
|
||||
<li>Вкладка «Application» → «Cookies» → https://tenchat.ru.</li>
|
||||
<li>Найдите куку TCRF и скопируйте её значение.</li>
|
||||
<li>Вставьте его в поле «Ключ TCRF» и нажмите «Сохранить».</li>
|
||||
</ol>
|
||||
<p class="form-hint">Перестала работать публикация — обновите ключ тем же способом.</p>
|
||||
</aside>
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}
|
||||
<script>
|
||||
document.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('[data-secret-toggle]'); if (!b) return;
|
||||
var input = b.parentNode.querySelector('input');
|
||||
var show = input.type === 'password';
|
||||
input.type = show ? 'text' : 'password';
|
||||
b.setAttribute('aria-label', show ? 'Скрыть ключ' : 'Показать ключ');
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -19,6 +19,19 @@ PIAPI_MODEL = os.getenv("PIAPI_MODEL", "gpt-4o")
|
||||
# Модель генерации картинок через PiAPI (список доступных: /v1/models)
|
||||
PIAPI_IMAGE_MODEL = os.getenv("PIAPI_IMAGE_MODEL", "gpt-image-1")
|
||||
|
||||
# === Qwen / внутренний OpenAI-совместимый сервер (провайдер по умолчанию) ===
|
||||
# Если заданы QWEN_BASE_URL и QWEN_API_KEY, текстовые запросы идут в Qwen,
|
||||
# а PiAPI остаётся запасным вариантом и провайдером для картинок.
|
||||
# Ключ хранится только в .env (файл в .gitignore), не в репозитории.
|
||||
QWEN_BASE_URL = os.getenv("QWEN_BASE_URL") or os.getenv("AI_BASE_URL")
|
||||
QWEN_API_KEY = os.getenv("QWEN_API_KEY") or os.getenv("AI_API_KEY")
|
||||
QWEN_MODEL = os.getenv("QWEN_MODEL") or os.getenv("AI_MODEL") or "qwen3.8-27b-heretic"
|
||||
# Модель сначала «размышляет», и размышления входят в лимит вывода:
|
||||
# меньше 512 токенов даёт пустой content, рабочий минимум — 2048.
|
||||
QWEN_MAX_TOKENS = int(os.getenv("QWEN_MAX_TOKENS", "2048"))
|
||||
# Длинные размышления занимают минуту-две, поэтому таймаут не меньше 180 с.
|
||||
QWEN_TIMEOUT = int(os.getenv("QWEN_TIMEOUT", "180"))
|
||||
|
||||
# Прокси для доступа к внешним API (PiAPI и др.).
|
||||
# Формат в .env: PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS
|
||||
PROXY_HOST = os.getenv("PROXY_HOST")
|
||||
|
||||
+49
-4
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
# Поля профиля, которые разрешено менять через "личный кабинет"
|
||||
@@ -364,13 +365,19 @@ def update_user_field_by_id(user_id, field, value):
|
||||
|
||||
|
||||
def delete_user_by_id(user_id):
|
||||
"""Удаляет пользователя веб-кабинета и всю его историю постов."""
|
||||
"""Удаляет пользователя веб-кабинета и все его данные (152-ФЗ).
|
||||
Возвращает имена файлов картинок — их удаляет вызывающий код из папки media."""
|
||||
conn = sqlite3.connect('users.db')
|
||||
cursor = conn.cursor()
|
||||
files = [r[0] for r in cursor.execute('SELECT filename FROM media WHERE user_id = ?', (user_id,))]
|
||||
files += [r[0] for r in cursor.execute('SELECT filename FROM post_images WHERE user_id = ?', (user_id,))]
|
||||
for table in ('post_revisions', 'post_images', 'posts', 'media', 'brand_surveys', 'content_plan',
|
||||
'channels', 'provider_settings', 'tasks'):
|
||||
cursor.execute(f'DELETE FROM {table} WHERE user_id = ?', (user_id,))
|
||||
cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
|
||||
cursor.execute('DELETE FROM posts WHERE user_id = ?', (user_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return [f for f in files if f]
|
||||
|
||||
|
||||
def save_post_for_user(user_id, platform, content, style=None, wishes=None):
|
||||
@@ -396,7 +403,7 @@ def get_posts_for_user(user_id, limit=10):
|
||||
conn = _row_conn()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT id, platform, content, style, wishes, created_at
|
||||
SELECT id, platform, content, style, wishes, created_at, published
|
||||
FROM posts
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at DESC
|
||||
@@ -528,16 +535,20 @@ def update_plan_status(user_id, item_id, status):
|
||||
'UPDATE content_plan SET status = ? WHERE id = ? AND user_id = ?',
|
||||
(status, item_id, user_id)
|
||||
)
|
||||
found = cursor.rowcount > 0
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return found
|
||||
|
||||
|
||||
def delete_plan_item(user_id, item_id):
|
||||
conn = sqlite3.connect('users.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('DELETE FROM content_plan WHERE id = ? AND user_id = ?', (item_id, user_id))
|
||||
found = cursor.rowcount > 0
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return found
|
||||
|
||||
|
||||
def get_plan_stats_for_user(user_id):
|
||||
@@ -642,7 +653,7 @@ def get_latest_brand_survey_for_user(user_id):
|
||||
conn = _row_conn()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
'SELECT * FROM brand_surveys WHERE user_id = ? ORDER BY created_at DESC LIMIT 1',
|
||||
'SELECT * FROM brand_surveys WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT 1',
|
||||
(user_id,)
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
@@ -770,6 +781,14 @@ def mark_post_published(post_id, user_id, channel_title):
|
||||
|
||||
# Пресеты провайдеров
|
||||
PROVIDER_PRESETS = {
|
||||
'qwen': {
|
||||
'name': 'Qwen (внутренний)',
|
||||
'base_url': os.getenv('QWEN_BASE_URL') or os.getenv('AI_BASE_URL') or '',
|
||||
'text_model': os.getenv('QWEN_MODEL') or os.getenv('AI_MODEL') or 'qwen3.8-27b-heretic',
|
||||
'image_model': '',
|
||||
'needs_key': True,
|
||||
'supports_images': False,
|
||||
},
|
||||
'piapi': {
|
||||
'name': 'PiAPI',
|
||||
'base_url': 'https://api.piapi.ai/v1',
|
||||
@@ -972,6 +991,32 @@ def update_task_status(task_id, status, result_json=None, error=None):
|
||||
conn.close()
|
||||
|
||||
|
||||
def count_user_tasks(user_id, minutes, active_only=False):
|
||||
"""Сколько задач пользователь запустил за последние minutes минут (active_only — только незавершённые)."""
|
||||
conn = sqlite3.connect('users.db')
|
||||
cursor = conn.cursor()
|
||||
query = "SELECT COUNT(*) FROM tasks WHERE user_id = ? AND created_at >= datetime('now', ?)"
|
||||
if active_only:
|
||||
query += " AND status IN ('pending', 'running')"
|
||||
cursor.execute(query, (user_id, f'-{int(minutes)} minutes'))
|
||||
n = cursor.fetchone()[0]
|
||||
conn.close()
|
||||
return n
|
||||
|
||||
|
||||
def fail_unfinished_tasks():
|
||||
"""После перезапуска сервиса потоки незавершённых задач потеряны — помечаем их ошибкой."""
|
||||
conn = sqlite3.connect('users.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"UPDATE tasks SET status = 'error', error = ?, updated_at = CURRENT_TIMESTAMP "
|
||||
"WHERE status IN ('pending', 'running')",
|
||||
('Задача прервана перезапуском сервиса. Повторите.',)
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_task(task_id):
|
||||
"""Возвращает задачу по ID."""
|
||||
conn = _row_conn()
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Reference in new issue
Block a user