feat: реферальная инвайт-ссылка + публичный лендинг на login-экране
Задача 1 (5.1): POST /api/my-invite — инвайт-ссылка любому авторизованному юзеру (rate-limit, кап 20 активных → 429, PUBLIC_BASE_URL, audit my_invite); кнопка «Пригласить коллегу» в шапке → инлайн-панель (не попап) с «Копировать»/ «Новая ссылка»; реферальный бонус REFERRAL_BONUS_DAYS (дефолт 0 = OFF, money-critical): начисляется ОБОИМ только на успешной верификации email — db.grant_referral_bonus в одной транзакции с атомарным claim-ом invites.bonus_granted (анти-фарм: самоприглашение/невериф/повтор/удалённый пригласивший не начисляют), audit referral_bonus. Задача 2 (1.2/5.3): login-screen обогащён в лендинг-витрину для незалогиненного — герой (h1 + 3 буллета ценности), галерея 4 синтетических карточек-примеров, ссылка «Получить доступ по приглашению» → /register; форма входа сохранена, адаптив (герой над формой на узком), light/dark через переменные темы, фокус на форме без автоскролла. Тесты: tests/test_referral_invite.py (19, red-green) + режим --logged-out в ui_smoke_harness + стаб /api/my-invite; Playwright-смоук обоих состояний. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+163
-11
@@ -44,8 +44,34 @@ button { font-family: inherit; }
|
||||
*::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* Login */
|
||||
#login-screen { display: flex; align-items: center; justify-content: center; height: 100vh; background: linear-gradient(135deg, #f5f0eb 0%, #ede5db 100%); }
|
||||
/* Лендинг-витрина для незалогиненного (1.2/5.3): герой + примеры + форма входа.
|
||||
Центрирование через margin:auto на .landing (не align-items:center) — иначе при
|
||||
переполнении по высоте флекс-центрирование обрезает верх без возможности доскроллить. */
|
||||
#login-screen { display: flex; height: 100vh; overflow-y: auto; background: linear-gradient(135deg, #f5f0eb 0%, #ede5db 100%); }
|
||||
.landing { margin: auto; display: flex; align-items: center; gap: var(--s6); max-width: 1060px; padding: var(--s6) var(--s4); }
|
||||
.landing-hero { flex: 1 1 auto; min-width: 0; }
|
||||
.landing-hero h1 { font-size: 1.6rem; line-height: 1.25; letter-spacing: -.015em; margin-bottom: .55rem; color: var(--text); }
|
||||
.landing-tagline { color: var(--text-muted); font-size: .95rem; margin-bottom: 1.1rem; max-width: 46rem; }
|
||||
.landing-points { list-style: none; margin: 0 0 1.5rem; }
|
||||
.landing-points li { position: relative; padding-left: 1.5rem; margin-bottom: .5rem; font-size: .92rem; }
|
||||
.landing-points li::before { content: "✓"; position: absolute; left: 0; color: var(--ok); font-weight: 700; }
|
||||
.landing-gallery h2 { font-size: 1rem; margin-bottom: .65rem; color: var(--text); }
|
||||
.landing-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: var(--s3); }
|
||||
.landing-card { background: var(--bg-card); border: 1px solid var(--border-light); border-radius: var(--radius); padding: .85rem .95rem; box-shadow: var(--shadow-sm); }
|
||||
.landing-card .ic { display: block; font-size: 1.25rem; margin-bottom: .3rem; }
|
||||
.landing-card h3 { font-size: .87rem; margin-bottom: .25rem; color: var(--text); }
|
||||
.landing-card p { font-size: .78rem; color: var(--text-muted); line-height: 1.45; }
|
||||
.landing-note { font-size: .72rem; color: var(--text-light); margin-top: .8rem; }
|
||||
.landing-login { flex: 0 0 340px; }
|
||||
.landing-login .register-link { text-align: center; margin-top: .8rem; font-size: .85rem; color: var(--text-muted); }
|
||||
.landing-login .register-link a { color: var(--accent); }
|
||||
@media (max-width: 900px) {
|
||||
.landing { flex-direction: column; align-items: stretch; } /* герой НАД формой на узком экране */
|
||||
.landing-login { flex: 0 0 auto; align-self: center; width: 100%; max-width: 380px; }
|
||||
.landing-hero h1 { font-size: 1.35rem; }
|
||||
}
|
||||
#login-form { background: var(--bg-card); padding: 2.5rem 2rem; border-radius: var(--radius-lg); box-shadow: var(--shadow-md); width: 340px; }
|
||||
.landing-login #login-form { width: 100%; }
|
||||
#login-form h2 { margin-bottom: .3rem; text-align: center; font-size: 1.4rem; font-weight: 700; color: var(--text); }
|
||||
#login-form .subtitle { text-align: center; color: var(--text-muted); font-size: .85rem; margin-bottom: 1.5rem; display: block; }
|
||||
#login-form input { width: 100%; padding: .7rem .9rem; margin-bottom: .7rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .95rem; transition: border-color .2s; outline: none; background: var(--bg); }
|
||||
@@ -53,6 +79,17 @@ button { font-family: inherit; }
|
||||
#login-form button { width: 100%; padding: .75rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; transition: background .2s; margin-top: .3rem; }
|
||||
#login-form button:hover { background: var(--accent-hover); }
|
||||
#login-form button:active { background: var(--accent-active); transform: translateY(1px); }
|
||||
|
||||
/* Инлайн-панель «Пригласить коллегу» (5.1): обычный поток под шапкой, НЕ попап */
|
||||
#invite-panel { background: var(--bg-card); border-bottom: 1px solid var(--border-light); padding: .55rem 1.4rem .65rem; }
|
||||
.invite-row { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; }
|
||||
.invite-row .invite-title { font-size: .8rem; color: var(--text-muted); }
|
||||
#invite-link { flex: 1 1 240px; min-width: 0; padding: .42rem .6rem; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--bg-input); color: var(--text); font-size: .8rem; }
|
||||
#invite-panel button { padding: .4rem .8rem; background: transparent; border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: .78rem; color: var(--text-muted); font-weight: 500; transition: all .15s; }
|
||||
#invite-panel button:hover { background: var(--bg); border-color: var(--accent); color: var(--accent); }
|
||||
#invite-panel button.copied { background: #d3f9d8; border-color: #69db7c; color: #2b8a3e; }
|
||||
:root[data-theme="dark"] #invite-panel button.copied { background: #1e3a25; border-color: #2f6b40; color: #86dca0; }
|
||||
#invite-error { font-size: .78rem; color: var(--accent); margin-top: .3rem; }
|
||||
#login-error { color: #e03131; font-size: .8rem; margin-bottom: .5rem; display: none; text-align: center; }
|
||||
|
||||
/* Chat */
|
||||
@@ -288,17 +325,53 @@ html { color-scheme: light; }
|
||||
регистрирует live-регион и озвучка недоступна до логина (Fable Ф2). -->
|
||||
<div id="sr-status" class="sr-only" aria-live="polite" aria-atomic="true"></div>
|
||||
|
||||
<!-- Login Screen -->
|
||||
<!-- Login Screen = публичный лендинг-витрина (1.2/5.3): герой + примеры + форма входа.
|
||||
Все примеры в галерее СИНТЕТИЧЕСКИЕ — никаких реальных смет/клиентов/реквизитов. -->
|
||||
<div id="login-screen" style="display:none">
|
||||
<form id="login-form" onsubmit="return doLogin(event)">
|
||||
<h2>Сметный ИИ</h2>
|
||||
<span class="subtitle">Профессиональный ассистент</span>
|
||||
<div id="login-error" role="alert"></div>
|
||||
<input type="text" id="login-user" placeholder="Email или логин" aria-label="Email или логин" autocomplete="username" required>
|
||||
<input type="password" id="login-pass" placeholder="Пароль" aria-label="Пароль" autocomplete="current-password" required>
|
||||
<button type="submit">Войти</button>
|
||||
<p style="text-align:center;margin-top:.8rem;font-size:.85rem;color:var(--text-muted)">Нет аккаунта? Попросите приглашение у администратора</p>
|
||||
</form>
|
||||
<div class="landing">
|
||||
<section class="landing-hero" aria-label="О сервисе">
|
||||
<h1>Сметный ИИ — проверка смет и нормативные ответы для сметчиков</h1>
|
||||
<p class="landing-tagline">Загрузите смету (ГГЭ-форматы, Excel, архивы) — ассистент пересчитает её, найдёт ошибки и ответит на вопросы по нормативной базе.</p>
|
||||
<ul class="landing-points">
|
||||
<li>Проверка смет детерминированным движком: пересчёт итогов, поиск арифметических и методических ошибок</li>
|
||||
<li>Нормы с источником: в ответе — пункт методики и номер приказа, который можно проверить</li>
|
||||
<li>Конъюнктурный анализ (КА-форма) и pre-check перед госэкспертизой</li>
|
||||
</ul>
|
||||
<div class="landing-gallery">
|
||||
<h2>Примеры того, что делает ассистент</h2>
|
||||
<div class="landing-cards">
|
||||
<div class="landing-card"><span class="ic" aria-hidden="true">🔍</span>
|
||||
<h3>Нашли 3 ошибки в смете</h3>
|
||||
<p>Движок пересчитал локальную смету: две арифметические ошибки в итогах и задвоенная позиция — с указанием конкретных строк.</p>
|
||||
</div>
|
||||
<div class="landing-card"><span class="ic" aria-hidden="true">📋</span>
|
||||
<h3>КА-форма за минуту</h3>
|
||||
<p>Конъюнктурный анализ по материалу: форма с ценами поставщиков, регионами и обоснованием — готова к вставке в смету.</p>
|
||||
</div>
|
||||
<div class="landing-card"><span class="ic" aria-hidden="true">🏛</span>
|
||||
<h3>Проверка перед экспертизой</h3>
|
||||
<p>Pre-check по типовым замечаниям ГГЭ: устаревшие нормативы и слабые обоснования видны до подачи, а не после.</p>
|
||||
</div>
|
||||
<div class="landing-card"><span class="ic" aria-hidden="true">📚</span>
|
||||
<h3>Нормы с источником</h3>
|
||||
<p>Ответ на нормативный вопрос — со ссылкой на пункт методики и номер приказа, а не «где-то так принято».</p>
|
||||
</div>
|
||||
</div>
|
||||
<p class="landing-note">Примеры синтетические — реальные сметы пользователей не публикуются.</p>
|
||||
</div>
|
||||
</section>
|
||||
<div class="landing-login">
|
||||
<form id="login-form" onsubmit="return doLogin(event)">
|
||||
<h2>Сметный ИИ</h2>
|
||||
<span class="subtitle">Профессиональный ассистент</span>
|
||||
<div id="login-error" role="alert"></div>
|
||||
<input type="text" id="login-user" placeholder="Email или логин" aria-label="Email или логин" autocomplete="username" required>
|
||||
<input type="password" id="login-pass" placeholder="Пароль" aria-label="Пароль" autocomplete="current-password" required>
|
||||
<button type="submit">Войти</button>
|
||||
<p class="register-link">Нет аккаунта? <a href="/register">Получить доступ по приглашению</a></p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Chat Screen -->
|
||||
@@ -336,10 +409,23 @@ html { color-scheme: light; }
|
||||
<button id="theme-toggle" onclick="toggleTheme()" title="Светлая / тёмная тема" aria-label="Переключить тему">☾</button>
|
||||
<button onclick="newChat()">Новый диалог</button>
|
||||
<button onclick="listFiles()">Файлы</button>
|
||||
<button id="btn-invite" onclick="toggleInvitePanel()" aria-expanded="false" aria-controls="invite-panel">Пригласить коллегу</button>
|
||||
<button onclick="logout()">Выйти</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Инлайн-панель приглашения (5.1): элемент обычного потока под шапкой, НЕ попап/модалка -->
|
||||
<div id="invite-panel" role="region" aria-label="Приглашение коллеги" style="display:none">
|
||||
<div class="invite-row">
|
||||
<span class="invite-title">Ссылка-приглашение (одноразовая, действует 72 часа):</span>
|
||||
<input id="invite-link" type="text" readonly aria-label="Ссылка-приглашение">
|
||||
<button type="button" id="invite-copy" onclick="copyInviteLink()">Копировать</button>
|
||||
<button type="button" onclick="newInviteLink()">Новая ссылка</button>
|
||||
<button type="button" onclick="hideInvitePanel()">Скрыть</button>
|
||||
</div>
|
||||
<div id="invite-error" role="alert" style="display:none"></div>
|
||||
</div>
|
||||
|
||||
<!-- Попап выбора даты сметы: нативный date-picker, тёмная тема через var(), без библиотек -->
|
||||
<div id="date-popover" role="dialog" aria-label="Дата сметы" style="display:none;position:fixed;z-index:2000;background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:14px 16px;box-shadow:0 8px 30px rgba(0,0,0,.22);min-width:264px">
|
||||
<div style="font-size:.85rem;font-weight:600;color:var(--text)">Дата сметы</div>
|
||||
@@ -812,6 +898,9 @@ function checkAdmin() {
|
||||
function showLogin() {
|
||||
document.getElementById('login-screen').style.display = 'flex';
|
||||
document.getElementById('chat-screen').style.display = 'none';
|
||||
// a11y: фокус на форме входа; preventScroll — на узком экране форма ПОД героем,
|
||||
// автопрокрутка мимо лендинга запрещена (анти-навязчивость)
|
||||
try { document.getElementById('login-user').focus({preventScroll: true}); } catch (e) {}
|
||||
}
|
||||
function showChat() {
|
||||
document.getElementById('login-screen').style.display = 'none';
|
||||
@@ -865,6 +954,9 @@ function logout() {
|
||||
token = null;
|
||||
localStorage.removeItem('refresh_token');
|
||||
localStorage.removeItem('token');
|
||||
// Инвайт-ссылка привязана к юзеру: кэш и открытую панель не отдаём следующему логину
|
||||
_inviteUrl = null;
|
||||
try { hideInvitePanel(); } catch (e) {}
|
||||
showLogin();
|
||||
}
|
||||
// --- Дата сметы диалога (as-of для нормативов) ---
|
||||
@@ -948,6 +1040,66 @@ async function authFetch(url, opts={}) {
|
||||
return r;
|
||||
}
|
||||
|
||||
// --- «Пригласить коллегу» (5.1): инлайн-панель с реферальной ссылкой ---
|
||||
// Ссылка кэшируется на сессию вкладки: открыть/закрыть панель НЕ создаёт новый инвайт
|
||||
// (иначе каждый toggle жёг бы кап 20 активных). Новый инвайт — явной кнопкой.
|
||||
let _inviteUrl = null;
|
||||
async function _fetchInviteLink() {
|
||||
const input = document.getElementById('invite-link');
|
||||
const err = document.getElementById('invite-error');
|
||||
err.style.display = 'none';
|
||||
input.value = 'Создаём ссылку…';
|
||||
try {
|
||||
const r = await authFetch('/api/my-invite', {method: 'POST'});
|
||||
const d = await r.json().catch(() => ({}));
|
||||
if (!r.ok || !d.url) {
|
||||
input.value = '';
|
||||
err.textContent = d.detail || 'Не удалось создать приглашение — попробуйте позже';
|
||||
err.style.display = 'block';
|
||||
return;
|
||||
}
|
||||
_inviteUrl = d.url;
|
||||
input.value = d.url;
|
||||
} catch (e) {
|
||||
input.value = '';
|
||||
err.textContent = 'Ошибка сети — попробуйте ещё раз';
|
||||
err.style.display = 'block';
|
||||
}
|
||||
}
|
||||
async function toggleInvitePanel() {
|
||||
const panel = document.getElementById('invite-panel');
|
||||
const btn = document.getElementById('btn-invite');
|
||||
if (panel.style.display !== 'none') { hideInvitePanel(); return; }
|
||||
panel.style.display = 'block';
|
||||
btn.setAttribute('aria-expanded', 'true');
|
||||
if (_inviteUrl) { document.getElementById('invite-link').value = _inviteUrl; return; }
|
||||
await _fetchInviteLink();
|
||||
}
|
||||
async function newInviteLink() { await _fetchInviteLink(); _resetCopyBtn(); }
|
||||
function hideInvitePanel() {
|
||||
document.getElementById('invite-panel').style.display = 'none';
|
||||
document.getElementById('btn-invite').setAttribute('aria-expanded', 'false');
|
||||
_resetCopyBtn();
|
||||
}
|
||||
function _resetCopyBtn() {
|
||||
const b = document.getElementById('invite-copy');
|
||||
b.textContent = 'Копировать'; b.classList.remove('copied');
|
||||
}
|
||||
async function copyInviteLink() {
|
||||
const input = document.getElementById('invite-link');
|
||||
if (!input.value || input.value.indexOf('http') !== 0) return;
|
||||
let ok = false;
|
||||
try { await navigator.clipboard.writeText(input.value); ok = true; }
|
||||
catch (e) { // фолбэк: clipboard API недоступен (http-dev/старый браузер)
|
||||
try { input.select(); ok = document.execCommand('copy'); } catch (e2) {}
|
||||
}
|
||||
if (ok) {
|
||||
const b = document.getElementById('invite-copy');
|
||||
b.textContent = 'Скопировано ✓'; b.classList.add('copied');
|
||||
setTimeout(_resetCopyBtn, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Messages ---
|
||||
const msgs = document.getElementById('messages');
|
||||
// Умный автоскролл: «прилипаем» к низу, пока пользователь сам не прокрутит вверх.
|
||||
|
||||
Reference in New Issue
Block a user