v1.3.1
This commit is contained in:
23
server.py
23
server.py
@@ -296,8 +296,8 @@ def get_db():
|
|||||||
class UserRegister(BaseModel):
|
class UserRegister(BaseModel):
|
||||||
full_name: str
|
full_name: str
|
||||||
email: EmailStr
|
email: EmailStr
|
||||||
phone: str
|
phone: str # больше не Optional
|
||||||
telegram: Optional[str] = None
|
telegram: str # больше не Optional
|
||||||
password: str
|
password: str
|
||||||
role: str
|
role: str
|
||||||
|
|
||||||
@@ -882,7 +882,7 @@ async def get_public_stats():
|
|||||||
async def register(user: UserRegister):
|
async def register(user: UserRegister):
|
||||||
"""Регистрация нового пользователя"""
|
"""Регистрация нового пользователя"""
|
||||||
try:
|
try:
|
||||||
print(f"📝 Registering user: {user.email}")
|
print(f"📝 Регистрация: {user.email}")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
@@ -904,17 +904,11 @@ async def register(user: UserRegister):
|
|||||||
user_id = cursor.lastrowid
|
user_id = cursor.lastrowid
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
print(f"✅ User created with ID: {user_id}")
|
print(f"✅ Пользователь создан: ID {user_id}")
|
||||||
|
|
||||||
# Создаем данные для токена
|
token = create_access_token({"sub": str(user_id), "role": user.role})
|
||||||
token_data = {
|
|
||||||
"sub": str(user_id), # Явно преобразуем в строку
|
|
||||||
"role": user.role,
|
|
||||||
"is_admin": bool(is_admin)
|
|
||||||
}
|
|
||||||
token = create_access_token(token_data)
|
|
||||||
|
|
||||||
response_data = {
|
return {
|
||||||
"access_token": token,
|
"access_token": token,
|
||||||
"token_type": "bearer",
|
"token_type": "bearer",
|
||||||
"user_id": user_id,
|
"user_id": user_id,
|
||||||
@@ -923,13 +917,10 @@ async def register(user: UserRegister):
|
|||||||
"is_admin": bool(is_admin)
|
"is_admin": bool(is_admin)
|
||||||
}
|
}
|
||||||
|
|
||||||
return response_data
|
|
||||||
|
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ Registration error: {e}")
|
print(f"❌ Ошибка регистрации: {e}")
|
||||||
traceback.print_exc()
|
|
||||||
raise HTTPException(status_code=500, detail=f"Внутренняя ошибка: {str(e)}")
|
raise HTTPException(status_code=500, detail=f"Внутренняя ошибка: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -6,12 +6,11 @@
|
|||||||
<title>Регистрация | Rabota.Today</title>
|
<title>Регистрация | Rabota.Today</title>
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
|
||||||
<style>
|
<style>
|
||||||
/* Мобильные стили */
|
|
||||||
* {
|
* {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@@ -123,6 +122,12 @@
|
|||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.required-star {
|
||||||
|
color: #ef4444;
|
||||||
|
margin-left: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
.input-group input {
|
.input-group input {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
padding: 14px 16px;
|
padding: 14px 16px;
|
||||||
@@ -142,6 +147,11 @@
|
|||||||
box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
|
box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.input-group input.error {
|
||||||
|
border-color: #ef4444;
|
||||||
|
background: #fef2f2;
|
||||||
|
}
|
||||||
|
|
||||||
.input-row {
|
.input-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
@@ -219,7 +229,61 @@
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Адаптация для очень маленьких экранов */
|
.password-requirements {
|
||||||
|
background: #f0f7ff;
|
||||||
|
border-radius: 20px;
|
||||||
|
padding: 12px 16px;
|
||||||
|
margin: 15px 0;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.password-requirements p {
|
||||||
|
color: #1f3f60;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.requirement {
|
||||||
|
color: #4f7092;
|
||||||
|
margin: 4px 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.requirement.valid {
|
||||||
|
color: #10b981;
|
||||||
|
}
|
||||||
|
|
||||||
|
.requirement.valid i {
|
||||||
|
color: #10b981;
|
||||||
|
}
|
||||||
|
|
||||||
|
.requirement.invalid {
|
||||||
|
color: #ef4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.requirement.invalid i {
|
||||||
|
color: #ef4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer {
|
||||||
|
text-align: center;
|
||||||
|
padding: 20px 30px;
|
||||||
|
background: #f8fafc;
|
||||||
|
border-top: 1px solid #dee9f5;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #4f7092;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer a {
|
||||||
|
color: #3b82f6;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 380px) {
|
@media (max-width: 380px) {
|
||||||
.input-row {
|
.input-row {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -237,7 +301,7 @@
|
|||||||
<div class="register-header">
|
<div class="register-header">
|
||||||
<h1>
|
<h1>
|
||||||
<i class="fas fa-briefcase"></i>
|
<i class="fas fa-briefcase"></i>
|
||||||
МП.Ярмарка
|
Rabota.Today
|
||||||
</h1>
|
</h1>
|
||||||
<p>Регистрация на ярмарке вакансий</p>
|
<p>Регистрация на ярмарке вакансий</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -264,36 +328,65 @@
|
|||||||
|
|
||||||
<form id="registerForm" onsubmit="handleRegister(event)">
|
<form id="registerForm" onsubmit="handleRegister(event)">
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label><i class="fas fa-user-circle"></i> ФИО *</label>
|
<label>
|
||||||
<input type="text" id="fullName" placeholder="Иванов Иван" required>
|
<i class="fas fa-user-circle"></i>
|
||||||
|
ФИО <span class="required-star">*</span>
|
||||||
|
</label>
|
||||||
|
<input type="text" id="fullName" placeholder="Иванов Иван Иванович" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label><i class="fas fa-envelope"></i> Email *</label>
|
<label>
|
||||||
|
<i class="fas fa-envelope"></i>
|
||||||
|
Email <span class="required-star">*</span>
|
||||||
|
</label>
|
||||||
<input type="email" id="email" placeholder="ivan@example.com" required>
|
<input type="email" id="email" placeholder="ivan@example.com" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-row">
|
<div class="input-row">
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label><i class="fas fa-phone-alt"></i> Телефон *</label>
|
<label>
|
||||||
|
<i class="fas fa-phone-alt"></i>
|
||||||
|
Телефон <span class="required-star">*</span>
|
||||||
|
</label>
|
||||||
<input type="tel" id="phone" placeholder="+7 (999) 123-45-67" required>
|
<input type="tel" id="phone" placeholder="+7 (999) 123-45-67" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label><i class="fab fa-telegram-plane"></i> Telegram</label>
|
<label>
|
||||||
<input type="text" id="telegram" placeholder="@username">
|
<i class="fab fa-telegram-plane"></i>
|
||||||
|
Telegram <span class="required-star">*</span>
|
||||||
|
</label>
|
||||||
|
<input type="text" id="telegram" placeholder="@username" required>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label><i class="fas fa-lock"></i> Пароль *</label>
|
<label>
|
||||||
|
<i class="fas fa-lock"></i>
|
||||||
|
Пароль <span class="required-star">*</span>
|
||||||
|
</label>
|
||||||
<input type="password" id="password" placeholder="Минимум 6 символов" required>
|
<input type="password" id="password" placeholder="Минимум 6 символов" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<label><i class="fas fa-lock"></i> Подтверждение *</label>
|
<label>
|
||||||
|
<i class="fas fa-lock"></i>
|
||||||
|
Подтверждение <span class="required-star">*</span>
|
||||||
|
</label>
|
||||||
<input type="password" id="confirmPassword" placeholder="Повторите пароль" required>
|
<input type="password" id="confirmPassword" placeholder="Повторите пароль" required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Требования к паролю -->
|
||||||
|
<div class="password-requirements" id="passwordRequirements">
|
||||||
|
<p><i class="fas fa-shield-alt"></i> Требования к паролю:</p>
|
||||||
|
<div class="requirement" id="reqLength">
|
||||||
|
<i class="far fa-circle"></i> Минимум 6 символов
|
||||||
|
</div>
|
||||||
|
<div class="requirement" id="reqMatch">
|
||||||
|
<i class="far fa-circle"></i> Пароли совпадают
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button type="submit" class="btn-register" id="registerBtn">
|
<button type="submit" class="btn-register" id="registerBtn">
|
||||||
<span>Зарегистрироваться</span>
|
<span>Зарегистрироваться</span>
|
||||||
<i class="fas fa-arrow-right"></i>
|
<i class="fas fa-arrow-right"></i>
|
||||||
@@ -305,17 +398,17 @@
|
|||||||
<a href="/login">Войти</a>
|
<a href="/login">Войти</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="footer">
|
||||||
|
© 2024 Rabota.Today - Ярмарка вакансий.
|
||||||
|
<a href="/">На главную</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const currentProtocol = window.location.protocol; // http: или https:
|
const API_BASE_URL = window.location.protocol + '//' + window.location.host + '/api';
|
||||||
const currentHost = window.location.host; // yarmarka.rabota.today или IP:порт
|
|
||||||
let API_BASE_URL = `${currentProtocol}//${currentHost}/api`;
|
|
||||||
let isSubmitting = false;
|
let isSubmitting = false;
|
||||||
|
|
||||||
// Определение мобильного устройства
|
|
||||||
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
|
|
||||||
|
|
||||||
// Переключение роли
|
// Переключение роли
|
||||||
document.getElementById('roleEmployeeBtn').addEventListener('click', () => {
|
document.getElementById('roleEmployeeBtn').addEventListener('click', () => {
|
||||||
document.getElementById('roleEmployeeBtn').classList.add('active');
|
document.getElementById('roleEmployeeBtn').classList.add('active');
|
||||||
@@ -327,6 +420,69 @@
|
|||||||
document.getElementById('roleEmployeeBtn').classList.remove('active');
|
document.getElementById('roleEmployeeBtn').classList.remove('active');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Валидация пароля в реальном времени
|
||||||
|
const passwordInput = document.getElementById('password');
|
||||||
|
const confirmInput = document.getElementById('confirmPassword');
|
||||||
|
|
||||||
|
function validatePassword() {
|
||||||
|
const password = passwordInput.value;
|
||||||
|
const confirm = confirmInput.value;
|
||||||
|
|
||||||
|
const reqLength = document.getElementById('reqLength');
|
||||||
|
const reqMatch = document.getElementById('reqMatch');
|
||||||
|
|
||||||
|
// Проверка длины
|
||||||
|
if (password.length >= 6) {
|
||||||
|
reqLength.className = 'requirement valid';
|
||||||
|
reqLength.innerHTML = '<i class="fas fa-check-circle"></i> Минимум 6 символов ✓';
|
||||||
|
} else {
|
||||||
|
reqLength.className = 'requirement invalid';
|
||||||
|
reqLength.innerHTML = '<i class="fas fa-times-circle"></i> Минимум 6 символов';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверка совпадения
|
||||||
|
if (password && confirm && password === confirm) {
|
||||||
|
reqMatch.className = 'requirement valid';
|
||||||
|
reqMatch.innerHTML = '<i class="fas fa-check-circle"></i> Пароли совпадают ✓';
|
||||||
|
} else if (confirm) {
|
||||||
|
reqMatch.className = 'requirement invalid';
|
||||||
|
reqMatch.innerHTML = '<i class="fas fa-times-circle"></i> Пароли совпадают';
|
||||||
|
} else {
|
||||||
|
reqMatch.className = 'requirement';
|
||||||
|
reqMatch.innerHTML = '<i class="far fa-circle"></i> Пароли совпадают';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
passwordInput.addEventListener('input', validatePassword);
|
||||||
|
confirmInput.addEventListener('input', validatePassword);
|
||||||
|
|
||||||
|
// Функция для проверки корректности Telegram username
|
||||||
|
function validateTelegram(telegram) {
|
||||||
|
if (!telegram) return false;
|
||||||
|
// Telegram username может начинаться с @ или без него
|
||||||
|
// Допустимые символы: буквы, цифры, подчеркивание
|
||||||
|
const cleanTelegram = telegram.replace('@', '');
|
||||||
|
return /^[a-zA-Z0-9_]{5,32}$/.test(cleanTelegram);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Функция для форматирования телефона
|
||||||
|
function formatPhone(phone) {
|
||||||
|
// Удаляем все нецифровые символы
|
||||||
|
let digits = phone.replace(/\D/g, '');
|
||||||
|
|
||||||
|
// Если номер начинается с 8 или 7, нормализуем
|
||||||
|
if (digits.length === 11) {
|
||||||
|
if (digits.startsWith('8')) {
|
||||||
|
digits = '7' + digits.substring(1);
|
||||||
|
}
|
||||||
|
} else if (digits.length === 10) {
|
||||||
|
digits = '7' + digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
return digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Показать сообщение об ошибке
|
||||||
function showError(message) {
|
function showError(message) {
|
||||||
const errorDiv = document.getElementById('errorMessage');
|
const errorDiv = document.getElementById('errorMessage');
|
||||||
const errorText = document.getElementById('errorText');
|
const errorText = document.getElementById('errorText');
|
||||||
@@ -335,112 +491,172 @@
|
|||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
errorDiv.style.display = 'none';
|
errorDiv.style.display = 'none';
|
||||||
}, 4000);
|
}, 5000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Показать сообщение об успехе
|
||||||
function showSuccess(message) {
|
function showSuccess(message) {
|
||||||
const successDiv = document.getElementById('successMessage');
|
const successDiv = document.getElementById('successMessage');
|
||||||
const successText = document.getElementById('successText');
|
const successText = document.getElementById('successText');
|
||||||
successText.textContent = message;
|
successText.textContent = message;
|
||||||
successDiv.style.display = 'flex';
|
successDiv.style.display = 'flex';
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
successDiv.style.display = 'none';
|
||||||
|
}, 3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Показать состояние загрузки
|
||||||
function setLoading(isLoading) {
|
function setLoading(isLoading) {
|
||||||
const btn = document.getElementById('registerBtn');
|
const registerBtn = document.getElementById('registerBtn');
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Регистрация...';
|
registerBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Регистрация...';
|
||||||
btn.disabled = true;
|
registerBtn.disabled = true;
|
||||||
isSubmitting = true;
|
isSubmitting = true;
|
||||||
} else {
|
} else {
|
||||||
btn.innerHTML = '<span>Зарегистрироваться</span><i class="fas fa-arrow-right"></i>';
|
registerBtn.innerHTML = '<span>Зарегистрироваться</span><i class="fas fa-arrow-right"></i>';
|
||||||
btn.disabled = false;
|
registerBtn.disabled = false;
|
||||||
isSubmitting = false;
|
isSubmitting = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Обработка регистрации
|
||||||
async function handleRegister(event) {
|
async function handleRegister(event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
||||||
if (isSubmitting) return;
|
if (isSubmitting) return;
|
||||||
|
|
||||||
|
// Получаем значения полей
|
||||||
const fullName = document.getElementById('fullName').value.trim();
|
const fullName = document.getElementById('fullName').value.trim();
|
||||||
const email = document.getElementById('email').value.trim();
|
const email = document.getElementById('email').value.trim();
|
||||||
const phone = document.getElementById('phone').value.trim();
|
const phone = document.getElementById('phone').value.trim();
|
||||||
const telegram = document.getElementById('telegram').value.trim() || null;
|
const telegram = document.getElementById('telegram').value.trim();
|
||||||
const password = document.getElementById('password').value;
|
const password = document.getElementById('password').value;
|
||||||
const confirmPassword = document.getElementById('confirmPassword').value;
|
const confirmPassword = document.getElementById('confirmPassword').value;
|
||||||
|
|
||||||
|
// Определяем роль
|
||||||
const role = document.getElementById('roleEmployeeBtn').classList.contains('active') ? 'employee' : 'employer';
|
const role = document.getElementById('roleEmployeeBtn').classList.contains('active') ? 'employee' : 'employer';
|
||||||
|
|
||||||
// Валидация
|
// Валидация ФИО
|
||||||
if (!fullName || !email || !phone || !password) {
|
if (!fullName) {
|
||||||
showError('Заполните все обязательные поля');
|
showError('Введите ФИО');
|
||||||
|
document.getElementById('fullName').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Валидация email
|
||||||
|
if (!email) {
|
||||||
|
showError('Введите email');
|
||||||
|
document.getElementById('email').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!email.includes('@') || !email.includes('.')) {
|
||||||
|
showError('Введите корректный email');
|
||||||
|
document.getElementById('email').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Валидация телефона
|
||||||
|
if (!phone) {
|
||||||
|
showError('Введите номер телефона');
|
||||||
|
document.getElementById('phone').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const phoneDigits = formatPhone(phone);
|
||||||
|
if (phoneDigits.length !== 11) {
|
||||||
|
showError('Введите корректный номер телефона (10 или 11 цифр)');
|
||||||
|
document.getElementById('phone').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Валидация Telegram
|
||||||
|
if (!telegram) {
|
||||||
|
showError('Введите Telegram username');
|
||||||
|
document.getElementById('telegram').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateTelegram(telegram)) {
|
||||||
|
showError('Telegram username должен содержать от 5 до 32 символов (буквы, цифры, _)');
|
||||||
|
document.getElementById('telegram').focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Валидация пароля
|
||||||
if (password.length < 6) {
|
if (password.length < 6) {
|
||||||
showError('Пароль должен быть минимум 6 символов');
|
showError('Пароль должен содержать минимум 6 символов');
|
||||||
|
document.getElementById('password').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (password !== confirmPassword) {
|
if (password !== confirmPassword) {
|
||||||
showError('Пароли не совпадают');
|
showError('Пароли не совпадают');
|
||||||
|
document.getElementById('confirmPassword').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Форматируем телефон для отправки
|
||||||
|
const formattedPhone = '+' + phoneDigits;
|
||||||
|
|
||||||
|
// Форматируем Telegram (добавляем @ если нет)
|
||||||
|
let formattedTelegram = telegram;
|
||||||
|
if (!telegram.startsWith('@')) {
|
||||||
|
formattedTelegram = '@' + telegram;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Подготавливаем данные для отправки
|
||||||
|
const userData = {
|
||||||
|
full_name: fullName,
|
||||||
|
email: email,
|
||||||
|
phone: formattedPhone,
|
||||||
|
telegram: formattedTelegram,
|
||||||
|
password: password,
|
||||||
|
role: role
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('📤 Отправка данных регистрации:', {
|
||||||
|
...userData,
|
||||||
|
password: '***скрыто***'
|
||||||
|
});
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const userData = {
|
|
||||||
full_name: fullName,
|
|
||||||
email: email,
|
|
||||||
phone: phone,
|
|
||||||
telegram: telegram,
|
|
||||||
password: password,
|
|
||||||
role: role
|
|
||||||
};
|
|
||||||
|
|
||||||
console.log('Sending registration request...', { email: userData.email });
|
|
||||||
|
|
||||||
const response = await fetch(`${API_BASE_URL}/register`, {
|
const response = await fetch(`${API_BASE_URL}/register`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Accept': 'application/json',
|
'Accept': 'application/json'
|
||||||
'X-Requested-With': 'XMLHttpRequest'
|
|
||||||
},
|
},
|
||||||
body: JSON.stringify(userData),
|
body: JSON.stringify(userData)
|
||||||
credentials: 'include' // Важно для мобильных
|
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Response status:', response.status);
|
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
console.log('📥 Ответ сервера:', data);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(data.detail || 'Ошибка регистрации');
|
throw new Error(data.detail || 'Ошибка регистрации');
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Registration successful');
|
// Успешная регистрация
|
||||||
|
showSuccess('Регистрация успешна! Перенаправляем...');
|
||||||
|
|
||||||
// Сохраняем токен
|
// Сохраняем токен
|
||||||
if (data.access_token) {
|
localStorage.setItem('accessToken', data.access_token);
|
||||||
localStorage.setItem('accessToken', data.access_token);
|
localStorage.setItem('userId', data.user_id);
|
||||||
localStorage.setItem('userId', data.user_id);
|
localStorage.setItem('userRole', data.role);
|
||||||
localStorage.setItem('userRole', data.role);
|
localStorage.setItem('userName', data.full_name);
|
||||||
localStorage.setItem('userName', data.full_name);
|
|
||||||
|
|
||||||
showSuccess('Регистрация успешна! Перенаправляем...');
|
// Перенаправляем в профиль через секунду
|
||||||
|
setTimeout(() => {
|
||||||
setTimeout(() => {
|
window.location.href = '/profile';
|
||||||
window.location.href = '/profile';
|
}, 1500);
|
||||||
}, 1500);
|
|
||||||
} else {
|
|
||||||
throw new Error('Токен не получен');
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Registration error:', error);
|
console.error('❌ Ошибка регистрации:', error);
|
||||||
showError(error.message || 'Ошибка соединения');
|
showError(error.message);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -454,6 +670,25 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Автоматическое добавление @ в Telegram
|
||||||
|
document.getElementById('telegram').addEventListener('blur', function(e) {
|
||||||
|
let value = e.target.value.trim();
|
||||||
|
if (value && !value.startsWith('@')) {
|
||||||
|
e.target.value = '@' + value.replace(/[^a-zA-Z0-9_]/g, '');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ограничение ввода для Telegram (только буквы, цифры, _)
|
||||||
|
document.getElementById('telegram').addEventListener('input', function(e) {
|
||||||
|
let value = e.target.value;
|
||||||
|
// Если начинается с @, разрешаем @ только в начале
|
||||||
|
if (value.startsWith('@')) {
|
||||||
|
e.target.value = '@' + value.substring(1).replace(/[^a-zA-Z0-9_]/g, '');
|
||||||
|
} else {
|
||||||
|
e.target.value = value.replace(/[^a-zA-Z0-9_]/g, '');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Проверка существующей сессии
|
// Проверка существующей сессии
|
||||||
if (localStorage.getItem('accessToken')) {
|
if (localStorage.getItem('accessToken')) {
|
||||||
window.location.href = '/profile';
|
window.location.href = '/profile';
|
||||||
|
|||||||
@@ -932,6 +932,10 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="qr-stats">
|
<div class="qr-stats">
|
||||||
|
<div class="qr-stat-item">
|
||||||
|
<div class="qr-stat-value" id="qrViewCount">0</div> <!-- Добавлено -->
|
||||||
|
<div class="qr-stat-label">просмотров</div>
|
||||||
|
</div>
|
||||||
<div class="qr-stat-item">
|
<div class="qr-stat-item">
|
||||||
<div class="qr-stat-value" id="qrUserRole">—</div>
|
<div class="qr-stat-value" id="qrUserRole">—</div>
|
||||||
<div class="qr-stat-label">роль</div>
|
<div class="qr-stat-label">роль</div>
|
||||||
@@ -940,10 +944,6 @@
|
|||||||
<div class="qr-stat-value" id="qrUserSince">—</div>
|
<div class="qr-stat-value" id="qrUserSince">—</div>
|
||||||
<div class="qr-stat-label">на платформе</div>
|
<div class="qr-stat-label">на платформе</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="qr-stat-item">
|
|
||||||
<div class="qr-stat-value" id="qrUserActivity">0</div>
|
|
||||||
<div class="qr-stat-label">активность</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="qr-actions">
|
<div class="qr-actions">
|
||||||
@@ -1488,54 +1488,44 @@
|
|||||||
const modal = document.getElementById('qrModal');
|
const modal = document.getElementById('qrModal');
|
||||||
if (!modal) {
|
if (!modal) {
|
||||||
console.error('❌ Модальное окно с id "qrModal" не найдено в DOM');
|
console.error('❌ Модальное окно с id "qrModal" не найдено в DOM');
|
||||||
console.log('🔍 Поиск всех элементов с классом qr-modal:', document.querySelectorAll('.qr-modal'));
|
|
||||||
showNotification('Ошибка: модальное окно не найдено', 'error');
|
showNotification('Ошибка: модальное окно не найдено', 'error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Проверяем все необходимые элементы
|
// Получаем элементы
|
||||||
const elements = {
|
const qrUserName = document.getElementById('qrUserName');
|
||||||
qrUserName: document.getElementById('qrUserName'),
|
const qrUserUrl = document.getElementById('qrUserUrl');
|
||||||
qrUserUrl: document.getElementById('qrUserUrl'),
|
const qrViewCountElement = document.getElementById('qrViewCount'); // Переименовал, чтобы не конфликтовать
|
||||||
qrViewCount: document.getElementById('qrViewCount'),
|
const qrUserRole = document.getElementById('qrUserRole');
|
||||||
qrUserRole: document.getElementById('qrUserRole'),
|
const qrUserSince = document.getElementById('qrUserSince');
|
||||||
qrUserSince: document.getElementById('qrUserSince'),
|
const qrCanvas = document.getElementById('qrCanvas');
|
||||||
qrUserActivity: document.getElementById('qrUserActivity'),
|
|
||||||
qrCanvas: document.getElementById('qrCanvas'),
|
|
||||||
qrLogoOverlay: document.getElementById('qrLogoOverlay'),
|
|
||||||
qrLogoIcon: document.getElementById('qrLogoIcon')
|
|
||||||
};
|
|
||||||
|
|
||||||
// Проверяем каждый элемент
|
// Проверяем наличие критически важных элементов
|
||||||
let missingElements = [];
|
if (!qrUserName || !qrUserUrl || !qrViewCountElement || !qrUserRole || !qrUserSince || !qrCanvas) {
|
||||||
for (let [key, element] of Object.entries(elements)) {
|
console.error('❌ Критические элементы модального окна не найдены');
|
||||||
if (!element) {
|
console.log('qrUserName:', qrUserName);
|
||||||
missingElements.push(key);
|
console.log('qrUserUrl:', qrUserUrl);
|
||||||
console.error(`❌ Элемент с id "${key}" не найден`);
|
console.log('qrViewCountElement:', qrViewCountElement);
|
||||||
}
|
console.log('qrUserRole:', qrUserRole);
|
||||||
}
|
console.log('qrUserSince:', qrUserSince);
|
||||||
|
console.log('qrCanvas:', qrCanvas);
|
||||||
if (missingElements.length > 0) {
|
|
||||||
console.error('❌ Отсутствуют элементы:', missingElements.join(', '));
|
|
||||||
showNotification('Ошибка отображения QR-кода', 'error');
|
showNotification('Ошибка отображения QR-кода', 'error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('✅ Все элементы модального окна найдены');
|
|
||||||
|
|
||||||
// Устанавливаем имя пользователя
|
// Устанавливаем имя пользователя
|
||||||
elements.qrUserName.textContent = escapeHtml(currentProfileUser.full_name);
|
qrUserName.textContent = escapeHtml(currentProfileUser.full_name);
|
||||||
|
|
||||||
// Формируем URL профиля
|
// Формируем URL профиля
|
||||||
const profileUrl = window.location.origin + '/user/' + currentProfileUser.id;
|
const profileUrl = window.location.origin + '/user/' + currentProfileUser.id;
|
||||||
elements.qrUserUrl.textContent = profileUrl.replace('https://', '').replace('http://', '');
|
qrUserUrl.textContent = profileUrl.replace('https://', '').replace('http://', '');
|
||||||
|
|
||||||
// Обновляем счетчик просмотров
|
// Обновляем счетчик просмотров - используем отдельную переменную
|
||||||
if (typeof qrViewCount === 'undefined') {
|
if (typeof window.qrViewCounter === 'undefined') {
|
||||||
window.qrViewCount = 0;
|
window.qrViewCounter = 0;
|
||||||
}
|
}
|
||||||
window.qrViewCount++;
|
window.qrViewCounter++;
|
||||||
elements.qrViewCount.textContent = window.qrViewCount;
|
qrViewCountElement.textContent = window.qrViewCounter;
|
||||||
|
|
||||||
// Роль пользователя
|
// Роль пользователя
|
||||||
let roleText = '';
|
let roleText = '';
|
||||||
@@ -1543,7 +1533,7 @@
|
|||||||
else if (currentProfileUser.role === 'employer') roleText = '🏢 Работодатель';
|
else if (currentProfileUser.role === 'employer') roleText = '🏢 Работодатель';
|
||||||
else if (currentProfileUser.role === 'admin') roleText = '👑 Админ';
|
else if (currentProfileUser.role === 'admin') roleText = '👑 Админ';
|
||||||
else roleText = '👤 Пользователь';
|
else roleText = '👤 Пользователь';
|
||||||
elements.qrUserRole.textContent = roleText;
|
qrUserRole.textContent = roleText;
|
||||||
|
|
||||||
// Дата регистрации
|
// Дата регистрации
|
||||||
if (currentProfileUser.created_at) {
|
if (currentProfileUser.created_at) {
|
||||||
@@ -1551,18 +1541,15 @@
|
|||||||
const date = new Date(currentProfileUser.created_at);
|
const date = new Date(currentProfileUser.created_at);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const months = Math.floor((now - date) / (1000 * 60 * 60 * 24 * 30));
|
const months = Math.floor((now - date) / (1000 * 60 * 60 * 24 * 30));
|
||||||
elements.qrUserSince.textContent = (months > 0 ? months : '< 1') + ' мес';
|
qrUserSince.textContent = (months > 0 ? months : '< 1') + ' мес';
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Ошибка при вычислении даты:', e);
|
console.error('Ошибка при вычислении даты:', e);
|
||||||
elements.qrUserSince.textContent = '—';
|
qrUserSince.textContent = '—';
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
elements.qrUserSince.textContent = '—';
|
qrUserSince.textContent = '—';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Активность
|
|
||||||
elements.qrUserActivity.textContent = 'активен';
|
|
||||||
|
|
||||||
// Генерируем QR-код
|
// Генерируем QR-код
|
||||||
try {
|
try {
|
||||||
generateQRCodeWithLogo(profileUrl);
|
generateQRCodeWithLogo(profileUrl);
|
||||||
@@ -1573,7 +1560,7 @@
|
|||||||
|
|
||||||
// Показываем модальное окно
|
// Показываем модальное окно
|
||||||
modal.classList.add('active');
|
modal.classList.add('active');
|
||||||
console.log('✅ QR-модальное окно открыто');
|
console.log('✅ QR-модальное окно открыто, счетчик:', window.qrViewCounter);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Закрыть модальное окно
|
// Закрыть модальное окно
|
||||||
|
|||||||
Reference in New Issue
Block a user