ваше сообщение коммита
This commit is contained in:
@@ -16,7 +16,9 @@
|
||||
"axios": "^1.8.4",
|
||||
"buffer": "^6.0.3",
|
||||
"connect-pg-simple": "^10.0.0",
|
||||
"dompurify": "^3.2.4",
|
||||
"ethers": "6.13.5",
|
||||
"marked": "^15.0.7",
|
||||
"siwe": "^2.1.4",
|
||||
"sortablejs": "^1.15.6",
|
||||
"vue": "^3.2.47",
|
||||
|
||||
378
frontend/src/assets/styles/home.css
Normal file
378
frontend/src/assets/styles/home.css
Normal file
@@ -0,0 +1,378 @@
|
||||
.app-container {
|
||||
display: flex;
|
||||
height: 100vh;
|
||||
width: 100%;
|
||||
background-color: #f5f5f5;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Стили для боковой панели */
|
||||
.sidebar {
|
||||
width: 84px;
|
||||
min-width: 84px;
|
||||
background-color: #FFDA58;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding-top: 20px;
|
||||
position: fixed;
|
||||
height: 100vh;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.sidebar.sidebar-expanded {
|
||||
width: 250px;
|
||||
min-width: 250px;
|
||||
}
|
||||
|
||||
.menu-button {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
background: white;
|
||||
border: 1px solid #333;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 68px;
|
||||
position: fixed;
|
||||
left: 22px;
|
||||
}
|
||||
|
||||
.hamburger {
|
||||
width: 24px;
|
||||
height: 3px;
|
||||
background-color: #333;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.hamburger::before,
|
||||
.hamburger::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 24px;
|
||||
height: 3px;
|
||||
background-color: #333;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.hamburger::before {
|
||||
top: -8px;
|
||||
}
|
||||
|
||||
.hamburger::after {
|
||||
bottom: -8px;
|
||||
}
|
||||
|
||||
.nav-buttons {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
width: 84px;
|
||||
padding: 0;
|
||||
position: fixed;
|
||||
left: 22px;
|
||||
top: 108px;
|
||||
}
|
||||
|
||||
.nav-btn {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 1px solid #333;
|
||||
border-radius: 4px;
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
padding: 0;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.nav-btn-text {
|
||||
font-size: 16px;
|
||||
color: #333;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
white-space: nowrap;
|
||||
position: absolute;
|
||||
left: 60px;
|
||||
}
|
||||
|
||||
.sidebar-expanded .nav-btn-text {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
/* Стили для основного контента */
|
||||
.main-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
margin-left: 84px;
|
||||
}
|
||||
|
||||
.sidebar-expanded ~ .main-content {
|
||||
margin-left: 250px;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.hand-emoji {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 14px;
|
||||
color: #555;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
/* Стили для чата */
|
||||
.chat-container {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0 20px 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
background-color: white;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 15px;
|
||||
padding: 10px 15px;
|
||||
border-radius: 8px;
|
||||
max-width: 80%;
|
||||
}
|
||||
|
||||
.user-message {
|
||||
background-color: #EFFAFF;
|
||||
align-self: flex-end;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.ai-message {
|
||||
background-color: #F8F8F8;
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
margin-bottom: 5px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.message-time {
|
||||
font-size: 12px;
|
||||
color: #777;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.chat-input {
|
||||
display: flex;
|
||||
background-color: white;
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.chat-input textarea {
|
||||
flex: 1;
|
||||
border: none;
|
||||
resize: none;
|
||||
padding: 10px;
|
||||
height: 40px;
|
||||
font-family: inherit;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.chat-input textarea:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.chat-input button {
|
||||
background-color: #E8E8E8;
|
||||
color: #555;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
padding: 0 20px;
|
||||
cursor: pointer;
|
||||
height: 40px;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.chat-input button:hover:not(:disabled) {
|
||||
background-color: #d8d8d8;
|
||||
}
|
||||
|
||||
.chat-input button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Стили для правой панели с информацией о кошельке */
|
||||
.wallet-sidebar {
|
||||
width: 250px;
|
||||
background-color: #FFDA58;
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.wallet-connect-btn {
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 12px 20px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.wallet-disconnect-btn {
|
||||
background-color: #f44336;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
padding: 12px 20px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.balance-container {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.balance-container h3 {
|
||||
margin-bottom: 15px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.token-balance {
|
||||
display: flex;
|
||||
margin-bottom: 10px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.token-name {
|
||||
width: 60px;
|
||||
}
|
||||
|
||||
.token-amount {
|
||||
flex: 1;
|
||||
text-align: right;
|
||||
padding-right: 10px;
|
||||
}
|
||||
|
||||
.token-symbol {
|
||||
width: 60px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.wallet-address {
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.wallet-address h3 {
|
||||
margin-bottom: 10px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.address {
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.language-selector {
|
||||
margin-top: auto;
|
||||
align-self: flex-end;
|
||||
background-color: white;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dropdown-icon {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* Стили для кнопок авторизации */
|
||||
.auth-buttons {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.auth-btn {
|
||||
padding: 12px 16px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.email-btn {
|
||||
background-color: #2196F3;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.telegram-btn {
|
||||
background-color: #0088cc;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.user-info h3 {
|
||||
margin-bottom: 10px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.user-info-item {
|
||||
display: flex;
|
||||
margin-bottom: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.user-info-label {
|
||||
min-width: 80px;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.user-info-value {
|
||||
font-weight: bold;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
663
frontend/src/views/HomeView.vue.bak
Normal file
663
frontend/src/views/HomeView.vue.bak
Normal file
@@ -0,0 +1,663 @@
|
||||
<template>
|
||||
<div class="app-container">
|
||||
<!-- Боковая панель -->
|
||||
<div class="sidebar">
|
||||
<button class="menu-button">
|
||||
<div class="hamburger"></div>
|
||||
</button>
|
||||
<div class="nav-buttons">
|
||||
<button class="nav-btn">1</button>
|
||||
<button class="nav-btn">2</button>
|
||||
<button class="nav-btn">3</button>
|
||||
<button class="nav-btn">4</button>
|
||||
<button class="nav-btn">5</button>
|
||||
<button class="nav-btn">6</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Основной контент -->
|
||||
<div class="main-content">
|
||||
<div class="header">
|
||||
<div class="title">
|
||||
<span class="hand-emoji">✌️</span> HB3 - Accelerator DLE (Digital Legal Entity - DAO Fork)
|
||||
</div>
|
||||
<div class="subtitle">
|
||||
Венчурный фонд и поставщик программного обеспечения
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-container">
|
||||
<div class="chat-messages" ref="messagesContainer">
|
||||
<div v-for="message in messages" :key="message.id"
|
||||
:class="['message', message.role === 'assistant' ? 'ai-message' : 'user-message']">
|
||||
<div class="message-content" v-html="formatMessage(message.content)"></div>
|
||||
<div class="message-time">{{ formatTime(message.timestamp || message.created_at) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-input">
|
||||
<textarea
|
||||
v-model="newMessage"
|
||||
placeholder="Введите сообщение..."
|
||||
@keydown.enter.prevent="handleMessage(newMessage)"
|
||||
:disabled="isLoading"
|
||||
></textarea>
|
||||
<button @click="handleMessage(newMessage)" :disabled="isLoading || !newMessage.trim()">
|
||||
{{ isLoading ? 'Отправка...' : 'Отправить' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Правая панель с информацией о кошельке -->
|
||||
<div class="wallet-sidebar">
|
||||
<button v-if="!isAuthenticated" @click="handleWalletAuth" class="wallet-connect-btn">
|
||||
Подключить кошелек
|
||||
</button>
|
||||
<button v-else @click="disconnectWallet" class="wallet-disconnect-btn">
|
||||
Отключить кошелек
|
||||
</button>
|
||||
|
||||
<!-- Добавляем дополнительные кнопки авторизации -->
|
||||
<div v-if="!isAuthenticated" class="auth-buttons">
|
||||
<button @click="handleTelegramAuth" class="auth-btn telegram-btn">
|
||||
Подключить Telegram
|
||||
</button>
|
||||
<button @click="handleEmailAuth" class="auth-btn email-btn">
|
||||
Подключить Email
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Блок для верификации Telegram -->
|
||||
<div v-if="showTelegramVerification" class="verification-block">
|
||||
<div class="verification-code">
|
||||
<span>Код верификации:</span>
|
||||
<code @click="copyCode(telegramVerificationCode)">{{ telegramVerificationCode }}</code>
|
||||
<span v-if="codeCopied" class="copied-message">Скопировано!</span>
|
||||
</div>
|
||||
<a :href="telegramBotLink" target="_blank" class="bot-link">Открыть бота Telegram</a>
|
||||
</div>
|
||||
|
||||
<!-- Форма для Email верификации -->
|
||||
<div v-if="showEmailForm" class="email-form">
|
||||
<p>Введите ваш email для получения кода подтверждения:</p>
|
||||
<div class="email-input-container">
|
||||
<input
|
||||
v-model="emailInput"
|
||||
type="email"
|
||||
placeholder="Ваш email"
|
||||
class="email-input"
|
||||
:class="{ 'email-input-error': emailFormatError }"
|
||||
/>
|
||||
<button @click="sendEmailVerification" class="send-email-btn" :disabled="isEmailSending">
|
||||
{{ isEmailSending ? 'Отправка...' : 'Отправить код' }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="emailFormatError" class="email-format-error">Пожалуйста, введите корректный email</p>
|
||||
</div>
|
||||
|
||||
<!-- Сообщение об ошибке в Email -->
|
||||
<div v-if="emailError" class="error-message">
|
||||
{{ emailError }}
|
||||
<button class="close-error" @click="clearEmailError">×</button>
|
||||
</div>
|
||||
|
||||
<!-- Форма для ввода кода верификации Email -->
|
||||
<div v-if="showEmailVerificationInput" class="email-verification-form">
|
||||
<p>На ваш email <strong>{{ emailVerificationEmail }}</strong> отправлен код подтверждения.</p>
|
||||
<div class="verification-input">
|
||||
<input
|
||||
v-model="emailVerificationCode"
|
||||
type="text"
|
||||
placeholder="Введите код верификации"
|
||||
maxlength="6"
|
||||
/>
|
||||
<button @click="verifyEmailCode" class="verify-btn" :disabled="isVerifying">
|
||||
{{ isVerifying ? 'Проверка...' : 'Подтвердить' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Блок баланса токенов -->
|
||||
<div class="balance-container">
|
||||
<h3>Баланс:</h3>
|
||||
<div class="token-balance">
|
||||
<span class="token-name">ETH:</span>
|
||||
<span class="token-amount">{{ isAuthenticated ? '1500000' : '0' }}</span>
|
||||
<span class="token-symbol">HB3A</span>
|
||||
</div>
|
||||
<div class="token-balance">
|
||||
<span class="token-name">ARB:</span>
|
||||
<span class="token-amount">{{ isAuthenticated ? '500000' : '0' }}</span>
|
||||
<span class="token-symbol">HB3A</span>
|
||||
</div>
|
||||
<div class="token-balance">
|
||||
<span class="token-name">POL:</span>
|
||||
<span class="token-amount">{{ isAuthenticated ? '500000' : '0' }}</span>
|
||||
<span class="token-symbol">HB3A</span>
|
||||
</div>
|
||||
<div class="token-balance">
|
||||
<span class="token-name">BNB:</span>
|
||||
<span class="token-amount">0</span>
|
||||
<span class="token-symbol">HB3A</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Блок информации о пользователе -->
|
||||
<div v-if="isAuthenticated" class="user-info">
|
||||
<h3>Идентификаторы:</h3>
|
||||
<div v-if="auth.address?.value" class="user-info-item">
|
||||
<span class="user-info-label">Кошелек:</span>
|
||||
<span class="user-info-value">{{ truncateAddress(auth.address.value) }}</span>
|
||||
</div>
|
||||
<div v-if="auth.telegramId?.value" class="user-info-item">
|
||||
<span class="user-info-label">Telegram:</span>
|
||||
<span class="user-info-value">{{ auth.telegramId.value }}</span>
|
||||
</div>
|
||||
<div v-if="auth.email?.value" class="user-info-item">
|
||||
<span class="user-info-label">Email:</span>
|
||||
<span class="user-info-value">{{ auth.email.value }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="language-selector">
|
||||
RU <span class="dropdown-icon">▼</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
|
||||
import { useAuth } from '../composables/useAuth';
|
||||
import { connectWithWallet } from '../services/wallet';
|
||||
import axios from 'axios';
|
||||
import api from '../api/axios';
|
||||
import DOMPurify from 'dompurify';
|
||||
import { marked } from 'marked';
|
||||
import '../assets/styles/home.css';
|
||||
|
||||
console.log('HomeView.vue: Version with chat loaded');
|
||||
|
||||
const auth = useAuth();
|
||||
const isAuthenticated = computed(() => auth.isAuthenticated.value);
|
||||
const isConnecting = ref(false);
|
||||
const messages = ref([]);
|
||||
const newMessage = ref('');
|
||||
const isLoading = ref(false);
|
||||
const messagesContainer = ref(null);
|
||||
const userLanguage = ref('ru');
|
||||
|
||||
// Состояния для пагинации
|
||||
const isLoadingMore = ref(false);
|
||||
const hasMoreMessages = ref(false);
|
||||
const offset = ref(0);
|
||||
const limit = ref(20);
|
||||
|
||||
// Состояния для верификации
|
||||
const showTelegramVerification = ref(false);
|
||||
const telegramVerificationCode = ref('');
|
||||
const telegramBotLink = ref('');
|
||||
const telegramAuthCheckInterval = ref(null);
|
||||
const showEmailVerification = ref(false);
|
||||
const emailVerificationCode = ref('');
|
||||
const emailError = ref('');
|
||||
const codeCopied = ref(false);
|
||||
const showEmailAlternatives = ref(false);
|
||||
|
||||
// Состояния для формы ввода кода
|
||||
const showEmailVerificationInput = ref(false);
|
||||
const emailVerificationEmail = ref('');
|
||||
|
||||
// Состояния для формы ввода email
|
||||
const showEmailForm = ref(false);
|
||||
const emailInput = ref('');
|
||||
const emailFormatError = ref(false);
|
||||
const isEmailSending = ref(false);
|
||||
|
||||
// Состояния для индикации и успешных сообщений
|
||||
const isVerifying = ref(false);
|
||||
const successMessage = ref('');
|
||||
const showSuccessMessage = ref(false);
|
||||
|
||||
// Функция для копирования кода
|
||||
const copyCode = (code) => {
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
codeCopied.value = true;
|
||||
setTimeout(() => {
|
||||
codeCopied.value = false;
|
||||
}, 2000);
|
||||
});
|
||||
};
|
||||
|
||||
// Функция для очистки ошибки
|
||||
const clearEmailError = () => {
|
||||
emailError.value = '';
|
||||
};
|
||||
|
||||
// Функция для обработки Email аутентификации
|
||||
const handleEmailAuth = async () => {
|
||||
try {
|
||||
// Показываем форму для ввода email
|
||||
showEmailForm.value = true;
|
||||
// Сбрасываем другие состояния форм
|
||||
showEmailVerification.value = false;
|
||||
showEmailVerificationInput.value = false;
|
||||
// Очищаем поля и ошибки
|
||||
emailInput.value = '';
|
||||
emailFormatError.value = false;
|
||||
emailError.value = '';
|
||||
} catch (error) {
|
||||
console.error('Error in email auth:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для отправки запроса на верификацию email
|
||||
const sendEmailVerification = async () => {
|
||||
try {
|
||||
emailFormatError.value = false;
|
||||
emailError.value = '';
|
||||
|
||||
// Проверяем формат email
|
||||
if (!emailInput.value || !emailInput.value.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
|
||||
emailFormatError.value = true;
|
||||
return;
|
||||
}
|
||||
|
||||
isEmailSending.value = true;
|
||||
|
||||
// Отправляем запрос на сервер для инициализации email аутентификации
|
||||
const response = await axios.post('/api/auth/email/init', { email: emailInput.value });
|
||||
|
||||
if (response.data.success) {
|
||||
// Скрываем форму ввода email
|
||||
showEmailForm.value = false;
|
||||
// Показываем форму для ввода кода
|
||||
showEmailVerificationInput.value = true;
|
||||
// Скрываем старую форму кода верификации
|
||||
showEmailVerification.value = false;
|
||||
// Сохраняем email
|
||||
emailVerificationEmail.value = emailInput.value;
|
||||
// Очищаем поле для ввода кода
|
||||
emailVerificationCode.value = '';
|
||||
} else {
|
||||
emailError.value = response.data.error || 'Ошибка инициализации аутентификации по email';
|
||||
}
|
||||
} catch (error) {
|
||||
emailError.value = 'Ошибка при запросе кода подтверждения';
|
||||
console.error('Error in email auth:', error);
|
||||
} finally {
|
||||
isEmailSending.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для проверки введенного кода
|
||||
const verifyEmailCode = async () => {
|
||||
try {
|
||||
// Очищаем сообщение об ошибке
|
||||
emailError.value = '';
|
||||
|
||||
if (!emailVerificationCode.value) {
|
||||
emailError.value = 'Пожалуйста, введите код верификации';
|
||||
return;
|
||||
}
|
||||
|
||||
// Показываем индикатор процесса верификации
|
||||
isVerifying.value = true;
|
||||
|
||||
const response = await axios.post('/api/auth/check-email-verification', {
|
||||
code: emailVerificationCode.value
|
||||
});
|
||||
|
||||
if (response.data.success) {
|
||||
// Сбрасываем все состояния форм email
|
||||
showEmailVerificationInput.value = false;
|
||||
showEmailForm.value = false;
|
||||
showEmailVerification.value = false;
|
||||
|
||||
// Показываем сообщение об успешной верификации
|
||||
successMessage.value = `Email ${emailVerificationEmail.value} успешно подтвержден!`;
|
||||
showSuccessMessage.value = true;
|
||||
|
||||
// Скрываем сообщение через 3 секунды
|
||||
setTimeout(() => {
|
||||
showSuccessMessage.value = false;
|
||||
}, 3000);
|
||||
|
||||
// Обновляем состояние аутентификации
|
||||
await auth.checkAuth();
|
||||
|
||||
// Перезагружаем страницу для обновления UI через 1 секунду
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
} else {
|
||||
emailError.value = response.data.message || 'Неверный код верификации';
|
||||
}
|
||||
} catch (error) {
|
||||
emailError.value = 'Ошибка при проверке кода';
|
||||
console.error('Error verifying email code:', error);
|
||||
} finally {
|
||||
isVerifying.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Обработчик для Telegram аутентификации
|
||||
const handleTelegramAuth = async () => {
|
||||
try {
|
||||
const { data } = await axios.post('/api/auth/telegram/init');
|
||||
const { verificationCode, botLink } = data;
|
||||
|
||||
// Показываем код верификации
|
||||
showTelegramVerification.value = true;
|
||||
telegramVerificationCode.value = verificationCode;
|
||||
telegramBotLink.value = botLink;
|
||||
|
||||
// Запускаем проверку статуса аутентификации
|
||||
telegramAuthCheckInterval.value = setInterval(async () => {
|
||||
try {
|
||||
const response = await axios.get('/api/auth/check');
|
||||
if (response.data.authenticated) {
|
||||
auth.updateAuth({
|
||||
isAuthenticated: true,
|
||||
authType: response.data.authType,
|
||||
userId: response.data.userId
|
||||
});
|
||||
|
||||
clearInterval(telegramAuthCheckInterval.value);
|
||||
telegramAuthCheckInterval.value = null;
|
||||
showTelegramVerification.value = false;
|
||||
|
||||
// Перезагружаем страницу для полного обновления состояния
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking auth status:', error);
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
// Очищаем интервал через 5 минут
|
||||
setTimeout(() => {
|
||||
if (telegramAuthCheckInterval.value) {
|
||||
clearInterval(telegramAuthCheckInterval.value);
|
||||
telegramAuthCheckInterval.value = null;
|
||||
showTelegramVerification.value = false;
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error initializing Telegram auth:', error);
|
||||
alert('Ошибка при инициализации Telegram аутентификации');
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для сокращения адреса кошелька
|
||||
const truncateAddress = (address) => {
|
||||
if (!address) return '';
|
||||
return `${address.slice(0, 6)}...${address.slice(-4)}`;
|
||||
};
|
||||
|
||||
// Функция прокрутки к последнему сообщению
|
||||
const scrollToBottom = () => {
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
|
||||
}
|
||||
};
|
||||
|
||||
// Загрузка сообщений
|
||||
const loadMoreMessages = async () => {
|
||||
if (!isAuthenticated.value) return;
|
||||
|
||||
try {
|
||||
isLoadingMore.value = true;
|
||||
const response = await api.get('/api/chat/history', {
|
||||
params: {
|
||||
limit: limit.value,
|
||||
offset: offset.value
|
||||
}
|
||||
});
|
||||
|
||||
if (response.data.success) {
|
||||
const newMessages = response.data.messages.map(msg => ({
|
||||
id: msg.id,
|
||||
content: msg.content,
|
||||
role: msg.role || (msg.sender_type === 'assistant' ? 'assistant' : 'user'),
|
||||
timestamp: msg.created_at,
|
||||
showAuthOptions: false
|
||||
}));
|
||||
|
||||
messages.value = [...messages.value, ...newMessages];
|
||||
hasMoreMessages.value = response.data.total > messages.value.length;
|
||||
offset.value += newMessages.length;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading chat history:', error);
|
||||
} finally {
|
||||
isLoadingMore.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Загружаем сообщения при изменении аутентификации
|
||||
watch(() => isAuthenticated.value, async (newValue) => {
|
||||
if (newValue) {
|
||||
messages.value = [];
|
||||
offset.value = 0;
|
||||
hasMoreMessages.value = true;
|
||||
|
||||
try {
|
||||
// Сначала загружаем историю из messages
|
||||
await loadMoreMessages();
|
||||
|
||||
// Связываем гостевые сообщения (копируем из guest_messages в messages)
|
||||
await api.post('/api/chat/link-guest-messages');
|
||||
console.log('Guest messages linked to authenticated user');
|
||||
|
||||
// Перезагружаем сообщения, чтобы получить все, включая перенесенные
|
||||
messages.value = [];
|
||||
offset.value = 0;
|
||||
await loadMoreMessages();
|
||||
|
||||
await nextTick();
|
||||
scrollToBottom();
|
||||
} catch (linkError) {
|
||||
console.error('Error linking guest messages:', linkError);
|
||||
}
|
||||
} else {
|
||||
messages.value = [];
|
||||
offset.value = 0;
|
||||
hasMoreMessages.value = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Функция для подключения кошелька
|
||||
const handleWalletAuth = async () => {
|
||||
if (isConnecting.value || isAuthenticated.value) return; // Предотвращаем повторное подключение
|
||||
|
||||
isConnecting.value = true;
|
||||
try {
|
||||
const result = await connectWithWallet();
|
||||
console.log('Wallet connection result:', result);
|
||||
|
||||
if (result.success) {
|
||||
// Обновляем состояние авторизации
|
||||
await auth.checkAuth();
|
||||
|
||||
// Добавляем небольшую задержку перед сбросом состояния isConnecting
|
||||
setTimeout(() => {
|
||||
isConnecting.value = false;
|
||||
}, 500);
|
||||
return;
|
||||
} else {
|
||||
console.error('Failed to connect wallet:', result.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error connecting wallet:', error);
|
||||
}
|
||||
|
||||
isConnecting.value = false;
|
||||
};
|
||||
|
||||
// Функция для отключения кошелька/выхода
|
||||
const disconnectWallet = async () => {
|
||||
try {
|
||||
await axios.post('/api/auth/logout');
|
||||
auth.isAuthenticated.value = false;
|
||||
auth.address.value = null;
|
||||
auth.authType.value = null;
|
||||
auth.telegramId = null;
|
||||
auth.email = null;
|
||||
|
||||
// Перезагружаем страницу для сброса состояния
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
console.error('Error disconnecting wallet:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Форматирование времени
|
||||
const formatTime = (timestamp) => {
|
||||
if (!timestamp) return '';
|
||||
|
||||
try {
|
||||
const date = new Date(timestamp);
|
||||
|
||||
// Проверяем, является ли дата валидной
|
||||
if (isNaN(date.getTime())) {
|
||||
console.warn('Invalid timestamp:', timestamp);
|
||||
return '';
|
||||
}
|
||||
|
||||
// Форматируем дату с указанием дня, месяца, года и времени
|
||||
return date.toLocaleString([], {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error formatting time:', error, timestamp);
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
// Форматирование сообщения с поддержкой markdown
|
||||
const formatMessage = (text) => {
|
||||
if (!text) return '';
|
||||
const rawHtml = marked.parse(text);
|
||||
return DOMPurify.sanitize(rawHtml);
|
||||
};
|
||||
|
||||
// Функция для отправки сообщения
|
||||
const handleMessage = async (text) => {
|
||||
try {
|
||||
const messageContent = text.trim();
|
||||
if (!messageContent) return;
|
||||
|
||||
newMessage.value = '';
|
||||
isLoading.value = true;
|
||||
|
||||
if (!isAuthenticated.value) {
|
||||
// Сохраняем в таблицу guest_messages
|
||||
const response = await api.post('/api/chat/guest-message', {
|
||||
message: messageContent,
|
||||
language: userLanguage.value
|
||||
});
|
||||
|
||||
if (response.data.success) {
|
||||
const userMessage = {
|
||||
id: response.data.messageId,
|
||||
content: messageContent,
|
||||
role: 'user',
|
||||
timestamp: new Date().toISOString(),
|
||||
showAuthButtons: false
|
||||
};
|
||||
messages.value.push(userMessage);
|
||||
|
||||
messages.value.push({
|
||||
id: Date.now() + 1,
|
||||
content: 'Для получения ответа от ассистента, пожалуйста, авторизуйтесь одним из способов:',
|
||||
role: 'assistant',
|
||||
timestamp: new Date().toISOString(),
|
||||
showAuthButtons: true
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Для авторизованного пользователя сохраняем в messages
|
||||
const response = await api.post('/api/chat/message', {
|
||||
message: messageContent,
|
||||
language: userLanguage.value
|
||||
});
|
||||
|
||||
if (response.data.success) {
|
||||
const message = {
|
||||
id: response.data.messageId,
|
||||
content: messageContent,
|
||||
role: 'user',
|
||||
timestamp: new Date().toISOString(),
|
||||
hasResponse: true
|
||||
};
|
||||
messages.value.push(message);
|
||||
|
||||
const aiMessage = {
|
||||
id: response.data.aiMessageId,
|
||||
content: response.data.message,
|
||||
role: 'assistant',
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
messages.value.push(aiMessage);
|
||||
}
|
||||
}
|
||||
|
||||
await nextTick();
|
||||
scrollToBottom();
|
||||
} catch (error) {
|
||||
console.error('Error sending message:', error);
|
||||
messages.value.push({
|
||||
id: Date.now(),
|
||||
content: 'Произошла ошибка при отправке сообщения.',
|
||||
role: 'assistant',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Обработка прокрутки
|
||||
const handleScroll = async () => {
|
||||
const element = messagesContainer.value;
|
||||
if (
|
||||
!isLoadingMore.value &&
|
||||
hasMoreMessages.value &&
|
||||
element.scrollTop === 0
|
||||
) {
|
||||
await loadMoreMessages();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
// Добавляем слушатель прокрутки
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.addEventListener('scroll', handleScroll);
|
||||
}
|
||||
console.log('Auth state on mount:', {
|
||||
isAuthenticated: auth.isAuthenticated.value,
|
||||
authType: auth.authType.value,
|
||||
telegramId: auth.telegramId.value
|
||||
});
|
||||
|
||||
// Проверяем статус авторизации
|
||||
auth.checkAuth();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
// Удаляем слушатель
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.removeEventListener('scroll', handleScroll);
|
||||
}
|
||||
if (telegramAuthCheckInterval.value) {
|
||||
clearInterval(telegramAuthCheckInterval.value);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -459,6 +459,11 @@
|
||||
dependencies:
|
||||
undici-types "~6.19.2"
|
||||
|
||||
"@types/trusted-types@^2.0.7":
|
||||
version "2.0.7"
|
||||
resolved "https://registry.yarnpkg.com/@types/trusted-types/-/trusted-types-2.0.7.tgz#baccb07a970b91707df3a3e8ba6896c57ead2d11"
|
||||
integrity sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==
|
||||
|
||||
"@vitejs/plugin-vue@^5.2.1":
|
||||
version "5.2.1"
|
||||
resolved "https://registry.yarnpkg.com/@vitejs/plugin-vue/-/plugin-vue-5.2.1.tgz#d1491f678ee3af899f7ae57d9c21dc52a65c7133"
|
||||
@@ -740,6 +745,13 @@ delayed-stream@~1.0.0:
|
||||
resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
|
||||
integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==
|
||||
|
||||
dompurify@^3.2.4:
|
||||
version "3.2.4"
|
||||
resolved "https://registry.yarnpkg.com/dompurify/-/dompurify-3.2.4.tgz#af5a5a11407524431456cf18836c55d13441cd8e"
|
||||
integrity sha512-ysFSFEDVduQpyhzAob/kkuJjf5zWkZD8/A9ywSp1byueyuCfHamrCBa14/Oc2iiB0e51B+NpxSl5gmzn+Ms/mg==
|
||||
optionalDependencies:
|
||||
"@types/trusted-types" "^2.0.7"
|
||||
|
||||
dunder-proto@^1.0.1:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/dunder-proto/-/dunder-proto-1.0.1.tgz#d7ae667e1dc83482f8b70fd0f6eefc50da30f58a"
|
||||
@@ -1226,6 +1238,11 @@ magic-string@^0.30.11, magic-string@^0.30.3:
|
||||
dependencies:
|
||||
"@jridgewell/sourcemap-codec" "^1.5.0"
|
||||
|
||||
marked@^15.0.7:
|
||||
version "15.0.7"
|
||||
resolved "https://registry.yarnpkg.com/marked/-/marked-15.0.7.tgz#f67d7e34d202ce087e6b879107b5efb04e743314"
|
||||
integrity sha512-dgLIeKGLx5FwziAnsk4ONoGwHwGPJzselimvlVskE9XLN4Orv9u2VA3GWw/lYUqjfA0rUT/6fqKwfZJapP9BEg==
|
||||
|
||||
math-intrinsics@^1.1.0:
|
||||
version "1.1.0"
|
||||
resolved "https://registry.yarnpkg.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz#a0dd74be81e2aa5c2f27e65ce283605ee4e2b7f9"
|
||||
|
||||
Reference in New Issue
Block a user